blob: bccb3b9927a03cec9e138ad02e7a73d8922e9e26 [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"
Gabor Greif89c4cea2010-06-25 08:48:19 +000034#include "llvm/Support/CallSite.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
Nick Lewycky6726b6d2009-10-25 06:33:48 +000041 class 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 ///
Chris Lattner1afcace2011-07-09 17:41:24 +000048 StructType *StackEntryTy;
49 StructType *FrameMapTy;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000050
Gordon Henriksen8fa89292008-01-07 01:30:53 +000051 /// Roots - GC roots in the current function. Each is a pair of the
52 /// intrinsic call and its corresponding alloca.
53 std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000054
Gordon Henriksen8fa89292008-01-07 01:30:53 +000055 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000056 ShadowStackGC();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000057
Gordon Henriksen8fa89292008-01-07 01:30:53 +000058 bool initializeCustomLowering(Module &M);
59 bool performCustomLowering(Function &F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000060
Gordon Henriksen8fa89292008-01-07 01:30:53 +000061 private:
62 bool IsNullValue(Value *V);
63 Constant *GetFrameMap(Function &F);
Chris Lattnerdb125cf2011-07-18 04:54:35 +000064 Type* GetConcreteStackEntryType(Function &F);
Gordon Henriksen8fa89292008-01-07 01:30:53 +000065 void CollectRoots(Function &F);
Owen Andersone922c022009-07-22 00:24:57 +000066 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000067 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000068 int Idx1, const char *Name);
Owen Andersone922c022009-07-22 00:24:57 +000069 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000070 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000071 int Idx1, int Idx2, const char *Name);
72 };
Dan Gohman844731a2008-05-13 00:00:25 +000073
74}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000075
Gordon Henriksen5eca0752008-08-17 18:44:35 +000076static GCRegistry::Add<ShadowStackGC>
77X("shadow-stack", "Very portable GC for uncooperative code generators");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000078
Dan Gohman844731a2008-05-13 00:00:25 +000079namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000080 /// EscapeEnumerator - This is a little algorithm to find all escape points
81 /// from a function so that "finally"-style code can be inserted. In addition
82 /// to finding the existing return and unwind instructions, it also (if
83 /// necessary) transforms any call instructions into invokes and sends them to
84 /// a landing pad.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000085 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000086 /// It's wrapped up in a state machine using the same transform C# uses for
87 /// 'yield return' enumerators, This transform allows it to be non-allocating.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000088 class EscapeEnumerator {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000089 Function &F;
90 const char *CleanupBBName;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000091
Gordon Henriksen8fa89292008-01-07 01:30:53 +000092 // State.
93 int State;
94 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000095 IRBuilder<> Builder;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000096
Gordon Henriksen8fa89292008-01-07 01:30:53 +000097 public:
98 EscapeEnumerator(Function &F, const char *N = "cleanup")
Owen Andersone922c022009-07-22 00:24:57 +000099 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000100
Eric Christopher7a61d702008-08-08 19:39:37 +0000101 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000102 switch (State) {
103 default:
104 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000105
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000106 case 0:
107 StateBB = F.begin();
108 StateE = F.end();
109 State = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000110
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000111 case 1:
112 // Find all 'return' and 'unwind' instructions.
113 while (StateBB != StateE) {
114 BasicBlock *CurBB = StateBB++;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000115
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000116 // Branches and invokes do not escape, only unwind, resume, and return
117 // do.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000118 TerminatorInst *TI = CurBB->getTerminator();
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000119 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI) &&
120 !isa<ResumeInst>(TI))
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000121 continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000122
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000123 Builder.SetInsertPoint(TI->getParent(), TI);
124 return &Builder;
125 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000126
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000127 State = 2;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000128
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000129 // Find all 'call' instructions.
130 SmallVector<Instruction*,16> Calls;
131 for (Function::iterator BB = F.begin(),
132 E = F.end(); BB != E; ++BB)
133 for (BasicBlock::iterator II = BB->begin(),
134 EE = BB->end(); II != EE; ++II)
135 if (CallInst *CI = dyn_cast<CallInst>(II))
136 if (!CI->getCalledFunction() ||
137 !CI->getCalledFunction()->getIntrinsicID())
138 Calls.push_back(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000139
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000140 if (Calls.empty())
141 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000142
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000143 // Create a cleanup block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000144 BasicBlock *CleanupBB = BasicBlock::Create(F.getContext(),
145 CleanupBBName, &F);
146 UnwindInst *UI = new UnwindInst(F.getContext(), CleanupBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000147
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000148 // Transform the 'call' instructions into 'invoke's branching to the
149 // cleanup block. Go in reverse order to make prettier BB names.
150 SmallVector<Value*,16> Args;
151 for (unsigned I = Calls.size(); I != 0; ) {
152 CallInst *CI = cast<CallInst>(Calls[--I]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000153
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000154 // Split the basic block containing the function call.
155 BasicBlock *CallBB = CI->getParent();
156 BasicBlock *NewBB =
157 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000158
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000159 // Remove the unconditional branch inserted at the end of CallBB.
160 CallBB->getInstList().pop_back();
161 NewBB->getInstList().remove(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000162
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000163 // Create a new invoke instruction.
164 Args.clear();
Gabor Greif89c4cea2010-06-25 08:48:19 +0000165 CallSite CS(CI);
166 Args.append(CS.arg_begin(), CS.arg_end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000167
Gabor Greifa9b23132010-04-20 13:13:04 +0000168 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
Gabor Greif051a9502008-04-06 20:25:17 +0000169 NewBB, CleanupBB,
Jay Foada3efbb12011-07-15 08:37:34 +0000170 Args, CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000171 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000172 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000173 CI->replaceAllUsesWith(II);
174 delete CI;
175 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000176
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000177 Builder.SetInsertPoint(UI->getParent(), UI);
178 return &Builder;
179 }
180 }
181 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000182}
183
184// -----------------------------------------------------------------------------
185
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000186void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000187
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000188ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000189 InitRoots = true;
190 CustomRoots = true;
191}
192
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000193Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000194 // doInitialization creates the abstract type of this value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000195 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000196
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000197 // Truncate the ShadowStackDescriptor if some metadata is null.
198 unsigned NumMeta = 0;
Chris Lattnerb065b062011-06-20 04:01:31 +0000199 SmallVector<Constant*, 16> Metadata;
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000200 for (unsigned I = 0; I != Roots.size(); ++I) {
Gabor Greif89c4cea2010-06-25 08:48:19 +0000201 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000202 if (!C->isNullValue())
203 NumMeta = I + 1;
204 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
205 }
Jay Foad26701082011-06-22 09:24:39 +0000206 Metadata.resize(NumMeta);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000207
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000208 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Chris Lattnerb065b062011-06-20 04:01:31 +0000209
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000210 Constant *BaseElts[] = {
Chris Lattnerb065b062011-06-20 04:01:31 +0000211 ConstantInt::get(Int32Ty, Roots.size(), false),
212 ConstantInt::get(Int32Ty, NumMeta, false),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000213 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000214
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000215 Constant *DescriptorElts[] = {
Chris Lattner1afcace2011-07-09 17:41:24 +0000216 ConstantStruct::get(FrameMapTy, BaseElts),
Jay Foad26701082011-06-22 09:24:39 +0000217 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000218 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000219
Chris Lattner1afcace2011-07-09 17:41:24 +0000220 Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
Chris Lattner3ebb6492011-08-12 18:06:37 +0000221 StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
Chris Lattner1afcace2011-07-09 17:41:24 +0000222
223 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000224
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000225 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
226 // that, short of multithreaded LLVM, it should be safe; all that is
227 // necessary is that a simple Module::iterator loop not be invalidated.
228 // Appending to the GlobalVariable list is safe in that sense.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000230 // All of the output passes emit globals last. The ExecutionEngine
231 // explicitly supports adding globals to the module after
232 // initialization.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000233 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000234 // Still, if it isn't deemed acceptable, then this transformation needs
235 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
236 // (which uses a FunctionPassManager (which segfaults (not asserts) if
237 // provided a ModulePass))).
Owen Andersone9b11b42009-07-08 19:03:57 +0000238 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000239 GlobalVariable::InternalLinkage,
Owen Andersone9b11b42009-07-08 19:03:57 +0000240 FrameMap, "__gc_" + F.getName());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000241
Owen Anderson1d0be152009-08-13 21:58:54 +0000242 Constant *GEPIndices[2] = {
243 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
244 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
245 };
Jay Foadb4263a62011-07-22 08:52:50 +0000246 return ConstantExpr::getGetElementPtr(GV, GEPIndices);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000247}
248
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000249Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000250 // doInitialization creates the generic version of this type.
Chris Lattner1afcace2011-07-09 17:41:24 +0000251 std::vector<Type*> EltTys;
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000252 EltTys.push_back(StackEntryTy);
253 for (size_t I = 0; I != Roots.size(); I++)
254 EltTys.push_back(Roots[I].second->getAllocatedType());
Chris Lattner1afcace2011-07-09 17:41:24 +0000255
Chris Lattner3ebb6492011-08-12 18:06:37 +0000256 return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000257}
258
259/// doInitialization - If this module uses the GC intrinsics, find them now. If
260/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000261bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000262 // struct FrameMap {
263 // int32_t NumRoots; // Number of roots in stack frame.
264 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
265 // void *Meta[]; // May be absent for roots without metadata.
266 // };
Chris Lattner1afcace2011-07-09 17:41:24 +0000267 std::vector<Type*> EltTys;
Owen Anderson1d0be152009-08-13 21:58:54 +0000268 // 32 bits is ok up to a 32GB stack frame. :)
269 EltTys.push_back(Type::getInt32Ty(M.getContext()));
270 // Specifies length of variable length array.
271 EltTys.push_back(Type::getInt32Ty(M.getContext()));
Chris Lattner3ebb6492011-08-12 18:06:37 +0000272 FrameMapTy = StructType::create(EltTys, "gc_map");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000273 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000274
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000275 // struct StackEntry {
276 // ShadowStackEntry *Next; // Caller's stack entry.
277 // FrameMap *Map; // Pointer to constant FrameMap.
278 // void *Roots[]; // Stack roots (in-place array, so we pretend).
279 // };
Chris Lattner1afcace2011-07-09 17:41:24 +0000280
Chris Lattner3ebb6492011-08-12 18:06:37 +0000281 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
Chris Lattner1afcace2011-07-09 17:41:24 +0000282
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000283 EltTys.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000284 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000285 EltTys.push_back(FrameMapPtrTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000286 StackEntryTy->setBody(EltTys);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000287 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000288
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000289 // Get the root chain if it already exists.
290 Head = M.getGlobalVariable("llvm_gc_root_chain");
291 if (!Head) {
292 // If the root chain does not exist, insert a new one with linkonce
293 // linkage!
Owen Andersone9b11b42009-07-08 19:03:57 +0000294 Head = new GlobalVariable(M, StackEntryPtrTy, false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000295 GlobalValue::LinkOnceAnyLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +0000296 Constant::getNullValue(StackEntryPtrTy),
Owen Andersone9b11b42009-07-08 19:03:57 +0000297 "llvm_gc_root_chain");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000298 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000299 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Duncan Sands667d4b82009-03-07 15:45:40 +0000300 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000301 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000302
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000303 return true;
304}
305
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000306bool ShadowStackGC::IsNullValue(Value *V) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000307 if (Constant *C = dyn_cast<Constant>(V))
308 return C->isNullValue();
309 return false;
310}
311
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000312void ShadowStackGC::CollectRoots(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000313 // FIXME: Account for original alignment. Could fragment the root array.
314 // Approach 1: Null initialize empty slots at runtime. Yuck.
315 // Approach 2: Emit a map of the array instead of just a count.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000316
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000317 assert(Roots.empty() && "Not cleaned up?");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000318
Gabor Greif89c4cea2010-06-25 08:48:19 +0000319 SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000320
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000321 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
322 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
323 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
324 if (Function *F = CI->getCalledFunction())
325 if (F->getIntrinsicID() == Intrinsic::gcroot) {
Gabor Greif89c4cea2010-06-25 08:48:19 +0000326 std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
327 CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
328 if (IsNullValue(CI->getArgOperand(1)))
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000329 Roots.push_back(Pair);
330 else
331 MetaRoots.push_back(Pair);
332 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000333
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000334 // Number roots with metadata (usually empty) at the beginning, so that the
335 // FrameMap::Meta array can be elided.
336 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
337}
338
339GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000340ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000341 int Idx, int Idx2, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000342 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
343 ConstantInt::get(Type::getInt32Ty(Context), Idx),
344 ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
Jay Foad0a2a60a2011-07-22 08:16:57 +0000345 Value* Val = B.CreateGEP(BasePtr, Indices, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000346
Duncan Sands89f6d882008-04-13 06:22:09 +0000347 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000348
Duncan Sands89f6d882008-04-13 06:22:09 +0000349 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000350}
351
352GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000353ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000354 int Idx, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000355 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
356 ConstantInt::get(Type::getInt32Ty(Context), Idx) };
Jay Foad0a2a60a2011-07-22 08:16:57 +0000357 Value *Val = B.CreateGEP(BasePtr, Indices, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000358
Duncan Sands89f6d882008-04-13 06:22:09 +0000359 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
360
361 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000362}
363
364/// runOnFunction - Insert code to maintain the shadow stack.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000365bool ShadowStackGC::performCustomLowering(Function &F) {
Owen Andersone922c022009-07-22 00:24:57 +0000366 LLVMContext &Context = F.getContext();
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000367
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000368 // Find calls to llvm.gcroot.
369 CollectRoots(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000370
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000371 // If there are no roots in this function, then there is no need to add a
372 // stack map entry for it.
373 if (Roots.empty())
374 return false;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000375
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000376 // Build the constant map and figure the type of the shadow stack entry.
377 Value *FrameMap = GetFrameMap(F);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000378 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000379
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000380 // Build the shadow stack entry at the very start of the function.
381 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000382 IRBuilder<> AtEntry(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000383
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000384 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
385 "gc_frame");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000386
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000387 while (isa<AllocaInst>(IP)) ++IP;
388 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000389
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000390 // Initialize the map pointer and load the current head of the shadow stack.
391 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000392 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
393 0,1,"gc_frame.map");
Chris Lattner1afcace2011-07-09 17:41:24 +0000394 AtEntry.CreateStore(FrameMap, EntryMapPtr);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000395
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000396 // After all the allocas...
397 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
398 // For each root, find the corresponding slot in the aggregate...
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000399 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000400
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000401 // And use it in lieu of the alloca.
402 AllocaInst *OriginalAlloca = Roots[I].second;
403 SlotPtr->takeName(OriginalAlloca);
404 OriginalAlloca->replaceAllUsesWith(SlotPtr);
405 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000406
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000407 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
408 // really necessary (the collector would never see the intermediate state at
409 // runtime), but it's nicer not to push the half-initialized entry onto the
410 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000411 while (isa<StoreInst>(IP)) ++IP;
412 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000413
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000414 // Push the entry onto the shadow stack.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000415 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
416 StackEntry,0,0,"gc_frame.next");
417 Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
418 StackEntry, 0, "gc_newhead");
419 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
420 AtEntry.CreateStore(NewHeadVal, Head);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000421
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000422 // For each instruction that escapes...
423 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000424 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000425 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
426 // AtEntry, since that would make the value live for the entire function.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000427 Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000428 "gc_frame.next");
429 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
430 AtExit->CreateStore(SavedHead, Head);
431 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000432
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000433 // Delete the original allocas (which are no longer used) and the intrinsic
434 // calls (which are no longer valid). Doing this last avoids invalidating
435 // iterators.
436 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
437 Roots[I].first->eraseFromParent();
438 Roots[I].second->eraseFromParent();
439 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000440
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000441 Roots.clear();
442 return true;
443}