LLVM  10.0.0svn
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/DebugInfo.h"
32 #include "llvm/IR/DebugLoc.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/IR/User.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Casting.h"
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 
66  "Insert stack protectors", false, true)
69  "Insert stack protectors", false, true)
70 
71 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
72 
76 }
77 
79  F = &Fn;
80  M = F->getParent();
82  getAnalysisIfAvailable<DominatorTreeWrapperPass>();
83  DT = DTWP ? &DTWP->getDomTree() : nullptr;
84  TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
85  Trip = TM->getTargetTriple();
86  TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
87  HasPrologue = false;
88  HasIRCheck = false;
89 
90  Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
91  if (Attr.isStringAttribute() &&
92  Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
93  return false; // Invalid integer string
94 
95  if (!RequiresStackProtector())
96  return false;
97 
98  // TODO(etienneb): Functions with funclets are not correctly supported now.
99  // Do nothing if this is funclet-based personality.
100  if (Fn.hasPersonalityFn()) {
102  if (isFuncletEHPersonality(Personality))
103  return false;
104  }
105 
106  ++NumFunProtected;
107  return InsertStackProtectors();
108 }
109 
110 /// \param [out] IsLarge is set to true if a protectable array is found and
111 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
112 /// multiple arrays, this gets set if any of them is large.
113 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
114  bool Strong,
115  bool InStruct) const {
116  if (!Ty)
117  return false;
118  if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
119  if (!AT->getElementType()->isIntegerTy(8)) {
120  // If we're on a non-Darwin platform or we're inside of a structure, don't
121  // add stack protectors unless the array is a character array.
122  // However, in strong mode any array, regardless of type and size,
123  // triggers a protector.
124  if (!Strong && (InStruct || !Trip.isOSDarwin()))
125  return false;
126  }
127 
128  // If an array has more than SSPBufferSize bytes of allocated space, then we
129  // emit stack protectors.
130  if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
131  IsLarge = true;
132  return true;
133  }
134 
135  if (Strong)
136  // Require a protector for all arrays in strong mode
137  return true;
138  }
139 
140  const StructType *ST = dyn_cast<StructType>(Ty);
141  if (!ST)
142  return false;
143 
144  bool NeedsProtector = false;
146  E = ST->element_end();
147  I != E; ++I)
148  if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
149  // If the element is a protectable array and is large (>= SSPBufferSize)
150  // then we are done. If the protectable array is not large, then
151  // keep looking in case a subsequent element is a large array.
152  if (IsLarge)
153  return true;
154  NeedsProtector = true;
155  }
156 
157  return NeedsProtector;
158 }
159 
160 /// Search for the first call to the llvm.stackprotector intrinsic and return it
161 /// if present.
163  for (const BasicBlock &BB : F)
164  for (const Instruction &I : BB)
165  if (const CallInst *CI = dyn_cast<CallInst>(&I))
166  if (CI->getCalledFunction() ==
167  Intrinsic::getDeclaration(F.getParent(), Intrinsic::stackprotector))
168  return CI;
169  return nullptr;
170 }
171 
172 /// Check whether or not this function needs a stack protector based
173 /// upon the stack protector level.
174 ///
175 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
176 /// The standard heuristic which will add a guard variable to functions that
177 /// call alloca with a either a variable size or a size >= SSPBufferSize,
178 /// functions with character buffers larger than SSPBufferSize, and functions
179 /// with aggregates containing character buffers larger than SSPBufferSize. The
180 /// strong heuristic will add a guard variables to functions that call alloca
181 /// regardless of size, functions with any buffer regardless of type and size,
182 /// functions with aggregates that contain any buffer regardless of type and
183 /// size, and functions that contain stack-based variables that have had their
184 /// address taken.
185 bool StackProtector::RequiresStackProtector() {
186  bool Strong = false;
187  bool NeedsProtector = false;
188  HasPrologue = findStackProtectorIntrinsic(*F);
189 
190  if (F->hasFnAttribute(Attribute::SafeStack))
191  return false;
192 
193  // We are constructing the OptimizationRemarkEmitter on the fly rather than
194  // using the analysis pass to avoid building DominatorTree and LoopInfo which
195  // are not available this late in the IR pipeline.
197 
198  if (F->hasFnAttribute(Attribute::StackProtectReq)) {
199  ORE.emit([&]() {
200  return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
201  << "Stack protection applied to function "
202  << ore::NV("Function", F)
203  << " due to a function attribute or command-line switch";
204  });
205  NeedsProtector = true;
206  Strong = true; // Use the same heuristic as strong to determine SSPLayout
207  } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
208  Strong = true;
209  else if (HasPrologue)
210  NeedsProtector = true;
211  else if (!F->hasFnAttribute(Attribute::StackProtect))
212  return false;
213 
214  for (const BasicBlock &BB : *F) {
215  for (const Instruction &I : BB) {
216  if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
217  if (AI->isArrayAllocation()) {
218  auto RemarkBuilder = [&]() {
219  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
220  &I)
221  << "Stack protection applied to function "
222  << ore::NV("Function", F)
223  << " due to a call to alloca or use of a variable length "
224  "array";
225  };
226  if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
227  if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
228  // A call to alloca with size >= SSPBufferSize requires
229  // stack protectors.
230  Layout.insert(std::make_pair(AI,
232  ORE.emit(RemarkBuilder);
233  NeedsProtector = true;
234  } else if (Strong) {
235  // Require protectors for all alloca calls in strong mode.
236  Layout.insert(std::make_pair(AI,
238  ORE.emit(RemarkBuilder);
239  NeedsProtector = true;
240  }
241  } else {
242  // A call to alloca with a variable size requires protectors.
243  Layout.insert(std::make_pair(AI,
245  ORE.emit(RemarkBuilder);
246  NeedsProtector = true;
247  }
248  continue;
249  }
250 
251  bool IsLarge = false;
252  if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
253  Layout.insert(std::make_pair(AI, IsLarge
256  ORE.emit([&]() {
257  return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
258  << "Stack protection applied to function "
259  << ore::NV("Function", F)
260  << " due to a stack allocated buffer or struct containing a "
261  "buffer";
262  });
263  NeedsProtector = true;
264  continue;
265  }
266 
267  if (Strong && PointerMayBeCaptured(AI,
268  /* ReturnCaptures */ false,
269  /* StoreCaptures */ true)) {
270  ++NumAddrTaken;
271  Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
272  ORE.emit([&]() {
273  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
274  &I)
275  << "Stack protection applied to function "
276  << ore::NV("Function", F)
277  << " due to the address of a local variable being taken";
278  });
279  NeedsProtector = true;
280  }
281  }
282  }
283  }
284 
285  return NeedsProtector;
286 }
287 
288 /// Create a stack guard loading and populate whether SelectionDAG SSP is
289 /// supported.
291  IRBuilder<> &B,
292  bool *SupportsSelectionDAGSP = nullptr) {
293  if (Value *Guard = TLI->getIRStackGuard(B))
294  return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
295 
296  // Use SelectionDAG SSP handling, since there isn't an IR guard.
297  //
298  // This is more or less weird, since we optionally output whether we
299  // should perform a SelectionDAG SP here. The reason is that it's strictly
300  // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
301  // mutating. There is no way to get this bit without mutating the IR, so
302  // getting this bit has to happen in this right time.
303  //
304  // We could have define a new function TLI::supportsSelectionDAGSP(), but that
305  // will put more burden on the backends' overriding work, especially when it
306  // actually conveys the same information getIRStackGuard() already gives.
307  if (SupportsSelectionDAGSP)
308  *SupportsSelectionDAGSP = true;
309  TLI->insertSSPDeclarations(*M);
310  return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
311 }
312 
313 /// Insert code into the entry block that stores the stack guard
314 /// variable onto the stack:
315 ///
316 /// entry:
317 /// StackGuardSlot = alloca i8*
318 /// StackGuard = <stack guard>
319 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
320 ///
321 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
322 /// node.
323 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
324  const TargetLoweringBase *TLI, AllocaInst *&AI) {
325  bool SupportsSelectionDAGSP = false;
326  IRBuilder<> B(&F->getEntryBlock().front());
327  PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
328  AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
329 
330  Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
331  B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
332  {GuardSlot, AI});
333  return SupportsSelectionDAGSP;
334 }
335 
336 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
337 /// function.
338 ///
339 /// - The prologue code loads and stores the stack guard onto the stack.
340 /// - The epilogue checks the value stored in the prologue against the original
341 /// value. It calls __stack_chk_fail if they differ.
342 bool StackProtector::InsertStackProtectors() {
343  // If the target wants to XOR the frame pointer into the guard value, it's
344  // impossible to emit the check in IR, so the target *must* support stack
345  // protection in SDAG.
346  bool SupportsSelectionDAGSP =
347  TLI->useStackGuardXorFP() ||
350  AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
351 
352  for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
353  BasicBlock *BB = &*I++;
355  if (!RI)
356  continue;
357 
358  // Generate prologue instrumentation if not already generated.
359  if (!HasPrologue) {
360  HasPrologue = true;
361  SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
362  }
363 
364  // SelectionDAG based code generation. Nothing else needs to be done here.
365  // The epilogue instrumentation is postponed to SelectionDAG.
366  if (SupportsSelectionDAGSP)
367  break;
368 
369  // Find the stack guard slot if the prologue was not created by this pass
370  // itself via a previous call to CreatePrologue().
371  if (!AI) {
372  const CallInst *SPCall = findStackProtectorIntrinsic(*F);
373  assert(SPCall && "Call to llvm.stackprotector is missing");
374  AI = cast<AllocaInst>(SPCall->getArgOperand(1));
375  }
376 
377  // Set HasIRCheck to true, so that SelectionDAG will not generate its own
378  // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
379  // instrumentation has already been generated.
380  HasIRCheck = true;
381 
382  // Generate epilogue instrumentation. The epilogue intrumentation can be
383  // function-based or inlined depending on which mechanism the target is
384  // providing.
385  if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
386  // Generate the function-based epilogue instrumentation.
387  // The target provides a guard check function, generate a call to it.
388  IRBuilder<> B(RI);
389  LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
390  CallInst *Call = B.CreateCall(GuardCheck, {Guard});
391  Call->setAttributes(GuardCheck->getAttributes());
392  Call->setCallingConv(GuardCheck->getCallingConv());
393  } else {
394  // Generate the epilogue with inline instrumentation.
395  // If we do not support SelectionDAG based tail calls, generate IR level
396  // tail calls.
397  //
398  // For each block with a return instruction, convert this:
399  //
400  // return:
401  // ...
402  // ret ...
403  //
404  // into this:
405  //
406  // return:
407  // ...
408  // %1 = <stack guard>
409  // %2 = load StackGuardSlot
410  // %3 = cmp i1 %1, %2
411  // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
412  //
413  // SP_return:
414  // ret ...
415  //
416  // CallStackCheckFailBlk:
417  // call void @__stack_chk_fail()
418  // unreachable
419 
420  // Create the FailBB. We duplicate the BB every time since the MI tail
421  // merge pass will merge together all of the various BB into one including
422  // fail BB generated by the stack protector pseudo instruction.
423  BasicBlock *FailBB = CreateFailBB();
424 
425  // Split the basic block before the return instruction.
426  BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
427 
428  // Update the dominator tree if we need to.
429  if (DT && DT->isReachableFromEntry(BB)) {
430  DT->addNewBlock(NewBB, BB);
431  DT->addNewBlock(FailBB, BB);
432  }
433 
434  // Remove default branch instruction to the new BB.
436 
437  // Move the newly created basic block to the point right after the old
438  // basic block so that it's in the "fall through" position.
439  NewBB->moveAfter(BB);
440 
441  // Generate the stack protector instructions in the old basic block.
442  IRBuilder<> B(BB);
443  Value *Guard = getStackGuard(TLI, M, B);
444  LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
445  Value *Cmp = B.CreateICmpEQ(Guard, LI2);
446  auto SuccessProb =
448  auto FailureProb =
450  MDNode *Weights = MDBuilder(F->getContext())
451  .createBranchWeights(SuccessProb.getNumerator(),
452  FailureProb.getNumerator());
453  B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
454  }
455  }
456 
457  // Return if we didn't modify any basic blocks. i.e., there are no return
458  // statements in the function.
459  return HasPrologue;
460 }
461 
462 /// CreateFailBB - Create a basic block to jump to when the stack protector
463 /// check fails.
464 BasicBlock *StackProtector::CreateFailBB() {
466  BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
467  IRBuilder<> B(FailBB);
469  if (Trip.isOSOpenBSD()) {
470  FunctionCallee StackChkFail = M->getOrInsertFunction(
471  "__stack_smash_handler", Type::getVoidTy(Context),
472  Type::getInt8PtrTy(Context));
473 
474  B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
475  } else {
476  FunctionCallee StackChkFail =
477  M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
478 
479  B.CreateCall(StackChkFail, {});
480  }
481  B.CreateUnreachable();
482  return FailBB;
483 }
484 
486  return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
487 }
488 
490  if (Layout.empty())
491  return;
492 
493  for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
494  if (MFI.isDeadObjectIndex(I))
495  continue;
496 
497  const AllocaInst *AI = MFI.getObjectAllocation(I);
498  if (!AI)
499  continue;
500 
501  SSPLayoutMap::const_iterator LI = Layout.find(AI);
502  if (LI == Layout.end())
503  continue;
504 
505  MFI.setObjectSSPLayout(I, LI->second);
506  }
507 }
Return a value (possibly void), from a function.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:481
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional &#39;br Cond, TrueDest, FalseDest&#39; instruction.
Definition: IRBuilder.h:890
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
LLVMContext & Context
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
Definition: AllocatorList.h:23
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1576
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
iterator end()
Definition: Function.h:682
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:165
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
This class represents a function call, abstracting a target machine&#39;s calling convention.
virtual const TargetLowering * getTargetLowering() const
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:733
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:863
block Block Frequency true
An instruction for reading from memory.
Definition: Instructions.h:167
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.cpp:144
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:299
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: ...
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1241
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
Definition: Attributes.cpp:194
Class to represent struct types.
Definition: DerivedTypes.h:233
static cl::opt< bool > EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden)
The address of this allocation is exposed and triggered protection.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:779
This file contains the simple types necessary to represent the attributes associated with functions a...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
DominatorTree & getDomTree()
Definition: Dominators.h:269
Target-Independent Code Generator Pass Configuration Options.
Class to represent array types.
Definition: DerivedTypes.h:403
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:732
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:156
iterator begin()
Definition: Function.h:680
Type::subtype_iterator element_iterator
Definition: DerivedTypes.h:333
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1079
Class to represent pointers.
Definition: DerivedTypes.h:570
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
#define DEBUG_TYPE
void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind)
Array or nested array >= SSP-buffer-size.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
unsigned EnableGlobalISel
EnableGlobalISel - This flag enables global instruction selection.
const BasicBlock & getEntryBlock() const
Definition: Function.h:664
virtual Value * getIRStackGuard(IRBuilder<> &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
UnreachableInst * CreateUnreachable()
Definition: IRBuilder.h:1050
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1504
bool isOSOpenBSD() const
Definition: Triple.h:497
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Definition: BasicBlock.h:285
Diagnostic information for applied optimization remarks.
element_iterator element_end() const
Definition: DerivedTypes.h:336
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:160
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1348
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
const Triple & getTargetTriple() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2102
self_iterator getIterator()
Definition: ilist_node.h:81
FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:205
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:421
virtual bool useStackGuardXorFP() const
If this function returns true, stack protection checks should XOR the frame pointer (or whichever poi...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:492
static const CallInst * findStackProtectorIntrinsic(Function &F)
Search for the first call to the llvm.stackprotector intrinsic and return it if present.
Iterator for intrusive lists based on ilist_node.
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:134
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
Insert stack protectors
Module.h This file contains the declarations for the Module class.
virtual Function * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
Constant * CreateGlobalStringPtr(StringRef Str, const Twine &Name="", unsigned AddressSpace=0)
Same as CreateGlobalString, but return a pointer with "i8*" type instead of a pointer to array of i8...
Definition: IRBuilder.h:1861
element_iterator element_begin() const
Definition: DerivedTypes.h:335
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, "Insert stack protectors", false, true) INITIALIZE_PASS_END(StackProtector
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:223
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:58
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
iterator end()
Definition: DenseMap.h:82
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1370
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2237
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:414
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:96
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1441
Array or nested array < SSP-buffer-size.
virtual void insertSSPDeclarations(Module &M) const
Inserts necessary declarations for SSP (stack protection) purpose.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
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.
bool shouldEmitSDCheck(const BasicBlock &BB) const
The optimization diagnostic interface.
static BranchProbability getBranchProbStackProtector(bool IsLikely)
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack
Definition: Instructions.h:59
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures, unsigned MaxUsesToExplore=DefaultMaxUsesToExplore)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...