blob: 0e6d4796e22ccfab8c454e581a8f5228a1be554f [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"
Duncan Sands89f6d882008-04-13 06:22:09 +000034#include "llvm/Support/IRBuilder.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000035
36using namespace llvm;
37
38namespace {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000039
Nick Lewycky6726b6d2009-10-25 06:33:48 +000040 class ShadowStackGC : public GCStrategy {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000041 /// RootChain - This is the global linked-list that contains the chain of GC
42 /// roots.
43 GlobalVariable *Head;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000044
Gordon Henriksen8fa89292008-01-07 01:30:53 +000045 /// StackEntryTy - Abstract type of a link in the shadow stack.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000046 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000047 const StructType *StackEntryTy;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000048
Gordon Henriksen8fa89292008-01-07 01:30:53 +000049 /// Roots - GC roots in the current function. Each is a pair of the
50 /// intrinsic call and its corresponding alloca.
51 std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000052
Gordon Henriksen8fa89292008-01-07 01:30:53 +000053 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000054 ShadowStackGC();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000055
Gordon Henriksen8fa89292008-01-07 01:30:53 +000056 bool initializeCustomLowering(Module &M);
57 bool performCustomLowering(Function &F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000058
Gordon Henriksen8fa89292008-01-07 01:30:53 +000059 private:
60 bool IsNullValue(Value *V);
61 Constant *GetFrameMap(Function &F);
62 const Type* GetConcreteStackEntryType(Function &F);
63 void CollectRoots(Function &F);
Owen Andersone922c022009-07-22 00:24:57 +000064 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000065 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000066 int Idx1, const char *Name);
Owen Andersone922c022009-07-22 00:24:57 +000067 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000068 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000069 int Idx1, int Idx2, const char *Name);
70 };
Dan Gohman844731a2008-05-13 00:00:25 +000071
72}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000073
Gordon Henriksen5eca0752008-08-17 18:44:35 +000074static GCRegistry::Add<ShadowStackGC>
75X("shadow-stack", "Very portable GC for uncooperative code generators");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000076
Dan Gohman844731a2008-05-13 00:00:25 +000077namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000078 /// EscapeEnumerator - This is a little algorithm to find all escape points
79 /// from a function so that "finally"-style code can be inserted. In addition
80 /// to finding the existing return and unwind instructions, it also (if
81 /// necessary) transforms any call instructions into invokes and sends them to
82 /// a landing pad.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000083 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000084 /// It's wrapped up in a state machine using the same transform C# uses for
85 /// 'yield return' enumerators, This transform allows it to be non-allocating.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000086 class EscapeEnumerator {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000087 Function &F;
88 const char *CleanupBBName;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000089
Gordon Henriksen8fa89292008-01-07 01:30:53 +000090 // State.
91 int State;
92 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000093 IRBuilder<> Builder;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000094
Gordon Henriksen8fa89292008-01-07 01:30:53 +000095 public:
96 EscapeEnumerator(Function &F, const char *N = "cleanup")
Owen Andersone922c022009-07-22 00:24:57 +000097 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000098
Eric Christopher7a61d702008-08-08 19:39:37 +000099 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000100 switch (State) {
101 default:
102 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000103
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000104 case 0:
105 StateBB = F.begin();
106 StateE = F.end();
107 State = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000108
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000109 case 1:
110 // Find all 'return' and 'unwind' instructions.
111 while (StateBB != StateE) {
112 BasicBlock *CurBB = StateBB++;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000113
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000114 // Branches and invokes do not escape, only unwind and return do.
115 TerminatorInst *TI = CurBB->getTerminator();
116 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
117 continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000118
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000119 Builder.SetInsertPoint(TI->getParent(), TI);
120 return &Builder;
121 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000122
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000123 State = 2;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000124
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000125 // Find all 'call' instructions.
126 SmallVector<Instruction*,16> Calls;
127 for (Function::iterator BB = F.begin(),
128 E = F.end(); BB != E; ++BB)
129 for (BasicBlock::iterator II = BB->begin(),
130 EE = BB->end(); II != EE; ++II)
131 if (CallInst *CI = dyn_cast<CallInst>(II))
132 if (!CI->getCalledFunction() ||
133 !CI->getCalledFunction()->getIntrinsicID())
134 Calls.push_back(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000135
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000136 if (Calls.empty())
137 return 0;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000138
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000139 // Create a cleanup block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000140 BasicBlock *CleanupBB = BasicBlock::Create(F.getContext(),
141 CleanupBBName, &F);
142 UnwindInst *UI = new UnwindInst(F.getContext(), CleanupBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000143
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000144 // Transform the 'call' instructions into 'invoke's branching to the
145 // cleanup block. Go in reverse order to make prettier BB names.
146 SmallVector<Value*,16> Args;
147 for (unsigned I = Calls.size(); I != 0; ) {
148 CallInst *CI = cast<CallInst>(Calls[--I]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000149
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000150 // Split the basic block containing the function call.
151 BasicBlock *CallBB = CI->getParent();
152 BasicBlock *NewBB =
153 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000154
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000155 // Remove the unconditional branch inserted at the end of CallBB.
156 CallBB->getInstList().pop_back();
157 NewBB->getInstList().remove(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000158
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000159 // Create a new invoke instruction.
160 Args.clear();
161 Args.append(CI->op_begin() + 1, CI->op_end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000162
Gabor Greif051a9502008-04-06 20:25:17 +0000163 InvokeInst *II = InvokeInst::Create(CI->getOperand(0),
164 NewBB, CleanupBB,
165 Args.begin(), Args.end(),
166 CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000167 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000168 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000169 CI->replaceAllUsesWith(II);
170 delete CI;
171 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000172
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000173 Builder.SetInsertPoint(UI->getParent(), UI);
174 return &Builder;
175 }
176 }
177 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000178}
179
180// -----------------------------------------------------------------------------
181
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000182void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000183
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000184ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000185 InitRoots = true;
186 CustomRoots = true;
187}
188
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000189Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000190 // doInitialization creates the abstract type of this value.
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000191 const Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000192
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000193 // Truncate the ShadowStackDescriptor if some metadata is null.
194 unsigned NumMeta = 0;
195 SmallVector<Constant*,16> Metadata;
196 for (unsigned I = 0; I != Roots.size(); ++I) {
197 Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
198 if (!C->isNullValue())
199 NumMeta = I + 1;
200 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
201 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000202
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000203 Constant *BaseElts[] = {
Owen Anderson1d0be152009-08-13 21:58:54 +0000204 ConstantInt::get(Type::getInt32Ty(F.getContext()), Roots.size(), false),
205 ConstantInt::get(Type::getInt32Ty(F.getContext()), NumMeta, false),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000206 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000207
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000208 Constant *DescriptorElts[] = {
Nick Lewyckyc332fba2009-09-19 20:30:26 +0000209 ConstantStruct::get(F.getContext(), BaseElts, 2, false),
Owen Andersondebcb012009-07-29 22:17:13 +0000210 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000211 Metadata.begin(), NumMeta)
212 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000213
Nick Lewyckyc332fba2009-09-19 20:30:26 +0000214 Constant *FrameMap = ConstantStruct::get(F.getContext(), DescriptorElts, 2,
215 false);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000216
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000217 std::string TypeName("gc_map.");
218 TypeName += utostr(NumMeta);
219 F.getParent()->addTypeName(TypeName, FrameMap->getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000220
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000221 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
222 // that, short of multithreaded LLVM, it should be safe; all that is
223 // necessary is that a simple Module::iterator loop not be invalidated.
224 // Appending to the GlobalVariable list is safe in that sense.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000225 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000226 // All of the output passes emit globals last. The ExecutionEngine
227 // explicitly supports adding globals to the module after
228 // initialization.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000230 // Still, if it isn't deemed acceptable, then this transformation needs
231 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
232 // (which uses a FunctionPassManager (which segfaults (not asserts) if
233 // provided a ModulePass))).
Owen Andersone9b11b42009-07-08 19:03:57 +0000234 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000235 GlobalVariable::InternalLinkage,
Owen Andersone9b11b42009-07-08 19:03:57 +0000236 FrameMap, "__gc_" + F.getName());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000237
Owen Anderson1d0be152009-08-13 21:58:54 +0000238 Constant *GEPIndices[2] = {
239 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
240 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
241 };
Owen Andersonbaf3c402009-07-29 18:55:55 +0000242 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000243}
244
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000245const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000246 // doInitialization creates the generic version of this type.
247 std::vector<const Type*> EltTys;
248 EltTys.push_back(StackEntryTy);
249 for (size_t I = 0; I != Roots.size(); I++)
250 EltTys.push_back(Roots[I].second->getAllocatedType());
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000251 Type *Ty = StructType::get(F.getContext(), EltTys);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000252
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000253 std::string TypeName("gc_stackentry.");
254 TypeName += F.getName();
255 F.getParent()->addTypeName(TypeName, Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000256
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000257 return Ty;
258}
259
260/// doInitialization - If this module uses the GC intrinsics, find them now. If
261/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000262bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000263 // struct FrameMap {
264 // int32_t NumRoots; // Number of roots in stack frame.
265 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
266 // void *Meta[]; // May be absent for roots without metadata.
267 // };
268 std::vector<const Type*> EltTys;
Owen Anderson1d0be152009-08-13 21:58:54 +0000269 // 32 bits is ok up to a 32GB stack frame. :)
270 EltTys.push_back(Type::getInt32Ty(M.getContext()));
271 // Specifies length of variable length array.
272 EltTys.push_back(Type::getInt32Ty(M.getContext()));
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000273 StructType *FrameMapTy = StructType::get(M.getContext(), EltTys);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000274 M.addTypeName("gc_map", FrameMapTy);
275 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000276
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000277 // struct StackEntry {
278 // ShadowStackEntry *Next; // Caller's stack entry.
279 // FrameMap *Map; // Pointer to constant FrameMap.
280 // void *Roots[]; // Stack roots (in-place array, so we pretend).
281 // };
Owen Anderson0e275dc2009-08-13 23:27:32 +0000282 OpaqueType *RecursiveTy = OpaqueType::get(M.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000283
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000284 EltTys.clear();
285 EltTys.push_back(PointerType::getUnqual(RecursiveTy));
286 EltTys.push_back(FrameMapPtrTy);
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000287 PATypeHolder LinkTyH = StructType::get(M.getContext(), EltTys);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000288
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000289 RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
290 StackEntryTy = cast<StructType>(LinkTyH.get());
291 const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
292 M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from
293 // a FunctionPass?
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000294
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000295 // Get the root chain if it already exists.
296 Head = M.getGlobalVariable("llvm_gc_root_chain");
297 if (!Head) {
298 // If the root chain does not exist, insert a new one with linkonce
299 // linkage!
Owen Andersone9b11b42009-07-08 19:03:57 +0000300 Head = new GlobalVariable(M, StackEntryPtrTy, false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000301 GlobalValue::LinkOnceAnyLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +0000302 Constant::getNullValue(StackEntryPtrTy),
Owen Andersone9b11b42009-07-08 19:03:57 +0000303 "llvm_gc_root_chain");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000304 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000305 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Duncan Sands667d4b82009-03-07 15:45:40 +0000306 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000307 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000308
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000309 return true;
310}
311
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000312bool ShadowStackGC::IsNullValue(Value *V) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000313 if (Constant *C = dyn_cast<Constant>(V))
314 return C->isNullValue();
315 return false;
316}
317
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000318void ShadowStackGC::CollectRoots(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000319 // FIXME: Account for original alignment. Could fragment the root array.
320 // Approach 1: Null initialize empty slots at runtime. Yuck.
321 // Approach 2: Emit a map of the array instead of just a count.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000322
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000323 assert(Roots.empty() && "Not cleaned up?");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000324
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000325 SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000326
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000327 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
328 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
329 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
330 if (Function *F = CI->getCalledFunction())
331 if (F->getIntrinsicID() == Intrinsic::gcroot) {
332 std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000333 CI, cast<AllocaInst>(CI->getOperand(1)->stripPointerCasts()));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000334 if (IsNullValue(CI->getOperand(2)))
335 Roots.push_back(Pair);
336 else
337 MetaRoots.push_back(Pair);
338 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000339
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000340 // Number roots with metadata (usually empty) at the beginning, so that the
341 // FrameMap::Meta array can be elided.
342 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
343}
344
345GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000346ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000347 int Idx, int Idx2, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000348 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
349 ConstantInt::get(Type::getInt32Ty(Context), Idx),
350 ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000351 Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000352
Duncan Sands89f6d882008-04-13 06:22:09 +0000353 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000354
Duncan Sands89f6d882008-04-13 06:22:09 +0000355 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000356}
357
358GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000359ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000360 int Idx, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000361 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
362 ConstantInt::get(Type::getInt32Ty(Context), Idx) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000363 Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000364
Duncan Sands89f6d882008-04-13 06:22:09 +0000365 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
366
367 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000368}
369
370/// runOnFunction - Insert code to maintain the shadow stack.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000371bool ShadowStackGC::performCustomLowering(Function &F) {
Owen Andersone922c022009-07-22 00:24:57 +0000372 LLVMContext &Context = F.getContext();
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000373
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000374 // Find calls to llvm.gcroot.
375 CollectRoots(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000376
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000377 // If there are no roots in this function, then there is no need to add a
378 // stack map entry for it.
379 if (Roots.empty())
380 return false;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000381
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000382 // Build the constant map and figure the type of the shadow stack entry.
383 Value *FrameMap = GetFrameMap(F);
384 const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000385
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000386 // Build the shadow stack entry at the very start of the function.
387 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000388 IRBuilder<> AtEntry(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000389
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000390 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
391 "gc_frame");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000392
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000393 while (isa<AllocaInst>(IP)) ++IP;
394 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000395
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000396 // Initialize the map pointer and load the current head of the shadow stack.
397 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000398 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
399 0,1,"gc_frame.map");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000400 AtEntry.CreateStore(FrameMap, EntryMapPtr);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000401
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000402 // After all the allocas...
403 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
404 // For each root, find the corresponding slot in the aggregate...
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000405 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000406
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000407 // And use it in lieu of the alloca.
408 AllocaInst *OriginalAlloca = Roots[I].second;
409 SlotPtr->takeName(OriginalAlloca);
410 OriginalAlloca->replaceAllUsesWith(SlotPtr);
411 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000412
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000413 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
414 // really necessary (the collector would never see the intermediate state at
415 // runtime), but it's nicer not to push the half-initialized entry onto the
416 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000417 while (isa<StoreInst>(IP)) ++IP;
418 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000419
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000420 // Push the entry onto the shadow stack.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000421 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
422 StackEntry,0,0,"gc_frame.next");
423 Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
424 StackEntry, 0, "gc_newhead");
425 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
426 AtEntry.CreateStore(NewHeadVal, Head);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000427
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000428 // For each instruction that escapes...
429 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000430 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000431 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
432 // AtEntry, since that would make the value live for the entire function.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000433 Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000434 "gc_frame.next");
435 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
436 AtExit->CreateStore(SavedHead, Head);
437 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000438
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000439 // Delete the original allocas (which are no longer used) and the intrinsic
440 // calls (which are no longer valid). Doing this last avoids invalidating
441 // iterators.
442 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
443 Roots[I].first->eraseFromParent();
444 Roots[I].second->eraseFromParent();
445 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000446
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000447 Roots.clear();
448 return true;
449}