LLVM 17.0.0git
StackProtector.cpp
Go to the documentation of this file.
1//===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass inserts stack protectors into functions which need them. A variable
10// with a random value in it is stored onto the stack before the local variables
11// are allocated. Upon exiting the block, the stored value is checked. If it's
12// changed, then there was some sort of violation and the program aborts.
13//
14//===----------------------------------------------------------------------===//
15
18#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/Passes.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/MDBuilder.h"
40#include "llvm/IR/Module.h"
41#include "llvm/IR/Type.h"
42#include "llvm/IR/User.h"
44#include "llvm/Pass.h"
50#include <optional>
51#include <utility>
52
53using namespace llvm;
54
55#define DEBUG_TYPE "stack-protector"
56
57STATISTIC(NumFunProtected, "Number of functions protected");
58STATISTIC(NumAddrTaken, "Number of local variables that have their address"
59 " taken.");
60
61static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
62 cl::init(true), cl::Hidden);
63static cl::opt<bool> DisableCheckNoReturn("disable-check-noreturn-call",
64 cl::init(false), cl::Hidden);
65
66char StackProtector::ID = 0;
67
70}
71
73 "Insert stack protectors", false, true)
77 "Insert stack protectors", false, true)
78
80
84}
85
87 F = &Fn;
88 M = F->getParent();
89 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
90 DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
91 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
92 Trip = TM->getTargetTriple();
93 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
94 HasPrologue = false;
95 HasIRCheck = false;
96
97 SSPBufferSize = Fn.getFnAttributeAsParsedInteger(
98 "stack-protector-buffer-size", DefaultSSPBufferSize);
99 if (!RequiresStackProtector())
100 return false;
101
102 // TODO(etienneb): Functions with funclets are not correctly supported now.
103 // Do nothing if this is funclet-based personality.
104 if (Fn.hasPersonalityFn()) {
106 if (isFuncletEHPersonality(Personality))
107 return false;
108 }
109
110 ++NumFunProtected;
111 bool Changed = InsertStackProtectors();
112#ifdef EXPENSIVE_CHECKS
113 assert((!DTU ||
114 DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
115 "Failed to maintain validity of domtree!");
116#endif
117 DTU.reset();
118 return Changed;
119}
120
121/// \param [out] IsLarge is set to true if a protectable array is found and
122/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
123/// multiple arrays, this gets set if any of them is large.
124bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
125 bool Strong,
126 bool InStruct) const {
127 if (!Ty)
128 return false;
129 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
130 if (!AT->getElementType()->isIntegerTy(8)) {
131 // If we're on a non-Darwin platform or we're inside of a structure, don't
132 // add stack protectors unless the array is a character array.
133 // However, in strong mode any array, regardless of type and size,
134 // triggers a protector.
135 if (!Strong && (InStruct || !Trip.isOSDarwin()))
136 return false;
137 }
138
139 // If an array has more than SSPBufferSize bytes of allocated space, then we
140 // emit stack protectors.
141 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
142 IsLarge = true;
143 return true;
144 }
145
146 if (Strong)
147 // Require a protector for all arrays in strong mode
148 return true;
149 }
150
151 const StructType *ST = dyn_cast<StructType>(Ty);
152 if (!ST)
153 return false;
154
155 bool NeedsProtector = false;
156 for (Type *ET : ST->elements())
157 if (ContainsProtectableArray(ET, IsLarge, Strong, true)) {
158 // If the element is a protectable array and is large (>= SSPBufferSize)
159 // then we are done. If the protectable array is not large, then
160 // keep looking in case a subsequent element is a large array.
161 if (IsLarge)
162 return true;
163 NeedsProtector = true;
164 }
165
166 return NeedsProtector;
167}
168
169bool StackProtector::HasAddressTaken(const Instruction *AI,
170 TypeSize AllocSize) {
171 const DataLayout &DL = M->getDataLayout();
172 for (const User *U : AI->users()) {
173 const auto *I = cast<Instruction>(U);
174 // If this instruction accesses memory make sure it doesn't access beyond
175 // the bounds of the allocated object.
176 std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
177 if (MemLoc && MemLoc->Size.hasValue() &&
178 !TypeSize::isKnownGE(AllocSize,
179 TypeSize::getFixed(MemLoc->Size.getValue())))
180 return true;
181 switch (I->getOpcode()) {
182 case Instruction::Store:
183 if (AI == cast<StoreInst>(I)->getValueOperand())
184 return true;
185 break;
186 case Instruction::AtomicCmpXchg:
187 // cmpxchg conceptually includes both a load and store from the same
188 // location. So, like store, the value being stored is what matters.
189 if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
190 return true;
191 break;
192 case Instruction::PtrToInt:
193 if (AI == cast<PtrToIntInst>(I)->getOperand(0))
194 return true;
195 break;
196 case Instruction::Call: {
197 // Ignore intrinsics that do not become real instructions.
198 // TODO: Narrow this to intrinsics that have store-like effects.
199 const auto *CI = cast<CallInst>(I);
200 if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
201 return true;
202 break;
203 }
204 case Instruction::Invoke:
205 return true;
206 case Instruction::GetElementPtr: {
207 // If the GEP offset is out-of-bounds, or is non-constant and so has to be
208 // assumed to be potentially out-of-bounds, then any memory access that
209 // would use it could also be out-of-bounds meaning stack protection is
210 // required.
211 const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
212 unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
213 APInt Offset(IndexSize, 0);
214 if (!GEP->accumulateConstantOffset(DL, Offset))
215 return true;
216 TypeSize OffsetSize = TypeSize::Fixed(Offset.getLimitedValue());
217 if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
218 return true;
219 // Adjust AllocSize to be the space remaining after this offset.
220 // We can't subtract a fixed size from a scalable one, so in that case
221 // assume the scalable value is of minimum size.
222 TypeSize NewAllocSize =
223 TypeSize::Fixed(AllocSize.getKnownMinValue()) - OffsetSize;
224 if (HasAddressTaken(I, NewAllocSize))
225 return true;
226 break;
227 }
228 case Instruction::BitCast:
229 case Instruction::Select:
230 case Instruction::AddrSpaceCast:
231 if (HasAddressTaken(I, AllocSize))
232 return true;
233 break;
234 case Instruction::PHI: {
235 // Keep track of what PHI nodes we have already visited to ensure
236 // they are only visited once.
237 const auto *PN = cast<PHINode>(I);
238 if (VisitedPHIs.insert(PN).second)
239 if (HasAddressTaken(PN, AllocSize))
240 return true;
241 break;
242 }
243 case Instruction::Load:
244 case Instruction::AtomicRMW:
245 case Instruction::Ret:
246 // These instructions take an address operand, but have load-like or
247 // other innocuous behavior that should not trigger a stack protector.
248 // atomicrmw conceptually has both load and store semantics, but the
249 // value being stored must be integer; so if a pointer is being stored,
250 // we'll catch it in the PtrToInt case above.
251 break;
252 default:
253 // Conservatively return true for any instruction that takes an address
254 // operand, but is not handled above.
255 return true;
256 }
257 }
258 return false;
259}
260
261/// Search for the first call to the llvm.stackprotector intrinsic and return it
262/// if present.
264 for (const BasicBlock &BB : F)
265 for (const Instruction &I : BB)
266 if (const auto *II = dyn_cast<IntrinsicInst>(&I))
267 if (II->getIntrinsicID() == Intrinsic::stackprotector)
268 return II;
269 return nullptr;
270}
271
272/// Check whether or not this function needs a stack protector based
273/// upon the stack protector level.
274///
275/// We use two heuristics: a standard (ssp) and strong (sspstrong).
276/// The standard heuristic which will add a guard variable to functions that
277/// call alloca with a either a variable size or a size >= SSPBufferSize,
278/// functions with character buffers larger than SSPBufferSize, and functions
279/// with aggregates containing character buffers larger than SSPBufferSize. The
280/// strong heuristic will add a guard variables to functions that call alloca
281/// regardless of size, functions with any buffer regardless of type and size,
282/// functions with aggregates that contain any buffer regardless of type and
283/// size, and functions that contain stack-based variables that have had their
284/// address taken.
285bool StackProtector::RequiresStackProtector() {
286 bool Strong = false;
287 bool NeedsProtector = false;
288
289 if (F->hasFnAttribute(Attribute::SafeStack))
290 return false;
291
292 // We are constructing the OptimizationRemarkEmitter on the fly rather than
293 // using the analysis pass to avoid building DominatorTree and LoopInfo which
294 // are not available this late in the IR pipeline.
296
297 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
298 ORE.emit([&]() {
299 return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
300 << "Stack protection applied to function "
301 << ore::NV("Function", F)
302 << " due to a function attribute or command-line switch";
303 });
304 NeedsProtector = true;
305 Strong = true; // Use the same heuristic as strong to determine SSPLayout
306 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
307 Strong = true;
308 else if (!F->hasFnAttribute(Attribute::StackProtect))
309 return false;
310
311 for (const BasicBlock &BB : *F) {
312 for (const Instruction &I : BB) {
313 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
314 if (AI->isArrayAllocation()) {
315 auto RemarkBuilder = [&]() {
316 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
317 &I)
318 << "Stack protection applied to function "
319 << ore::NV("Function", F)
320 << " due to a call to alloca or use of a variable length "
321 "array";
322 };
323 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
324 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
325 // A call to alloca with size >= SSPBufferSize requires
326 // stack protectors.
327 Layout.insert(std::make_pair(AI,
329 ORE.emit(RemarkBuilder);
330 NeedsProtector = true;
331 } else if (Strong) {
332 // Require protectors for all alloca calls in strong mode.
333 Layout.insert(std::make_pair(AI,
335 ORE.emit(RemarkBuilder);
336 NeedsProtector = true;
337 }
338 } else {
339 // A call to alloca with a variable size requires protectors.
340 Layout.insert(std::make_pair(AI,
342 ORE.emit(RemarkBuilder);
343 NeedsProtector = true;
344 }
345 continue;
346 }
347
348 bool IsLarge = false;
349 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
350 Layout.insert(std::make_pair(AI, IsLarge
353 ORE.emit([&]() {
354 return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
355 << "Stack protection applied to function "
356 << ore::NV("Function", F)
357 << " due to a stack allocated buffer or struct containing a "
358 "buffer";
359 });
360 NeedsProtector = true;
361 continue;
362 }
363
364 if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
365 AI->getAllocatedType()))) {
366 ++NumAddrTaken;
367 Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
368 ORE.emit([&]() {
369 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
370 &I)
371 << "Stack protection applied to function "
372 << ore::NV("Function", F)
373 << " due to the address of a local variable being taken";
374 });
375 NeedsProtector = true;
376 }
377 // Clear any PHIs that we visited, to make sure we examine all uses of
378 // any subsequent allocas that we look at.
379 VisitedPHIs.clear();
380 }
381 }
382 }
383
384 return NeedsProtector;
385}
386
387/// Create a stack guard loading and populate whether SelectionDAG SSP is
388/// supported.
390 IRBuilder<> &B,
391 bool *SupportsSelectionDAGSP = nullptr) {
392 Value *Guard = TLI->getIRStackGuard(B);
393 StringRef GuardMode = M->getStackProtectorGuard();
394 if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
395 return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
396
397 // Use SelectionDAG SSP handling, since there isn't an IR guard.
398 //
399 // This is more or less weird, since we optionally output whether we
400 // should perform a SelectionDAG SP here. The reason is that it's strictly
401 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
402 // mutating. There is no way to get this bit without mutating the IR, so
403 // getting this bit has to happen in this right time.
404 //
405 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
406 // will put more burden on the backends' overriding work, especially when it
407 // actually conveys the same information getIRStackGuard() already gives.
408 if (SupportsSelectionDAGSP)
409 *SupportsSelectionDAGSP = true;
410 TLI->insertSSPDeclarations(*M);
411 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
412}
413
414/// Insert code into the entry block that stores the stack guard
415/// variable onto the stack:
416///
417/// entry:
418/// StackGuardSlot = alloca i8*
419/// StackGuard = <stack guard>
420/// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
421///
422/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
423/// node.
424static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
425 const TargetLoweringBase *TLI, AllocaInst *&AI) {
426 bool SupportsSelectionDAGSP = false;
427 IRBuilder<> B(&F->getEntryBlock().front());
428 PointerType *PtrTy = Type::getInt8PtrTy(CheckLoc->getContext());
429 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
430
431 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
432 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
433 {GuardSlot, AI});
434 return SupportsSelectionDAGSP;
435}
436
437/// InsertStackProtectors - Insert code into the prologue and epilogue of the
438/// function.
439///
440/// - The prologue code loads and stores the stack guard onto the stack.
441/// - The epilogue checks the value stored in the prologue against the original
442/// value. It calls __stack_chk_fail if they differ.
443bool StackProtector::InsertStackProtectors() {
444 // If the target wants to XOR the frame pointer into the guard value, it's
445 // impossible to emit the check in IR, so the target *must* support stack
446 // protection in SDAG.
447 bool SupportsSelectionDAGSP =
448 TLI->useStackGuardXorFP() ||
450 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
451 BasicBlock *FailBB = nullptr;
452
453 for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
454 // This is stack protector auto generated check BB, skip it.
455 if (&BB == FailBB)
456 continue;
457 Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
458 if (!CheckLoc && !DisableCheckNoReturn) {
459 for (auto &Inst : BB) {
460 auto *CB = dyn_cast<CallBase>(&Inst);
461 if (!CB)
462 continue;
463 if (!CB->doesNotReturn())
464 continue;
465 // Do stack check before non-return calls (e.g: __cxa_throw)
466 CheckLoc = CB;
467 break;
468 }
469 }
470
471 if (!CheckLoc)
472 continue;
473
474 // Generate prologue instrumentation if not already generated.
475 if (!HasPrologue) {
476 HasPrologue = true;
477 SupportsSelectionDAGSP &= CreatePrologue(F, M, CheckLoc, TLI, AI);
478 }
479
480 // SelectionDAG based code generation. Nothing else needs to be done here.
481 // The epilogue instrumentation is postponed to SelectionDAG.
482 if (SupportsSelectionDAGSP)
483 break;
484
485 // Find the stack guard slot if the prologue was not created by this pass
486 // itself via a previous call to CreatePrologue().
487 if (!AI) {
488 const CallInst *SPCall = findStackProtectorIntrinsic(*F);
489 assert(SPCall && "Call to llvm.stackprotector is missing");
490 AI = cast<AllocaInst>(SPCall->getArgOperand(1));
491 }
492
493 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
494 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
495 // instrumentation has already been generated.
496 HasIRCheck = true;
497
498 // If we're instrumenting a block with a tail call, the check has to be
499 // inserted before the call rather than between it and the return. The
500 // verifier guarantees that a tail call is either directly before the
501 // return or with a single correct bitcast of the return value in between so
502 // we don't need to worry about many situations here.
503 Instruction *Prev = CheckLoc->getPrevNonDebugInstruction();
504 if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
505 CheckLoc = Prev;
506 else if (Prev) {
507 Prev = Prev->getPrevNonDebugInstruction();
508 if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
509 CheckLoc = Prev;
510 }
511
512 // Generate epilogue instrumentation. The epilogue intrumentation can be
513 // function-based or inlined depending on which mechanism the target is
514 // providing.
515 if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
516 // Generate the function-based epilogue instrumentation.
517 // The target provides a guard check function, generate a call to it.
518 IRBuilder<> B(CheckLoc);
519 LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
520 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
521 Call->setAttributes(GuardCheck->getAttributes());
522 Call->setCallingConv(GuardCheck->getCallingConv());
523 } else {
524 // Generate the epilogue with inline instrumentation.
525 // If we do not support SelectionDAG based calls, generate IR level
526 // calls.
527 //
528 // For each block with a return instruction, convert this:
529 //
530 // return:
531 // ...
532 // ret ...
533 //
534 // into this:
535 //
536 // return:
537 // ...
538 // %1 = <stack guard>
539 // %2 = load StackGuardSlot
540 // %3 = icmp ne i1 %1, %2
541 // br i1 %3, label %CallStackCheckFailBlk, label %SP_return
542 //
543 // SP_return:
544 // ret ...
545 //
546 // CallStackCheckFailBlk:
547 // call void @__stack_chk_fail()
548 // unreachable
549
550 // Create the FailBB. We duplicate the BB every time since the MI tail
551 // merge pass will merge together all of the various BB into one including
552 // fail BB generated by the stack protector pseudo instruction.
553 if (!FailBB)
554 FailBB = CreateFailBB();
555
556 IRBuilder<> B(CheckLoc);
557 Value *Guard = getStackGuard(TLI, M, B);
558 LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
559 auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
560 auto SuccessProb =
562 auto FailureProb =
564 MDNode *Weights = MDBuilder(F->getContext())
565 .createBranchWeights(FailureProb.getNumerator(),
566 SuccessProb.getNumerator());
567
568 SplitBlockAndInsertIfThen(Cmp, CheckLoc,
569 /*Unreachable=*/false, Weights,
570 DTU ? &*DTU : nullptr,
571 /*LI=*/nullptr, /*ThenBlock=*/FailBB);
572
573 auto *BI = cast<BranchInst>(Cmp->getParent()->getTerminator());
574 BasicBlock *NewBB = BI->getSuccessor(1);
575 NewBB->setName("SP_return");
576 NewBB->moveAfter(&BB);
577
578 Cmp->setPredicate(Cmp->getInversePredicate());
579 BI->swapSuccessors();
580 }
581 }
582
583 // Return if we didn't modify any basic blocks. i.e., there are no return
584 // statements in the function.
585 return HasPrologue;
586}
587
588/// CreateFailBB - Create a basic block to jump to when the stack protector
589/// check fails.
590BasicBlock *StackProtector::CreateFailBB() {
591 LLVMContext &Context = F->getContext();
592 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
593 IRBuilder<> B(FailBB);
594 if (F->getSubprogram())
595 B.SetCurrentDebugLocation(
596 DILocation::get(Context, 0, 0, F->getSubprogram()));
597 if (Trip.isOSOpenBSD()) {
598 FunctionCallee StackChkFail = M->getOrInsertFunction(
599 "__stack_smash_handler", Type::getVoidTy(Context),
600 Type::getInt8PtrTy(Context));
601
602 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
603 } else {
604 FunctionCallee StackChkFail =
605 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
606
607 B.CreateCall(StackChkFail, {});
608 }
609 B.CreateUnreachable();
610 return FailBB;
611}
612
614 return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
615}
616
618 if (Layout.empty())
619 return;
620
621 for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
622 if (MFI.isDeadObjectIndex(I))
623 continue;
624
625 const AllocaInst *AI = MFI.getObjectAllocation(I);
626 if (!AI)
627 continue;
628
629 SSPLayoutMap::const_iterator LI = Layout.find(AI);
630 if (LI == Layout.end())
631 continue;
632
633 MFI.setObjectSSPLayout(I, LI->second);
634 }
635}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
basic Basic Alias true
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file provides utility analysis objects describing memory locations.
Module.h This file contains the declarations for the Module class.
LLVMContext & Context
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet 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 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:
Insert stack protectors
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)
Definition: Statistic.h:167
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Definition: APInt.h:75
an instruction to allocate memory on the stack
Definition: Instructions.h:58
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.
Class to represent array types.
Definition: DerivedTypes.h:357
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:141
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...
Definition: BasicBlock.h:127
static BranchProbability getBranchProbStackProtector(bool IsLikely)
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1351
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.
Definition: DataLayout.h:114
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:507
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
bool empty() const
Definition: DenseMap.h:98
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:207
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:314
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:165
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition: Function.cpp:674
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:803
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1995
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:640
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:940
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2550
const Instruction * getPrevNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the previous non-debug instruction in the same basic block as 'this',...
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:177
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
Metadata node.
Definition: Metadata.h:943
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1399
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 std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:398
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:144
The optimization diagnostic interface.
Diagnostic information for applied optimization remarks.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool shouldEmitSDCheck(const BasicBlock &BB) const
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
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.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
Class to represent struct types.
Definition: DerivedTypes.h:213
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
virtual bool useStackGuardXorFP() const
If this function returns true, stack protection checks should XOR the frame pointer (or whichever poi...
virtual Function * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
virtual Value * getIRStackGuard(IRBuilderBase &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
virtual void insertSSPDeclarations(Module &M) const
Inserts necessary declarations for SSP (stack protection) purpose.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:78
const Triple & getTargetTriple() const
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Target-Independent Code Generator Pass Configuration Options.
virtual const TargetLowering * getTargetLowering() const
bool isOSOpenBSD() const
Definition: Triple.h:540
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, or DriverKit).
Definition: Triple.h:518
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition: TypeSize.h:322
static constexpr TypeSize Fixed(ScalarTy ExactSize)
Definition: TypeSize.h:331
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:375
iterator_range< user_iterator > users()
Definition: Value.h:421
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:994
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:163
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:205
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:219
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1502
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:406
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...
Definition: STLExtras.h:721
FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
void initializeStackProtectorPass(PassRegistry &)
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...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights, DominatorTree *DT, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...