blob: 1b619c966808b1b5c8803f38727e5e1519d73959 [file] [log] [blame]
Gordon Henriksen8fa89292008-01-07 01:30:53 +00001//===-- ShadowStackCollector.cpp - GC support for uncooperative targets ---===//
2//
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
12// generated is not quite as efficient as collectors which generate stack maps
13// 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
20// this collector.
21//
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"
29#include "llvm/CodeGen/Collectors.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/CodeGen/Collector.h"
33#include "llvm/Constants.h"
34#include "llvm/DerivedTypes.h"
35#include "llvm/Instructions.h"
36#include "llvm/IntrinsicInst.h"
37#include "llvm/Module.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/Compiler.h"
40#include "llvm/Support/LLVMBuilder.h"
41#include "llvm/Analysis/Verifier.h"
42#include <cstdlib>
43
44using namespace llvm;
45
46namespace {
47
48 class VISIBILITY_HIDDEN ShadowStackCollector : public Collector {
49 /// RootChain - This is the global linked-list that contains the chain of GC
50 /// roots.
51 GlobalVariable *Head;
52
53 /// StackEntryTy - Abstract type of a link in the shadow stack.
54 ///
55 const StructType *StackEntryTy;
56
57 /// Roots - GC roots in the current function. Each is a pair of the
58 /// intrinsic call and its corresponding alloca.
59 std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
60
61 public:
62 ShadowStackCollector();
63
64 bool initializeCustomLowering(Module &M);
65 bool performCustomLowering(Function &F);
66
67 private:
68 bool IsNullValue(Value *V);
69 Constant *GetFrameMap(Function &F);
70 const Type* GetConcreteStackEntryType(Function &F);
71 void CollectRoots(Function &F);
72 static GetElementPtrInst *CreateGEP(LLVMBuilder &B, Value *BasePtr,
73 int Idx1, const char *Name);
74 static GetElementPtrInst *CreateGEP(LLVMBuilder &B, Value *BasePtr,
75 int Idx1, int Idx2, const char *Name);
76 };
77
78 CollectorRegistry::Add<ShadowStackCollector>
79 Y("shadow-stack",
80 "Very portable collector for uncooperative code generators");
81
82 /// EscapeEnumerator - This is a little algorithm to find all escape points
83 /// from a function so that "finally"-style code can be inserted. In addition
84 /// to finding the existing return and unwind instructions, it also (if
85 /// necessary) transforms any call instructions into invokes and sends them to
86 /// a landing pad.
87 ///
88 /// It's wrapped up in a state machine using the same transform C# uses for
89 /// 'yield return' enumerators, This transform allows it to be non-allocating.
90 class VISIBILITY_HIDDEN EscapeEnumerator {
91 Function &F;
92 const char *CleanupBBName;
93
94 // State.
95 int State;
96 Function::iterator StateBB, StateE;
97 LLVMBuilder Builder;
98
99 public:
100 EscapeEnumerator(Function &F, const char *N = "cleanup")
101 : F(F), CleanupBBName(N), State(0) {}
102
103 LLVMBuilder *Next() {
104 switch (State) {
105 default:
106 return 0;
107
108 case 0:
109 StateBB = F.begin();
110 StateE = F.end();
111 State = 1;
112
113 case 1:
114 // Find all 'return' and 'unwind' instructions.
115 while (StateBB != StateE) {
116 BasicBlock *CurBB = StateBB++;
117
118 // Branches and invokes do not escape, only unwind and return do.
119 TerminatorInst *TI = CurBB->getTerminator();
120 if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI))
121 continue;
122
123 Builder.SetInsertPoint(TI->getParent(), TI);
124 return &Builder;
125 }
126
127 State = 2;
128
129 // 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);
139
140 if (Calls.empty())
141 return 0;
142
143 // Create a cleanup block.
144 BasicBlock *CleanupBB = new BasicBlock(CleanupBBName, &F);
145 UnwindInst *UI = new UnwindInst(CleanupBB);
146
147 // Transform the 'call' instructions into 'invoke's branching to the
148 // cleanup block. Go in reverse order to make prettier BB names.
149 SmallVector<Value*,16> Args;
150 for (unsigned I = Calls.size(); I != 0; ) {
151 CallInst *CI = cast<CallInst>(Calls[--I]);
152
153 // Split the basic block containing the function call.
154 BasicBlock *CallBB = CI->getParent();
155 BasicBlock *NewBB =
156 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
157
158 // Remove the unconditional branch inserted at the end of CallBB.
159 CallBB->getInstList().pop_back();
160 NewBB->getInstList().remove(CI);
161
162 // Create a new invoke instruction.
163 Args.clear();
164 Args.append(CI->op_begin() + 1, CI->op_end());
165
166 InvokeInst *II = new InvokeInst(CI->getOperand(0),
167 NewBB, CleanupBB,
168 Args.begin(), Args.end(),
169 CI->getName(), CallBB);
170 II->setCallingConv(CI->getCallingConv());
171 II->setParamAttrs(CI->getParamAttrs());
172 CI->replaceAllUsesWith(II);
173 delete CI;
174 }
175
176 Builder.SetInsertPoint(UI->getParent(), UI);
177 return &Builder;
178 }
179 }
180 };
181
182}
183
184// -----------------------------------------------------------------------------
185
186Collector *llvm::createShadowStackCollector() {
187 return new ShadowStackCollector();
188}
189
190ShadowStackCollector::ShadowStackCollector() : Head(0), StackEntryTy(0) {
191 InitRoots = true;
192 CustomRoots = true;
193}
194
195Constant *ShadowStackCollector::GetFrameMap(Function &F) {
196 // doInitialization creates the abstract type of this value.
197
198 Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
199
200 // Truncate the ShadowStackDescriptor if some metadata is null.
201 unsigned NumMeta = 0;
202 SmallVector<Constant*,16> Metadata;
203 for (unsigned I = 0; I != Roots.size(); ++I) {
204 Constant *C = cast<Constant>(Roots[I].first->getOperand(2));
205 if (!C->isNullValue())
206 NumMeta = I + 1;
207 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
208 }
209
210 Constant *BaseElts[] = {
211 ConstantInt::get(Type::Int32Ty, Roots.size(), false),
212 ConstantInt::get(Type::Int32Ty, NumMeta, false),
213 };
214
215 Constant *DescriptorElts[] = {
216 ConstantStruct::get(BaseElts, 2),
217 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta),
218 Metadata.begin(), NumMeta)
219 };
220
221 Constant *FrameMap = ConstantStruct::get(DescriptorElts, 2);
222
223 std::string TypeName("gc_map.");
224 TypeName += utostr(NumMeta);
225 F.getParent()->addTypeName(TypeName, FrameMap->getType());
226
227 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
228 // that, short of multithreaded LLVM, it should be safe; all that is
229 // necessary is that a simple Module::iterator loop not be invalidated.
230 // Appending to the GlobalVariable list is safe in that sense.
231 //
232 // All of the output passes emit globals last. The ExecutionEngine
233 // explicitly supports adding globals to the module after
234 // initialization.
235 //
236 // Still, if it isn't deemed acceptable, then this transformation needs
237 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
238 // (which uses a FunctionPassManager (which segfaults (not asserts) if
239 // provided a ModulePass))).
240 Constant *GV = new GlobalVariable(FrameMap->getType(), true,
241 GlobalVariable::InternalLinkage,
242 FrameMap, "__gc_" + F.getName(),
243 F.getParent());
244
245 Constant *GEPIndices[2] = { ConstantInt::get(Type::Int32Ty, 0),
246 ConstantInt::get(Type::Int32Ty, 0) };
247 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
248}
249
250const Type* ShadowStackCollector::GetConcreteStackEntryType(Function &F) {
251 // doInitialization creates the generic version of this type.
252 std::vector<const Type*> EltTys;
253 EltTys.push_back(StackEntryTy);
254 for (size_t I = 0; I != Roots.size(); I++)
255 EltTys.push_back(Roots[I].second->getAllocatedType());
256 Type *Ty = StructType::get(EltTys);
257
258 std::string TypeName("gc_stackentry.");
259 TypeName += F.getName();
260 F.getParent()->addTypeName(TypeName, Ty);
261
262 return Ty;
263}
264
265/// doInitialization - If this module uses the GC intrinsics, find them now. If
266/// not, exit fast.
267bool ShadowStackCollector::initializeCustomLowering(Module &M) {
268 // struct FrameMap {
269 // int32_t NumRoots; // Number of roots in stack frame.
270 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
271 // void *Meta[]; // May be absent for roots without metadata.
272 // };
273 std::vector<const Type*> EltTys;
274 EltTys.push_back(Type::Int32Ty); // 32 bits is ok up to a 32GB stack frame. :)
275 EltTys.push_back(Type::Int32Ty); // Specifies length of variable length array.
276 StructType *FrameMapTy = StructType::get(EltTys);
277 M.addTypeName("gc_map", FrameMapTy);
278 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
279
280 // struct StackEntry {
281 // ShadowStackEntry *Next; // Caller's stack entry.
282 // FrameMap *Map; // Pointer to constant FrameMap.
283 // void *Roots[]; // Stack roots (in-place array, so we pretend).
284 // };
285 OpaqueType *RecursiveTy = OpaqueType::get();
286
287 EltTys.clear();
288 EltTys.push_back(PointerType::getUnqual(RecursiveTy));
289 EltTys.push_back(FrameMapPtrTy);
290 PATypeHolder LinkTyH = StructType::get(EltTys);
291
292 RecursiveTy->refineAbstractTypeTo(LinkTyH.get());
293 StackEntryTy = cast<StructType>(LinkTyH.get());
294 const PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
295 M.addTypeName("gc_stackentry", LinkTyH.get()); // FIXME: Is this safe from
296 // a FunctionPass?
297
298 // Get the root chain if it already exists.
299 Head = M.getGlobalVariable("llvm_gc_root_chain");
300 if (!Head) {
301 // If the root chain does not exist, insert a new one with linkonce
302 // linkage!
303 Head = new GlobalVariable(StackEntryPtrTy, false,
304 GlobalValue::LinkOnceLinkage,
305 Constant::getNullValue(StackEntryPtrTy),
306 "llvm_gc_root_chain", &M);
307 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
308 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
309 Head->setLinkage(GlobalValue::LinkOnceLinkage);
310 }
311
312 return true;
313}
314
315bool ShadowStackCollector::IsNullValue(Value *V) {
316 if (Constant *C = dyn_cast<Constant>(V))
317 return C->isNullValue();
318 return false;
319}
320
321void ShadowStackCollector::CollectRoots(Function &F) {
322 // FIXME: Account for original alignment. Could fragment the root array.
323 // Approach 1: Null initialize empty slots at runtime. Yuck.
324 // Approach 2: Emit a map of the array instead of just a count.
325
326 assert(Roots.empty() && "Not cleaned up?");
327
328 SmallVector<std::pair<CallInst*,AllocaInst*>,16> MetaRoots;
329
330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
331 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
332 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
333 if (Function *F = CI->getCalledFunction())
334 if (F->getIntrinsicID() == Intrinsic::gcroot) {
335 std::pair<CallInst*,AllocaInst*> Pair = std::make_pair(
336 CI, cast<AllocaInst>(
337 IntrinsicInst::StripPointerCasts(CI->getOperand(1))));
338 if (IsNullValue(CI->getOperand(2)))
339 Roots.push_back(Pair);
340 else
341 MetaRoots.push_back(Pair);
342 }
343
344 // Number roots with metadata (usually empty) at the beginning, so that the
345 // FrameMap::Meta array can be elided.
346 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
347}
348
349GetElementPtrInst *
350ShadowStackCollector::CreateGEP(LLVMBuilder &B, Value *BasePtr,
351 int Idx, int Idx2, const char *Name) {
352 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
353 ConstantInt::get(Type::Int32Ty, Idx),
354 ConstantInt::get(Type::Int32Ty, Idx2) };
355 return B.CreateGEP(BasePtr, Indices, Indices + 3, Name);
356}
357
358GetElementPtrInst *
359ShadowStackCollector::CreateGEP(LLVMBuilder &B, Value *BasePtr,
360 int Idx, const char *Name) {
361 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
362 ConstantInt::get(Type::Int32Ty, Idx) };
363 return B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
364}
365
366/// runOnFunction - Insert code to maintain the shadow stack.
367bool ShadowStackCollector::performCustomLowering(Function &F) {
368 // Find calls to llvm.gcroot.
369 CollectRoots(F);
370
371 // 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;
375
376 // Build the constant map and figure the type of the shadow stack entry.
377 Value *FrameMap = GetFrameMap(F);
378 const Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
379
380 // Build the shadow stack entry at the very start of the function.
381 BasicBlock::iterator IP = F.getEntryBlock().begin();
382 LLVMBuilder AtEntry(IP->getParent(), IP);
383
384 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, 0,
385 "gc_frame");
386
387 while (isa<AllocaInst>(IP)) ++IP;
388 AtEntry.SetInsertPoint(IP->getParent(), IP);
389
390 // Initialize the map pointer and load the current head of the shadow stack.
391 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
392 Instruction *EntryMapPtr = CreateGEP(AtEntry, StackEntry,0,1,"gc_frame.map");
393 AtEntry.CreateStore(FrameMap, EntryMapPtr);
394
395 // After all the allocas...
396 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
397 // For each root, find the corresponding slot in the aggregate...
398 Value *SlotPtr = CreateGEP(AtEntry, StackEntry, 1 + I, "gc_root");
399
400 // And use it in lieu of the alloca.
401 AllocaInst *OriginalAlloca = Roots[I].second;
402 SlotPtr->takeName(OriginalAlloca);
403 OriginalAlloca->replaceAllUsesWith(SlotPtr);
404 }
405
406 // Move past the original stores inserted by Collector::InitRoots. This isn't
407 // really necessary (the collector would never see the intermediate state),
408 // but it's nicer not to push the half-initialized entry onto the stack.
409 while (isa<StoreInst>(IP)) ++IP;
410 AtEntry.SetInsertPoint(IP->getParent(), IP);
411
412 // 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);
417
418 // For each instruction that escapes...
419 EscapeEnumerator EE(F, "gc_cleanup");
420 while (LLVMBuilder *AtExit = EE.Next()) {
421 // 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 }
428
429 // 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 }
436
437 F.dump();
438
439 Roots.clear();
440 return true;
441}