blob: 0576228bd23b52f5cddfdb0e7593247e4b3b332c [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 {
39
Gordon Henriksen5eca0752008-08-17 18:44:35 +000040 class VISIBILITY_HIDDEN 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;
44
45 /// StackEntryTy - Abstract type of a link in the shadow stack.
46 ///
47 const StructType *StackEntryTy;
48
49 /// 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;
52
53 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000054 ShadowStackGC();
Gordon Henriksen8fa89292008-01-07 01:30:53 +000055
56 bool initializeCustomLowering(Module &M);
57 bool performCustomLowering(Function &F);
58
59 private:
60 bool IsNullValue(Value *V);
61 Constant *GetFrameMap(Function &F);
62 const Type* GetConcreteStackEntryType(Function &F);
63 void CollectRoots(Function &F);
Eric Christopher7a61d702008-08-08 19:39:37 +000064 static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000065 int Idx1, const char *Name);
Eric Christopher7a61d702008-08-08 19:39:37 +000066 static GetElementPtrInst *CreateGEP(IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000067 int Idx1, int Idx2, const char *Name);
68 };
Dan Gohman844731a2008-05-13 00:00:25 +000069
70}
Gordon Henriksen8fa89292008-01-07 01:30:53 +000071
Gordon Henriksen5eca0752008-08-17 18:44:35 +000072static GCRegistry::Add<ShadowStackGC>
73X("shadow-stack", "Very portable GC for uncooperative code generators");
Gordon Henriksen8fa89292008-01-07 01:30:53 +000074
Dan Gohman844731a2008-05-13 00:00:25 +000075namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000076 /// EscapeEnumerator - This is a little algorithm to find all escape points
77 /// from a function so that "finally"-style code can be inserted. In addition
78 /// to finding the existing return and unwind instructions, it also (if
79 /// necessary) transforms any call instructions into invokes and sends them to
80 /// a landing pad.
81 ///
82 /// It's wrapped up in a state machine using the same transform C# uses for
83 /// 'yield return' enumerators, This transform allows it to be non-allocating.
84 class VISIBILITY_HIDDEN EscapeEnumerator {
85 Function &F;
86 const char *CleanupBBName;
87
88 // State.
89 int State;
90 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000091 IRBuilder<> Builder;
Gordon Henriksen8fa89292008-01-07 01:30:53 +000092
93 public:
94 EscapeEnumerator(Function &F, const char *N = "cleanup")
95 : F(F), CleanupBBName(N), State(0) {}
96
Eric Christopher7a61d702008-08-08 19:39:37 +000097 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000098 switch (State) {
99 default:
100 return 0;
101
102 case 0:
103 StateBB = F.begin();
104 StateE = F.end();
105 State = 1;
106
107 case 1:
108 // Find all 'return' and 'unwind' instructions.
109 while (StateBB != StateE) {
110 BasicBlock *CurBB = StateBB++;
111
112 // Branches and invokes do not escape, only unwind and return do.
113 TerminatorInst *TI = CurBB->getTerminator();
114 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
115 continue;
116
117 Builder.SetInsertPoint(TI->getParent(), TI);
118 return &Builder;
119 }
120
121 State = 2;
122
123 // Find all 'call' instructions.
124 SmallVector<Instruction*,16> Calls;
125 for (Function::iterator BB = F.begin(),
126 E = F.end(); BB != E; ++BB)
127 for (BasicBlock::iterator II = BB->begin(),
128 EE = BB->end(); II != EE; ++II)
129 if (CallInst *CI = dyn_cast<CallInst>(II))
130 if (!CI->getCalledFunction() ||
131 !CI->getCalledFunction()->getIntrinsicID())
132 Calls.push_back(CI);
133
134 if (Calls.empty())
135 return 0;
136
137 // Create a cleanup block.
Gabor Greif051a9502008-04-06 20:25:17 +0000138 BasicBlock *CleanupBB = BasicBlock::Create(CleanupBBName, &F);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000139 UnwindInst *UI = new UnwindInst(CleanupBB);
140
141 // Transform the 'call' instructions into 'invoke's branching to the
142 // cleanup block. Go in reverse order to make prettier BB names.
143 SmallVector<Value*,16> Args;
144 for (unsigned I = Calls.size(); I != 0; ) {
145 CallInst *CI = cast<CallInst>(Calls[--I]);
146
147 // Split the basic block containing the function call.
148 BasicBlock *CallBB = CI->getParent();
149 BasicBlock *NewBB =
150 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
151
152 // Remove the unconditional branch inserted at the end of CallBB.
153 CallBB->getInstList().pop_back();
154 NewBB->getInstList().remove(CI);
155
156 // Create a new invoke instruction.
157 Args.clear();
158 Args.append(CI->op_begin() + 1, CI->op_end());
159
Gabor Greif051a9502008-04-06 20:25:17 +0000160 InvokeInst *II = InvokeInst::Create(CI->getOperand(0),
161 NewBB, CleanupBB,
162 Args.begin(), Args.end(),
163 CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000164 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000165 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000166 CI->replaceAllUsesWith(II);
167 delete CI;
168 }
169
170 Builder.SetInsertPoint(UI->getParent(), UI);
171 return &Builder;
172 }
173 }
174 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000175}
176
177// -----------------------------------------------------------------------------
178
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000179void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000180
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000181ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000182 InitRoots = true;
183 CustomRoots = true;
184}
185
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000186Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000187 // doInitialization creates the abstract type of this value.
188
189 Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
190
191 // Truncate the ShadowStackDescriptor if some metadata is null.
192 unsigned NumMeta = 0;
193 SmallVector<Constant*,16> Metadata;
194 for (unsigned I = 0; I != Roots.size(); ++I) {
195 Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
196 if (!C->isNullValue())
197 NumMeta = I + 1;
198 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
199 }
200
201 Constant *BaseElts[] = {
202 ConstantInt::get(Type::Int32Ty, Roots.size(), false),
203 ConstantInt::get(Type::Int32Ty, NumMeta, false),
204 };
205
206 Constant *DescriptorElts[] = {
207 ConstantStruct::get(BaseElts, 2),
208 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
209 Metadata.begin(), NumMeta)
210 };
211
212 Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2);
213
214 std::string TypeName("gc_map.");
215 TypeName += utostr(NumMeta);
216 F.getParent()->addTypeName(TypeName, FrameMap->getType());
217
218 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
219 // that, short of multithreaded LLVM, it should be safe; all that is
220 // necessary is that a simple Module::iterator loop not be invalidated.
221 // Appending to the GlobalVariable list is safe in that sense.
222 //
223 // All of the output passes emit globals last. The ExecutionEngine
224 // explicitly supports adding globals to the module after
225 // initialization.
226 //
227 // Still, if it isn't deemed acceptable, then this transformation needs
228 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
229 // (which uses a FunctionPassManager (which segfaults (not asserts) if
230 // provided a ModulePass))).
231 Constant *GV = new GlobalVariable(FrameMap->getType(), true,
232 GlobalVariable::InternalLinkage,
233 FrameMap, "__gc_" + F.getName(),
234 F.getParent());
235
236 Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0),
237 ConstantInt::get(Type::Int32Ty, 0) };
238 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
239}
240
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000241const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000242 // doInitialization creates the generic version of this type.
243 std::vector<const Type*> EltTys;
244 EltTys.push_back(StackEntryTy);
245 for (size_t I = 0; I != Roots.size(); I++)
246 EltTys.push_back(Roots[I].second->getAllocatedType());
247 Type *Ty = StructType::get(EltTys);
248
249 std::string TypeName("gc_stackentry.");
250 TypeName += F.getName();
251 F.getParent()->addTypeName(TypeName, Ty);
252
253 return Ty;
254}
255
256/// doInitialization - If this module uses the GC intrinsics, find them now. If
257/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000258bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000259 // struct FrameMap {
260 // int32_t NumRoots; // Number of roots in stack frame.
261 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
262 // void *Meta[]; // May be absent for roots without metadata.
263 // };
264 std::vector<const Type*> EltTys;
265 EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :)
266 EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array.
267 StructType *FrameMapTy = StructType::get(EltTys);
268 M.addTypeName("gc_map", FrameMapTy);
269 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
270
271 // struct StackEntry {
272 // ShadowStackEntry *Next; // Caller's stack entry.
273 // FrameMap *Map; // Pointer to constant FrameMap.
274 // void *Roots[]; // Stack roots (in-place array, so we pretend).
275 // };
276 OpaqueType *RecursiveTy = OpaqueType::get();
277
278 EltTys.clear();
279 EltTys.push_back(PointerType::getUnqual(RecursiveTy));
280 EltTys.push_back(FrameMapPtrTy);
281 PATypeHolder LinkTyH = StructType::get(EltTys);
282
283 RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
284 StackEntryTy = cast<StructType>(LinkTyH.get());
285 const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
286 M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from
287 // a FunctionPass?
288
289 // 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!
294 Head = new GlobalVariable(StackEntryPtrTy, false,
295 GlobalValue::LinkOnceLinkage,
296 Constant::getNullValue(StackEntryPtrTy),
297 "llvm_gc_root_chain", &M);
298 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
299 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
300 Head->setLinkage(GlobalValue::LinkOnceLinkage);
301 }
302
303 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.
316
317 assert(Roots.empty() && "Not cleaned up?");
318
319 SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
320
321 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) {
326 std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000327 CI, cast<AllocaInst>(CI->getOperand(1)->stripPointerCasts()));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000328 if (IsNullValue(CI->getOperand(2)))
329 Roots.push_back(Pair);
330 else
331 MetaRoots.push_back(Pair);
332 }
333
334 // 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 *
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000340ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
341 int Idx, int Idx2, const char *Name) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000342 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
343 ConstantInt::get(Type::Int32Ty, Idx),
344 ConstantInt::get(Type::Int32Ty, Idx2) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000345 Value* Val = B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
346
347 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
348
349 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000350}
351
352GetElementPtrInst *
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000353ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
354 int Idx, const char *Name) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000355 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
356 ConstantInt::get(Type::Int32Ty, Idx) };
Duncan Sands89f6d882008-04-13 06:22:09 +0000357 Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
358
359 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) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000366 // Find calls to llvm.gcroot.
367 CollectRoots(F);
368
369 // If there are no roots in this function, then there is no need to add a
370 // stack map entry for it.
371 if (Roots.empty())
372 return false;
373
374 // Build the constant map and figure the type of the shadow stack entry.
375 Value *FrameMap = GetFrameMap(F);
376 const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
377
378 // Build the shadow stack entry at the very start of the function.
379 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000380 IRBuilder<> AtEntry(IP->getParent(), IP);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000381
382 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
383 "gc_frame");
384
385 while (isa<AllocaInst>(IP)) ++IP;
386 AtEntry.SetInsertPoint(IP->getParent(), IP);
387
388 // Initialize the map pointer and load the current head of the shadow stack.
389 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
390 Instruction *EntryMapPtr = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map");
391 AtEntry.CreateStore(FrameMap, EntryMapPtr);
392
393 // After all the allocas...
394 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
395 // For each root, find the corresponding slot in the aggregate...
396 Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root");
397
398 // And use it in lieu of the alloca.
399 AllocaInst *OriginalAlloca = Roots[I].second;
400 SlotPtr->takeName(OriginalAlloca);
401 OriginalAlloca->replaceAllUsesWith(SlotPtr);
402 }
403
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000404 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
405 // really necessary (the collector would never see the intermediate state at
406 // runtime), but it's nicer not to push the half-initialized entry onto the
407 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000408 while (isa<StoreInst>(IP)) ++IP;
409 AtEntry.SetInsertPoint(IP->getParent(), IP);
410
411 // Push the entry onto the shadow stack.
412 Instruction *EntryNextPtr = CreateGEP(AtEntry,StackEntry,0,0,"gc_frame.next");
413 Instruction *NewHeadVal = CreateGEP(AtEntry,StackEntry, 0, "gc_newhead");
414 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
415 AtEntry.CreateStore(NewHeadVal, Head);
416
417 // For each instruction that escapes...
418 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000419 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000420 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
421 // AtEntry, since that would make the value live for the entire function.
422 Instruction *EntryNextPtr2 = CreateGEP(*AtExit, StackEntry, 0, 0,
423 "gc_frame.next");
424 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
425 AtExit->CreateStore(SavedHead, Head);
426 }
427
428 // Delete the original allocas (which are no longer used) and the intrinsic
429 // calls (which are no longer valid). Doing this last avoids invalidating
430 // iterators.
431 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
432 Roots[I].first->eraseFromParent();
433 Roots[I].second->eraseFromParent();
434 }
435
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000436 Roots.clear();
437 return true;
438}