56#define DEBUG_TYPE "stack-protector"
58STATISTIC(NumFunProtected,
"Number of functions protected");
59STATISTIC(NumAddrTaken,
"Number of local variables that have their address"
82 return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.
getTerminator());
98 if (LI == Layout.
end())
109 Info.RequireStackProtector =
111 Info.SSPBufferSize =
F.getFnAttributeAsParsedInteger(
112 "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
124 if (!
Info.RequireStackProtector)
129 if (
F.hasPersonalityFn()) {
138#ifdef EXPENSIVE_CHECKS
140 DTU.getDomTree().
verify(DominatorTree::VerificationLevel::Full)) &&
141 "Failed to maintain validity of domtree!");
159 "Insert stack protectors",
false,
true)
175 if (
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
176 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
177 TM = &getAnalysis<TargetPassConfig>().getTM<
TargetMachine>();
178 LayoutInfo.HasPrologue =
false;
179 LayoutInfo.HasIRCheck =
false;
182 "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
197 LayoutInfo.HasPrologue, LayoutInfo.HasIRCheck);
198#ifdef EXPENSIVE_CHECKS
200 DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
201 "Failed to maintain validity of domtree!");
211 bool &IsLarge,
bool Strong,
215 if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
216 if (!AT->getElementType()->isIntegerTy(8)) {
221 if (!Strong && (InStruct || !M->getTargetTriple().isOSDarwin()))
227 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
237 const StructType *ST = dyn_cast<StructType>(Ty);
241 bool NeedsProtector =
false;
242 for (
Type *ET : ST->elements())
249 NeedsProtector =
true;
252 return NeedsProtector;
260 unsigned NumDecreased = 0;
261 static constexpr unsigned MaxNumDecreased = 3;
272 const auto *
I = cast<Instruction>(U);
276 if (MemLoc && MemLoc->Size.hasValue() &&
279 switch (
I->getOpcode()) {
280 case Instruction::Store:
281 if (AI == cast<StoreInst>(
I)->getValueOperand())
284 case Instruction::AtomicCmpXchg:
287 if (AI == cast<AtomicCmpXchgInst>(
I)->getNewValOperand())
290 case Instruction::AtomicRMW:
291 if (AI == cast<AtomicRMWInst>(
I)->getValOperand())
294 case Instruction::PtrToInt:
295 if (AI == cast<PtrToIntInst>(
I)->getOperand(0))
298 case Instruction::Call: {
301 const auto *CI = cast<CallInst>(
I);
302 if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
306 case Instruction::Invoke:
308 case Instruction::GetElementPtr: {
314 unsigned IndexSize =
DL.getIndexTypeSizeInBits(
I->getType());
330 case Instruction::BitCast:
331 case Instruction::Select:
332 case Instruction::AddrSpaceCast:
336 case Instruction::PHI: {
339 const auto *PN = cast<PHINode>(
I);
340 auto [It, Inserted] = VisitedPHIs.
try_emplace(PN, AllocSize);
349 It->second.AllocSize = AllocSize;
350 ++It->second.NumDecreased;
356 case Instruction::Load:
357 case Instruction::Ret:
375 if (
const auto *
II = dyn_cast<IntrinsicInst>(&
I))
376 if (
II->getIntrinsicID() == Intrinsic::stackprotector)
398 bool NeedsProtector =
false;
405 unsigned SSPBufferSize =
F->getFnAttributeAsParsedInteger(
406 "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
408 if (
F->hasFnAttribute(Attribute::SafeStack))
416 if (
F->hasFnAttribute(Attribute::StackProtectReq)) {
421 <<
"Stack protection applied to function "
423 <<
" due to a function attribute or command-line switch";
425 NeedsProtector =
true;
427 }
else if (
F->hasFnAttribute(Attribute::StackProtectStrong))
429 else if (!
F->hasFnAttribute(Attribute::StackProtect))
434 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
435 if (AI->isArrayAllocation()) {
436 auto RemarkBuilder = [&]() {
439 <<
"Stack protection applied to function "
441 <<
" due to a call to alloca or use of a variable length "
444 if (
const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
445 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
452 ORE.
emit(RemarkBuilder);
453 NeedsProtector =
true;
460 ORE.
emit(RemarkBuilder);
461 NeedsProtector =
true;
469 ORE.
emit(RemarkBuilder);
470 NeedsProtector =
true;
475 bool IsLarge =
false;
477 IsLarge, Strong,
false)) {
480 Layout->
insert(std::make_pair(
485 <<
"Stack protection applied to function "
487 <<
" due to a stack allocated buffer or struct containing a "
490 NeedsProtector =
true;
496 AI, M->getDataLayout().getTypeAllocSize(AI->getAllocatedType()),
505 <<
"Stack protection applied to function "
507 <<
" due to the address of a local variable being taken";
509 NeedsProtector =
true;
518 return NeedsProtector;
525 bool *SupportsSelectionDAGSP =
nullptr) {
527 StringRef GuardMode = M->getStackProtectorGuard();
528 if ((GuardMode ==
"tls" || GuardMode.
empty()) && Guard)
529 return B.CreateLoad(
B.getPtrTy(), Guard,
true,
"StackGuard");
542 if (SupportsSelectionDAGSP)
543 *SupportsSelectionDAGSP =
true;
545 return B.CreateIntrinsic(Intrinsic::stackguard, {});
560 bool SupportsSelectionDAGSP =
false;
563 AI =
B.CreateAlloca(PtrTy,
nullptr,
"StackGuardSlot");
566 B.CreateIntrinsic(Intrinsic::stackprotector, {GuardSlot, AI});
567 return SupportsSelectionDAGSP;
573 auto *M =
F->getParent();
574 auto *TLI = TM->getSubtargetImpl(*F)->getTargetLowering();
579 bool SupportsSelectionDAGSP =
580 TLI->useStackGuardXorFP() ||
589 Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
591 for (
auto &Inst : BB) {
593 IB && (IB->getIntrinsicID() == Intrinsic::eh_sjlj_callsite)) {
599 if (
auto *CB = dyn_cast<CallBase>(&Inst))
602 if (CB->doesNotReturn() && !CB->doesNotThrow()) {
619 if (SupportsSelectionDAGSP)
626 assert(SPCall &&
"Call to llvm.stackprotector is missing");
638 if (
auto *CI = dyn_cast_if_present<CallInst>(Prev))
645 if (
Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
649 LoadInst *Guard =
B.CreateLoad(
B.getPtrTy(), AI,
true,
"Guard");
650 CallInst *Call =
B.CreateCall(GuardCheck, {Guard});
651 Call->setAttributes(GuardCheck->getAttributes());
652 Call->setCallingConv(GuardCheck->getCallingConv());
688 LoadInst *LI2 =
B.CreateLoad(
B.getPtrTy(), AI,
true);
689 auto *Cmp = cast<ICmpInst>(
B.CreateICmpNE(Guard, LI2));
696 SuccessProb.getNumerator());
702 auto *BI = cast<BranchInst>(Cmp->getParent()->getTerminator());
707 Cmp->setPredicate(Cmp->getInversePredicate());
708 BI->swapSuccessors();
718 auto *M =
F->getParent();
722 if (
F->getSubprogram())
723 B.SetCurrentDebugLocation(
728 if (
const char *ChkFailName =
732 }
else if (
const char *SSHName =
736 Args.push_back(
B.CreateGlobalString(
F->getName(),
"SSH"));
738 Context.emitError(
"no libcall available for stack protector");
742 CallInst *Call =
B.CreateCall(StackChkFail, Args);
743 Call->addFnAttr(Attribute::NoReturn);
746 B.CreateUnreachable();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#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.
static Value * getStackGuard(const TargetLoweringBase *TLI, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP=nullptr)
Create a stack guard loading and populate whether SelectionDAG SSP is supported.
static BasicBlock * CreateFailBB(Function *F, const TargetLowering &TLI)
CreateFailBB - Create a basic block to jump to when the stack protector check fails.
static bool InsertStackProtectors(const TargetMachine *TM, Function *F, DomTreeUpdater *DTU, bool &HasPrologue, bool &HasIRCheck)
InsertStackProtectors - Insert code into the prologue and epilogue of the function.
static bool HasAddressTaken(const Instruction *AI, TypeSize AllocSize, Module *M, PhiMap &VisitedPHIs)
Check whether a stack allocation has its address taken.
static cl::opt< bool > DisableCheckNoReturn("disable-check-noreturn-call", cl::init(false), cl::Hidden)
static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc, const TargetLoweringBase *TLI, AllocaInst *&AI)
Insert code into the entry block that stores the stack guard variable onto the stack:
static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize, bool &IsLarge, bool Strong, bool InStruct)
static cl::opt< bool > EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden)
static const CallInst * findStackProtectorIntrinsic(Function &F)
Search for the first call to the llvm.stackprotector intrinsic and return it if present.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
an instruction to allocate memory on the stack
A container for analyses that lazily runs them and caches their results.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static BranchProbability getBranchProbStackProtector(bool IsLikely)
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Legacy analysis pass which computes a DominatorTree.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionPass class - This class is used to implement most global optimizations.
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
@ SSPLK_SmallArray
Array or nested array < SSP-buffer-size.
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind)
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
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.
static bool requiresStackProtector(Function *F, SSPLayoutMap *Layout=nullptr)
Check whether or not F needs a stack protector based upon the stack protector level.
Result run(Function &F, FunctionAnalysisManager &FAM)
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
bool shouldEmitSDCheck(const BasicBlock &BB) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static bool requiresStackProtector(Function *F, SSPLayoutMap *Layout=nullptr)
Check whether or not F needs a stack protector based upon the stack protector level.
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
Class to represent struct types.
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
virtual Value * getIRStackGuard(IRBuilderBase &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
virtual void insertSSPDeclarations(Module &M) const
Inserts necessary declarations for SSP (stack protection) purpose.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
Target-Independent Code Generator Pass Configuration Options.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
LLVM Value Representation.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
iterator_range< user_iterator > users()
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
LLVM_ABI void initializeStackProtectorPass(PassRegistry &)
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
Maximum remaining allocation size observed for a phi node, and how often the allocation size has alre...
PhiInfo(TypeSize AllocSize)
static constexpr unsigned MaxNumDecreased
A special type used by analysis passes to provide an address that identifies that particular analysis...