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