1 //===-- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ---===//
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 contains the custom lowering code required by the shadow-stack GC
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/CodeGen/GCStrategy.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/Module.h"
25 #define DEBUG_TYPE "shadowstackgclowering"
29 class ShadowStackGCLowering : public FunctionPass {
30 /// RootChain - This is the global linked-list that contains the chain of GC
34 /// StackEntryTy - Abstract type of a link in the shadow stack.
36 StructType *StackEntryTy;
37 StructType *FrameMapTy;
39 /// Roots - GC roots in the current function. Each is a pair of the
40 /// intrinsic call and its corresponding alloca.
41 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
45 ShadowStackGCLowering();
47 bool doInitialization(Module &M) override;
48 bool runOnFunction(Function &F) override;
51 bool IsNullValue(Value *V);
52 Constant *GetFrameMap(Function &F);
53 Type *GetConcreteStackEntryType(Function &F);
54 void CollectRoots(Function &F);
55 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
56 Type *Ty, Value *BasePtr, int Idx1,
58 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
59 Type *Ty, Value *BasePtr, int Idx1, int Idx2,
64 INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, "shadow-stack-gc-lowering",
65 "Shadow Stack GC Lowering", false, false)
66 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
67 INITIALIZE_PASS_END(ShadowStackGCLowering, "shadow-stack-gc-lowering",
68 "Shadow Stack GC Lowering", false, false)
70 FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
72 char ShadowStackGCLowering::ID = 0;
74 ShadowStackGCLowering::ShadowStackGCLowering()
75 : FunctionPass(ID), Head(nullptr), StackEntryTy(nullptr),
77 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
81 /// EscapeEnumerator - This is a little algorithm to find all escape points
82 /// from a function so that "finally"-style code can be inserted. In addition
83 /// to finding the existing return and unwind instructions, it also (if
84 /// necessary) transforms any call instructions into invokes and sends them to
87 /// It's wrapped up in a state machine using the same transform C# uses for
88 /// 'yield return' enumerators, This transform allows it to be non-allocating.
89 class EscapeEnumerator {
91 const char *CleanupBBName;
95 Function::iterator StateBB, StateE;
99 EscapeEnumerator(Function &F, const char *N = "cleanup")
100 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
102 IRBuilder<> *Next() {
113 // Find all 'return', 'resume', and 'unwind' instructions.
114 while (StateBB != StateE) {
115 BasicBlock *CurBB = StateBB++;
117 // Branches and invokes do not escape, only unwind, resume, and return
119 TerminatorInst *TI = CurBB->getTerminator();
120 if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
123 Builder.SetInsertPoint(TI->getParent(), TI);
129 // Find all 'call' instructions.
130 SmallVector<Instruction *, 16> Calls;
131 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
132 for (BasicBlock::iterator II = BB->begin(), EE = BB->end(); II != EE;
134 if (CallInst *CI = dyn_cast<CallInst>(II))
135 if (!CI->getCalledFunction() ||
136 !CI->getCalledFunction()->getIntrinsicID())
142 // Create a cleanup block.
143 LLVMContext &C = F.getContext();
144 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
146 StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C), nullptr);
147 if (!F.hasPersonalityFn()) {
148 Constant *PersFn = F.getParent()->getOrInsertFunction(
149 "__gcc_personality_v0",
150 FunctionType::get(Type::getInt32Ty(C), true));
151 F.setPersonalityFn(PersFn);
153 LandingPadInst *LPad =
154 LandingPadInst::Create(ExnTy, 1, "cleanup.lpad", CleanupBB);
155 LPad->setCleanup(true);
156 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
158 // Transform the 'call' instructions into 'invoke's branching to the
159 // cleanup block. Go in reverse order to make prettier BB names.
160 SmallVector<Value *, 16> Args;
161 for (unsigned I = Calls.size(); I != 0;) {
162 CallInst *CI = cast<CallInst>(Calls[--I]);
164 // Split the basic block containing the function call.
165 BasicBlock *CallBB = CI->getParent();
167 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
169 // Remove the unconditional branch inserted at the end of CallBB.
170 CallBB->getInstList().pop_back();
171 NewBB->getInstList().remove(CI);
173 // Create a new invoke instruction.
176 Args.append(CS.arg_begin(), CS.arg_end());
179 InvokeInst::Create(CI->getCalledValue(), NewBB, CleanupBB, Args,
180 CI->getName(), CallBB);
181 II->setCallingConv(CI->getCallingConv());
182 II->setAttributes(CI->getAttributes());
183 CI->replaceAllUsesWith(II);
187 Builder.SetInsertPoint(RI->getParent(), RI);
195 Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
196 // doInitialization creates the abstract type of this value.
197 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
199 // Truncate the ShadowStackDescriptor if some metadata is null.
200 unsigned NumMeta = 0;
201 SmallVector<Constant *, 16> Metadata;
202 for (unsigned I = 0; I != Roots.size(); ++I) {
203 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
204 if (!C->isNullValue())
206 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
208 Metadata.resize(NumMeta);
210 Type *Int32Ty = Type::getInt32Ty(F.getContext());
212 Constant *BaseElts[] = {
213 ConstantInt::get(Int32Ty, Roots.size(), false),
214 ConstantInt::get(Int32Ty, NumMeta, false),
217 Constant *DescriptorElts[] = {
218 ConstantStruct::get(FrameMapTy, BaseElts),
219 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
221 Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
222 StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
224 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
226 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
227 // that, short of multithreaded LLVM, it should be safe; all that is
228 // necessary is that a simple Module::iterator loop not be invalidated.
229 // Appending to the GlobalVariable list is safe in that sense.
231 // All of the output passes emit globals last. The ExecutionEngine
232 // explicitly supports adding globals to the module after
235 // Still, if it isn't deemed acceptable, then this transformation needs
236 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
237 // (which uses a FunctionPassManager (which segfaults (not asserts) if
238 // provided a ModulePass))).
239 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
240 GlobalVariable::InternalLinkage, FrameMap,
241 "__gc_" + F.getName());
243 Constant *GEPIndices[2] = {
244 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
245 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
246 return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
249 Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
250 // doInitialization creates the generic version of this type.
251 std::vector<Type *> EltTys;
252 EltTys.push_back(StackEntryTy);
253 for (size_t I = 0; I != Roots.size(); I++)
254 EltTys.push_back(Roots[I].second->getAllocatedType());
256 return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
259 /// doInitialization - If this module uses the GC intrinsics, find them now. If
261 bool ShadowStackGCLowering::doInitialization(Module &M) {
263 for (Function &F : M) {
264 if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
273 // int32_t NumRoots; // Number of roots in stack frame.
274 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
275 // void *Meta[]; // May be absent for roots without metadata.
277 std::vector<Type *> EltTys;
278 // 32 bits is ok up to a 32GB stack frame. :)
279 EltTys.push_back(Type::getInt32Ty(M.getContext()));
280 // Specifies length of variable length array.
281 EltTys.push_back(Type::getInt32Ty(M.getContext()));
282 FrameMapTy = StructType::create(EltTys, "gc_map");
283 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
285 // struct StackEntry {
286 // ShadowStackEntry *Next; // Caller's stack entry.
287 // FrameMap *Map; // Pointer to constant FrameMap.
288 // void *Roots[]; // Stack roots (in-place array, so we pretend).
291 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
294 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
295 EltTys.push_back(FrameMapPtrTy);
296 StackEntryTy->setBody(EltTys);
297 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
299 // Get the root chain if it already exists.
300 Head = M.getGlobalVariable("llvm_gc_root_chain");
302 // If the root chain does not exist, insert a new one with linkonce
304 Head = new GlobalVariable(
305 M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
306 Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
307 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
308 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
309 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
315 bool ShadowStackGCLowering::IsNullValue(Value *V) {
316 if (Constant *C = dyn_cast<Constant>(V))
317 return C->isNullValue();
321 void ShadowStackGCLowering::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(
337 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
338 if (IsNullValue(CI->getArgOperand(1)))
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());
349 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
350 IRBuilder<> &B, Type *Ty,
351 Value *BasePtr, int Idx,
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(Ty, BasePtr, Indices, Name);
359 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
361 return dyn_cast<GetElementPtrInst>(Val);
364 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
365 IRBuilder<> &B, Type *Ty, 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(Ty, BasePtr, Indices, Name);
371 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
373 return dyn_cast<GetElementPtrInst>(Val);
376 /// runOnFunction - Insert code to maintain the shadow stack.
377 bool ShadowStackGCLowering::runOnFunction(Function &F) {
378 // Quick exit for functions that do not use the shadow stack GC.
380 F.getGC() != std::string("shadow-stack"))
383 LLVMContext &Context = F.getContext();
385 // Find calls to llvm.gcroot.
388 // If there are no roots in this function, then there is no need to add a
389 // stack map entry for it.
393 // Build the constant map and figure the type of the shadow stack entry.
394 Value *FrameMap = GetFrameMap(F);
395 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
397 // Build the shadow stack entry at the very start of the function.
398 BasicBlock::iterator IP = F.getEntryBlock().begin();
399 IRBuilder<> AtEntry(IP->getParent(), IP);
401 Instruction *StackEntry =
402 AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
404 while (isa<AllocaInst>(IP))
406 AtEntry.SetInsertPoint(IP->getParent(), IP);
408 // Initialize the map pointer and load the current head of the shadow stack.
409 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
410 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
411 StackEntry, 0, 1, "gc_frame.map");
412 AtEntry.CreateStore(FrameMap, EntryMapPtr);
414 // After all the allocas...
415 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
416 // For each root, find the corresponding slot in the aggregate...
417 Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
418 StackEntry, 1 + I, "gc_root");
420 // And use it in lieu of the alloca.
421 AllocaInst *OriginalAlloca = Roots[I].second;
422 SlotPtr->takeName(OriginalAlloca);
423 OriginalAlloca->replaceAllUsesWith(SlotPtr);
426 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
427 // really necessary (the collector would never see the intermediate state at
428 // runtime), but it's nicer not to push the half-initialized entry onto the
430 while (isa<StoreInst>(IP))
432 AtEntry.SetInsertPoint(IP->getParent(), IP);
434 // Push the entry onto the shadow stack.
435 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
436 StackEntry, 0, 0, "gc_frame.next");
437 Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
438 StackEntry, 0, "gc_newhead");
439 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
440 AtEntry.CreateStore(NewHeadVal, Head);
442 // For each instruction that escapes...
443 EscapeEnumerator EE(F, "gc_cleanup");
444 while (IRBuilder<> *AtExit = EE.Next()) {
445 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
446 // AtEntry, since that would make the value live for the entire function.
447 Instruction *EntryNextPtr2 =
448 CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
450 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
451 AtExit->CreateStore(SavedHead, Head);
454 // Delete the original allocas (which are no longer used) and the intrinsic
455 // calls (which are no longer valid). Doing this last avoids invalidating
457 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
458 Roots[I].first->eraseFromParent();
459 Roots[I].second->eraseFromParent();