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