blob: 17a4d76c4c8026681f2a1903f5b4b98710c7192d [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ----===//
Philip Reames23cf2e22015-01-28 19:28:03 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Philip Reames23cf2e22015-01-28 19:28:03 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the custom lowering code required by the shadow-stack GC
Philip Reames31955002016-01-19 03:57:18 +000010// strategy.
11//
12// This pass implements the code transformation described in this paper:
13// "Accurate Garbage Collection in an Uncooperative Environment"
14// Fergus Henderson, ISMM, 2002
Philip Reames23cf2e22015-01-28 19:28:03 +000015//
16//===----------------------------------------------------------------------===//
17
Eugene Zelenko618c5552017-09-13 21:15:20 +000018#include "llvm/ADT/SmallVector.h"
Philip Reames23cf2e22015-01-28 19:28:03 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/CodeGen/Passes.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000021#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constant.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/GlobalVariable.h"
Philip Reames23cf2e22015-01-28 19:28:03 +000028#include "llvm/IR/IRBuilder.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000029#include "llvm/IR/Instructions.h"
Philip Reames23cf2e22015-01-28 19:28:03 +000030#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000031#include "llvm/IR/Intrinsics.h"
Philip Reames23cf2e22015-01-28 19:28:03 +000032#include "llvm/IR/Module.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000033#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
35#include "llvm/Pass.h"
36#include "llvm/Support/Casting.h"
Kuba Breckaddfdba32016-11-14 21:41:13 +000037#include "llvm/Transforms/Utils/EscapeEnumerator.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000038#include <cassert>
39#include <cstddef>
40#include <string>
41#include <utility>
42#include <vector>
Philip Reames23cf2e22015-01-28 19:28:03 +000043
44using namespace llvm;
45
Matthias Braun1527baa2017-05-25 21:26:32 +000046#define DEBUG_TYPE "shadow-stack-gc-lowering"
Philip Reames23cf2e22015-01-28 19:28:03 +000047
48namespace {
49
50class ShadowStackGCLowering : public FunctionPass {
51 /// RootChain - This is the global linked-list that contains the chain of GC
52 /// roots.
Eugene Zelenko618c5552017-09-13 21:15:20 +000053 GlobalVariable *Head = nullptr;
Philip Reames23cf2e22015-01-28 19:28:03 +000054
55 /// StackEntryTy - Abstract type of a link in the shadow stack.
Eugene Zelenko618c5552017-09-13 21:15:20 +000056 StructType *StackEntryTy = nullptr;
57 StructType *FrameMapTy = nullptr;
Philip Reames23cf2e22015-01-28 19:28:03 +000058
59 /// Roots - GC roots in the current function. Each is a pair of the
60 /// intrinsic call and its corresponding alloca.
61 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
62
63public:
64 static char ID;
Eugene Zelenko618c5552017-09-13 21:15:20 +000065
Philip Reames23cf2e22015-01-28 19:28:03 +000066 ShadowStackGCLowering();
67
68 bool doInitialization(Module &M) override;
69 bool runOnFunction(Function &F) override;
70
71private:
72 bool IsNullValue(Value *V);
73 Constant *GetFrameMap(Function &F);
74 Type *GetConcreteStackEntryType(Function &F);
75 void CollectRoots(Function &F);
Eugene Zelenko618c5552017-09-13 21:15:20 +000076
Philip Reames23cf2e22015-01-28 19:28:03 +000077 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
David Blaikie86ecb1b2015-03-15 01:03:19 +000078 Type *Ty, Value *BasePtr, int Idx1,
Philip Reames23cf2e22015-01-28 19:28:03 +000079 const char *Name);
80 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
David Blaikie86ecb1b2015-03-15 01:03:19 +000081 Type *Ty, Value *BasePtr, int Idx1, int Idx2,
Philip Reames23cf2e22015-01-28 19:28:03 +000082 const char *Name);
83};
Eugene Zelenko618c5552017-09-13 21:15:20 +000084
85} // end anonymous namespace
86
87char ShadowStackGCLowering::ID = 0;
Philip Reames23cf2e22015-01-28 19:28:03 +000088
Matthias Braun1527baa2017-05-25 21:26:32 +000089INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
Philip Reames23cf2e22015-01-28 19:28:03 +000090 "Shadow Stack GC Lowering", false, false)
91INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +000092INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
Philip Reames23cf2e22015-01-28 19:28:03 +000093 "Shadow Stack GC Lowering", false, false)
94
95FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
96
Eugene Zelenko618c5552017-09-13 21:15:20 +000097ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) {
Philip Reames23cf2e22015-01-28 19:28:03 +000098 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
99}
100
Philip Reames23cf2e22015-01-28 19:28:03 +0000101Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
102 // doInitialization creates the abstract type of this value.
103 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
104
105 // Truncate the ShadowStackDescriptor if some metadata is null.
106 unsigned NumMeta = 0;
107 SmallVector<Constant *, 16> Metadata;
108 for (unsigned I = 0; I != Roots.size(); ++I) {
109 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
110 if (!C->isNullValue())
111 NumMeta = I + 1;
112 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
113 }
114 Metadata.resize(NumMeta);
115
116 Type *Int32Ty = Type::getInt32Ty(F.getContext());
117
118 Constant *BaseElts[] = {
119 ConstantInt::get(Int32Ty, Roots.size(), false),
120 ConstantInt::get(Int32Ty, NumMeta, false),
121 };
122
123 Constant *DescriptorElts[] = {
124 ConstantStruct::get(FrameMapTy, BaseElts),
125 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
126
127 Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
128 StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
129
130 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
131
132 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
133 // that, short of multithreaded LLVM, it should be safe; all that is
134 // necessary is that a simple Module::iterator loop not be invalidated.
135 // Appending to the GlobalVariable list is safe in that sense.
136 //
137 // All of the output passes emit globals last. The ExecutionEngine
138 // explicitly supports adding globals to the module after
139 // initialization.
140 //
141 // Still, if it isn't deemed acceptable, then this transformation needs
142 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
143 // (which uses a FunctionPassManager (which segfaults (not asserts) if
144 // provided a ModulePass))).
145 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
146 GlobalVariable::InternalLinkage, FrameMap,
147 "__gc_" + F.getName());
148
149 Constant *GEPIndices[2] = {
150 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
151 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
David Blaikie4a2e73b2015-04-02 18:55:32 +0000152 return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
Philip Reames23cf2e22015-01-28 19:28:03 +0000153}
154
155Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
156 // doInitialization creates the generic version of this type.
157 std::vector<Type *> EltTys;
158 EltTys.push_back(StackEntryTy);
159 for (size_t I = 0; I != Roots.size(); I++)
160 EltTys.push_back(Roots[I].second->getAllocatedType());
161
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000162 return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
Philip Reames23cf2e22015-01-28 19:28:03 +0000163}
164
165/// doInitialization - If this module uses the GC intrinsics, find them now. If
166/// not, exit fast.
167bool ShadowStackGCLowering::doInitialization(Module &M) {
168 bool Active = false;
169 for (Function &F : M) {
170 if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
171 Active = true;
172 break;
173 }
174 }
175 if (!Active)
176 return false;
Fangrui Songf78650a2018-07-30 19:41:25 +0000177
Philip Reames23cf2e22015-01-28 19:28:03 +0000178 // struct FrameMap {
179 // int32_t NumRoots; // Number of roots in stack frame.
180 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
181 // void *Meta[]; // May be absent for roots without metadata.
182 // };
183 std::vector<Type *> EltTys;
184 // 32 bits is ok up to a 32GB stack frame. :)
185 EltTys.push_back(Type::getInt32Ty(M.getContext()));
186 // Specifies length of variable length array.
187 EltTys.push_back(Type::getInt32Ty(M.getContext()));
188 FrameMapTy = StructType::create(EltTys, "gc_map");
189 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
190
191 // struct StackEntry {
192 // ShadowStackEntry *Next; // Caller's stack entry.
193 // FrameMap *Map; // Pointer to constant FrameMap.
194 // void *Roots[]; // Stack roots (in-place array, so we pretend).
195 // };
196
197 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
198
199 EltTys.clear();
200 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
201 EltTys.push_back(FrameMapPtrTy);
202 StackEntryTy->setBody(EltTys);
203 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
204
205 // Get the root chain if it already exists.
206 Head = M.getGlobalVariable("llvm_gc_root_chain");
207 if (!Head) {
208 // If the root chain does not exist, insert a new one with linkonce
209 // linkage!
210 Head = new GlobalVariable(
211 M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
212 Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
213 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
214 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
215 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
216 }
217
218 return true;
219}
220
221bool ShadowStackGCLowering::IsNullValue(Value *V) {
222 if (Constant *C = dyn_cast<Constant>(V))
223 return C->isNullValue();
224 return false;
225}
226
227void ShadowStackGCLowering::CollectRoots(Function &F) {
228 // FIXME: Account for original alignment. Could fragment the root array.
229 // Approach 1: Null initialize empty slots at runtime. Yuck.
230 // Approach 2: Emit a map of the array instead of just a count.
231
232 assert(Roots.empty() && "Not cleaned up?");
233
234 SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
235
236 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
237 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
238 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
239 if (Function *F = CI->getCalledFunction())
240 if (F->getIntrinsicID() == Intrinsic::gcroot) {
241 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
242 CI,
243 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
244 if (IsNullValue(CI->getArgOperand(1)))
245 Roots.push_back(Pair);
246 else
247 MetaRoots.push_back(Pair);
248 }
249
250 // Number roots with metadata (usually empty) at the beginning, so that the
251 // FrameMap::Meta array can be elided.
252 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
253}
254
255GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
David Blaikie86ecb1b2015-03-15 01:03:19 +0000256 IRBuilder<> &B, Type *Ty,
257 Value *BasePtr, int Idx,
258 int Idx2,
259 const char *Name) {
Philip Reames23cf2e22015-01-28 19:28:03 +0000260 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
261 ConstantInt::get(Type::getInt32Ty(Context), Idx),
262 ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
David Blaikie86ecb1b2015-03-15 01:03:19 +0000263 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
Philip Reames23cf2e22015-01-28 19:28:03 +0000264
265 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
266
267 return dyn_cast<GetElementPtrInst>(Val);
268}
269
270GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
David Blaikie86ecb1b2015-03-15 01:03:19 +0000271 IRBuilder<> &B, Type *Ty, Value *BasePtr,
Philip Reames23cf2e22015-01-28 19:28:03 +0000272 int Idx, const char *Name) {
273 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
274 ConstantInt::get(Type::getInt32Ty(Context), Idx)};
David Blaikie86ecb1b2015-03-15 01:03:19 +0000275 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
Philip Reames23cf2e22015-01-28 19:28:03 +0000276
277 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
278
279 return dyn_cast<GetElementPtrInst>(Val);
280}
281
282/// runOnFunction - Insert code to maintain the shadow stack.
283bool ShadowStackGCLowering::runOnFunction(Function &F) {
284 // Quick exit for functions that do not use the shadow stack GC.
285 if (!F.hasGC() ||
286 F.getGC() != std::string("shadow-stack"))
287 return false;
Fangrui Songf78650a2018-07-30 19:41:25 +0000288
Philip Reames23cf2e22015-01-28 19:28:03 +0000289 LLVMContext &Context = F.getContext();
290
291 // Find calls to llvm.gcroot.
292 CollectRoots(F);
293
294 // If there are no roots in this function, then there is no need to add a
295 // stack map entry for it.
296 if (Roots.empty())
297 return false;
298
299 // Build the constant map and figure the type of the shadow stack entry.
300 Value *FrameMap = GetFrameMap(F);
301 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
302
303 // Build the shadow stack entry at the very start of the function.
304 BasicBlock::iterator IP = F.getEntryBlock().begin();
305 IRBuilder<> AtEntry(IP->getParent(), IP);
306
307 Instruction *StackEntry =
308 AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
309
310 while (isa<AllocaInst>(IP))
311 ++IP;
312 AtEntry.SetInsertPoint(IP->getParent(), IP);
313
314 // Initialize the map pointer and load the current head of the shadow stack.
James Y Knight14359ef2019-02-01 20:44:24 +0000315 Instruction *CurrentHead =
316 AtEntry.CreateLoad(StackEntryTy->getPointerTo(), Head, "gc_currhead");
David Blaikie86ecb1b2015-03-15 01:03:19 +0000317 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
318 StackEntry, 0, 1, "gc_frame.map");
Philip Reames23cf2e22015-01-28 19:28:03 +0000319 AtEntry.CreateStore(FrameMap, EntryMapPtr);
320
321 // After all the allocas...
322 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
323 // For each root, find the corresponding slot in the aggregate...
David Blaikie86ecb1b2015-03-15 01:03:19 +0000324 Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
325 StackEntry, 1 + I, "gc_root");
Philip Reames23cf2e22015-01-28 19:28:03 +0000326
327 // And use it in lieu of the alloca.
328 AllocaInst *OriginalAlloca = Roots[I].second;
329 SlotPtr->takeName(OriginalAlloca);
330 OriginalAlloca->replaceAllUsesWith(SlotPtr);
331 }
332
333 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
334 // really necessary (the collector would never see the intermediate state at
335 // runtime), but it's nicer not to push the half-initialized entry onto the
336 // shadow stack.
337 while (isa<StoreInst>(IP))
338 ++IP;
339 AtEntry.SetInsertPoint(IP->getParent(), IP);
340
341 // Push the entry onto the shadow stack.
David Blaikie86ecb1b2015-03-15 01:03:19 +0000342 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
343 StackEntry, 0, 0, "gc_frame.next");
344 Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
345 StackEntry, 0, "gc_newhead");
Philip Reames23cf2e22015-01-28 19:28:03 +0000346 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
347 AtEntry.CreateStore(NewHeadVal, Head);
348
349 // For each instruction that escapes...
350 EscapeEnumerator EE(F, "gc_cleanup");
351 while (IRBuilder<> *AtExit = EE.Next()) {
352 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
353 // AtEntry, since that would make the value live for the entire function.
354 Instruction *EntryNextPtr2 =
David Blaikie86ecb1b2015-03-15 01:03:19 +0000355 CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
356 "gc_frame.next");
James Y Knight14359ef2019-02-01 20:44:24 +0000357 Value *SavedHead = AtExit->CreateLoad(StackEntryTy->getPointerTo(),
358 EntryNextPtr2, "gc_savedhead");
Philip Reames23cf2e22015-01-28 19:28:03 +0000359 AtExit->CreateStore(SavedHead, Head);
360 }
361
362 // Delete the original allocas (which are no longer used) and the intrinsic
363 // calls (which are no longer valid). Doing this last avoids invalidating
364 // iterators.
365 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
366 Roots[I].first->eraseFromParent();
367 Roots[I].second->eraseFromParent();
368 }
369
370 Roots.clear();
371 return true;
372}