850c00542ce6ddd01ab66e5620533786d1cbece1
[oota-llvm.git] / lib / CodeGen / ShadowStackGC.cpp
1 //===-- ShadowStackCollector.cpp - GC support for uncooperative targets ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
13 // to identify roots.
14 //
15 // This pass implements the code transformation described in this paper:
16 //   "Accurate Garbage Collection in an Uncooperative Environment"
17 //   Fergus Henderson, ISMM, 2002
18 //
19 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
20 // this collector.
21 //
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.
25 //
26 //===----------------------------------------------------------------------===//
27
28 #define DEBUG_TYPE "shadowstackgc"
29 #include "llvm/CodeGen/GCs.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/CodeGen/GCStrategy.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/Module.h"
34 #include "llvm/Support/IRBuilder.h"
35
36 using namespace llvm;
37
38 namespace {
39   
40   class VISIBILITY_HIDDEN ShadowStackCollector : public Collector {
41     /// RootChain - This is the global linked-list that contains the chain of GC
42     /// roots.
43     GlobalVariable *Head;
44     
45     /// StackEntryTy - Abstract type of a link in the shadow stack.
46     /// 
47     const StructType *StackEntryTy;
48     
49     /// Roots - GC roots in the current function. Each is a pair of the
50     /// intrinsic call and its corresponding alloca.
51     std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
52     
53   public:
54     ShadowStackCollector();
55     
56     bool initializeCustomLowering(Module &M);
57     bool performCustomLowering(Function &F);
58     
59   private:
60     bool IsNullValue(Value *V);
61     Constant *GetFrameMap(Function &F);
62     const Type* GetConcreteStackEntryType(Function &F);
63     void CollectRoots(Function &F);
64     static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
65                                         int Idx1, const char *Name);
66     static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
67                                         int Idx1, int Idx2, const char *Name);
68   };
69
70 }
71   
72 static CollectorRegistry::Add<ShadowStackCollector>
73 Y("shadow-stack",
74   "Very portable collector for uncooperative code generators");
75   
76 namespace {
77   /// EscapeEnumerator - This is a little algorithm to find all escape points
78   /// from a function so that "finally"-style code can be inserted. In addition
79   /// to finding the existing return and unwind instructions, it also (if
80   /// necessary) transforms any call instructions into invokes and sends them to
81   /// a landing pad.
82   /// 
83   /// It's wrapped up in a state machine using the same transform C# uses for
84   /// 'yield return' enumerators, This transform allows it to be non-allocating.
85   class VISIBILITY_HIDDEN EscapeEnumerator {
86     Function &F;
87     const char *CleanupBBName;
88     
89     // State.
90     int State;
91     Function::iterator StateBB, StateE;
92     IRBuilder<> Builder;
93     
94   public:
95     EscapeEnumerator(Function &F, const char *N = "cleanup")
96       : F(F), CleanupBBName(N), State(0) {}
97     
98     IRBuilder<> *Next() {
99       switch (State) {
100       default:
101         return 0;
102         
103       case 0:
104         StateBB = F.begin();
105         StateE = F.end();
106         State = 1;
107         
108       case 1:
109         // Find all 'return' and 'unwind' instructions.
110         while (StateBB != StateE) {
111           BasicBlock *CurBB = StateBB++;
112           
113           // Branches and invokes do not escape, only unwind and return do.
114           TerminatorInst *TI = CurBB->getTerminator();
115           if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
116             continue;
117           
118           Builder.SetInsertPoint(TI->getParent(), TI);
119           return &Builder;
120         }
121         
122         State = 2;
123         
124         // Find all 'call' instructions.
125         SmallVector<Instruction*,16> Calls;
126         for (Function::iterator BB = F.begin(),
127                                 E = F.end(); BB != E; ++BB)
128           for (BasicBlock::iterator II = BB->begin(),
129                                     EE = BB->end(); II != EE; ++II)
130             if (CallInst *CI = dyn_cast<CallInst>(II))
131               if (!CI->getCalledFunction() ||
132                   !CI->getCalledFunction()->getIntrinsicID())
133                 Calls.push_back(CI);
134         
135         if (Calls.empty())
136           return 0;
137         
138         // Create a cleanup block.
139         BasicBlock *CleanupBB = BasicBlock::Create(CleanupBBName, &F);
140         UnwindInst *UI = new UnwindInst(CleanupBB);
141         
142         // Transform the 'call' instructions into 'invoke's branching to the
143         // cleanup block. Go in reverse order to make prettier BB names.
144         SmallVector<Value*,16> Args;
145         for (unsigned I = Calls.size(); I != 0; ) {
146           CallInst *CI = cast<CallInst>(Calls[--I]);
147           
148           // Split the basic block containing the function call.
149           BasicBlock *CallBB = CI->getParent();
150           BasicBlock *NewBB =
151             CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
152           
153           // Remove the unconditional branch inserted at the end of CallBB.
154           CallBB->getInstList().pop_back();
155           NewBB->getInstList().remove(CI);
156           
157           // Create a new invoke instruction.
158           Args.clear();
159           Args.append(CI->op_begin() + 1, CI->op_end());
160           
161           InvokeInst *II = InvokeInst::Create(CI->getOperand(0),
162                                               NewBB, CleanupBB,
163                                               Args.begin(), Args.end(),
164                                               CI->getName(), CallBB);
165           II->setCallingConv(CI->getCallingConv());
166           II->setParamAttrs(CI->getParamAttrs());
167           CI->replaceAllUsesWith(II);
168           delete CI;
169         }
170         
171         Builder.SetInsertPoint(UI->getParent(), UI);
172         return &Builder;
173       }
174     }
175   };
176
177 }
178
179 // -----------------------------------------------------------------------------
180
181 Collector *llvm::createShadowStackCollector() {
182   return new ShadowStackCollector();
183 }
184
185 ShadowStackCollector::ShadowStackCollector() : Head(0), StackEntryTy(0) {
186   InitRoots = true;
187   CustomRoots = true;
188 }
189
190 Constant *ShadowStackCollector::GetFrameMap(Function &F) {
191   // doInitialization creates the abstract type of this value.
192   
193   Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
194   
195   // Truncate the ShadowStackDescriptor if some metadata is null.
196   unsigned NumMeta = 0;
197   SmallVector<Constant*,16> Metadata;
198   for (unsigned I = 0; I != Roots.size(); ++I) {
199     Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
200     if (!C->isNullValue())
201       NumMeta = I + 1;
202     Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
203   }
204   
205   Constant *BaseElts[] = {
206     ConstantInt::get(Type::Int32Ty, Roots.size(), false),
207     ConstantInt::get(Type::Int32Ty, NumMeta, false),
208   };
209   
210   Constant *DescriptorElts[] = {
211     ConstantStruct::get(BaseElts, 2),
212     ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
213                        Metadata.begin(), NumMeta)
214   };
215   
216   Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2);
217   
218   std::string TypeName("gc_map.");
219   TypeName += utostr(NumMeta);
220   F.getParent()->addTypeName(TypeName, FrameMap->getType());
221   
222   // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
223   //        that, short of multithreaded LLVM, it should be safe; all that is
224   //        necessary is that a simple Module::iterator loop not be invalidated.
225   //        Appending to the GlobalVariable list is safe in that sense.
226   // 
227   //        All of the output passes emit globals last. The ExecutionEngine
228   //        explicitly supports adding globals to the module after
229   //        initialization.
230   // 
231   //        Still, if it isn't deemed acceptable, then this transformation needs
232   //        to be a ModulePass (which means it cannot be in the 'llc' pipeline
233   //        (which uses a FunctionPassManager (which segfaults (not asserts) if
234   //        provided a ModulePass))).
235   Constant *GV = new GlobalVariable(FrameMap->getType(), true,
236                                     GlobalVariable::InternalLinkage,
237                                     FrameMap, "__gc_" + F.getName(),
238                                     F.getParent());
239   
240   Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0),
241                               ConstantInt::get(Type::Int32Ty, 0) };
242   return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
243 }
244
245 const Type* ShadowStackCollector::GetConcreteStackEntryType(Function &F) {
246   // doInitialization creates the generic version of this type.
247   std::vector<const Type*> EltTys;
248   EltTys.push_back(StackEntryTy);
249   for (size_t I = 0; I != Roots.size(); I++)
250     EltTys.push_back(Roots[I].second->getAllocatedType());
251   Type *Ty = StructType::get(EltTys);
252   
253   std::string TypeName("gc_stackentry.");
254   TypeName += F.getName();
255   F.getParent()->addTypeName(TypeName, Ty);
256   
257   return Ty;
258 }
259
260 /// doInitialization - If this module uses the GC intrinsics, find them now. If
261 /// not, exit fast.
262 bool ShadowStackCollector::initializeCustomLowering(Module &M) {
263   // struct FrameMap {
264   //   int32_t NumRoots; // Number of roots in stack frame.
265   //   int32_t NumMeta;  // Number of metadata descriptors. May be < NumRoots.
266   //   void *Meta[];     // May be absent for roots without metadata.
267   // };
268   std::vector<const Type*> EltTys;
269   EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :)
270   EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array.
271   StructType *FrameMapTy = StructType::get(EltTys);
272   M.addTypeName("gc_map", FrameMapTy);
273   PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
274   
275   // struct StackEntry {
276   //   ShadowStackEntry *Next; // Caller's stack entry.
277   //   FrameMap *Map;          // Pointer to constant FrameMap.
278   //   void *Roots[];          // Stack roots (in-place array, so we pretend).
279   // };
280   OpaqueType *RecursiveTy = OpaqueType::get();
281   
282   EltTys.clear();
283   EltTys.push_back(PointerType::getUnqual(RecursiveTy));
284   EltTys.push_back(FrameMapPtrTy);
285   PATypeHolder LinkTyH = StructType::get(EltTys);
286   
287   RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
288   StackEntryTy = cast<StructType>(LinkTyH.get());
289   const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
290   M.addTypeName("gc_stackentry", LinkTyH.get());  // FIXME: Is this safe from
291                                                   //        a FunctionPass?
292   
293   // Get the root chain if it already exists.
294   Head = M.getGlobalVariable("llvm_gc_root_chain");
295   if (!Head) {
296     // If the root chain does not exist, insert a new one with linkonce
297     // linkage!
298     Head = new GlobalVariable(StackEntryPtrTy, false,
299                               GlobalValue::LinkOnceLinkage,
300                               Constant::getNullValue(StackEntryPtrTy),
301                               "llvm_gc_root_chain", &M);
302   } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
303     Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
304     Head->setLinkage(GlobalValue::LinkOnceLinkage);
305   }
306   
307   return true;
308 }
309
310 bool ShadowStackCollector::IsNullValue(Value *V) {
311   if (Constant *C = dyn_cast<Constant>(V))
312     return C->isNullValue();
313   return false;
314 }
315
316 void ShadowStackCollector::CollectRoots(Function &F) {
317   // FIXME: Account for original alignment. Could fragment the root array.
318   //   Approach 1: Null initialize empty slots at runtime. Yuck.
319   //   Approach 2: Emit a map of the array instead of just a count.
320   
321   assert(Roots.empty() && "Not cleaned up?");
322   
323   SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
324   
325   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
326     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
327       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
328         if (Function *F = CI->getCalledFunction())
329           if (F->getIntrinsicID() == Intrinsic::gcroot) {
330             std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
331               CI, cast<AllocaInst>(CI->getOperand(1)->stripPointerCasts()));
332             if (IsNullValue(CI->getOperand(2)))
333               Roots.push_back(Pair);
334             else
335               MetaRoots.push_back(Pair);
336           }
337   
338   // Number roots with metadata (usually empty) at the beginning, so that the
339   // FrameMap::Meta array can be elided.
340   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
341 }
342
343 GetElementPtrInst *
344 ShadowStackCollector::CreateGEP(IRBuilder<> &B, Value *BasePtr,
345                                 int Idx, int Idx2, const char *Name) {
346   Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
347                        ConstantInt::get(Type::Int32Ty, Idx),
348                        ConstantInt::get(Type::Int32Ty, Idx2) };
349   Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
350     
351   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
352     
353   return dyn_cast<GetElementPtrInst>(Val);
354 }
355
356 GetElementPtrInst *
357 ShadowStackCollector::CreateGEP(IRBuilder<> &B, Value *BasePtr,
358                                 int Idx, const char *Name) {
359   Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
360                        ConstantInt::get(Type::Int32Ty, Idx) };
361   Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
362     
363   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
364
365   return dyn_cast<GetElementPtrInst>(Val);
366 }
367
368 /// runOnFunction - Insert code to maintain the shadow stack.
369 bool ShadowStackCollector::performCustomLowering(Function &F) {
370   // Find calls to llvm.gcroot.
371   CollectRoots(F);
372   
373   // If there are no roots in this function, then there is no need to add a
374   // stack map entry for it.
375   if (Roots.empty())
376     return false;
377   
378   // Build the constant map and figure the type of the shadow stack entry.
379   Value *FrameMap = GetFrameMap(F);
380   const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
381   
382   // Build the shadow stack entry at the very start of the function.
383   BasicBlock::iterator IP = F.getEntryBlock().begin();
384   IRBuilder<> AtEntry(IP->getParent(), IP);
385   
386   Instruction *StackEntry   = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
387                                                    "gc_frame");
388   
389   while (isa<AllocaInst>(IP)) ++IP;
390   AtEntry.SetInsertPoint(IP->getParent(), IP);
391   
392   // Initialize the map pointer and load the current head of the shadow stack.
393   Instruction *CurrentHead  = AtEntry.CreateLoad(Head, "gc_currhead");
394   Instruction *EntryMapPtr  = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map");
395                               AtEntry.CreateStore(FrameMap, EntryMapPtr);
396   
397   // After all the allocas...
398   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
399     // For each root, find the corresponding slot in the aggregate...
400     Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root");
401     
402     // And use it in lieu of the alloca.
403     AllocaInst *OriginalAlloca = Roots[I].second;
404     SlotPtr->takeName(OriginalAlloca);
405     OriginalAlloca->replaceAllUsesWith(SlotPtr);
406   }
407   
408   // Move past the original stores inserted by Collector::InitRoots. This isn't
409   // really necessary (the collector would never see the intermediate state),
410   // but it's nicer not to push the half-initialized entry onto the stack.
411   while (isa<StoreInst>(IP)) ++IP;
412   AtEntry.SetInsertPoint(IP->getParent(), IP);
413   
414   // Push the entry onto the shadow stack.
415   Instruction *EntryNextPtr = CreateGEP(AtEntry,StackEntry,0,0,"gc_frame.next");
416   Instruction *NewHeadVal   = CreateGEP(AtEntry,StackEntry, 0, "gc_newhead");
417                               AtEntry.CreateStore(CurrentHead, EntryNextPtr);
418                               AtEntry.CreateStore(NewHeadVal, Head);
419   
420   // For each instruction that escapes...
421   EscapeEnumerator EE(F, "gc_cleanup");
422   while (IRBuilder<> *AtExit = EE.Next()) {
423     // Pop the entry from the shadow stack. Don't reuse CurrentHead from
424     // AtEntry, since that would make the value live for the entire function.
425     Instruction *EntryNextPtr2 = CreateGEP(*AtExit, StackEntry, 0, 0,
426                                            "gc_frame.next");
427     Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
428                        AtExit->CreateStore(SavedHead, Head);
429   }
430   
431   // Delete the original allocas (which are no longer used) and the intrinsic
432   // calls (which are no longer valid). Doing this last avoids invalidating
433   // iterators.
434   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
435     Roots[I].first->eraseFromParent();
436     Roots[I].second->eraseFromParent();
437   }
438   
439   Roots.clear();
440   return true;
441 }