blob: 0be00f0e7ce5eaf7eda8cb9784ad7ccda369b68d [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
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/CodeGen/GCs.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/CodeGen/GCStrategy.h"
Stephen Hines36b56882014-04-23 16:57:46 -070031#include "llvm/IR/CallSite.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000032#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Gordon Henriksen8fa89292008-01-07 01:30:53 +000035
36using namespace llvm;
37
Stephen Hinesdce4a402014-05-29 02:49:00 -070038#define DEBUG_TYPE "shadowstackgc"
39
Gordon Henriksen8fa89292008-01-07 01:30:53 +000040namespace {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000041
Nick Lewycky6726b6d2009-10-25 06:33:48 +000042 class ShadowStackGC : public GCStrategy {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000043 /// RootChain - This is the global linked-list that contains the chain of GC
44 /// roots.
45 GlobalVariable *Head;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000046
Gordon Henriksen8fa89292008-01-07 01:30:53 +000047 /// StackEntryTy - Abstract type of a link in the shadow stack.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000048 ///
Chris Lattner1afcace2011-07-09 17:41:24 +000049 StructType *StackEntryTy;
50 StructType *FrameMapTy;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000051
Gordon Henriksen8fa89292008-01-07 01:30:53 +000052 /// Roots - GC roots in the current function. Each is a pair of the
53 /// intrinsic call and its corresponding alloca.
54 std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000055
Gordon Henriksen8fa89292008-01-07 01:30:53 +000056 public:
Gordon Henriksen5eca0752008-08-17 18:44:35 +000057 ShadowStackGC();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000058
Stephen Hines36b56882014-04-23 16:57:46 -070059 bool initializeCustomLowering(Module &M) override;
60 bool performCustomLowering(Function &F) override;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000061
Gordon Henriksen8fa89292008-01-07 01:30:53 +000062 private:
63 bool IsNullValue(Value *V);
64 Constant *GetFrameMap(Function &F);
Chris Lattnerdb125cf2011-07-18 04:54:35 +000065 Type* GetConcreteStackEntryType(Function &F);
Gordon Henriksen8fa89292008-01-07 01:30:53 +000066 void CollectRoots(Function &F);
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, const char *Name);
Owen Andersone922c022009-07-22 00:24:57 +000070 static GetElementPtrInst *CreateGEP(LLVMContext &Context,
Owen Anderson9adc0ab2009-07-14 23:09:55 +000071 IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen8fa89292008-01-07 01:30:53 +000072 int Idx1, int Idx2, const char *Name);
73 };
Dan Gohman844731a2008-05-13 00:00:25 +000074
75}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000076
Gordon Henriksen5eca0752008-08-17 18:44:35 +000077static GCRegistry::Add<ShadowStackGC>
78X("shadow-stack", "Very portable GC for uncooperative code generators");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000079
Dan Gohman844731a2008-05-13 00:00:25 +000080namespace {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000081 /// EscapeEnumerator - This is a little algorithm to find all escape points
82 /// from a function so that "finally"-style code can be inserted. In addition
83 /// to finding the existing return and unwind instructions, it also (if
84 /// necessary) transforms any call instructions into invokes and sends them to
85 /// a landing pad.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000086 ///
Gordon Henriksen8fa89292008-01-07 01:30:53 +000087 /// It's wrapped up in a state machine using the same transform C# uses for
88 /// 'yield return' enumerators, This transform allows it to be non-allocating.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000089 class EscapeEnumerator {
Gordon Henriksen8fa89292008-01-07 01:30:53 +000090 Function &F;
91 const char *CleanupBBName;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000092
Gordon Henriksen8fa89292008-01-07 01:30:53 +000093 // State.
94 int State;
95 Function::iterator StateBB, StateE;
Eric Christopher7a61d702008-08-08 19:39:37 +000096 IRBuilder<> Builder;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000097
Gordon Henriksen8fa89292008-01-07 01:30:53 +000098 public:
99 EscapeEnumerator(Function &F, const char *N = "cleanup")
Owen Andersone922c022009-07-22 00:24:57 +0000100 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000101
Eric Christopher7a61d702008-08-08 19:39:37 +0000102 IRBuilder<> *Next() {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000103 switch (State) {
104 default:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700105 return nullptr;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000106
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000107 case 0:
108 StateBB = F.begin();
109 StateE = F.end();
110 State = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000111
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000112 case 1:
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000113 // Find all 'return', 'resume', and 'unwind' instructions.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000114 while (StateBB != StateE) {
115 BasicBlock *CurBB = StateBB++;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000116
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000117 // Branches and invokes do not escape, only unwind, resume, and return
118 // do.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000119 TerminatorInst *TI = CurBB->getTerminator();
Bill Wendlingaa5abe82012-02-06 21:16:41 +0000120 if (!isa<ReturnInst>(TI) && !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())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700141 return nullptr;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000142
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000143 // Create a cleanup block.
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000144 LLVMContext &C = F.getContext();
145 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
146 Type *ExnTy = StructType::get(Type::getInt8PtrTy(C),
Stephen Hines37ed9c12014-12-01 14:51:49 -0800147 Type::getInt32Ty(C), nullptr);
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000148 Constant *PersFn =
149 F.getParent()->
Bill Wendling71139552011-09-22 17:56:40 +0000150 getOrInsertFunction("__gcc_personality_v0",
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000151 FunctionType::get(Type::getInt32Ty(C), true));
152 LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1,
153 "cleanup.lpad",
154 CleanupBB);
155 LPad->setCleanup(true);
156 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000157
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000158 // Transform the 'call' instructions into 'invoke's branching to the
159 // cleanup block. Go in reverse order to make prettier BB names.
160 SmallVector<Value*,16> Args;
161 for (unsigned I = Calls.size(); I != 0; ) {
162 CallInst *CI = cast<CallInst>(Calls[--I]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000163
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000164 // Split the basic block containing the function call.
165 BasicBlock *CallBB = CI->getParent();
166 BasicBlock *NewBB =
167 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000168
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000169 // Remove the unconditional branch inserted at the end of CallBB.
170 CallBB->getInstList().pop_back();
171 NewBB->getInstList().remove(CI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000172
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000173 // Create a new invoke instruction.
174 Args.clear();
Gabor Greif89c4cea2010-06-25 08:48:19 +0000175 CallSite CS(CI);
176 Args.append(CS.arg_begin(), CS.arg_end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000177
Gabor Greifa9b23132010-04-20 13:13:04 +0000178 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
Gabor Greif051a9502008-04-06 20:25:17 +0000179 NewBB, CleanupBB,
Jay Foada3efbb12011-07-15 08:37:34 +0000180 Args, CI->getName(), CallBB);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000181 II->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000182 II->setAttributes(CI->getAttributes());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000183 CI->replaceAllUsesWith(II);
184 delete CI;
185 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000186
Bill Wendling3ca2ad12011-09-21 22:14:28 +0000187 Builder.SetInsertPoint(RI->getParent(), RI);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000188 return &Builder;
189 }
190 }
191 };
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000192}
193
194// -----------------------------------------------------------------------------
195
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000196void llvm::linkShadowStackGC() { }
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000197
Stephen Hinesdce4a402014-05-29 02:49:00 -0700198ShadowStackGC::ShadowStackGC() : Head(nullptr), StackEntryTy(nullptr) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000199 InitRoots = true;
200 CustomRoots = true;
201}
202
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000203Constant *ShadowStackGC::GetFrameMap(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000204 // doInitialization creates the abstract type of this value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000205 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000206
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000207 // Truncate the ShadowStackDescriptor if some metadata is null.
208 unsigned NumMeta = 0;
Chris Lattnerb065b062011-06-20 04:01:31 +0000209 SmallVector<Constant*, 16> Metadata;
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000210 for (unsigned I = 0; I != Roots.size(); ++I) {
Gabor Greif89c4cea2010-06-25 08:48:19 +0000211 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000212 if (!C->isNullValue())
213 NumMeta = I + 1;
214 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
215 }
Jay Foad26701082011-06-22 09:24:39 +0000216 Metadata.resize(NumMeta);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000217
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000218 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Chris Lattnerb065b062011-06-20 04:01:31 +0000219
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000220 Constant *BaseElts[] = {
Chris Lattnerb065b062011-06-20 04:01:31 +0000221 ConstantInt::get(Int32Ty, Roots.size(), false),
222 ConstantInt::get(Int32Ty, NumMeta, false),
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000223 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000224
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000225 Constant *DescriptorElts[] = {
Chris Lattner1afcace2011-07-09 17:41:24 +0000226 ConstantStruct::get(FrameMapTy, BaseElts),
Jay Foad26701082011-06-22 09:24:39 +0000227 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000228 };
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229
Chris Lattner1afcace2011-07-09 17:41:24 +0000230 Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
Chris Lattner3ebb6492011-08-12 18:06:37 +0000231 StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
Chris Lattner1afcace2011-07-09 17:41:24 +0000232
233 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000234
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000235 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
236 // that, short of multithreaded LLVM, it should be safe; all that is
237 // necessary is that a simple Module::iterator loop not be invalidated.
238 // Appending to the GlobalVariable list is safe in that sense.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000239 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000240 // All of the output passes emit globals last. The ExecutionEngine
241 // explicitly supports adding globals to the module after
242 // initialization.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000243 //
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000244 // Still, if it isn't deemed acceptable, then this transformation needs
245 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
246 // (which uses a FunctionPassManager (which segfaults (not asserts) if
247 // provided a ModulePass))).
Owen Andersone9b11b42009-07-08 19:03:57 +0000248 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000249 GlobalVariable::InternalLinkage,
Owen Andersone9b11b42009-07-08 19:03:57 +0000250 FrameMap, "__gc_" + F.getName());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000251
Owen Anderson1d0be152009-08-13 21:58:54 +0000252 Constant *GEPIndices[2] = {
253 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
254 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
255 };
Jay Foadb4263a62011-07-22 08:52:50 +0000256 return ConstantExpr::getGetElementPtr(GV, GEPIndices);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000257}
258
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000260 // doInitialization creates the generic version of this type.
Chris Lattner1afcace2011-07-09 17:41:24 +0000261 std::vector<Type*> EltTys;
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000262 EltTys.push_back(StackEntryTy);
263 for (size_t I = 0; I != Roots.size(); I++)
264 EltTys.push_back(Roots[I].second->getAllocatedType());
Chris Lattner1afcace2011-07-09 17:41:24 +0000265
Chris Lattner3ebb6492011-08-12 18:06:37 +0000266 return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000267}
268
269/// doInitialization - If this module uses the GC intrinsics, find them now. If
270/// not, exit fast.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000271bool ShadowStackGC::initializeCustomLowering(Module &M) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000272 // struct FrameMap {
273 // int32_t NumRoots; // Number of roots in stack frame.
274 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
275 // void *Meta[]; // May be absent for roots without metadata.
276 // };
Chris Lattner1afcace2011-07-09 17:41:24 +0000277 std::vector<Type*> EltTys;
Owen Anderson1d0be152009-08-13 21:58:54 +0000278 // 32 bits is ok up to a 32GB stack frame. :)
279 EltTys.push_back(Type::getInt32Ty(M.getContext()));
280 // Specifies length of variable length array.
281 EltTys.push_back(Type::getInt32Ty(M.getContext()));
Chris Lattner3ebb6492011-08-12 18:06:37 +0000282 FrameMapTy = StructType::create(EltTys, "gc_map");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000283 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000284
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000285 // struct StackEntry {
286 // ShadowStackEntry *Next; // Caller's stack entry.
287 // FrameMap *Map; // Pointer to constant FrameMap.
288 // void *Roots[]; // Stack roots (in-place array, so we pretend).
289 // };
Chris Lattner1afcace2011-07-09 17:41:24 +0000290
Chris Lattner3ebb6492011-08-12 18:06:37 +0000291 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
Chris Lattner1afcace2011-07-09 17:41:24 +0000292
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000293 EltTys.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000294 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000295 EltTys.push_back(FrameMapPtrTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000296 StackEntryTy->setBody(EltTys);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000297 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000298
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000299 // Get the root chain if it already exists.
300 Head = M.getGlobalVariable("llvm_gc_root_chain");
301 if (!Head) {
302 // If the root chain does not exist, insert a new one with linkonce
303 // linkage!
Owen Andersone9b11b42009-07-08 19:03:57 +0000304 Head = new GlobalVariable(M, StackEntryPtrTy, false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000305 GlobalValue::LinkOnceAnyLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +0000306 Constant::getNullValue(StackEntryPtrTy),
Owen Andersone9b11b42009-07-08 19:03:57 +0000307 "llvm_gc_root_chain");
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000308 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000309 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Duncan Sands667d4b82009-03-07 15:45:40 +0000310 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000311 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000312
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000313 return true;
314}
315
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000316bool ShadowStackGC::IsNullValue(Value *V) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000317 if (Constant *C = dyn_cast<Constant>(V))
318 return C->isNullValue();
319 return false;
320}
321
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000322void ShadowStackGC::CollectRoots(Function &F) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000323 // FIXME: Account for original alignment. Could fragment the root array.
324 // Approach 1: Null initialize empty slots at runtime. Yuck.
325 // Approach 2: Emit a map of the array instead of just a count.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000326
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000327 assert(Roots.empty() && "Not cleaned up?");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000328
Gabor Greif89c4cea2010-06-25 08:48:19 +0000329 SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000330
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000331 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
332 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
333 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
334 if (Function *F = CI->getCalledFunction())
335 if (F->getIntrinsicID() == Intrinsic::gcroot) {
Gabor Greif89c4cea2010-06-25 08:48:19 +0000336 std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
337 CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
338 if (IsNullValue(CI->getArgOperand(1)))
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000339 Roots.push_back(Pair);
340 else
341 MetaRoots.push_back(Pair);
342 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000343
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000344 // 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 *
Owen Andersone922c022009-07-22 00:24:57 +0000350ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000351 int Idx, int Idx2, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000352 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
353 ConstantInt::get(Type::getInt32Ty(Context), Idx),
354 ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
Jay Foad0a2a60a2011-07-22 08:16:57 +0000355 Value* Val = B.CreateGEP(BasePtr, Indices, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000356
Duncan Sands89f6d882008-04-13 06:22:09 +0000357 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000358
Duncan Sands89f6d882008-04-13 06:22:09 +0000359 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000360}
361
362GetElementPtrInst *
Owen Andersone922c022009-07-22 00:24:57 +0000363ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000364 int Idx, const char *Name) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000365 Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
366 ConstantInt::get(Type::getInt32Ty(Context), Idx) };
Jay Foad0a2a60a2011-07-22 08:16:57 +0000367 Value *Val = B.CreateGEP(BasePtr, Indices, Name);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000368
Duncan Sands89f6d882008-04-13 06:22:09 +0000369 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
370
371 return dyn_cast<GetElementPtrInst>(Val);
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000372}
373
374/// runOnFunction - Insert code to maintain the shadow stack.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000375bool ShadowStackGC::performCustomLowering(Function &F) {
Owen Andersone922c022009-07-22 00:24:57 +0000376 LLVMContext &Context = F.getContext();
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000377
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000378 // Find calls to llvm.gcroot.
379 CollectRoots(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000380
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000381 // If there are no roots in this function, then there is no need to add a
382 // stack map entry for it.
383 if (Roots.empty())
384 return false;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000385
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000386 // Build the constant map and figure the type of the shadow stack entry.
387 Value *FrameMap = GetFrameMap(F);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000388 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000389
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000390 // Build the shadow stack entry at the very start of the function.
391 BasicBlock::iterator IP = F.getEntryBlock().begin();
Eric Christopher7a61d702008-08-08 19:39:37 +0000392 IRBuilder<> AtEntry(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000393
Stephen Hinesdce4a402014-05-29 02:49:00 -0700394 Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr,
395 "gc_frame");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000396
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000397 while (isa<AllocaInst>(IP)) ++IP;
398 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000399
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000400 // Initialize the map pointer and load the current head of the shadow stack.
401 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000402 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
403 0,1,"gc_frame.map");
Chris Lattner1afcace2011-07-09 17:41:24 +0000404 AtEntry.CreateStore(FrameMap, EntryMapPtr);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000405
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000406 // After all the allocas...
407 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
408 // For each root, find the corresponding slot in the aggregate...
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000409 Value *SlotPtr = CreateGEP(Context, AtEntry, StackEntry, 1 + I, "gc_root");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000410
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000411 // And use it in lieu of the alloca.
412 AllocaInst *OriginalAlloca = Roots[I].second;
413 SlotPtr->takeName(OriginalAlloca);
414 OriginalAlloca->replaceAllUsesWith(SlotPtr);
415 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000416
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000417 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
418 // really necessary (the collector would never see the intermediate state at
419 // runtime), but it's nicer not to push the half-initialized entry onto the
420 // shadow stack.
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000421 while (isa<StoreInst>(IP)) ++IP;
422 AtEntry.SetInsertPoint(IP->getParent(), IP);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000423
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000424 // Push the entry onto the shadow stack.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000425 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
426 StackEntry,0,0,"gc_frame.next");
427 Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
428 StackEntry, 0, "gc_newhead");
429 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
430 AtEntry.CreateStore(NewHeadVal, Head);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000431
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000432 // For each instruction that escapes...
433 EscapeEnumerator EE(F, "gc_cleanup");
Eric Christopher7a61d702008-08-08 19:39:37 +0000434 while (IRBuilder<> *AtExit = EE.Next()) {
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000435 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
436 // AtEntry, since that would make the value live for the entire function.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000437 Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000438 "gc_frame.next");
439 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
440 AtExit->CreateStore(SavedHead, Head);
441 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000442
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000443 // Delete the original allocas (which are no longer used) and the intrinsic
444 // calls (which are no longer valid). Doing this last avoids invalidating
445 // iterators.
446 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
447 Roots[I].first->eraseFromParent();
448 Roots[I].second->eraseFromParent();
449 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000450
Gordon Henriksen8fa89292008-01-07 01:30:53 +0000451 Roots.clear();
452 return true;
453}