50#define DEBUG_TYPE "shadow-stack-gc-lowering"
54class ShadowStackGCLoweringImpl {
65 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
68 ShadowStackGCLoweringImpl() =
default;
70 bool doInitialization(
Module &M);
74 bool IsNullValue(
Value *V);
83 Type *Ty,
Value *BasePtr,
int Idx1,
int Idx2,
88 ShadowStackGCLoweringImpl Impl;
93 ShadowStackGCLowering();
95 bool doInitialization(
Module &M)
override {
return Impl.doInitialization(M); }
100 std::optional<DomTreeUpdater> DTU;
101 if (
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
102 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
103 return Impl.runOnFunction(
F, DTU ? &*DTU :
nullptr);
112 if (!Map.contains(
"shadow-stack"))
115 ShadowStackGCLoweringImpl Impl;
116 bool Changed = Impl.doInitialization(M);
122 Changed |= Impl.runOnFunction(
F, DT ? &DTU :
nullptr);
132char ShadowStackGCLowering::ID = 0;
136 "Shadow Stack GC Lowering",
false,
false)
144ShadowStackGCLowering::ShadowStackGCLowering() :
FunctionPass(
ID) {}
148 Type *VoidPtr = PointerType::getUnqual(
F.getContext());
151 unsigned NumMeta = 0;
153 for (
unsigned I = 0;
I != Roots.size(); ++
I) {
155 if (!
C->isNullValue())
164 ConstantInt::get(
Int32Ty, Roots.size(),
false),
165 ConstantInt::get(
Int32Ty, NumMeta,
false),
190 Constant *GV =
new GlobalVariable(*
F.getParent(), FrameMap->
getType(),
true,
191 GlobalVariable::InternalLinkage, FrameMap,
192 "__gc_" +
F.getName());
195 ConstantInt::get(Type::getInt32Ty(
F.getContext()), 0),
196 ConstantInt::get(Type::getInt32Ty(
F.getContext()), 0)};
200Type *ShadowStackGCLoweringImpl::GetConcreteStackEntryType(Function &
F) {
202 std::vector<Type *> EltTys;
203 EltTys.push_back(StackEntryTy);
204 for (
const std::pair<CallInst *, AllocaInst *> &Root : Roots)
205 EltTys.push_back(Root.second->getAllocatedType());
212bool ShadowStackGCLoweringImpl::doInitialization(
Module &M) {
214 for (Function &
F : M) {
215 if (
F.hasGC() &&
F.getGC() ==
"shadow-stack") {
228 std::vector<Type *> EltTys;
230 EltTys.push_back(Type::getInt32Ty(
M.getContext()));
232 EltTys.push_back(Type::getInt32Ty(
M.getContext()));
234 PointerType *FrameMapPtrTy = PointerType::getUnqual(
M.getContext());
242 PointerType *StackEntryPtrTy = PointerType::getUnqual(
M.getContext());
245 EltTys.push_back(StackEntryPtrTy);
246 EltTys.push_back(FrameMapPtrTy);
250 Head =
M.getGlobalVariable(
"llvm_gc_root_chain");
254 Head =
new GlobalVariable(
265bool ShadowStackGCLoweringImpl::IsNullValue(
Value *V) {
267 return C->isNullValue();
271void ShadowStackGCLoweringImpl::CollectRoots(Function &
F) {
276 assert(Roots.empty() &&
"Not cleaned up?");
280 for (BasicBlock &BB :
F)
281 for (Instruction &
I : BB)
283 if (Function *
F = CI->getCalledFunction())
284 if (
F->getIntrinsicID() == Intrinsic::gcroot) {
285 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
288 if (IsNullValue(CI->getArgOperand(1)))
289 Roots.push_back(Pair);
296 Roots.insert(Roots.begin(), MetaRoots.
begin(), MetaRoots.
end());
302 int Idx2,
const char *Name) {
303 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(
Context), 0),
304 ConstantInt::get(Type::getInt32Ty(
Context), Idx),
305 ConstantInt::get(Type::getInt32Ty(
Context), Idx2)};
306 Value *Val =
B.CreateGEP(Ty, BasePtr, Indices, Name);
313GetElementPtrInst *ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &
Context,
316 Value *BasePtr,
int Idx,
318 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(
Context), 0),
319 ConstantInt::get(Type::getInt32Ty(
Context), Idx)};
320 Value *Val =
B.CreateGEP(Ty, BasePtr, Indices, Name);
328bool ShadowStackGCLoweringImpl::runOnFunction(Function &
F,
329 DomTreeUpdater *DTU) {
331 if (!
F.hasGC() ||
F.getGC() !=
"shadow-stack")
334 LLVMContext &
Context =
F.getContext();
345 Value *FrameMap = GetFrameMap(
F);
346 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(
F);
353 AtEntry.CreateAlloca(ConcreteStackEntryTy,
nullptr,
"gc_frame");
355 AtEntry.SetInsertPointPastAllocas(&
F);
356 IP = AtEntry.GetInsertPoint();
360 AtEntry.CreateLoad(AtEntry.getPtrTy(), Head,
"gc_currhead");
362 StackEntry, 0, 1,
"gc_frame.map");
363 AtEntry.CreateStore(FrameMap, EntryMapPtr);
366 for (
unsigned I = 0,
E = Roots.size();
I !=
E; ++
I) {
368 Value *SlotPtr = CreateGEP(
Context, AtEntry, ConcreteStackEntryTy,
369 StackEntry, 1 +
I,
"gc_root");
372 AllocaInst *OriginalAlloca = Roots[
I].second;
383 AtEntry.SetInsertPoint(IP->getParent(), IP);
387 StackEntry, 0, 0,
"gc_frame.next");
389 StackEntry, 0,
"gc_newhead");
390 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
391 AtEntry.CreateStore(NewHeadVal, Head);
394 EscapeEnumerator EE(
F,
"gc_cleanup",
true, DTU);
399 CreateGEP(
Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
402 AtExit->CreateLoad(AtExit->getPtrTy(), EntryNextPtr2,
"gc_savedhead");
403 AtExit->CreateStore(SavedHead, Head);
409 for (std::pair<CallInst *, AllocaInst *> &Root : Roots) {
410 Root.first->eraseFromParent();
411 Root.second->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
InstListType::iterator iterator
Instruction iterators...
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Analysis pass which computes a DominatorTree.
Legacy analysis pass which computes a DominatorTree.
FunctionPass class - This class is used to implement most global optimizations.
An analysis pass which caches information about the entire Module.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
bool hasExternalLinkage() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void setLinkage(LinkageTypes LT)
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This is an important class for using LLVM in a threaded context.
A Module instance is used to store all the information related to an LLVM module.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
void push_back(const T &Elt)
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
LLVM_ABI char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI FunctionPass * createShadowStackGCLoweringPass()
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.