1 //===- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains the custom lowering code required by the shadow-stack GC
12 // This pass implements the code transformation described in this paper:
13 // "Accurate Garbage Collection in an Uncooperative Environment"
14 // Fergus Henderson, ISMM, 2002
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
46 #define DEBUG_TYPE "shadow-stack-gc-lowering"
50 class ShadowStackGCLowering
: public FunctionPass
{
51 /// RootChain - This is the global linked-list that contains the chain of GC
53 GlobalVariable
*Head
= nullptr;
55 /// StackEntryTy - Abstract type of a link in the shadow stack.
56 StructType
*StackEntryTy
= nullptr;
57 StructType
*FrameMapTy
= nullptr;
59 /// Roots - GC roots in the current function. Each is a pair of the
60 /// intrinsic call and its corresponding alloca.
61 std::vector
<std::pair
<CallInst
*, AllocaInst
*>> Roots
;
66 ShadowStackGCLowering();
68 bool doInitialization(Module
&M
) override
;
69 bool runOnFunction(Function
&F
) override
;
72 bool IsNullValue(Value
*V
);
73 Constant
*GetFrameMap(Function
&F
);
74 Type
*GetConcreteStackEntryType(Function
&F
);
75 void CollectRoots(Function
&F
);
77 static GetElementPtrInst
*CreateGEP(LLVMContext
&Context
, IRBuilder
<> &B
,
78 Type
*Ty
, Value
*BasePtr
, int Idx1
,
80 static GetElementPtrInst
*CreateGEP(LLVMContext
&Context
, IRBuilder
<> &B
,
81 Type
*Ty
, Value
*BasePtr
, int Idx1
, int Idx2
,
85 } // end anonymous namespace
87 char ShadowStackGCLowering::ID
= 0;
89 INITIALIZE_PASS_BEGIN(ShadowStackGCLowering
, DEBUG_TYPE
,
90 "Shadow Stack GC Lowering", false, false)
91 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo
)
92 INITIALIZE_PASS_END(ShadowStackGCLowering
, DEBUG_TYPE
,
93 "Shadow Stack GC Lowering", false, false)
95 FunctionPass
*llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
97 ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID
) {
98 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
101 Constant
*ShadowStackGCLowering::GetFrameMap(Function
&F
) {
102 // doInitialization creates the abstract type of this value.
103 Type
*VoidPtr
= Type::getInt8PtrTy(F
.getContext());
105 // Truncate the ShadowStackDescriptor if some metadata is null.
106 unsigned NumMeta
= 0;
107 SmallVector
<Constant
*, 16> Metadata
;
108 for (unsigned I
= 0; I
!= Roots
.size(); ++I
) {
109 Constant
*C
= cast
<Constant
>(Roots
[I
].first
->getArgOperand(1));
110 if (!C
->isNullValue())
112 Metadata
.push_back(ConstantExpr::getBitCast(C
, VoidPtr
));
114 Metadata
.resize(NumMeta
);
116 Type
*Int32Ty
= Type::getInt32Ty(F
.getContext());
118 Constant
*BaseElts
[] = {
119 ConstantInt::get(Int32Ty
, Roots
.size(), false),
120 ConstantInt::get(Int32Ty
, NumMeta
, false),
123 Constant
*DescriptorElts
[] = {
124 ConstantStruct::get(FrameMapTy
, BaseElts
),
125 ConstantArray::get(ArrayType::get(VoidPtr
, NumMeta
), Metadata
)};
127 Type
*EltTys
[] = {DescriptorElts
[0]->getType(), DescriptorElts
[1]->getType()};
128 StructType
*STy
= StructType::create(EltTys
, "gc_map." + utostr(NumMeta
));
130 Constant
*FrameMap
= ConstantStruct::get(STy
, DescriptorElts
);
132 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
133 // that, short of multithreaded LLVM, it should be safe; all that is
134 // necessary is that a simple Module::iterator loop not be invalidated.
135 // Appending to the GlobalVariable list is safe in that sense.
137 // All of the output passes emit globals last. The ExecutionEngine
138 // explicitly supports adding globals to the module after
141 // Still, if it isn't deemed acceptable, then this transformation needs
142 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
143 // (which uses a FunctionPassManager (which segfaults (not asserts) if
144 // provided a ModulePass))).
145 Constant
*GV
= new GlobalVariable(*F
.getParent(), FrameMap
->getType(), true,
146 GlobalVariable::InternalLinkage
, FrameMap
,
147 "__gc_" + F
.getName());
149 Constant
*GEPIndices
[2] = {
150 ConstantInt::get(Type::getInt32Ty(F
.getContext()), 0),
151 ConstantInt::get(Type::getInt32Ty(F
.getContext()), 0)};
152 return ConstantExpr::getGetElementPtr(FrameMap
->getType(), GV
, GEPIndices
);
155 Type
*ShadowStackGCLowering::GetConcreteStackEntryType(Function
&F
) {
156 // doInitialization creates the generic version of this type.
157 std::vector
<Type
*> EltTys
;
158 EltTys
.push_back(StackEntryTy
);
159 for (size_t I
= 0; I
!= Roots
.size(); I
++)
160 EltTys
.push_back(Roots
[I
].second
->getAllocatedType());
162 return StructType::create(EltTys
, ("gc_stackentry." + F
.getName()).str());
165 /// doInitialization - If this module uses the GC intrinsics, find them now. If
167 bool ShadowStackGCLowering::doInitialization(Module
&M
) {
169 for (Function
&F
: M
) {
170 if (F
.hasGC() && F
.getGC() == std::string("shadow-stack")) {
179 // int32_t NumRoots; // Number of roots in stack frame.
180 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
181 // void *Meta[]; // May be absent for roots without metadata.
183 std::vector
<Type
*> EltTys
;
184 // 32 bits is ok up to a 32GB stack frame. :)
185 EltTys
.push_back(Type::getInt32Ty(M
.getContext()));
186 // Specifies length of variable length array.
187 EltTys
.push_back(Type::getInt32Ty(M
.getContext()));
188 FrameMapTy
= StructType::create(EltTys
, "gc_map");
189 PointerType
*FrameMapPtrTy
= PointerType::getUnqual(FrameMapTy
);
191 // struct StackEntry {
192 // ShadowStackEntry *Next; // Caller's stack entry.
193 // FrameMap *Map; // Pointer to constant FrameMap.
194 // void *Roots[]; // Stack roots (in-place array, so we pretend).
197 StackEntryTy
= StructType::create(M
.getContext(), "gc_stackentry");
200 EltTys
.push_back(PointerType::getUnqual(StackEntryTy
));
201 EltTys
.push_back(FrameMapPtrTy
);
202 StackEntryTy
->setBody(EltTys
);
203 PointerType
*StackEntryPtrTy
= PointerType::getUnqual(StackEntryTy
);
205 // Get the root chain if it already exists.
206 Head
= M
.getGlobalVariable("llvm_gc_root_chain");
208 // If the root chain does not exist, insert a new one with linkonce
210 Head
= new GlobalVariable(
211 M
, StackEntryPtrTy
, false, GlobalValue::LinkOnceAnyLinkage
,
212 Constant::getNullValue(StackEntryPtrTy
), "llvm_gc_root_chain");
213 } else if (Head
->hasExternalLinkage() && Head
->isDeclaration()) {
214 Head
->setInitializer(Constant::getNullValue(StackEntryPtrTy
));
215 Head
->setLinkage(GlobalValue::LinkOnceAnyLinkage
);
221 bool ShadowStackGCLowering::IsNullValue(Value
*V
) {
222 if (Constant
*C
= dyn_cast
<Constant
>(V
))
223 return C
->isNullValue();
227 void ShadowStackGCLowering::CollectRoots(Function
&F
) {
228 // FIXME: Account for original alignment. Could fragment the root array.
229 // Approach 1: Null initialize empty slots at runtime. Yuck.
230 // Approach 2: Emit a map of the array instead of just a count.
232 assert(Roots
.empty() && "Not cleaned up?");
234 SmallVector
<std::pair
<CallInst
*, AllocaInst
*>, 16> MetaRoots
;
236 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
)
237 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
;)
238 if (IntrinsicInst
*CI
= dyn_cast
<IntrinsicInst
>(II
++))
239 if (Function
*F
= CI
->getCalledFunction())
240 if (F
->getIntrinsicID() == Intrinsic::gcroot
) {
241 std::pair
<CallInst
*, AllocaInst
*> Pair
= std::make_pair(
243 cast
<AllocaInst
>(CI
->getArgOperand(0)->stripPointerCasts()));
244 if (IsNullValue(CI
->getArgOperand(1)))
245 Roots
.push_back(Pair
);
247 MetaRoots
.push_back(Pair
);
250 // Number roots with metadata (usually empty) at the beginning, so that the
251 // FrameMap::Meta array can be elided.
252 Roots
.insert(Roots
.begin(), MetaRoots
.begin(), MetaRoots
.end());
255 GetElementPtrInst
*ShadowStackGCLowering::CreateGEP(LLVMContext
&Context
,
256 IRBuilder
<> &B
, Type
*Ty
,
257 Value
*BasePtr
, int Idx
,
260 Value
*Indices
[] = {ConstantInt::get(Type::getInt32Ty(Context
), 0),
261 ConstantInt::get(Type::getInt32Ty(Context
), Idx
),
262 ConstantInt::get(Type::getInt32Ty(Context
), Idx2
)};
263 Value
*Val
= B
.CreateGEP(Ty
, BasePtr
, Indices
, Name
);
265 assert(isa
<GetElementPtrInst
>(Val
) && "Unexpected folded constant");
267 return dyn_cast
<GetElementPtrInst
>(Val
);
270 GetElementPtrInst
*ShadowStackGCLowering::CreateGEP(LLVMContext
&Context
,
271 IRBuilder
<> &B
, Type
*Ty
, Value
*BasePtr
,
272 int Idx
, const char *Name
) {
273 Value
*Indices
[] = {ConstantInt::get(Type::getInt32Ty(Context
), 0),
274 ConstantInt::get(Type::getInt32Ty(Context
), Idx
)};
275 Value
*Val
= B
.CreateGEP(Ty
, BasePtr
, Indices
, Name
);
277 assert(isa
<GetElementPtrInst
>(Val
) && "Unexpected folded constant");
279 return dyn_cast
<GetElementPtrInst
>(Val
);
282 /// runOnFunction - Insert code to maintain the shadow stack.
283 bool ShadowStackGCLowering::runOnFunction(Function
&F
) {
284 // Quick exit for functions that do not use the shadow stack GC.
286 F
.getGC() != std::string("shadow-stack"))
289 LLVMContext
&Context
= F
.getContext();
291 // Find calls to llvm.gcroot.
294 // If there are no roots in this function, then there is no need to add a
295 // stack map entry for it.
299 // Build the constant map and figure the type of the shadow stack entry.
300 Value
*FrameMap
= GetFrameMap(F
);
301 Type
*ConcreteStackEntryTy
= GetConcreteStackEntryType(F
);
303 // Build the shadow stack entry at the very start of the function.
304 BasicBlock::iterator IP
= F
.getEntryBlock().begin();
305 IRBuilder
<> AtEntry(IP
->getParent(), IP
);
307 Instruction
*StackEntry
=
308 AtEntry
.CreateAlloca(ConcreteStackEntryTy
, nullptr, "gc_frame");
310 while (isa
<AllocaInst
>(IP
))
312 AtEntry
.SetInsertPoint(IP
->getParent(), IP
);
314 // Initialize the map pointer and load the current head of the shadow stack.
315 Instruction
*CurrentHead
=
316 AtEntry
.CreateLoad(StackEntryTy
->getPointerTo(), Head
, "gc_currhead");
317 Instruction
*EntryMapPtr
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
318 StackEntry
, 0, 1, "gc_frame.map");
319 AtEntry
.CreateStore(FrameMap
, EntryMapPtr
);
321 // After all the allocas...
322 for (unsigned I
= 0, E
= Roots
.size(); I
!= E
; ++I
) {
323 // For each root, find the corresponding slot in the aggregate...
324 Value
*SlotPtr
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
325 StackEntry
, 1 + I
, "gc_root");
327 // And use it in lieu of the alloca.
328 AllocaInst
*OriginalAlloca
= Roots
[I
].second
;
329 SlotPtr
->takeName(OriginalAlloca
);
330 OriginalAlloca
->replaceAllUsesWith(SlotPtr
);
333 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
334 // really necessary (the collector would never see the intermediate state at
335 // runtime), but it's nicer not to push the half-initialized entry onto the
337 while (isa
<StoreInst
>(IP
))
339 AtEntry
.SetInsertPoint(IP
->getParent(), IP
);
341 // Push the entry onto the shadow stack.
342 Instruction
*EntryNextPtr
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
343 StackEntry
, 0, 0, "gc_frame.next");
344 Instruction
*NewHeadVal
= CreateGEP(Context
, AtEntry
, ConcreteStackEntryTy
,
345 StackEntry
, 0, "gc_newhead");
346 AtEntry
.CreateStore(CurrentHead
, EntryNextPtr
);
347 AtEntry
.CreateStore(NewHeadVal
, Head
);
349 // For each instruction that escapes...
350 EscapeEnumerator
EE(F
, "gc_cleanup");
351 while (IRBuilder
<> *AtExit
= EE
.Next()) {
352 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
353 // AtEntry, since that would make the value live for the entire function.
354 Instruction
*EntryNextPtr2
=
355 CreateGEP(Context
, *AtExit
, ConcreteStackEntryTy
, StackEntry
, 0, 0,
357 Value
*SavedHead
= AtExit
->CreateLoad(StackEntryTy
->getPointerTo(),
358 EntryNextPtr2
, "gc_savedhead");
359 AtExit
->CreateStore(SavedHead
, Head
);
362 // Delete the original allocas (which are no longer used) and the intrinsic
363 // calls (which are no longer valid). Doing this last avoids invalidating
365 for (unsigned I
= 0, E
= Roots
.size(); I
!= E
; ++I
) {
366 Roots
[I
].first
->eraseFromParent();
367 Roots
[I
].second
->eraseFromParent();