10b57cec5SDimitry Andric //===- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ----===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file contains the custom lowering code required by the shadow-stack GC 100b57cec5SDimitry Andric // strategy. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric // This pass implements the code transformation described in this paper: 130b57cec5SDimitry Andric // "Accurate Garbage Collection in an Uncooperative Environment" 140b57cec5SDimitry Andric // Fergus Henderson, ISMM, 2002 150b57cec5SDimitry Andric // 160b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 170b57cec5SDimitry Andric 18*1db9f3b2SDimitry Andric #include "llvm/CodeGen/ShadowStackGCLowering.h" 190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 200b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h" 21fe6060f1SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h" 22*1db9f3b2SDimitry Andric #include "llvm/CodeGen/GCMetadata.h" 230b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h" 240b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 250b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 260b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 270b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 28fe6060f1SDimitry Andric #include "llvm/IR/Dominators.h" 290b57cec5SDimitry Andric #include "llvm/IR/Function.h" 300b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h" 310b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h" 320b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h" 330b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 340b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 350b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 360b57cec5SDimitry Andric #include "llvm/IR/Module.h" 370b57cec5SDimitry Andric #include "llvm/IR/Type.h" 380b57cec5SDimitry Andric #include "llvm/IR/Value.h" 39480093f4SDimitry Andric #include "llvm/InitializePasses.h" 400b57cec5SDimitry Andric #include "llvm/Pass.h" 410b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 420b57cec5SDimitry Andric #include "llvm/Transforms/Utils/EscapeEnumerator.h" 430b57cec5SDimitry Andric #include <cassert> 44bdd1243dSDimitry Andric #include <optional> 450b57cec5SDimitry Andric #include <string> 460b57cec5SDimitry Andric #include <utility> 470b57cec5SDimitry Andric #include <vector> 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric using namespace llvm; 500b57cec5SDimitry Andric 510b57cec5SDimitry Andric #define DEBUG_TYPE "shadow-stack-gc-lowering" 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric namespace { 540b57cec5SDimitry Andric 55*1db9f3b2SDimitry Andric class ShadowStackGCLoweringImpl { 560b57cec5SDimitry Andric /// RootChain - This is the global linked-list that contains the chain of GC 570b57cec5SDimitry Andric /// roots. 580b57cec5SDimitry Andric GlobalVariable *Head = nullptr; 590b57cec5SDimitry Andric 600b57cec5SDimitry Andric /// StackEntryTy - Abstract type of a link in the shadow stack. 610b57cec5SDimitry Andric StructType *StackEntryTy = nullptr; 620b57cec5SDimitry Andric StructType *FrameMapTy = nullptr; 630b57cec5SDimitry Andric 640b57cec5SDimitry Andric /// Roots - GC roots in the current function. Each is a pair of the 650b57cec5SDimitry Andric /// intrinsic call and its corresponding alloca. 660b57cec5SDimitry Andric std::vector<std::pair<CallInst *, AllocaInst *>> Roots; 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric public: 69*1db9f3b2SDimitry Andric ShadowStackGCLoweringImpl() = default; 700b57cec5SDimitry Andric 71*1db9f3b2SDimitry Andric bool doInitialization(Module &M); 72*1db9f3b2SDimitry Andric bool runOnFunction(Function &F, DomTreeUpdater *DTU); 730b57cec5SDimitry Andric 740b57cec5SDimitry Andric private: 750b57cec5SDimitry Andric bool IsNullValue(Value *V); 760b57cec5SDimitry Andric Constant *GetFrameMap(Function &F); 770b57cec5SDimitry Andric Type *GetConcreteStackEntryType(Function &F); 780b57cec5SDimitry Andric void CollectRoots(Function &F); 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B, 810b57cec5SDimitry Andric Type *Ty, Value *BasePtr, int Idx1, 820b57cec5SDimitry Andric const char *Name); 830b57cec5SDimitry Andric static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B, 840b57cec5SDimitry Andric Type *Ty, Value *BasePtr, int Idx1, int Idx2, 850b57cec5SDimitry Andric const char *Name); 860b57cec5SDimitry Andric }; 870b57cec5SDimitry Andric 88*1db9f3b2SDimitry Andric class ShadowStackGCLowering : public FunctionPass { 89*1db9f3b2SDimitry Andric ShadowStackGCLoweringImpl Impl; 90*1db9f3b2SDimitry Andric 91*1db9f3b2SDimitry Andric public: 92*1db9f3b2SDimitry Andric static char ID; 93*1db9f3b2SDimitry Andric 94*1db9f3b2SDimitry Andric ShadowStackGCLowering(); 95*1db9f3b2SDimitry Andric 96*1db9f3b2SDimitry Andric bool doInitialization(Module &M) override { return Impl.doInitialization(M); } 97*1db9f3b2SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 98*1db9f3b2SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 99*1db9f3b2SDimitry Andric } 100*1db9f3b2SDimitry Andric bool runOnFunction(Function &F) override { 101*1db9f3b2SDimitry Andric std::optional<DomTreeUpdater> DTU; 102*1db9f3b2SDimitry Andric if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>()) 103*1db9f3b2SDimitry Andric DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy); 104*1db9f3b2SDimitry Andric return Impl.runOnFunction(F, DTU ? &*DTU : nullptr); 105*1db9f3b2SDimitry Andric } 106*1db9f3b2SDimitry Andric }; 107*1db9f3b2SDimitry Andric 1080b57cec5SDimitry Andric } // end anonymous namespace 1090b57cec5SDimitry Andric 110*1db9f3b2SDimitry Andric PreservedAnalyses ShadowStackGCLoweringPass::run(Module &M, 111*1db9f3b2SDimitry Andric ModuleAnalysisManager &MAM) { 112*1db9f3b2SDimitry Andric auto &Map = MAM.getResult<CollectorMetadataAnalysis>(M); 113*1db9f3b2SDimitry Andric if (Map.StrategyMap.contains("shadow-stack")) 114*1db9f3b2SDimitry Andric return PreservedAnalyses::all(); 115*1db9f3b2SDimitry Andric 116*1db9f3b2SDimitry Andric ShadowStackGCLoweringImpl Impl; 117*1db9f3b2SDimitry Andric bool Changed = Impl.doInitialization(M); 118*1db9f3b2SDimitry Andric for (auto &F : M) { 119*1db9f3b2SDimitry Andric auto &FAM = 120*1db9f3b2SDimitry Andric MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 121*1db9f3b2SDimitry Andric auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F); 122*1db9f3b2SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 123*1db9f3b2SDimitry Andric Changed |= Impl.runOnFunction(F, DT ? &DTU : nullptr); 124*1db9f3b2SDimitry Andric } 125*1db9f3b2SDimitry Andric 126*1db9f3b2SDimitry Andric if (!Changed) 127*1db9f3b2SDimitry Andric return PreservedAnalyses::all(); 128*1db9f3b2SDimitry Andric PreservedAnalyses PA; 129*1db9f3b2SDimitry Andric PA.preserve<DominatorTreeAnalysis>(); 130*1db9f3b2SDimitry Andric return PA; 131*1db9f3b2SDimitry Andric } 132*1db9f3b2SDimitry Andric 1330b57cec5SDimitry Andric char ShadowStackGCLowering::ID = 0; 134fe6060f1SDimitry Andric char &llvm::ShadowStackGCLoweringID = ShadowStackGCLowering::ID; 1350b57cec5SDimitry Andric 1360b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE, 1370b57cec5SDimitry Andric "Shadow Stack GC Lowering", false, false) 1380b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(GCModuleInfo) 139fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1400b57cec5SDimitry Andric INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE, 1410b57cec5SDimitry Andric "Shadow Stack GC Lowering", false, false) 1420b57cec5SDimitry Andric 1430b57cec5SDimitry Andric FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); } 1440b57cec5SDimitry Andric 1450b57cec5SDimitry Andric ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) { 1460b57cec5SDimitry Andric initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry()); 1470b57cec5SDimitry Andric } 1480b57cec5SDimitry Andric 149*1db9f3b2SDimitry Andric Constant *ShadowStackGCLoweringImpl::GetFrameMap(Function &F) { 1500b57cec5SDimitry Andric // doInitialization creates the abstract type of this value. 1515f757f3fSDimitry Andric Type *VoidPtr = PointerType::getUnqual(F.getContext()); 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric // Truncate the ShadowStackDescriptor if some metadata is null. 1540b57cec5SDimitry Andric unsigned NumMeta = 0; 1550b57cec5SDimitry Andric SmallVector<Constant *, 16> Metadata; 1560b57cec5SDimitry Andric for (unsigned I = 0; I != Roots.size(); ++I) { 1570b57cec5SDimitry Andric Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1)); 1580b57cec5SDimitry Andric if (!C->isNullValue()) 1590b57cec5SDimitry Andric NumMeta = I + 1; 160cb14a3feSDimitry Andric Metadata.push_back(C); 1610b57cec5SDimitry Andric } 1620b57cec5SDimitry Andric Metadata.resize(NumMeta); 1630b57cec5SDimitry Andric 1640b57cec5SDimitry Andric Type *Int32Ty = Type::getInt32Ty(F.getContext()); 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric Constant *BaseElts[] = { 1670b57cec5SDimitry Andric ConstantInt::get(Int32Ty, Roots.size(), false), 1680b57cec5SDimitry Andric ConstantInt::get(Int32Ty, NumMeta, false), 1690b57cec5SDimitry Andric }; 1700b57cec5SDimitry Andric 1710b57cec5SDimitry Andric Constant *DescriptorElts[] = { 1720b57cec5SDimitry Andric ConstantStruct::get(FrameMapTy, BaseElts), 1730b57cec5SDimitry Andric ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)}; 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()}; 1760b57cec5SDimitry Andric StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta)); 1770b57cec5SDimitry Andric 1780b57cec5SDimitry Andric Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts); 1790b57cec5SDimitry Andric 1800b57cec5SDimitry Andric // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems 1810b57cec5SDimitry Andric // that, short of multithreaded LLVM, it should be safe; all that is 1820b57cec5SDimitry Andric // necessary is that a simple Module::iterator loop not be invalidated. 1830b57cec5SDimitry Andric // Appending to the GlobalVariable list is safe in that sense. 1840b57cec5SDimitry Andric // 1850b57cec5SDimitry Andric // All of the output passes emit globals last. The ExecutionEngine 1860b57cec5SDimitry Andric // explicitly supports adding globals to the module after 1870b57cec5SDimitry Andric // initialization. 1880b57cec5SDimitry Andric // 1890b57cec5SDimitry Andric // Still, if it isn't deemed acceptable, then this transformation needs 1900b57cec5SDimitry Andric // to be a ModulePass (which means it cannot be in the 'llc' pipeline 1910b57cec5SDimitry Andric // (which uses a FunctionPassManager (which segfaults (not asserts) if 1920b57cec5SDimitry Andric // provided a ModulePass))). 1930b57cec5SDimitry Andric Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true, 1940b57cec5SDimitry Andric GlobalVariable::InternalLinkage, FrameMap, 1950b57cec5SDimitry Andric "__gc_" + F.getName()); 1960b57cec5SDimitry Andric 1970b57cec5SDimitry Andric Constant *GEPIndices[2] = { 1980b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), 1990b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)}; 2000b57cec5SDimitry Andric return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices); 2010b57cec5SDimitry Andric } 2020b57cec5SDimitry Andric 203*1db9f3b2SDimitry Andric Type *ShadowStackGCLoweringImpl::GetConcreteStackEntryType(Function &F) { 2040b57cec5SDimitry Andric // doInitialization creates the generic version of this type. 2050b57cec5SDimitry Andric std::vector<Type *> EltTys; 2060b57cec5SDimitry Andric EltTys.push_back(StackEntryTy); 2070eae32dcSDimitry Andric for (const std::pair<CallInst *, AllocaInst *> &Root : Roots) 2080eae32dcSDimitry Andric EltTys.push_back(Root.second->getAllocatedType()); 2090b57cec5SDimitry Andric 2100b57cec5SDimitry Andric return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str()); 2110b57cec5SDimitry Andric } 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric /// doInitialization - If this module uses the GC intrinsics, find them now. If 2140b57cec5SDimitry Andric /// not, exit fast. 215*1db9f3b2SDimitry Andric bool ShadowStackGCLoweringImpl::doInitialization(Module &M) { 2160b57cec5SDimitry Andric bool Active = false; 2170b57cec5SDimitry Andric for (Function &F : M) { 218cb14a3feSDimitry Andric if (F.hasGC() && F.getGC() == "shadow-stack") { 2190b57cec5SDimitry Andric Active = true; 2200b57cec5SDimitry Andric break; 2210b57cec5SDimitry Andric } 2220b57cec5SDimitry Andric } 2230b57cec5SDimitry Andric if (!Active) 2240b57cec5SDimitry Andric return false; 2250b57cec5SDimitry Andric 2260b57cec5SDimitry Andric // struct FrameMap { 2270b57cec5SDimitry Andric // int32_t NumRoots; // Number of roots in stack frame. 2280b57cec5SDimitry Andric // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots. 2290b57cec5SDimitry Andric // void *Meta[]; // May be absent for roots without metadata. 2300b57cec5SDimitry Andric // }; 2310b57cec5SDimitry Andric std::vector<Type *> EltTys; 2320b57cec5SDimitry Andric // 32 bits is ok up to a 32GB stack frame. :) 2330b57cec5SDimitry Andric EltTys.push_back(Type::getInt32Ty(M.getContext())); 2340b57cec5SDimitry Andric // Specifies length of variable length array. 2350b57cec5SDimitry Andric EltTys.push_back(Type::getInt32Ty(M.getContext())); 2360b57cec5SDimitry Andric FrameMapTy = StructType::create(EltTys, "gc_map"); 2370b57cec5SDimitry Andric PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy); 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric // struct StackEntry { 2400b57cec5SDimitry Andric // ShadowStackEntry *Next; // Caller's stack entry. 2410b57cec5SDimitry Andric // FrameMap *Map; // Pointer to constant FrameMap. 2420b57cec5SDimitry Andric // void *Roots[]; // Stack roots (in-place array, so we pretend). 2430b57cec5SDimitry Andric // }; 2440b57cec5SDimitry Andric 2450b57cec5SDimitry Andric StackEntryTy = StructType::create(M.getContext(), "gc_stackentry"); 2460b57cec5SDimitry Andric 2470b57cec5SDimitry Andric EltTys.clear(); 2480b57cec5SDimitry Andric EltTys.push_back(PointerType::getUnqual(StackEntryTy)); 2490b57cec5SDimitry Andric EltTys.push_back(FrameMapPtrTy); 2500b57cec5SDimitry Andric StackEntryTy->setBody(EltTys); 2510b57cec5SDimitry Andric PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy); 2520b57cec5SDimitry Andric 2530b57cec5SDimitry Andric // Get the root chain if it already exists. 2540b57cec5SDimitry Andric Head = M.getGlobalVariable("llvm_gc_root_chain"); 2550b57cec5SDimitry Andric if (!Head) { 2560b57cec5SDimitry Andric // If the root chain does not exist, insert a new one with linkonce 2570b57cec5SDimitry Andric // linkage! 2580b57cec5SDimitry Andric Head = new GlobalVariable( 2590b57cec5SDimitry Andric M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage, 2600b57cec5SDimitry Andric Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain"); 2610b57cec5SDimitry Andric } else if (Head->hasExternalLinkage() && Head->isDeclaration()) { 2620b57cec5SDimitry Andric Head->setInitializer(Constant::getNullValue(StackEntryPtrTy)); 2630b57cec5SDimitry Andric Head->setLinkage(GlobalValue::LinkOnceAnyLinkage); 2640b57cec5SDimitry Andric } 2650b57cec5SDimitry Andric 2660b57cec5SDimitry Andric return true; 2670b57cec5SDimitry Andric } 2680b57cec5SDimitry Andric 269*1db9f3b2SDimitry Andric bool ShadowStackGCLoweringImpl::IsNullValue(Value *V) { 2700b57cec5SDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) 2710b57cec5SDimitry Andric return C->isNullValue(); 2720b57cec5SDimitry Andric return false; 2730b57cec5SDimitry Andric } 2740b57cec5SDimitry Andric 275*1db9f3b2SDimitry Andric void ShadowStackGCLoweringImpl::CollectRoots(Function &F) { 2760b57cec5SDimitry Andric // FIXME: Account for original alignment. Could fragment the root array. 2770b57cec5SDimitry Andric // Approach 1: Null initialize empty slots at runtime. Yuck. 2780b57cec5SDimitry Andric // Approach 2: Emit a map of the array instead of just a count. 2790b57cec5SDimitry Andric 2800b57cec5SDimitry Andric assert(Roots.empty() && "Not cleaned up?"); 2810b57cec5SDimitry Andric 2820b57cec5SDimitry Andric SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots; 2830b57cec5SDimitry Andric 284fe6060f1SDimitry Andric for (BasicBlock &BB : F) 2850eae32dcSDimitry Andric for (Instruction &I : BB) 2860eae32dcSDimitry Andric if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(&I)) 2870b57cec5SDimitry Andric if (Function *F = CI->getCalledFunction()) 2880b57cec5SDimitry Andric if (F->getIntrinsicID() == Intrinsic::gcroot) { 2890b57cec5SDimitry Andric std::pair<CallInst *, AllocaInst *> Pair = std::make_pair( 2900b57cec5SDimitry Andric CI, 2910b57cec5SDimitry Andric cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts())); 2920b57cec5SDimitry Andric if (IsNullValue(CI->getArgOperand(1))) 2930b57cec5SDimitry Andric Roots.push_back(Pair); 2940b57cec5SDimitry Andric else 2950b57cec5SDimitry Andric MetaRoots.push_back(Pair); 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric // Number roots with metadata (usually empty) at the beginning, so that the 2990b57cec5SDimitry Andric // FrameMap::Meta array can be elided. 3000b57cec5SDimitry Andric Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end()); 3010b57cec5SDimitry Andric } 3020b57cec5SDimitry Andric 303*1db9f3b2SDimitry Andric GetElementPtrInst * 304*1db9f3b2SDimitry Andric ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &Context, IRBuilder<> &B, 305*1db9f3b2SDimitry Andric Type *Ty, Value *BasePtr, int Idx, 306*1db9f3b2SDimitry Andric int Idx2, const char *Name) { 3070b57cec5SDimitry Andric Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0), 3080b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx), 3090b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx2)}; 3100b57cec5SDimitry Andric Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name); 3110b57cec5SDimitry Andric 3120b57cec5SDimitry Andric assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric return dyn_cast<GetElementPtrInst>(Val); 3150b57cec5SDimitry Andric } 3160b57cec5SDimitry Andric 317*1db9f3b2SDimitry Andric GetElementPtrInst *ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &Context, 318*1db9f3b2SDimitry Andric IRBuilder<> &B, 319*1db9f3b2SDimitry Andric Type *Ty, 320*1db9f3b2SDimitry Andric Value *BasePtr, int Idx, 321*1db9f3b2SDimitry Andric const char *Name) { 3220b57cec5SDimitry Andric Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0), 3230b57cec5SDimitry Andric ConstantInt::get(Type::getInt32Ty(Context), Idx)}; 3240b57cec5SDimitry Andric Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name); 3250b57cec5SDimitry Andric 3260b57cec5SDimitry Andric assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); 3270b57cec5SDimitry Andric 3280b57cec5SDimitry Andric return dyn_cast<GetElementPtrInst>(Val); 3290b57cec5SDimitry Andric } 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric /// runOnFunction - Insert code to maintain the shadow stack. 332*1db9f3b2SDimitry Andric bool ShadowStackGCLoweringImpl::runOnFunction(Function &F, 333*1db9f3b2SDimitry Andric DomTreeUpdater *DTU) { 3340b57cec5SDimitry Andric // Quick exit for functions that do not use the shadow stack GC. 335cb14a3feSDimitry Andric if (!F.hasGC() || F.getGC() != "shadow-stack") 3360b57cec5SDimitry Andric return false; 3370b57cec5SDimitry Andric 3380b57cec5SDimitry Andric LLVMContext &Context = F.getContext(); 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric // Find calls to llvm.gcroot. 3410b57cec5SDimitry Andric CollectRoots(F); 3420b57cec5SDimitry Andric 3430b57cec5SDimitry Andric // If there are no roots in this function, then there is no need to add a 3440b57cec5SDimitry Andric // stack map entry for it. 3450b57cec5SDimitry Andric if (Roots.empty()) 3460b57cec5SDimitry Andric return false; 3470b57cec5SDimitry Andric 3480b57cec5SDimitry Andric // Build the constant map and figure the type of the shadow stack entry. 3490b57cec5SDimitry Andric Value *FrameMap = GetFrameMap(F); 3500b57cec5SDimitry Andric Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F); 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric // Build the shadow stack entry at the very start of the function. 3530b57cec5SDimitry Andric BasicBlock::iterator IP = F.getEntryBlock().begin(); 3540b57cec5SDimitry Andric IRBuilder<> AtEntry(IP->getParent(), IP); 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric Instruction *StackEntry = 3570b57cec5SDimitry Andric AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame"); 3580b57cec5SDimitry Andric 359bdd1243dSDimitry Andric AtEntry.SetInsertPointPastAllocas(&F); 360bdd1243dSDimitry Andric IP = AtEntry.GetInsertPoint(); 3610b57cec5SDimitry Andric 3620b57cec5SDimitry Andric // Initialize the map pointer and load the current head of the shadow stack. 3630b57cec5SDimitry Andric Instruction *CurrentHead = 3645f757f3fSDimitry Andric AtEntry.CreateLoad(AtEntry.getPtrTy(), Head, "gc_currhead"); 3650b57cec5SDimitry Andric Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 3660b57cec5SDimitry Andric StackEntry, 0, 1, "gc_frame.map"); 3670b57cec5SDimitry Andric AtEntry.CreateStore(FrameMap, EntryMapPtr); 3680b57cec5SDimitry Andric 3690b57cec5SDimitry Andric // After all the allocas... 3700b57cec5SDimitry Andric for (unsigned I = 0, E = Roots.size(); I != E; ++I) { 3710b57cec5SDimitry Andric // For each root, find the corresponding slot in the aggregate... 3720b57cec5SDimitry Andric Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 3730b57cec5SDimitry Andric StackEntry, 1 + I, "gc_root"); 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric // And use it in lieu of the alloca. 3760b57cec5SDimitry Andric AllocaInst *OriginalAlloca = Roots[I].second; 3770b57cec5SDimitry Andric SlotPtr->takeName(OriginalAlloca); 3780b57cec5SDimitry Andric OriginalAlloca->replaceAllUsesWith(SlotPtr); 3790b57cec5SDimitry Andric } 3800b57cec5SDimitry Andric 3810b57cec5SDimitry Andric // Move past the original stores inserted by GCStrategy::InitRoots. This isn't 3820b57cec5SDimitry Andric // really necessary (the collector would never see the intermediate state at 3830b57cec5SDimitry Andric // runtime), but it's nicer not to push the half-initialized entry onto the 3840b57cec5SDimitry Andric // shadow stack. 3850b57cec5SDimitry Andric while (isa<StoreInst>(IP)) 3860b57cec5SDimitry Andric ++IP; 3870b57cec5SDimitry Andric AtEntry.SetInsertPoint(IP->getParent(), IP); 3880b57cec5SDimitry Andric 3890b57cec5SDimitry Andric // Push the entry onto the shadow stack. 3900b57cec5SDimitry Andric Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 3910b57cec5SDimitry Andric StackEntry, 0, 0, "gc_frame.next"); 3920b57cec5SDimitry Andric Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 3930b57cec5SDimitry Andric StackEntry, 0, "gc_newhead"); 3940b57cec5SDimitry Andric AtEntry.CreateStore(CurrentHead, EntryNextPtr); 3950b57cec5SDimitry Andric AtEntry.CreateStore(NewHeadVal, Head); 3960b57cec5SDimitry Andric 3970b57cec5SDimitry Andric // For each instruction that escapes... 398*1db9f3b2SDimitry Andric EscapeEnumerator EE(F, "gc_cleanup", /*HandleExceptions=*/true, DTU); 3990b57cec5SDimitry Andric while (IRBuilder<> *AtExit = EE.Next()) { 4000b57cec5SDimitry Andric // Pop the entry from the shadow stack. Don't reuse CurrentHead from 4010b57cec5SDimitry Andric // AtEntry, since that would make the value live for the entire function. 4020b57cec5SDimitry Andric Instruction *EntryNextPtr2 = 4030b57cec5SDimitry Andric CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0, 4040b57cec5SDimitry Andric "gc_frame.next"); 4055f757f3fSDimitry Andric Value *SavedHead = 4065f757f3fSDimitry Andric AtExit->CreateLoad(AtExit->getPtrTy(), EntryNextPtr2, "gc_savedhead"); 4070b57cec5SDimitry Andric AtExit->CreateStore(SavedHead, Head); 4080b57cec5SDimitry Andric } 4090b57cec5SDimitry Andric 4100b57cec5SDimitry Andric // Delete the original allocas (which are no longer used) and the intrinsic 4110b57cec5SDimitry Andric // calls (which are no longer valid). Doing this last avoids invalidating 4120b57cec5SDimitry Andric // iterators. 4130eae32dcSDimitry Andric for (std::pair<CallInst *, AllocaInst *> &Root : Roots) { 4140eae32dcSDimitry Andric Root.first->eraseFromParent(); 4150eae32dcSDimitry Andric Root.second->eraseFromParent(); 4160b57cec5SDimitry Andric } 4170b57cec5SDimitry Andric 4180b57cec5SDimitry Andric Roots.clear(); 4190b57cec5SDimitry Andric return true; 4200b57cec5SDimitry Andric } 421