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