LLVM API Documentation

ShadowStackGC.cpp

Go to the documentation of this file.
00001 //===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements lowering for the llvm.gc* intrinsics for targets that do
00011 // not natively support them (which includes the C backend). Note that the code
00012 // generated is not quite as efficient as algorithms which generate stack maps
00013 // to identify roots.
00014 //
00015 // This pass implements the code transformation described in this paper:
00016 //   "Accurate Garbage Collection in an Uncooperative Environment"
00017 //   Fergus Henderson, ISMM, 2002
00018 //
00019 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
00020 // ShadowStackGC.
00021 //
00022 // In order to support this particular transformation, all stack roots are
00023 // coallocated in the stack. This allows a fully target-independent stack map
00024 // while introducing only minor runtime overhead.
00025 //
00026 //===----------------------------------------------------------------------===//
00027 
00028 #define DEBUG_TYPE "shadowstackgc"
00029 #include "llvm/CodeGen/GCs.h"
00030 #include "llvm/ADT/StringExtras.h"
00031 #include "llvm/CodeGen/GCStrategy.h"
00032 #include "llvm/IntrinsicInst.h"
00033 #include "llvm/Module.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include "llvm/Support/IRBuilder.h"
00036 
00037 using namespace llvm;
00038 
00039 namespace {
00040 
00041   class VISIBILITY_HIDDEN ShadowStackGC : public GCStrategy {
00042     /// RootChain - This is the global linked-list that contains the chain of GC
00043     /// roots.
00044     GlobalVariable *Head;
00045 
00046     /// StackEntryTy - Abstract type of a link in the shadow stack.
00047     ///
00048     const StructType *StackEntryTy;
00049 
00050     /// Roots - GC roots in the current function. Each is a pair of the
00051     /// intrinsic call and its corresponding alloca.
00052     std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
00053 
00054   public:
00055     ShadowStackGC();
00056 
00057     bool initializeCustomLowering(Module &M);
00058     bool performCustomLowering(Function &F);
00059 
00060   private:
00061     bool IsNullValue(Value *V);
00062     Constant *GetFrameMap(Function &F);
00063     const Type* GetConcreteStackEntryType(Function &F);
00064     void CollectRoots(Function &F);
00065     static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
00066                                         int Idx1, const char *Name);
00067     static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
00068                                         int Idx1, int Idx2, const char *Name);
00069   };
00070 
00071 }
00072 
00073 static GCRegistry::Add<ShadowStackGC>
00074 X("shadow-stack", "Very portable GC for uncooperative code generators");
00075 
00076 namespace {
00077   /// EscapeEnumerator - This is a little algorithm to find all escape points
00078   /// from a function so that "finally"-style code can be inserted. In addition
00079   /// to finding the existing return and unwind instructions, it also (if
00080   /// necessary) transforms any call instructions into invokes and sends them to
00081   /// a landing pad.
00082   ///
00083   /// It's wrapped up in a state machine using the same transform C# uses for
00084   /// 'yield return' enumerators, This transform allows it to be non-allocating.
00085   class VISIBILITY_HIDDEN EscapeEnumerator {
00086     Function &F;
00087     const char *CleanupBBName;
00088 
00089     // State.
00090     int State;
00091     Function::iterator StateBB, StateE;
00092     IRBuilder<> Builder;
00093 
00094   public:
00095     EscapeEnumerator(Function &F, const char *N = "cleanup")
00096       : F(F), CleanupBBName(N), State(0) {}
00097 
00098     IRBuilder<> *Next() {
00099       switch (State) {
00100       default:
00101         return 0;
00102 
00103       case 0:
00104         StateBB = F.begin();
00105         StateE = F.end();
00106         State = 1;
00107 
00108       case 1:
00109         // Find all 'return' and 'unwind' instructions.
00110         while (StateBB != StateE) {
00111           BasicBlock *CurBB = StateBB++;
00112 
00113           // Branches and invokes do not escape, only unwind and return do.
00114           TerminatorInst *TI = CurBB->getTerminator();
00115           if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
00116             continue;
00117 
00118           Builder.SetInsertPoint(TI->getParent(), TI);
00119           return &Builder;
00120         }
00121 
00122         State = 2;
00123 
00124         // Find all 'call' instructions.
00125         SmallVector<Instruction*,16> Calls;
00126         for (Function::iterator BB = F.begin(),
00127                                 E = F.end(); BB != E; ++BB)
00128           for (BasicBlock::iterator II = BB->begin(),
00129                                     EE = BB->end(); II != EE; ++II)
00130             if (CallInst *CI = dyn_cast<CallInst>(II))
00131               if (!CI->getCalledFunction() ||
00132                   !CI->getCalledFunction()->getIntrinsicID())
00133                 Calls.push_back(CI);
00134 
00135         if (Calls.empty())
00136           return 0;
00137 
00138         // Create a cleanup block.
00139         BasicBlock *CleanupBB = BasicBlock::Create(CleanupBBName, &F);
00140         UnwindInst *UI = new UnwindInst(CleanupBB);
00141 
00142         // Transform the 'call' instructions into 'invoke's branching to the
00143         // cleanup block. Go in reverse order to make prettier BB names.
00144         SmallVector<Value*,16> Args;
00145         for (unsigned I = Calls.size(); I != 0; ) {
00146           CallInst *CI = cast<CallInst>(Calls[--I]);
00147 
00148           // Split the basic block containing the function call.
00149           BasicBlock *CallBB = CI->getParent();
00150           BasicBlock *NewBB =
00151             CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
00152 
00153           // Remove the unconditional branch inserted at the end of CallBB.
00154           CallBB->getInstList().pop_back();
00155           NewBB->getInstList().remove(CI);
00156 
00157           // Create a new invoke instruction.
00158           Args.clear();
00159           Args.append(CI->op_begin() + 1, CI->op_end());
00160 
00161           InvokeInst *II = InvokeInst::Create(CI->getOperand(0),
00162                                               NewBB, CleanupBB,
00163                                               Args.begin(), Args.end(),
00164                                               CI->getName(), CallBB);
00165           II->setCallingConv(CI->getCallingConv());
00166           II->setAttributes(CI->getAttributes());
00167           CI->replaceAllUsesWith(II);
00168           delete CI;
00169         }
00170 
00171         Builder.SetInsertPoint(UI->getParent(), UI);
00172         return &Builder;
00173       }
00174     }
00175   };
00176 }
00177 
00178 // -----------------------------------------------------------------------------
00179 
00180 void llvm::linkShadowStackGC() { }
00181 
00182 ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
00183   InitRoots = true;
00184   CustomRoots = true;
00185 }
00186 
00187 Constant *ShadowStackGC::GetFrameMap(Function &F) {
00188   // doInitialization creates the abstract type of this value.
00189 
00190   Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
00191 
00192   // Truncate the ShadowStackDescriptor if some metadata is null.
00193   unsigned NumMeta = 0;
00194   SmallVector<Constant*,16> Metadata;
00195   for (unsigned I = 0; I != Roots.size(); ++I) {
00196     Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
00197     if (!C->isNullValue())
00198       NumMeta = I + 1;
00199     Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
00200   }
00201 
00202   Constant *BaseElts[] = {
00203     ConstantInt::get(Type::Int32Ty, Roots.size(), false),
00204     ConstantInt::get(Type::Int32Ty, NumMeta, false),
00205   };
00206 
00207   Constant *DescriptorElts[] = {
00208     ConstantStruct::get(BaseElts, 2),
00209     ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
00210                        Metadata.begin(), NumMeta)
00211   };
00212 
00213   Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2);
00214 
00215   std::string TypeName("gc_map.");
00216   TypeName += utostr(NumMeta);
00217   F.getParent()->addTypeName(TypeName, FrameMap->getType());
00218 
00219   // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
00220   //        that, short of multithreaded LLVM, it should be safe; all that is
00221   //        necessary is that a simple Module::iterator loop not be invalidated.
00222   //        Appending to the GlobalVariable list is safe in that sense.
00223   //
00224   //        All of the output passes emit globals last. The ExecutionEngine
00225   //        explicitly supports adding globals to the module after
00226   //        initialization.
00227   //
00228   //        Still, if it isn't deemed acceptable, then this transformation needs
00229   //        to be a ModulePass (which means it cannot be in the 'llc' pipeline
00230   //        (which uses a FunctionPassManager (which segfaults (not asserts) if
00231   //        provided a ModulePass))).
00232   Constant *GV = new GlobalVariable(FrameMap->getType(), true,
00233                                     GlobalVariable::InternalLinkage,
00234                                     FrameMap, "__gc_" + F.getName(),
00235                                     F.getParent());
00236 
00237   Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0),
00238                               ConstantInt::get(Type::Int32Ty, 0) };
00239   return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
00240 }
00241 
00242 const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
00243   // doInitialization creates the generic version of this type.
00244   std::vector<const Type*> EltTys;
00245   EltTys.push_back(StackEntryTy);
00246   for (size_t I = 0; I != Roots.size(); I++)
00247     EltTys.push_back(Roots[I].second->getAllocatedType());
00248   Type *Ty = StructType::get(EltTys);
00249 
00250   std::string TypeName("gc_stackentry.");
00251   TypeName += F.getName();
00252   F.getParent()->addTypeName(TypeName, Ty);
00253 
00254   return Ty;
00255 }
00256 
00257 /// doInitialization - If this module uses the GC intrinsics, find them now. If
00258 /// not, exit fast.
00259 bool ShadowStackGC::initializeCustomLowering(Module &M) {
00260   // struct FrameMap {
00261   //   int32_t NumRoots; // Number of roots in stack frame.
00262   //   int32_t NumMeta;  // Number of metadata descriptors. May be < NumRoots.
00263   //   void *Meta[];     // May be absent for roots without metadata.
00264   // };
00265   std::vector<const Type*> EltTys;
00266   EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :)
00267   EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array.
00268   StructType *FrameMapTy = StructType::get(EltTys);
00269   M.addTypeName("gc_map", FrameMapTy);
00270   PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
00271 
00272   // struct StackEntry {
00273   //   ShadowStackEntry *Next; // Caller's stack entry.
00274   //   FrameMap *Map;          // Pointer to constant FrameMap.
00275   //   void *Roots[];          // Stack roots (in-place array, so we pretend).
00276   // };
00277   OpaqueType *RecursiveTy = OpaqueType::get();
00278 
00279   EltTys.clear();
00280   EltTys.push_back(PointerType::getUnqual(RecursiveTy));
00281   EltTys.push_back(FrameMapPtrTy);
00282   PATypeHolder LinkTyH = StructType::get(EltTys);
00283 
00284   RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
00285   StackEntryTy = cast<StructType>(LinkTyH.get());
00286   const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
00287   M.addTypeName("gc_stackentry", LinkTyH.get());  // FIXME: Is this safe from
00288                                                   //        a FunctionPass?
00289 
00290   // Get the root chain if it already exists.
00291   Head = M.getGlobalVariable("llvm_gc_root_chain");
00292   if (!Head) {
00293     // If the root chain does not exist, insert a new one with linkonce
00294     // linkage!
00295     Head = new GlobalVariable(StackEntryPtrTy, false,
00296                               GlobalValue::LinkOnceLinkage,
00297                               Constant::getNullValue(StackEntryPtrTy),
00298                               "llvm_gc_root_chain", &M);
00299   } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
00300     Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
00301     Head->setLinkage(GlobalValue::LinkOnceLinkage);
00302   }
00303 
00304   return true;
00305 }
00306 
00307 bool ShadowStackGC::IsNullValue(Value *V) {
00308   if (Constant *C = dyn_cast<Constant>(V))
00309     return C->isNullValue();
00310   return false;
00311 }
00312 
00313 void ShadowStackGC::CollectRoots(Function &F) {
00314   // FIXME: Account for original alignment. Could fragment the root array.
00315   //   Approach 1: Null initialize empty slots at runtime. Yuck.
00316   //   Approach 2: Emit a map of the array instead of just a count.
00317 
00318   assert(Roots.empty() && "Not cleaned up?");
00319 
00320   SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
00321 
00322   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00323     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
00324       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
00325         if (Function *F = CI->getCalledFunction())
00326           if (F->getIntrinsicID() == Intrinsic::gcroot) {
00327             std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
00328               CI, cast<AllocaInst>(CI->getOperand(1)->stripPointerCasts()));
00329             if (IsNullValue(CI->getOperand(2)))
00330               Roots.push_back(Pair);
00331             else
00332               MetaRoots.push_back(Pair);
00333           }
00334 
00335   // Number roots with metadata (usually empty) at the beginning, so that the
00336   // FrameMap::Meta array can be elided.
00337   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
00338 }
00339 
00340 GetElementPtrInst *
00341 ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
00342                          int Idx, int Idx2, const char *Name) {
00343   Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
00344                        ConstantInt::get(Type::Int32Ty, Idx),
00345                        ConstantInt::get(Type::Int32Ty, Idx2) };
00346   Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
00347 
00348   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
00349 
00350   return dyn_cast<GetElementPtrInst>(Val);
00351 }
00352 
00353 GetElementPtrInst *
00354 ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
00355                          int Idx, const char *Name) {
00356   Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
00357                        ConstantInt::get(Type::Int32Ty, Idx) };
00358   Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
00359 
00360   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
00361 
00362   return dyn_cast<GetElementPtrInst>(Val);
00363 }
00364 
00365 /// runOnFunction - Insert code to maintain the shadow stack.
00366 bool ShadowStackGC::performCustomLowering(Function &F) {
00367   // Find calls to llvm.gcroot.
00368   CollectRoots(F);
00369 
00370   // If there are no roots in this function, then there is no need to add a
00371   // stack map entry for it.
00372   if (Roots.empty())
00373     return false;
00374 
00375   // Build the constant map and figure the type of the shadow stack entry.
00376   Value *FrameMap = GetFrameMap(F);
00377   const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
00378 
00379   // Build the shadow stack entry at the very start of the function.
00380   BasicBlock::iterator IP = F.getEntryBlock().begin();
00381   IRBuilder<> AtEntry(IP->getParent(), IP);
00382 
00383   Instruction *StackEntry   = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
00384                                                    "gc_frame");
00385 
00386   while (isa<AllocaInst>(IP)) ++IP;
00387   AtEntry.SetInsertPoint(IP->getParent(), IP);
00388 
00389   // Initialize the map pointer and load the current head of the shadow stack.
00390   Instruction *CurrentHead  = AtEntry.CreateLoad(Head, "gc_currhead");
00391   Instruction *EntryMapPtr  = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map");
00392                               AtEntry.CreateStore(FrameMap, EntryMapPtr);
00393 
00394   // After all the allocas...
00395   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
00396     // For each root, find the corresponding slot in the aggregate...
00397     Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root");
00398 
00399     // And use it in lieu of the alloca.
00400     AllocaInst *OriginalAlloca = Roots[I].second;
00401     SlotPtr->takeName(OriginalAlloca);
00402     OriginalAlloca->replaceAllUsesWith(SlotPtr);
00403   }
00404 
00405   // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
00406   // really necessary (the collector would never see the intermediate state at
00407   // runtime), but it's nicer not to push the half-initialized entry onto the
00408   // shadow stack.
00409   while (isa<StoreInst>(IP)) ++IP;
00410   AtEntry.SetInsertPoint(IP->getParent(), IP);
00411 
00412   // Push the entry onto the shadow stack.
00413   Instruction *EntryNextPtr = CreateGEP(AtEntry,StackEntry,0,0,"gc_frame.next");
00414   Instruction *NewHeadVal   = CreateGEP(AtEntry,StackEntry, 0, "gc_newhead");
00415                               AtEntry.CreateStore(CurrentHead, EntryNextPtr);
00416                               AtEntry.CreateStore(NewHeadVal, Head);
00417 
00418   // For each instruction that escapes...
00419   EscapeEnumerator EE(F, "gc_cleanup");
00420   while (IRBuilder<> *AtExit = EE.Next()) {
00421     // Pop the entry from the shadow stack. Don't reuse CurrentHead from
00422     // AtEntry, since that would make the value live for the entire function.
00423     Instruction *EntryNextPtr2 = CreateGEP(*AtExit, StackEntry, 0, 0,
00424                                            "gc_frame.next");
00425     Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
00426                        AtExit->CreateStore(SavedHead, Head);
00427   }
00428 
00429   // Delete the original allocas (which are no longer used) and the intrinsic
00430   // calls (which are no longer valid). Doing this last avoids invalidating
00431   // iterators.
00432   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
00433     Roots[I].first->eraseFromParent();
00434     Roots[I].second->eraseFromParent();
00435   }
00436 
00437   Roots.clear();
00438   return true;
00439 }