55#define DEBUG_TYPE "stack-protector"
57STATISTIC(NumFunProtected,
"Number of functions protected");
58STATISTIC(NumAddrTaken,
"Number of local variables that have their address"
70 bool &HasPrologue,
bool &HasIRCheck);
94 if (LI == Layout.end())
105 Info.RequireStackProtector =
118 if (!Info.RequireStackProtector)
123 if (
F.hasPersonalityFn()) {
133 if (!LibcallLowering) {
135 "' analysis required");
146 Info.HasPrologue, Info.HasIRCheck);
147#ifdef EXPENSIVE_CHECKS
149 DTU.getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
150 "Failed to maintain validity of domtree!");
166 "Insert stack protectors",
false,
true)
185 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
187 LayoutInfo.HasPrologue =
false;
188 LayoutInfo.HasIRCheck =
false;
211 LayoutInfo.HasPrologue, LayoutInfo.HasIRCheck);
212#ifdef EXPENSIVE_CHECKS
214 DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
215 "Failed to maintain validity of domtree!");
225 bool &IsLarge,
bool Strong,
230 if (!AT->getElementType()->isIntegerTy(8)) {
235 if (!Strong && (InStruct || !M->getTargetTriple().isOSDarwin()))
241 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
255 bool NeedsProtector =
false;
256 for (
Type *ET : ST->elements())
263 NeedsProtector =
true;
266 return NeedsProtector;
290 if (MemLoc && MemLoc->Size.hasValue() &&
293 switch (
I->getOpcode()) {
294 case Instruction::Store:
298 case Instruction::AtomicCmpXchg:
304 case Instruction::AtomicRMW:
308 case Instruction::PtrToInt:
312 case Instruction::Call: {
320 case Instruction::Invoke:
322 case Instruction::GetElementPtr: {
328 unsigned IndexSize =
DL.getIndexTypeSizeInBits(
I->getType());
344 case Instruction::BitCast:
345 case Instruction::Select:
346 case Instruction::AddrSpaceCast:
350 case Instruction::PHI: {
354 auto [It, Inserted] = VisitedPHIs.
try_emplace(PN, AllocSize);
363 It->second.AllocSize = AllocSize;
364 ++It->second.NumDecreased;
370 case Instruction::Load:
371 case Instruction::Ret:
390 if (
II->getIntrinsicID() == Intrinsic::stackprotector)
409 SSPLayoutMap *Layout) {
412 bool NeedsProtector =
false;
419 unsigned SSPBufferSize =
F->getFnAttributeAsParsedInteger(
420 "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
422 if (
F->hasFnAttribute(Attribute::SafeStack))
430 if (
F->hasFnAttribute(Attribute::StackProtectReq)) {
435 <<
"Stack protection applied to function "
437 <<
" due to a function attribute or command-line switch";
439 NeedsProtector =
true;
441 }
else if (
F->hasFnAttribute(Attribute::StackProtectStrong))
443 else if (!
F->hasFnAttribute(Attribute::StackProtect))
449 if (
const MDNode *MD = AI->getMetadata(
"stack-protector")) {
454 if (AI->isArrayAllocation()) {
455 auto RemarkBuilder = [&]() {
458 <<
"Stack protection applied to function "
460 <<
" due to a call to alloca or use of a variable length "
464 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
471 ORE.
emit(RemarkBuilder);
472 NeedsProtector =
true;
479 ORE.
emit(RemarkBuilder);
480 NeedsProtector =
true;
488 ORE.
emit(RemarkBuilder);
489 NeedsProtector =
true;
494 bool IsLarge =
false;
496 IsLarge, Strong,
false)) {
499 Layout->
insert(std::make_pair(
504 <<
"Stack protection applied to function "
506 <<
" due to a stack allocated buffer or struct containing a "
509 NeedsProtector =
true;
514 std::optional<TypeSize> AllocSize =
515 AI->getAllocationSize(M->getDataLayout());
523 "StackProtectorAddressTaken", &
I)
524 <<
"Stack protection applied to function "
526 <<
" due to the address of a local variable being taken";
528 NeedsProtector =
true;
538 return NeedsProtector;
546 bool *SupportsSelectionDAGSP =
nullptr) {
547 Value *Guard =
TLI.getIRStackGuard(
B, Libcalls);
548 StringRef GuardMode = M->getStackProtectorGuard();
549 if ((GuardMode ==
"tls" || GuardMode.
empty()) && Guard)
550 return B.CreateLoad(
B.getPtrTy(), Guard,
true,
"StackGuard");
563 if (SupportsSelectionDAGSP)
564 *SupportsSelectionDAGSP =
true;
565 TLI.insertSSPDeclarations(*M, Libcalls);
566 return B.CreateIntrinsic(Intrinsic::stackguard, {});
583 bool SupportsSelectionDAGSP =
false;
586 AI =
B.CreateAlloca(PtrTy,
nullptr,
"StackGuardSlot");
590 B.CreateIntrinsic(Intrinsic::stackprotector, {GuardSlot, AI});
591 return SupportsSelectionDAGSP;
599 auto *M =
F->getParent();
604 bool SupportsSelectionDAGSP =
605 TLI.useStackGuardMixFP() ||
606 (Opts.stack_protector_selectiondag &&
607 !
TLI.getTargetMachine().
Options.EnableFastISel);
616 if (!CheckLoc && Opts.stack_protector_check_noreturn_call)
617 for (
auto &Inst : BB) {
619 IB && (IB->getIntrinsicID() == Intrinsic::eh_sjlj_callsite)) {
628 if (CB->doesNotReturn() && !CB->doesNotThrow()) {
640 SupportsSelectionDAGSP &=
646 if (SupportsSelectionDAGSP)
653 assert(SPCall &&
"Call to llvm.stackprotector is missing");
672 if (
Function *GuardCheck =
TLI.getSSPStackGuardCheck(*M, Libcalls)) {
676 LoadInst *Guard =
B.CreateLoad(
B.getPtrTy(), AI,
true,
"Guard");
678 Call->setAttributes(GuardCheck->getAttributes());
679 Call->setCallingConv(GuardCheck->getCallingConv());
715 LoadInst *LI2 =
B.CreateLoad(
B.getPtrTy(), AI,
true);
723 SuccessProb.getNumerator());
734 Cmp->setPredicate(Cmp->getInversePredicate());
735 BI->swapSuccessors();
745 auto *M =
F->getParent();
749 if (
F->getSubprogram())
750 B.SetCurrentDebugLocation(
752 bool IsSmashHandler =
false;
753 RTLIB::LibcallImpl ChkFailImpl =
755 if (ChkFailImpl == RTLIB::Unsupported) {
756 ChkFailImpl = Libcalls.
getLibcallImpl(RTLIB::STACK_SMASH_HANDLER);
757 IsSmashHandler =
true;
760 if (ChkFailImpl == RTLIB::Unsupported) {
761 Context.emitError(
"no libcall available for stack protector");
762 B.CreateUnreachable();
770 if (IsSmashHandler) {
772 B.CreateCall(StackChkFail,
B.CreateGlobalString(
F->getName(),
"SSH"));
774 Call =
B.CreateCall(StackChkFail);
778 Call->addFnAttr(Attribute::NoReturn);
779 B.CreateUnreachable();
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
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")
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 bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc, const TargetLoweringBase *TLI, const LibcallLoweringInfo &Libcalls, AllocaInst *&AI)
Insert code into the entry block that stores the stack guard variable onto the stack:
static Value * getStackGuard(const TargetLoweringBase &TLI, const LibcallLoweringInfo &Libcalls, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP=nullptr)
Create a stack guard loading and populate whether SelectionDAG SSP is supported.
static bool HasAddressTaken(const Instruction *AI, TypeSize AllocSize, Module *M, PhiMap &VisitedPHIs)
Check whether a stack allocation has its address taken.
static bool InsertStackProtectors(const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, Function *F, DomTreeUpdater *DTU, bool &HasPrologue, bool &HasIRCheck)
InsertStackProtectors - Insert code into the prologue and epilogue of the function.
SmallDenseMap< const PHINode *, PhiInfo, 16 > PhiMap
static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize, bool &IsLarge, bool Strong, bool InStruct)
static BasicBlock * CreateFailBB(Function *F, const LibcallLoweringInfo &Libcalls)
CreateFailBB - Create a basic block to jump to when the stack protector check fails.
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
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; assumes that the block is well-formed.
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.
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
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.
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...
iterator_range< user_iterator > users()
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Tracks which library functions to use for a particular subtarget or function.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
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)
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
A Module instance is used to store all the information related to an LLVM module.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
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 LLVM_ABI bool requiresStackProtector(Function *F, SSPLayoutMap *Layout=nullptr)
Check whether or not F needs a stack protector based upon the stack protector level.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
LLVM_ABI void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
LLVM_ABI bool shouldEmitSDCheck(const BasicBlock &BB) const
LLVM_ABI 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.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
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 ...
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.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetLowering * getTargetLowering() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
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)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
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 const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
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...
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
LLVM_ABI 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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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 ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
PhiInfo(TypeSize AllocSize)
static constexpr unsigned MaxNumDecreased
A special type used by analysis passes to provide an address that identifies that particular analysis...
LLVM_ABI FunctionCallee getOrInsertLibcallDecl(Module &M, RTLIB::LibcallImpl LibcallImpl) const