blob: 5a55760c7c56abd5ba9d3a2af1e3079e5ea0c22d [file] [log] [blame]
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001//===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
Gordon Henriksen8fa89292008-01-07 01:30:53 +00002//
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
Gordon Henriksen5eca0752008-08-17 18:44:35 +000012// generated is not quite as efficient as algorithms which generate stack maps
Gordon Henriksen8fa89292008-01-07 01:30:53 +000013// 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
Gordon Henriksen5eca0752008-08-17 18:44:35 +000020// ShadowStackGC.
Gordon Henriksen8fa89292008-01-07 01:30:53 +000021//
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"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000029#include "llvm/CodeGen/GCs.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000030#include "llvm/ADT/StringExtras.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000031#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000032#include "llvm/IntrinsicInst.h"
33#include "llvm/Module.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000034#include "llvm/Support/Compiler.h"
Duncan Sands89f6d882008-04-13 06:22:09 +000035#include "llvm/Support/IRBuilder.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000036
37using namespace llvm;
38
39namespace {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000040
Gordon Henriksen5eca0752008-08-17 18:44:35 +000041 class VISIBILITY_HIDDEN ShadowStackGC : public GCStrategy {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000042 /// RootChain - This is the global linked-list that contains the chain of GC
43 /// roots.
44 GlobalVariable *Head;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000045
Gordon Henriksen8fa89292008-01-07 01:30:53 +000046 /// StackEntryTy - Abstract type of a link in the shadow stack.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000047 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000048 const StructType *StackEntryTy;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000049
Gordon Henriksen8fa89292008-01-07 01:30:53 +000050 /// 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;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000053
Gordon Henriksen8fa89292008-01-07 01:30:53 +000054 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000055 ShadowStackGC();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000056
Gordon Henriksen8fa89292008-01-07 01:30:53 +000057 bool initializeCustomLowering(Module &M);
58 bool performCustomLowering(Function &F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000059
Gordon Henriksen8fa89292008-01-07 01:30:53 +000060 private:
61 bool IsNullValue(Value *V);
62 Constant *GetFrameMap(Function &F);
63 const Type* GetConcreteStackEntryType(Function &F);
64 void CollectRoots(Function &F);
Eric Christopher7a61d702008-08-08 19:39:37 +000065 static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000066 int Idx1, const char *Name);
Eric Christopher7a61d702008-08-08 19:39:37 +000067 static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000068 int Idx1, int Idx2, const char *Name);
69 };
Dan Gohman844731a2008-05-13 00:00:25 +000070
71}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000072
Gordon Henriksen5eca0752008-08-17 18:44:35 +000073static GCRegistry::Add<ShadowStackGC>
74X("shadow-stack", "Very portable GC for uncooperative code generators");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000075
Dan Gohman844731a2008-05-13 00:00:25 +000076namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000077 /// EscapeEnumerator - This is a little algorithm to find all escape points
78 /// from a function so that "finally"-style code can be inserted. In addition
79 /// to finding the existing return and unwind instructions, it also (if
80 /// necessary) transforms any call instructions into invokes and sends them to
81 /// a landing pad.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000082 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000083 /// It's wrapped up in a state machine using the same transform C# uses for
84 /// 'yield return' enumerators, This transform allows it to be non-allocating.
85 class VISIBILITY_HIDDEN EscapeEnumerator {
86 Function &F;
87 const char *CleanupBBName;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000088
Gordon Henriksen8fa89292008-01-07 01:30:53 +000089 // State.
90 int State;
91 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000092 IRBuilder<> Builder;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000093
Gordon Henriksen8fa89292008-01-07 01:30:53 +000094 public:
95 EscapeEnumerator(Function &F, const char *N = "cleanup")
96 : F(F), CleanupBBName(N), State(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000097
Eric Christopher7a61d702008-08-08 19:39:37 +000098 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000099 switch (State) {
100 default:
101 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000102
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000103 case 0:
104 StateBB = F.begin();
105 StateE = F.end();
106 State = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000107
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000108 case 1:
109 // Find all 'return' and 'unwind' instructions.
110 while (StateBB != StateE) {
111 BasicBlock *CurBB = StateBB++;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000112
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000113 // Branches and invokes do not escape, only unwind and return do.
114 TerminatorInst *TI = CurBB->getTerminator();
115 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
116 continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000117
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000118 Builder.SetInsertPoint(TI->getParent(), TI);
119 return &Builder;
120 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000121
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000122 State = 2;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000123
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000124 // Find all 'call' instructions.
125 SmallVector<Instruction*,16> Calls;
126 for (Function::iterator BB = F.begin(),
127 E = F.end(); BB != E; ++BB)
128 for (BasicBlock::iterator II = BB->begin(),
129 EE = BB->end(); II != EE; ++II)
130 if (CallInst *CI = dyn_cast<CallInst>(II))
131 if (!CI->getCalledFunction() ||
132 !CI->getCalledFunction()->getIntrinsicID())
133 Calls.push_back(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000134
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000135 if (Calls.empty())
136 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000137
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000138 // Create a cleanup block.
Gabor Greif051a9502008-04-06 20:25:17 +0000139 BasicBlock *CleanupBB = BasicBlock::Create(CleanupBBName, &F);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000140 UnwindInst *UI = new UnwindInst(CleanupBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000141
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000142 // Transform the 'call' instructions into 'invoke's branching to the
143 // cleanup block. Go in reverse order to make prettier BB names.
144 SmallVector<Value*,16> Args;
145 for (unsigned I = Calls.size(); I != 0; ) {
146 CallInst *CI = cast<CallInst>(Calls[--I]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000147
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000148 // Split the basic block containing the function call.
149 BasicBlock *CallBB = CI->getParent();
150 BasicBlock *NewBB =
151 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000152
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000153 // Remove the unconditional branch inserted at the end of CallBB.
154 CallBB->getInstList().pop_back();
155 NewBB->getInstList().remove(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000156
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000157 // Create a new invoke instruction.
158 Args.clear();
159 Args.append(CI->op_begin() + 1, CI->op_end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000160
Gabor Greif051a9502008-04-06 20:25:17 +0000161 InvokeInst *II = InvokeInst::Create(CI->getOperand(0),
162 NewBB, CleanupBB,
163 Args.begin(), Args.end(),
164 CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000165 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000166 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000167 CI->replaceAllUsesWith(II);
168 delete CI;
169 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000170
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000171 Builder.SetInsertPoint(UI->getParent(), UI);
172 return &Builder;
173 }
174 }
175 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000176}
177
178// -----------------------------------------------------------------------------
179
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000180void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000181
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000182ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000183 InitRoots = true;
184 CustomRoots = true;
185}
186
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000187Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000188 // doInitialization creates the abstract type of this value.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000189
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000190 Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000191
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000192 // Truncate the ShadowStackDescriptor if some metadata is null.
193 unsigned NumMeta = 0;
194 SmallVector<Constant*,16> Metadata;
195 for (unsigned I = 0; I != Roots.size(); ++I) {
196 Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
197 if (!C->isNullValue())
198 NumMeta = I + 1;
199 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
200 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000201
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000202 Constant *BaseElts[] = {
203 ConstantInt::get(Type::Int32Ty, Roots.size(), false),
204 ConstantInt::get(Type::Int32Ty, NumMeta, false),
205 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000206
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000207 Constant *DescriptorElts[] = {
208 ConstantStruct::get(BaseElts, 2),
209 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
210 Metadata.begin(), NumMeta)
211 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000212
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000213 Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000214
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000215 std::string TypeName("gc_map.");
216 TypeName += utostr(NumMeta);
217 F.getParent()->addTypeName(TypeName, FrameMap->getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000218
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000219 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
220 // that, short of multithreaded LLVM, it should be safe; all that is
221 // necessary is that a simple Module::iterator loop not be invalidated.
222 // Appending to the GlobalVariable list is safe in that sense.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000223 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000224 // All of the output passes emit globals last. The ExecutionEngine
225 // explicitly supports adding globals to the module after
226 // initialization.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000227 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000228 // Still, if it isn't deemed acceptable, then this transformation needs
229 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
230 // (which uses a FunctionPassManager (which segfaults (not asserts) if
231 // provided a ModulePass))).
232 Constant *GV = new GlobalVariable(FrameMap->getType(), true,
233 GlobalVariable::InternalLinkage,
234 FrameMap, "__gc_" + F.getName(),
235 F.getParent());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000236
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000237 Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0),
238 ConstantInt::get(Type::Int32Ty, 0) };
239 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
240}
241
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000242const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000243 // doInitialization creates the generic version of this type.
244 std::vector<const Type*> EltTys;
245 EltTys.push_back(StackEntryTy);
246 for (size_t I = 0; I != Roots.size(); I++)
247 EltTys.push_back(Roots[I].second->getAllocatedType());
248 Type *Ty = StructType::get(EltTys);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000249
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000250 std::string TypeName("gc_stackentry.");
251 TypeName += F.getName();
252 F.getParent()->addTypeName(TypeName, Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000253
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000254 return Ty;
255}
256
257/// doInitialization - If this module uses the GC intrinsics, find them now. If
258/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000259bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000260 // struct FrameMap {
261 // int32_t NumRoots; // Number of roots in stack frame.
262 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
263 // void *Meta[]; // May be absent for roots without metadata.
264 // };
265 std::vector<const Type*> EltTys;
266 EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :)
267 EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array.
268 StructType *FrameMapTy = StructType::get(EltTys);
269 M.addTypeName("gc_map", FrameMapTy);
270 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000271
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000272 // struct StackEntry {
273 // ShadowStackEntry *Next; // Caller's stack entry.
274 // FrameMap *Map; // Pointer to constant FrameMap.
275 // void *Roots[]; // Stack roots (in-place array, so we pretend).
276 // };
277 OpaqueType *RecursiveTy = OpaqueType::get();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000278
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000279 EltTys.clear();
280 EltTys.push_back(PointerType::getUnqual(RecursiveTy));
281 EltTys.push_back(FrameMapPtrTy);
282 PATypeHolder LinkTyH = StructType::get(EltTys);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000283
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000284 RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
285 StackEntryTy = cast<StructType>(LinkTyH.get());
286 const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
287 M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from
288 // a FunctionPass?
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000289
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000290 // Get the root chain if it already exists.
291 Head = M.getGlobalVariable("llvm_gc_root_chain");
292 if (!Head) {
293 // If the root chain does not exist, insert a new one with linkonce
294 // linkage!
295 Head = new GlobalVariable(StackEntryPtrTy, false,
296 GlobalValue::LinkOnceLinkage,
297 Constant::getNullValue(StackEntryPtrTy),
298 "llvm_gc_root_chain", &M);
299 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
300 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
301 Head->setLinkage(GlobalValue::LinkOnceLinkage);
302 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000303
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000304 return true;
305}
306
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000307bool ShadowStackGC::IsNullValue(Value *V) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000308 if (Constant *C = dyn_cast<Constant>(V))
309 return C->isNullValue();
310 return false;
311}
312
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000313void ShadowStackGC::CollectRoots(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000314 // FIXME: Account for original alignment. Could fragment the root array.
315 // Approach 1: Null initialize empty slots at runtime. Yuck.
316 // Approach 2: Emit a map of the array instead of just a count.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000317
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000318 assert(Roots.empty() && "Not cleaned up?");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000319
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000320 SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000321
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000322 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
323 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
324 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
325 if (Function *F = CI->getCalledFunction())
326 if (F->getIntrinsicID() == Intrinsic::gcroot) {
327 std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000328 CI, cast<AllocaInst>(CI->getOperand(1)->stripPointerCasts()));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000329 if (IsNullValue(CI->getOperand(2)))
330 Roots.push_back(Pair);
331 else
332 MetaRoots.push_back(Pair);
333 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000334
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000335 // Number roots with metadata (usually empty) at the beginning, so that the
336 // FrameMap::Meta array can be elided.
337 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
338}
339
340GetElementPtrInst *
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000341ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
342 int Idx, int Idx2, const char *Name) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000343 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
344 ConstantInt::get(Type::Int32Ty, Idx),
345 ConstantInt::get(Type::Int32Ty, Idx2) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000346 Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000347
Duncan Sands89f6d882008-04-13 06:22:09 +0000348 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000349
Duncan Sands89f6d882008-04-13 06:22:09 +0000350 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000351}
352
353GetElementPtrInst *
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000354ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
355 int Idx, const char *Name) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000356 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
357 ConstantInt::get(Type::Int32Ty, Idx) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000358 Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000359
Duncan Sands89f6d882008-04-13 06:22:09 +0000360 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
361
362 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000363}
364
365/// runOnFunction - Insert code to maintain the shadow stack.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000366bool ShadowStackGC::performCustomLowering(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000367 // Find calls to llvm.gcroot.
368 CollectRoots(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000369
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000370 // If there are no roots in this function, then there is no need to add a
371 // stack map entry for it.
372 if (Roots.empty())
373 return false;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000374
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000375 // Build the constant map and figure the type of the shadow stack entry.
376 Value *FrameMap = GetFrameMap(F);
377 const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000378
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000379 // Build the shadow stack entry at the very start of the function.
380 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000381 IRBuilder<> AtEntry(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000382
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000383 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
384 "gc_frame");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000385
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000386 while (isa<AllocaInst>(IP)) ++IP;
387 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000388
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000389 // Initialize the map pointer and load the current head of the shadow stack.
390 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
391 Instruction *EntryMapPtr = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map");
392 AtEntry.CreateStore(FrameMap, EntryMapPtr);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000393
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000394 // After all the allocas...
395 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
396 // For each root, find the corresponding slot in the aggregate...
397 Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000398
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000399 // And use it in lieu of the alloca.
400 AllocaInst *OriginalAlloca = Roots[I].second;
401 SlotPtr->takeName(OriginalAlloca);
402 OriginalAlloca->replaceAllUsesWith(SlotPtr);
403 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000404
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000405 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
406 // really necessary (the collector would never see the intermediate state at
407 // runtime), but it's nicer not to push the half-initialized entry onto the
408 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000409 while (isa<StoreInst>(IP)) ++IP;
410 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000411
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000412 // Push the entry onto the shadow stack.
413 Instruction *EntryNextPtr = CreateGEP(AtEntry,StackEntry,0,0,"gc_frame.next");
414 Instruction *NewHeadVal = CreateGEP(AtEntry,StackEntry, 0, "gc_newhead");
415 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
416 AtEntry.CreateStore(NewHeadVal, Head);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000417
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000418 // For each instruction that escapes...
419 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000420 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000421 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
422 // AtEntry, since that would make the value live for the entire function.
423 Instruction *EntryNextPtr2 = CreateGEP(*AtExit, StackEntry, 0, 0,
424 "gc_frame.next");
425 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
426 AtExit->CreateStore(SavedHead, Head);
427 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000428
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000429 // Delete the original allocas (which are no longer used) and the intrinsic
430 // calls (which are no longer valid). Doing this last avoids invalidating
431 // iterators.
432 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
433 Roots[I].first->eraseFromParent();
434 Roots[I].second->eraseFromParent();
435 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000436
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000437 Roots.clear();
438 return true;
439}