LLVM  7.0.0svn
StackProtector.cpp
Go to the documentation of this file.
1 //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass inserts stack protectors into functions which need them. A variable
11 // with a random value in it is stored onto the stack before the local variables
12 // are allocated. Upon exiting the block, the stored value is checked. If it's
13 // changed, then there was some sort of violation and the program aborts.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/SmallPtrSet.h"
19 #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 
75  return AI ? Layout.lookup(AI) : SSPLK_None;
76 }
77 
79  const AllocaInst *To) {
80  // When coloring replaces one alloca with another, transfer the SSPLayoutKind
81  // tag from the remapped to the target alloca. The remapped alloca should
82  // have a size smaller than or equal to the replacement alloca.
83  SSPLayoutMap::iterator I = Layout.find(From);
84  if (I != Layout.end()) {
85  SSPLayoutKind Kind = I->second;
86  Layout.erase(I);
87 
88  // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
89  // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
90  // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
91  I = Layout.find(To);
92  if (I == Layout.end())
93  Layout.insert(std::make_pair(To, Kind));
94  else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
95  I->second = Kind;
96  }
97 }
98 
102 }
103 
105  F = &Fn;
106  M = F->getParent();
108  getAnalysisIfAvailable<DominatorTreeWrapperPass>();
109  DT = DTWP ? &DTWP->getDomTree() : nullptr;
110  TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
111  Trip = TM->getTargetTriple();
112  TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
113  HasPrologue = false;
114  HasIRCheck = false;
115 
116  Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
117  if (Attr.isStringAttribute() &&
118  Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
119  return false; // Invalid integer string
120 
121  if (!RequiresStackProtector())
122  return false;
123 
124  // TODO(etienneb): Functions with funclets are not correctly supported now.
125  // Do nothing if this is funclet-based personality.
126  if (Fn.hasPersonalityFn()) {
128  if (isFuncletEHPersonality(Personality))
129  return false;
130  }
131 
132  ++NumFunProtected;
133  return InsertStackProtectors();
134 }
135 
136 /// \param [out] IsLarge is set to true if a protectable array is found and
137 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
138 /// multiple arrays, this gets set if any of them is large.
139 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
140  bool Strong,
141  bool InStruct) const {
142  if (!Ty)
143  return false;
144  if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
145  if (!AT->getElementType()->isIntegerTy(8)) {
146  // If we're on a non-Darwin platform or we're inside of a structure, don't
147  // add stack protectors unless the array is a character array.
148  // However, in strong mode any array, regardless of type and size,
149  // triggers a protector.
150  if (!Strong && (InStruct || !Trip.isOSDarwin()))
151  return false;
152  }
153 
154  // If an array has more than SSPBufferSize bytes of allocated space, then we
155  // emit stack protectors.
156  if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
157  IsLarge = true;
158  return true;
159  }
160 
161  if (Strong)
162  // Require a protector for all arrays in strong mode
163  return true;
164  }
165 
166  const StructType *ST = dyn_cast<StructType>(Ty);
167  if (!ST)
168  return false;
169 
170  bool NeedsProtector = false;
172  E = ST->element_end();
173  I != E; ++I)
174  if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
175  // If the element is a protectable array and is large (>= SSPBufferSize)
176  // then we are done. If the protectable array is not large, then
177  // keep looking in case a subsequent element is a large array.
178  if (IsLarge)
179  return true;
180  NeedsProtector = true;
181  }
182 
183  return NeedsProtector;
184 }
185 
186 static bool isLifetimeInst(const Instruction *I) {
187  if (const auto Intrinsic = dyn_cast<IntrinsicInst>(I)) {
188  const auto Id = Intrinsic->getIntrinsicID();
189  return Id == Intrinsic::lifetime_start || Id == Intrinsic::lifetime_end;
190  }
191  return false;
192 }
193 
194 bool StackProtector::HasAddressTaken(const Instruction *AI) {
195  for (const User *U : AI->users()) {
196  if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
197  if (AI == SI->getValueOperand())
198  return true;
199  } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
200  if (AI == SI->getOperand(0))
201  return true;
202  } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
203  // Ignore intrinsics that are not calls. TODO: Use isLoweredToCall().
204  if (!isa<DbgInfoIntrinsic>(CI) && !isLifetimeInst(CI))
205  return true;
206  } else if (isa<InvokeInst>(U)) {
207  return true;
208  } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
209  if (HasAddressTaken(SI))
210  return true;
211  } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
212  // Keep track of what PHI nodes we have already visited to ensure
213  // they are only visited once.
214  if (VisitedPHIs.insert(PN).second)
215  if (HasAddressTaken(PN))
216  return true;
217  } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
218  if (HasAddressTaken(GEP))
219  return true;
220  } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
221  if (HasAddressTaken(BI))
222  return true;
223  }
224  }
225  return false;
226 }
227 
228 /// \brief Check whether or not this function needs a stack protector based
229 /// upon the stack protector level.
230 ///
231 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
232 /// The standard heuristic which will add a guard variable to functions that
233 /// call alloca with a either a variable size or a size >= SSPBufferSize,
234 /// functions with character buffers larger than SSPBufferSize, and functions
235 /// with aggregates containing character buffers larger than SSPBufferSize. The
236 /// strong heuristic will add a guard variables to functions that call alloca
237 /// regardless of size, functions with any buffer regardless of type and size,
238 /// functions with aggregates that contain any buffer regardless of type and
239 /// size, and functions that contain stack-based variables that have had their
240 /// address taken.
241 bool StackProtector::RequiresStackProtector() {
242  bool Strong = false;
243  bool NeedsProtector = false;
244  for (const BasicBlock &BB : *F)
245  for (const Instruction &I : BB)
246  if (const CallInst *CI = dyn_cast<CallInst>(&I))
247  if (CI->getCalledFunction() ==
248  Intrinsic::getDeclaration(F->getParent(),
249  Intrinsic::stackprotector))
250  HasPrologue = true;
251 
252  if (F->hasFnAttribute(Attribute::SafeStack))
253  return false;
254 
255  // We are constructing the OptimizationRemarkEmitter on the fly rather than
256  // using the analysis pass to avoid building DominatorTree and LoopInfo which
257  // are not available this late in the IR pipeline.
259 
260  if (F->hasFnAttribute(Attribute::StackProtectReq)) {
261  ORE.emit([&]() {
262  return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
263  << "Stack protection applied to function "
264  << ore::NV("Function", F)
265  << " due to a function attribute or command-line switch";
266  });
267  NeedsProtector = true;
268  Strong = true; // Use the same heuristic as strong to determine SSPLayout
269  } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
270  Strong = true;
271  else if (HasPrologue)
272  NeedsProtector = true;
273  else if (!F->hasFnAttribute(Attribute::StackProtect))
274  return false;
275 
276  for (const BasicBlock &BB : *F) {
277  for (const Instruction &I : BB) {
278  if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
279  if (AI->isArrayAllocation()) {
280  auto RemarkBuilder = [&]() {
281  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
282  &I)
283  << "Stack protection applied to function "
284  << ore::NV("Function", F)
285  << " due to a call to alloca or use of a variable length "
286  "array";
287  };
288  if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
289  if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
290  // A call to alloca with size >= SSPBufferSize requires
291  // stack protectors.
292  Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
293  ORE.emit(RemarkBuilder);
294  NeedsProtector = true;
295  } else if (Strong) {
296  // Require protectors for all alloca calls in strong mode.
297  Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
298  ORE.emit(RemarkBuilder);
299  NeedsProtector = true;
300  }
301  } else {
302  // A call to alloca with a variable size requires protectors.
303  Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
304  ORE.emit(RemarkBuilder);
305  NeedsProtector = true;
306  }
307  continue;
308  }
309 
310  bool IsLarge = false;
311  if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
312  Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
313  : SSPLK_SmallArray));
314  ORE.emit([&]() {
315  return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
316  << "Stack protection applied to function "
317  << ore::NV("Function", F)
318  << " due to a stack allocated buffer or struct containing a "
319  "buffer";
320  });
321  NeedsProtector = true;
322  continue;
323  }
324 
325  if (Strong && HasAddressTaken(AI)) {
326  ++NumAddrTaken;
327  Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
328  ORE.emit([&]() {
329  return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
330  &I)
331  << "Stack protection applied to function "
332  << ore::NV("Function", F)
333  << " due to the address of a local variable being taken";
334  });
335  NeedsProtector = true;
336  }
337  }
338  }
339  }
340 
341  return NeedsProtector;
342 }
343 
344 /// Create a stack guard loading and populate whether SelectionDAG SSP is
345 /// supported.
347  IRBuilder<> &B,
348  bool *SupportsSelectionDAGSP = nullptr) {
349  if (Value *Guard = TLI->getIRStackGuard(B))
350  return B.CreateLoad(Guard, true, "StackGuard");
351 
352  // Use SelectionDAG SSP handling, since there isn't an IR guard.
353  //
354  // This is more or less weird, since we optionally output whether we
355  // should perform a SelectionDAG SP here. The reason is that it's strictly
356  // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
357  // mutating. There is no way to get this bit without mutating the IR, so
358  // getting this bit has to happen in this right time.
359  //
360  // We could have define a new function TLI::supportsSelectionDAGSP(), but that
361  // will put more burden on the backends' overriding work, especially when it
362  // actually conveys the same information getIRStackGuard() already gives.
363  if (SupportsSelectionDAGSP)
364  *SupportsSelectionDAGSP = true;
365  TLI->insertSSPDeclarations(*M);
366  return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
367 }
368 
369 /// Insert code into the entry block that stores the stack guard
370 /// variable onto the stack:
371 ///
372 /// entry:
373 /// StackGuardSlot = alloca i8*
374 /// StackGuard = <stack guard>
375 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
376 ///
377 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
378 /// node.
379 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
380  const TargetLoweringBase *TLI, AllocaInst *&AI) {
381  bool SupportsSelectionDAGSP = false;
382  IRBuilder<> B(&F->getEntryBlock().front());
383  PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
384  AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
385 
386  Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
387  B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
388  {GuardSlot, AI});
389  return SupportsSelectionDAGSP;
390 }
391 
392 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
393 /// function.
394 ///
395 /// - The prologue code loads and stores the stack guard onto the stack.
396 /// - The epilogue checks the value stored in the prologue against the original
397 /// value. It calls __stack_chk_fail if they differ.
398 bool StackProtector::InsertStackProtectors() {
399  // If the target wants to XOR the frame pointer into the guard value, it's
400  // impossible to emit the check in IR, so the target *must* support stack
401  // protection in SDAG.
402  bool SupportsSelectionDAGSP =
403  TLI->useStackGuardXorFP() ||
405  AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
406 
407  for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
408  BasicBlock *BB = &*I++;
410  if (!RI)
411  continue;
412 
413  // Generate prologue instrumentation if not already generated.
414  if (!HasPrologue) {
415  HasPrologue = true;
416  SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
417  }
418 
419  // SelectionDAG based code generation. Nothing else needs to be done here.
420  // The epilogue instrumentation is postponed to SelectionDAG.
421  if (SupportsSelectionDAGSP)
422  break;
423 
424  // Set HasIRCheck to true, so that SelectionDAG will not generate its own
425  // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
426  // instrumentation has already been generated.
427  HasIRCheck = true;
428 
429  // Generate epilogue instrumentation. The epilogue intrumentation can be
430  // function-based or inlined depending on which mechanism the target is
431  // providing.
432  if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
433  // Generate the function-based epilogue instrumentation.
434  // The target provides a guard check function, generate a call to it.
435  IRBuilder<> B(RI);
436  LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
437  CallInst *Call = B.CreateCall(GuardCheck, {Guard});
438  llvm::Function *Function = cast<llvm::Function>(GuardCheck);
439  Call->setAttributes(Function->getAttributes());
440  Call->setCallingConv(Function->getCallingConv());
441  } else {
442  // Generate the epilogue with inline instrumentation.
443  // If we do not support SelectionDAG based tail calls, generate IR level
444  // tail calls.
445  //
446  // For each block with a return instruction, convert this:
447  //
448  // return:
449  // ...
450  // ret ...
451  //
452  // into this:
453  //
454  // return:
455  // ...
456  // %1 = <stack guard>
457  // %2 = load StackGuardSlot
458  // %3 = cmp i1 %1, %2
459  // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
460  //
461  // SP_return:
462  // ret ...
463  //
464  // CallStackCheckFailBlk:
465  // call void @__stack_chk_fail()
466  // unreachable
467 
468  // Create the FailBB. We duplicate the BB every time since the MI tail
469  // merge pass will merge together all of the various BB into one including
470  // fail BB generated by the stack protector pseudo instruction.
471  BasicBlock *FailBB = CreateFailBB();
472 
473  // Split the basic block before the return instruction.
474  BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
475 
476  // Update the dominator tree if we need to.
477  if (DT && DT->isReachableFromEntry(BB)) {
478  DT->addNewBlock(NewBB, BB);
479  DT->addNewBlock(FailBB, BB);
480  }
481 
482  // Remove default branch instruction to the new BB.
484 
485  // Move the newly created basic block to the point right after the old
486  // basic block so that it's in the "fall through" position.
487  NewBB->moveAfter(BB);
488 
489  // Generate the stack protector instructions in the old basic block.
490  IRBuilder<> B(BB);
491  Value *Guard = getStackGuard(TLI, M, B);
492  LoadInst *LI2 = B.CreateLoad(AI, true);
493  Value *Cmp = B.CreateICmpEQ(Guard, LI2);
494  auto SuccessProb =
496  auto FailureProb =
498  MDNode *Weights = MDBuilder(F->getContext())
499  .createBranchWeights(SuccessProb.getNumerator(),
500  FailureProb.getNumerator());
501  B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
502  }
503  }
504 
505  // Return if we didn't modify any basic blocks. i.e., there are no return
506  // statements in the function.
507  return HasPrologue;
508 }
509 
510 /// CreateFailBB - Create a basic block to jump to when the stack protector
511 /// check fails.
512 BasicBlock *StackProtector::CreateFailBB() {
514  BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
515  IRBuilder<> B(FailBB);
517  if (Trip.isOSOpenBSD()) {
518  Constant *StackChkFail =
519  M->getOrInsertFunction("__stack_smash_handler",
520  Type::getVoidTy(Context),
521  Type::getInt8PtrTy(Context));
522 
523  B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
524  } else {
525  Constant *StackChkFail =
526  M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
527 
528  B.CreateCall(StackChkFail, {});
529  }
530  B.CreateUnreachable();
531  return FailBB;
532 }
533 
535  return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
536 }
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:468
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:788
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
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: ValueMap.h:179
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:142
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:63
iterator end()
Definition: Function.h:639
SSPLayoutKind getSSPLayout(const AllocaInst *AI) const
This class represents a function call, abstracting a target machine&#39;s calling convention.
virtual const TargetLowering * getTargetLowering() const
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:738
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:862
An instruction for reading from memory.
Definition: Instructions.h:164
static bool isLifetimeInst(const Instruction *I)
Hexagon Common GEP
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:294
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: ...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
Did not trigger a stack protector.
This class represents the LLVM &#39;select&#39; instruction.
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
Definition: Attributes.cpp:169
Class to represent struct types.
Definition: DerivedTypes.h:201
static cl::opt< bool > EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:677
This file contains the simple types necessary to represent the attributes associated with functions a...
DominatorTree & getDomTree()
Definition: Dominators.h:264
The address of this allocation is exposed and triggered protection.
Target-Independent Code Generator Pass Configuration Options.
This class represents a cast from a pointer to an integer.
Class to represent array types.
Definition: DerivedTypes.h:369
Value * 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:1481
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
iterator find(const KeyT &Val)
Definition: ValueMap.h:162
SSPLayoutKind
SSPLayoutKind.
This class represents a no-op cast from one type to another.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:205
An instruction for storing to memory.
Definition: Instructions.h:306
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:683
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:151
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:171
iterator begin()
Definition: Function.h:637
Type::subtype_iterator element_iterator
Definition: DerivedTypes.h:301
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:993
Class to represent pointers.
Definition: DerivedTypes.h:467
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
#define DEBUG_TYPE
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
const BasicBlock & getEntryBlock() const
Definition: Function.h:621
virtual Value * getIRStackGuard(IRBuilder<> &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:837
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool&#39; fo...
Definition: IRBuilder.h:1251
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
UnreachableInst * CreateUnreachable()
Definition: IRBuilder.h:872
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1505
bool isOSOpenBSD() const
Definition: Triple.h:480
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Definition: BasicBlock.h:264
Diagnostic information for applied optimization remarks.
element_iterator element_end() const
Definition: DerivedTypes.h:304
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:161
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
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:101
void adjustForColoring(const AllocaInst *From, const AllocaInst *To)
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1677
self_iterator getIterator()
Definition: ilist_node.h:82
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:193
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
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
void setCallingConv(CallingConv::ID CC)
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:497
iterator end()
Definition: ValueMap.h:142
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:110
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
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:194
Module.h This file contains the declarations for the Module class.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
iterator_range< user_iterator > users()
Definition: Value.h:405
element_iterator element_begin() const
Definition: DerivedTypes.h:303
virtual Value * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
Basic Alias true
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:194
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
TargetOptions Options
Definition: TargetMachine.h:98
#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.
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:323
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:383
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1273
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:312
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:254
const TerminatorInst * 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:120
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)
Array or nested array >= SSP-buffer-size.
bool erase(const KeyT &Val)
Definition: ValueMap.h:197
Array or nested array < SSP-buffer-size.
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack
Definition: Instructions.h:60
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1812