1 //===-- ShadowStackCollector.cpp - GC support for uncooperative targets ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements lowering for the llvm.gc* intrinsics for targets that do
11 // not natively support them (which includes the C backend). Note that the code
12 // generated is not quite as efficient as collectors which generate stack maps
15 // This pass implements the code transformation described in this paper:
16 // "Accurate Garbage Collection in an Uncooperative Environment"
17 // Fergus Henderson, ISMM, 2002
19 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
22 // In order to support this particular transformation, all stack roots are
23 // coallocated in the stack. This allows a fully target-independent stack map
24 // while introducing only minor runtime overhead.
26 //===----------------------------------------------------------------------===//
28 #define DEBUG_TYPE "shadowstackgc"
29 #include "llvm/CodeGen/Collectors.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/CodeGen/Collector.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/Module.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/LLVMBuilder.h"
41 #include "llvm/Analysis/Verifier.h"
48 class VISIBILITY_HIDDEN ShadowStackCollector : public Collector {
49 /// RootChain - This is the global linked-list that contains the chain of GC
53 /// StackEntryTy - Abstract type of a link in the shadow stack.
55 const StructType *StackEntryTy;
57 /// Roots - GC roots in the current function. Each is a pair of the
58 /// intrinsic call and its corresponding alloca.
59 std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
62 ShadowStackCollector();
64 bool initializeCustomLowering(Module &M);
65 bool performCustomLowering(Function &F);
68 bool IsNullValue(Value *V);
69 Constant *GetFrameMap(Function &F);
70 const Type* GetConcreteStackEntryType(Function &F);
71 void CollectRoots(Function &F);
72 static GetElementPtrInst *CreateGEP(LLVMBuilder &B, Value *BasePtr,
73 int Idx1, const char *Name);
74 static GetElementPtrInst *CreateGEP(LLVMBuilder &B, Value *BasePtr,
75 int Idx1, int Idx2, const char *Name);
78 CollectorRegistry::Add<ShadowStackCollector>
80 "Very portable collector for uncooperative code generators");
82 /// EscapeEnumerator - This is a little algorithm to find all escape points
83 /// from a function so that "finally"-style code can be inserted. In addition
84 /// to finding the existing return and unwind instructions, it also (if
85 /// necessary) transforms any call instructions into invokes and sends them to
88 /// It's wrapped up in a state machine using the same transform C# uses for
89 /// 'yield return' enumerators, This transform allows it to be non-allocating.
90 class VISIBILITY_HIDDEN EscapeEnumerator {
92 const char *CleanupBBName;
96 Function::iterator StateBB, StateE;
100 EscapeEnumerator(Function &F, const char *N = "cleanup")
101 : F(F), CleanupBBName(N), State(0) {}
103 LLVMBuilder *Next() {
114 // Find all 'return' and 'unwind' instructions.
115 while (StateBB != StateE) {
116 BasicBlock *CurBB = StateBB++;
118 // Branches and invokes do not escape, only unwind and return do.
119 TerminatorInst *TI = CurBB->getTerminator();
120 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
123 Builder.SetInsertPoint(TI->getParent(), TI);
129 // Find all 'call' instructions.
130 SmallVector<Instruction*,16> Calls;
131 for (Function::iterator BB = F.begin(),
132 E = F.end(); BB != E; ++BB)
133 for (BasicBlock::iterator II = BB->begin(),
134 EE = BB->end(); II != EE; ++II)
135 if (CallInst *CI = dyn_cast<CallInst>(II))
136 if (!CI->getCalledFunction() ||
137 !CI->getCalledFunction()->getIntrinsicID())
143 // Create a cleanup block.
144 BasicBlock *CleanupBB = new BasicBlock(CleanupBBName, &F);
145 UnwindInst *UI = new UnwindInst(CleanupBB);
147 // Transform the 'call' instructions into 'invoke's branching to the
148 // cleanup block. Go in reverse order to make prettier BB names.
149 SmallVector<Value*,16> Args;
150 for (unsigned I = Calls.size(); I != 0; ) {
151 CallInst *CI = cast<CallInst>(Calls[--I]);
153 // Split the basic block containing the function call.
154 BasicBlock *CallBB = CI->getParent();
156 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
158 // Remove the unconditional branch inserted at the end of CallBB.
159 CallBB->getInstList().pop_back();
160 NewBB->getInstList().remove(CI);
162 // Create a new invoke instruction.
164 Args.append(CI->op_begin() + 1, CI->op_end());
166 InvokeInst *II = new InvokeInst(CI->getOperand(0),
168 Args.begin(), Args.end(),
169 CI->getName(), CallBB);
170 II->setCallingConv(CI->getCallingConv());
171 II->setParamAttrs(CI->getParamAttrs());
172 CI->replaceAllUsesWith(II);
176 Builder.SetInsertPoint(UI->getParent(), UI);
184 // -----------------------------------------------------------------------------
186 Collector *llvm::createShadowStackCollector() {
187 return new ShadowStackCollector();
190 ShadowStackCollector::ShadowStackCollector() : Head(0), StackEntryTy(0) {
195 Constant *ShadowStackCollector::GetFrameMap(Function &F) {
196 // doInitialization creates the abstract type of this value.
198 Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
200 // Truncate the ShadowStackDescriptor if some metadata is null.
201 unsigned NumMeta = 0;
202 SmallVector<Constant*,16> Metadata;
203 for (unsigned I = 0; I != Roots.size(); ++I) {
204 Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
205 if (!C->isNullValue())
207 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
210 Constant *BaseElts[] = {
211 ConstantInt::get(Type::Int32Ty, Roots.size(), false),
212 ConstantInt::get(Type::Int32Ty, NumMeta, false),
215 Constant *DescriptorElts[] = {
216 ConstantStruct::get(BaseElts, 2),
217 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
218 Metadata.begin(), NumMeta)
221 Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2);
223 std::string TypeName("gc_map.");
224 TypeName += utostr(NumMeta);
225 F.getParent()->addTypeName(TypeName, FrameMap->getType());
227 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
228 // that, short of multithreaded LLVM, it should be safe; all that is
229 // necessary is that a simple Module::iterator loop not be invalidated.
230 // Appending to the GlobalVariable list is safe in that sense.
232 // All of the output passes emit globals last. The ExecutionEngine
233 // explicitly supports adding globals to the module after
236 // Still, if it isn't deemed acceptable, then this transformation needs
237 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
238 // (which uses a FunctionPassManager (which segfaults (not asserts) if
239 // provided a ModulePass))).
240 Constant *GV = new GlobalVariable(FrameMap->getType(), true,
241 GlobalVariable::InternalLinkage,
242 FrameMap, "__gc_" + F.getName(),
245 Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0),
246 ConstantInt::get(Type::Int32Ty, 0) };
247 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
250 const Type* ShadowStackCollector::GetConcreteStackEntryType(Function &F) {
251 // doInitialization creates the generic version of this type.
252 std::vector<const Type*> EltTys;
253 EltTys.push_back(StackEntryTy);
254 for (size_t I = 0; I != Roots.size(); I++)
255 EltTys.push_back(Roots[I].second->getAllocatedType());
256 Type *Ty = StructType::get(EltTys);
258 std::string TypeName("gc_stackentry.");
259 TypeName += F.getName();
260 F.getParent()->addTypeName(TypeName, Ty);
265 /// doInitialization - If this module uses the GC intrinsics, find them now. If
267 bool ShadowStackCollector::initializeCustomLowering(Module &M) {
269 // int32_t NumRoots; // Number of roots in stack frame.
270 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
271 // void *Meta[]; // May be absent for roots without metadata.
273 std::vector<const Type*> EltTys;
274 EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :)
275 EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array.
276 StructType *FrameMapTy = StructType::get(EltTys);
277 M.addTypeName("gc_map", FrameMapTy);
278 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
280 // struct StackEntry {
281 // ShadowStackEntry *Next; // Caller's stack entry.
282 // FrameMap *Map; // Pointer to constant FrameMap.
283 // void *Roots[]; // Stack roots (in-place array, so we pretend).
285 OpaqueType *RecursiveTy = OpaqueType::get();
288 EltTys.push_back(PointerType::getUnqual(RecursiveTy));
289 EltTys.push_back(FrameMapPtrTy);
290 PATypeHolder LinkTyH = StructType::get(EltTys);
292 RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
293 StackEntryTy = cast<StructType>(LinkTyH.get());
294 const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
295 M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from
298 // Get the root chain if it already exists.
299 Head = M.getGlobalVariable("llvm_gc_root_chain");
301 // If the root chain does not exist, insert a new one with linkonce
303 Head = new GlobalVariable(StackEntryPtrTy, false,
304 GlobalValue::LinkOnceLinkage,
305 Constant::getNullValue(StackEntryPtrTy),
306 "llvm_gc_root_chain", &M);
307 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
308 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
309 Head->setLinkage(GlobalValue::LinkOnceLinkage);
315 bool ShadowStackCollector::IsNullValue(Value *V) {
316 if (Constant *C = dyn_cast<Constant>(V))
317 return C->isNullValue();
321 void ShadowStackCollector::CollectRoots(Function &F) {
322 // FIXME: Account for original alignment. Could fragment the root array.
323 // Approach 1: Null initialize empty slots at runtime. Yuck.
324 // Approach 2: Emit a map of the array instead of just a count.
326 assert(Roots.empty() && "Not cleaned up?");
328 SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
331 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
332 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
333 if (Function *F = CI->getCalledFunction())
334 if (F->getIntrinsicID() == Intrinsic::gcroot) {
335 std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
336 CI, cast<AllocaInst>(
337 IntrinsicInst::StripPointerCasts(CI->getOperand(1))));
338 if (IsNullValue(CI->getOperand(2)))
339 Roots.push_back(Pair);
341 MetaRoots.push_back(Pair);
344 // Number roots with metadata (usually empty) at the beginning, so that the
345 // FrameMap::Meta array can be elided.
346 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
350 ShadowStackCollector::CreateGEP(LLVMBuilder &B, Value *BasePtr,
351 int Idx, int Idx2, const char *Name) {
352 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
353 ConstantInt::get(Type::Int32Ty, Idx),
354 ConstantInt::get(Type::Int32Ty, Idx2) };
355 return B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
359 ShadowStackCollector::CreateGEP(LLVMBuilder &B, Value *BasePtr,
360 int Idx, const char *Name) {
361 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
362 ConstantInt::get(Type::Int32Ty, Idx) };
363 return B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
366 /// runOnFunction - Insert code to maintain the shadow stack.
367 bool ShadowStackCollector::performCustomLowering(Function &F) {
368 // Find calls to llvm.gcroot.
371 // If there are no roots in this function, then there is no need to add a
372 // stack map entry for it.
376 // Build the constant map and figure the type of the shadow stack entry.
377 Value *FrameMap = GetFrameMap(F);
378 const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
380 // Build the shadow stack entry at the very start of the function.
381 BasicBlock::iterator IP = F.getEntryBlock().begin();
382 LLVMBuilder AtEntry(IP->getParent(), IP);
384 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
387 while (isa<AllocaInst>(IP)) ++IP;
388 AtEntry.SetInsertPoint(IP->getParent(), IP);
390 // Initialize the map pointer and load the current head of the shadow stack.
391 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
392 Instruction *EntryMapPtr = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map");
393 AtEntry.CreateStore(FrameMap, EntryMapPtr);
395 // After all the allocas...
396 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
397 // For each root, find the corresponding slot in the aggregate...
398 Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root");
400 // And use it in lieu of the alloca.
401 AllocaInst *OriginalAlloca = Roots[I].second;
402 SlotPtr->takeName(OriginalAlloca);
403 OriginalAlloca->replaceAllUsesWith(SlotPtr);
406 // Move past the original stores inserted by Collector::InitRoots. This isn't
407 // really necessary (the collector would never see the intermediate state),
408 // but it's nicer not to push the half-initialized entry onto the stack.
409 while (isa<StoreInst>(IP)) ++IP;
410 AtEntry.SetInsertPoint(IP->getParent(), IP);
412 // Push the entry onto the shadow stack.
413 Instruction *EntryNextPtr = CreateGEP(AtEntry,StackEntry,0,0,"gc_frame.next");
414 Instruction *NewHeadVal = CreateGEP(AtEntry,StackEntry, 0, "gc_newhead");
415 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
416 AtEntry.CreateStore(NewHeadVal, Head);
418 // For each instruction that escapes...
419 EscapeEnumerator EE(F, "gc_cleanup");
420 while (LLVMBuilder *AtExit = EE.Next()) {
421 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
422 // AtEntry, since that would make the value live for the entire function.
423 Instruction *EntryNextPtr2 = CreateGEP(*AtExit, StackEntry, 0, 0,
425 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
426 AtExit->CreateStore(SavedHead, Head);
429 // Delete the original allocas (which are no longer used) and the intrinsic
430 // calls (which are no longer valid). Doing this last avoids invalidating
432 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
433 Roots[I].first->eraseFromParent();
434 Roots[I].second->eraseFromParent();