xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/ShadowStackGCLowering.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ----===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file contains the custom lowering code required by the shadow-stack GC
10*0b57cec5SDimitry Andric // strategy.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric // This pass implements the code transformation described in this paper:
13*0b57cec5SDimitry Andric //   "Accurate Garbage Collection in an Uncooperative Environment"
14*0b57cec5SDimitry Andric //   Fergus Henderson, ISMM, 2002
15*0b57cec5SDimitry Andric //
16*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17*0b57cec5SDimitry Andric 
18*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
20*0b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
21*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
22*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
23*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
24*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
25*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
26*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
28*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
29*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
35*0b57cec5SDimitry Andric #include "llvm/Pass.h"
36*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
37*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/EscapeEnumerator.h"
38*0b57cec5SDimitry Andric #include <cassert>
39*0b57cec5SDimitry Andric #include <cstddef>
40*0b57cec5SDimitry Andric #include <string>
41*0b57cec5SDimitry Andric #include <utility>
42*0b57cec5SDimitry Andric #include <vector>
43*0b57cec5SDimitry Andric 
44*0b57cec5SDimitry Andric using namespace llvm;
45*0b57cec5SDimitry Andric 
46*0b57cec5SDimitry Andric #define DEBUG_TYPE "shadow-stack-gc-lowering"
47*0b57cec5SDimitry Andric 
48*0b57cec5SDimitry Andric namespace {
49*0b57cec5SDimitry Andric 
50*0b57cec5SDimitry Andric class ShadowStackGCLowering : public FunctionPass {
51*0b57cec5SDimitry Andric   /// RootChain - This is the global linked-list that contains the chain of GC
52*0b57cec5SDimitry Andric   /// roots.
53*0b57cec5SDimitry Andric   GlobalVariable *Head = nullptr;
54*0b57cec5SDimitry Andric 
55*0b57cec5SDimitry Andric   /// StackEntryTy - Abstract type of a link in the shadow stack.
56*0b57cec5SDimitry Andric   StructType *StackEntryTy = nullptr;
57*0b57cec5SDimitry Andric   StructType *FrameMapTy = nullptr;
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric   /// Roots - GC roots in the current function. Each is a pair of the
60*0b57cec5SDimitry Andric   /// intrinsic call and its corresponding alloca.
61*0b57cec5SDimitry Andric   std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
62*0b57cec5SDimitry Andric 
63*0b57cec5SDimitry Andric public:
64*0b57cec5SDimitry Andric   static char ID;
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric   ShadowStackGCLowering();
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric   bool doInitialization(Module &M) override;
69*0b57cec5SDimitry Andric   bool runOnFunction(Function &F) override;
70*0b57cec5SDimitry Andric 
71*0b57cec5SDimitry Andric private:
72*0b57cec5SDimitry Andric   bool IsNullValue(Value *V);
73*0b57cec5SDimitry Andric   Constant *GetFrameMap(Function &F);
74*0b57cec5SDimitry Andric   Type *GetConcreteStackEntryType(Function &F);
75*0b57cec5SDimitry Andric   void CollectRoots(Function &F);
76*0b57cec5SDimitry Andric 
77*0b57cec5SDimitry Andric   static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
78*0b57cec5SDimitry Andric                                       Type *Ty, Value *BasePtr, int Idx1,
79*0b57cec5SDimitry Andric                                       const char *Name);
80*0b57cec5SDimitry Andric   static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
81*0b57cec5SDimitry Andric                                       Type *Ty, Value *BasePtr, int Idx1, int Idx2,
82*0b57cec5SDimitry Andric                                       const char *Name);
83*0b57cec5SDimitry Andric };
84*0b57cec5SDimitry Andric 
85*0b57cec5SDimitry Andric } // end anonymous namespace
86*0b57cec5SDimitry Andric 
87*0b57cec5SDimitry Andric char ShadowStackGCLowering::ID = 0;
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
90*0b57cec5SDimitry Andric                       "Shadow Stack GC Lowering", false, false)
91*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
92*0b57cec5SDimitry Andric INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
93*0b57cec5SDimitry Andric                     "Shadow Stack GC Lowering", false, false)
94*0b57cec5SDimitry Andric 
95*0b57cec5SDimitry Andric FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) {
98*0b57cec5SDimitry Andric   initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
99*0b57cec5SDimitry Andric }
100*0b57cec5SDimitry Andric 
101*0b57cec5SDimitry Andric Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
102*0b57cec5SDimitry Andric   // doInitialization creates the abstract type of this value.
103*0b57cec5SDimitry Andric   Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
104*0b57cec5SDimitry Andric 
105*0b57cec5SDimitry Andric   // Truncate the ShadowStackDescriptor if some metadata is null.
106*0b57cec5SDimitry Andric   unsigned NumMeta = 0;
107*0b57cec5SDimitry Andric   SmallVector<Constant *, 16> Metadata;
108*0b57cec5SDimitry Andric   for (unsigned I = 0; I != Roots.size(); ++I) {
109*0b57cec5SDimitry Andric     Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
110*0b57cec5SDimitry Andric     if (!C->isNullValue())
111*0b57cec5SDimitry Andric       NumMeta = I + 1;
112*0b57cec5SDimitry Andric     Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
113*0b57cec5SDimitry Andric   }
114*0b57cec5SDimitry Andric   Metadata.resize(NumMeta);
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(F.getContext());
117*0b57cec5SDimitry Andric 
118*0b57cec5SDimitry Andric   Constant *BaseElts[] = {
119*0b57cec5SDimitry Andric       ConstantInt::get(Int32Ty, Roots.size(), false),
120*0b57cec5SDimitry Andric       ConstantInt::get(Int32Ty, NumMeta, false),
121*0b57cec5SDimitry Andric   };
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric   Constant *DescriptorElts[] = {
124*0b57cec5SDimitry Andric       ConstantStruct::get(FrameMapTy, BaseElts),
125*0b57cec5SDimitry Andric       ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
126*0b57cec5SDimitry Andric 
127*0b57cec5SDimitry Andric   Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
128*0b57cec5SDimitry Andric   StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
129*0b57cec5SDimitry Andric 
130*0b57cec5SDimitry Andric   Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric   // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
133*0b57cec5SDimitry Andric   //        that, short of multithreaded LLVM, it should be safe; all that is
134*0b57cec5SDimitry Andric   //        necessary is that a simple Module::iterator loop not be invalidated.
135*0b57cec5SDimitry Andric   //        Appending to the GlobalVariable list is safe in that sense.
136*0b57cec5SDimitry Andric   //
137*0b57cec5SDimitry Andric   //        All of the output passes emit globals last. The ExecutionEngine
138*0b57cec5SDimitry Andric   //        explicitly supports adding globals to the module after
139*0b57cec5SDimitry Andric   //        initialization.
140*0b57cec5SDimitry Andric   //
141*0b57cec5SDimitry Andric   //        Still, if it isn't deemed acceptable, then this transformation needs
142*0b57cec5SDimitry Andric   //        to be a ModulePass (which means it cannot be in the 'llc' pipeline
143*0b57cec5SDimitry Andric   //        (which uses a FunctionPassManager (which segfaults (not asserts) if
144*0b57cec5SDimitry Andric   //        provided a ModulePass))).
145*0b57cec5SDimitry Andric   Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
146*0b57cec5SDimitry Andric                                     GlobalVariable::InternalLinkage, FrameMap,
147*0b57cec5SDimitry Andric                                     "__gc_" + F.getName());
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric   Constant *GEPIndices[2] = {
150*0b57cec5SDimitry Andric       ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
151*0b57cec5SDimitry Andric       ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
152*0b57cec5SDimitry Andric   return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
153*0b57cec5SDimitry Andric }
154*0b57cec5SDimitry Andric 
155*0b57cec5SDimitry Andric Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
156*0b57cec5SDimitry Andric   // doInitialization creates the generic version of this type.
157*0b57cec5SDimitry Andric   std::vector<Type *> EltTys;
158*0b57cec5SDimitry Andric   EltTys.push_back(StackEntryTy);
159*0b57cec5SDimitry Andric   for (size_t I = 0; I != Roots.size(); I++)
160*0b57cec5SDimitry Andric     EltTys.push_back(Roots[I].second->getAllocatedType());
161*0b57cec5SDimitry Andric 
162*0b57cec5SDimitry Andric   return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
163*0b57cec5SDimitry Andric }
164*0b57cec5SDimitry Andric 
165*0b57cec5SDimitry Andric /// doInitialization - If this module uses the GC intrinsics, find them now. If
166*0b57cec5SDimitry Andric /// not, exit fast.
167*0b57cec5SDimitry Andric bool ShadowStackGCLowering::doInitialization(Module &M) {
168*0b57cec5SDimitry Andric   bool Active = false;
169*0b57cec5SDimitry Andric   for (Function &F : M) {
170*0b57cec5SDimitry Andric     if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
171*0b57cec5SDimitry Andric       Active = true;
172*0b57cec5SDimitry Andric       break;
173*0b57cec5SDimitry Andric     }
174*0b57cec5SDimitry Andric   }
175*0b57cec5SDimitry Andric   if (!Active)
176*0b57cec5SDimitry Andric     return false;
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   // struct FrameMap {
179*0b57cec5SDimitry Andric   //   int32_t NumRoots; // Number of roots in stack frame.
180*0b57cec5SDimitry Andric   //   int32_t NumMeta;  // Number of metadata descriptors. May be < NumRoots.
181*0b57cec5SDimitry Andric   //   void *Meta[];     // May be absent for roots without metadata.
182*0b57cec5SDimitry Andric   // };
183*0b57cec5SDimitry Andric   std::vector<Type *> EltTys;
184*0b57cec5SDimitry Andric   // 32 bits is ok up to a 32GB stack frame. :)
185*0b57cec5SDimitry Andric   EltTys.push_back(Type::getInt32Ty(M.getContext()));
186*0b57cec5SDimitry Andric   // Specifies length of variable length array.
187*0b57cec5SDimitry Andric   EltTys.push_back(Type::getInt32Ty(M.getContext()));
188*0b57cec5SDimitry Andric   FrameMapTy = StructType::create(EltTys, "gc_map");
189*0b57cec5SDimitry Andric   PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric   // struct StackEntry {
192*0b57cec5SDimitry Andric   //   ShadowStackEntry *Next; // Caller's stack entry.
193*0b57cec5SDimitry Andric   //   FrameMap *Map;          // Pointer to constant FrameMap.
194*0b57cec5SDimitry Andric   //   void *Roots[];          // Stack roots (in-place array, so we pretend).
195*0b57cec5SDimitry Andric   // };
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric   StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
198*0b57cec5SDimitry Andric 
199*0b57cec5SDimitry Andric   EltTys.clear();
200*0b57cec5SDimitry Andric   EltTys.push_back(PointerType::getUnqual(StackEntryTy));
201*0b57cec5SDimitry Andric   EltTys.push_back(FrameMapPtrTy);
202*0b57cec5SDimitry Andric   StackEntryTy->setBody(EltTys);
203*0b57cec5SDimitry Andric   PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
204*0b57cec5SDimitry Andric 
205*0b57cec5SDimitry Andric   // Get the root chain if it already exists.
206*0b57cec5SDimitry Andric   Head = M.getGlobalVariable("llvm_gc_root_chain");
207*0b57cec5SDimitry Andric   if (!Head) {
208*0b57cec5SDimitry Andric     // If the root chain does not exist, insert a new one with linkonce
209*0b57cec5SDimitry Andric     // linkage!
210*0b57cec5SDimitry Andric     Head = new GlobalVariable(
211*0b57cec5SDimitry Andric         M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
212*0b57cec5SDimitry Andric         Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
213*0b57cec5SDimitry Andric   } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
214*0b57cec5SDimitry Andric     Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
215*0b57cec5SDimitry Andric     Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
216*0b57cec5SDimitry Andric   }
217*0b57cec5SDimitry Andric 
218*0b57cec5SDimitry Andric   return true;
219*0b57cec5SDimitry Andric }
220*0b57cec5SDimitry Andric 
221*0b57cec5SDimitry Andric bool ShadowStackGCLowering::IsNullValue(Value *V) {
222*0b57cec5SDimitry Andric   if (Constant *C = dyn_cast<Constant>(V))
223*0b57cec5SDimitry Andric     return C->isNullValue();
224*0b57cec5SDimitry Andric   return false;
225*0b57cec5SDimitry Andric }
226*0b57cec5SDimitry Andric 
227*0b57cec5SDimitry Andric void ShadowStackGCLowering::CollectRoots(Function &F) {
228*0b57cec5SDimitry Andric   // FIXME: Account for original alignment. Could fragment the root array.
229*0b57cec5SDimitry Andric   //   Approach 1: Null initialize empty slots at runtime. Yuck.
230*0b57cec5SDimitry Andric   //   Approach 2: Emit a map of the array instead of just a count.
231*0b57cec5SDimitry Andric 
232*0b57cec5SDimitry Andric   assert(Roots.empty() && "Not cleaned up?");
233*0b57cec5SDimitry Andric 
234*0b57cec5SDimitry Andric   SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
235*0b57cec5SDimitry Andric 
236*0b57cec5SDimitry Andric   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
237*0b57cec5SDimitry Andric     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
238*0b57cec5SDimitry Andric       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
239*0b57cec5SDimitry Andric         if (Function *F = CI->getCalledFunction())
240*0b57cec5SDimitry Andric           if (F->getIntrinsicID() == Intrinsic::gcroot) {
241*0b57cec5SDimitry Andric             std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
242*0b57cec5SDimitry Andric                 CI,
243*0b57cec5SDimitry Andric                 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
244*0b57cec5SDimitry Andric             if (IsNullValue(CI->getArgOperand(1)))
245*0b57cec5SDimitry Andric               Roots.push_back(Pair);
246*0b57cec5SDimitry Andric             else
247*0b57cec5SDimitry Andric               MetaRoots.push_back(Pair);
248*0b57cec5SDimitry Andric           }
249*0b57cec5SDimitry Andric 
250*0b57cec5SDimitry Andric   // Number roots with metadata (usually empty) at the beginning, so that the
251*0b57cec5SDimitry Andric   // FrameMap::Meta array can be elided.
252*0b57cec5SDimitry Andric   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
253*0b57cec5SDimitry Andric }
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
256*0b57cec5SDimitry Andric                                                     IRBuilder<> &B, Type *Ty,
257*0b57cec5SDimitry Andric                                                     Value *BasePtr, int Idx,
258*0b57cec5SDimitry Andric                                                     int Idx2,
259*0b57cec5SDimitry Andric                                                     const char *Name) {
260*0b57cec5SDimitry Andric   Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
261*0b57cec5SDimitry Andric                       ConstantInt::get(Type::getInt32Ty(Context), Idx),
262*0b57cec5SDimitry Andric                       ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
263*0b57cec5SDimitry Andric   Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
264*0b57cec5SDimitry Andric 
265*0b57cec5SDimitry Andric   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
266*0b57cec5SDimitry Andric 
267*0b57cec5SDimitry Andric   return dyn_cast<GetElementPtrInst>(Val);
268*0b57cec5SDimitry Andric }
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
271*0b57cec5SDimitry Andric                                             IRBuilder<> &B, Type *Ty, Value *BasePtr,
272*0b57cec5SDimitry Andric                                             int Idx, const char *Name) {
273*0b57cec5SDimitry Andric   Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
274*0b57cec5SDimitry Andric                       ConstantInt::get(Type::getInt32Ty(Context), Idx)};
275*0b57cec5SDimitry Andric   Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
276*0b57cec5SDimitry Andric 
277*0b57cec5SDimitry Andric   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
278*0b57cec5SDimitry Andric 
279*0b57cec5SDimitry Andric   return dyn_cast<GetElementPtrInst>(Val);
280*0b57cec5SDimitry Andric }
281*0b57cec5SDimitry Andric 
282*0b57cec5SDimitry Andric /// runOnFunction - Insert code to maintain the shadow stack.
283*0b57cec5SDimitry Andric bool ShadowStackGCLowering::runOnFunction(Function &F) {
284*0b57cec5SDimitry Andric   // Quick exit for functions that do not use the shadow stack GC.
285*0b57cec5SDimitry Andric   if (!F.hasGC() ||
286*0b57cec5SDimitry Andric       F.getGC() != std::string("shadow-stack"))
287*0b57cec5SDimitry Andric     return false;
288*0b57cec5SDimitry Andric 
289*0b57cec5SDimitry Andric   LLVMContext &Context = F.getContext();
290*0b57cec5SDimitry Andric 
291*0b57cec5SDimitry Andric   // Find calls to llvm.gcroot.
292*0b57cec5SDimitry Andric   CollectRoots(F);
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric   // If there are no roots in this function, then there is no need to add a
295*0b57cec5SDimitry Andric   // stack map entry for it.
296*0b57cec5SDimitry Andric   if (Roots.empty())
297*0b57cec5SDimitry Andric     return false;
298*0b57cec5SDimitry Andric 
299*0b57cec5SDimitry Andric   // Build the constant map and figure the type of the shadow stack entry.
300*0b57cec5SDimitry Andric   Value *FrameMap = GetFrameMap(F);
301*0b57cec5SDimitry Andric   Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
302*0b57cec5SDimitry Andric 
303*0b57cec5SDimitry Andric   // Build the shadow stack entry at the very start of the function.
304*0b57cec5SDimitry Andric   BasicBlock::iterator IP = F.getEntryBlock().begin();
305*0b57cec5SDimitry Andric   IRBuilder<> AtEntry(IP->getParent(), IP);
306*0b57cec5SDimitry Andric 
307*0b57cec5SDimitry Andric   Instruction *StackEntry =
308*0b57cec5SDimitry Andric       AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
309*0b57cec5SDimitry Andric 
310*0b57cec5SDimitry Andric   while (isa<AllocaInst>(IP))
311*0b57cec5SDimitry Andric     ++IP;
312*0b57cec5SDimitry Andric   AtEntry.SetInsertPoint(IP->getParent(), IP);
313*0b57cec5SDimitry Andric 
314*0b57cec5SDimitry Andric   // Initialize the map pointer and load the current head of the shadow stack.
315*0b57cec5SDimitry Andric   Instruction *CurrentHead =
316*0b57cec5SDimitry Andric       AtEntry.CreateLoad(StackEntryTy->getPointerTo(), Head, "gc_currhead");
317*0b57cec5SDimitry Andric   Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
318*0b57cec5SDimitry Andric                                        StackEntry, 0, 1, "gc_frame.map");
319*0b57cec5SDimitry Andric   AtEntry.CreateStore(FrameMap, EntryMapPtr);
320*0b57cec5SDimitry Andric 
321*0b57cec5SDimitry Andric   // After all the allocas...
322*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
323*0b57cec5SDimitry Andric     // For each root, find the corresponding slot in the aggregate...
324*0b57cec5SDimitry Andric     Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
325*0b57cec5SDimitry Andric                                StackEntry, 1 + I, "gc_root");
326*0b57cec5SDimitry Andric 
327*0b57cec5SDimitry Andric     // And use it in lieu of the alloca.
328*0b57cec5SDimitry Andric     AllocaInst *OriginalAlloca = Roots[I].second;
329*0b57cec5SDimitry Andric     SlotPtr->takeName(OriginalAlloca);
330*0b57cec5SDimitry Andric     OriginalAlloca->replaceAllUsesWith(SlotPtr);
331*0b57cec5SDimitry Andric   }
332*0b57cec5SDimitry Andric 
333*0b57cec5SDimitry Andric   // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
334*0b57cec5SDimitry Andric   // really necessary (the collector would never see the intermediate state at
335*0b57cec5SDimitry Andric   // runtime), but it's nicer not to push the half-initialized entry onto the
336*0b57cec5SDimitry Andric   // shadow stack.
337*0b57cec5SDimitry Andric   while (isa<StoreInst>(IP))
338*0b57cec5SDimitry Andric     ++IP;
339*0b57cec5SDimitry Andric   AtEntry.SetInsertPoint(IP->getParent(), IP);
340*0b57cec5SDimitry Andric 
341*0b57cec5SDimitry Andric   // Push the entry onto the shadow stack.
342*0b57cec5SDimitry Andric   Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
343*0b57cec5SDimitry Andric                                         StackEntry, 0, 0, "gc_frame.next");
344*0b57cec5SDimitry Andric   Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
345*0b57cec5SDimitry Andric                                       StackEntry, 0, "gc_newhead");
346*0b57cec5SDimitry Andric   AtEntry.CreateStore(CurrentHead, EntryNextPtr);
347*0b57cec5SDimitry Andric   AtEntry.CreateStore(NewHeadVal, Head);
348*0b57cec5SDimitry Andric 
349*0b57cec5SDimitry Andric   // For each instruction that escapes...
350*0b57cec5SDimitry Andric   EscapeEnumerator EE(F, "gc_cleanup");
351*0b57cec5SDimitry Andric   while (IRBuilder<> *AtExit = EE.Next()) {
352*0b57cec5SDimitry Andric     // Pop the entry from the shadow stack. Don't reuse CurrentHead from
353*0b57cec5SDimitry Andric     // AtEntry, since that would make the value live for the entire function.
354*0b57cec5SDimitry Andric     Instruction *EntryNextPtr2 =
355*0b57cec5SDimitry Andric         CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
356*0b57cec5SDimitry Andric                   "gc_frame.next");
357*0b57cec5SDimitry Andric     Value *SavedHead = AtExit->CreateLoad(StackEntryTy->getPointerTo(),
358*0b57cec5SDimitry Andric                                           EntryNextPtr2, "gc_savedhead");
359*0b57cec5SDimitry Andric     AtExit->CreateStore(SavedHead, Head);
360*0b57cec5SDimitry Andric   }
361*0b57cec5SDimitry Andric 
362*0b57cec5SDimitry Andric   // Delete the original allocas (which are no longer used) and the intrinsic
363*0b57cec5SDimitry Andric   // calls (which are no longer valid). Doing this last avoids invalidating
364*0b57cec5SDimitry Andric   // iterators.
365*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
366*0b57cec5SDimitry Andric     Roots[I].first->eraseFromParent();
367*0b57cec5SDimitry Andric     Roots[I].second->eraseFromParent();
368*0b57cec5SDimitry Andric   }
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric   Roots.clear();
371*0b57cec5SDimitry Andric   return true;
372*0b57cec5SDimitry Andric }
373