LCOV - code coverage report
Current view: top level - lib/CodeGen - StackProtector.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 167 173 96.5 %
Date: 2018-06-17 00:07:59 Functions: 21 21 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       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             : 
      17             : #include "llvm/CodeGen/StackProtector.h"
      18             : #include "llvm/ADT/SmallPtrSet.h"
      19             : #include "llvm/ADT/Statistic.h"
      20             : #include "llvm/Analysis/BranchProbabilityInfo.h"
      21             : #include "llvm/Analysis/EHPersonalities.h"
      22             : #include "llvm/Analysis/OptimizationRemarkEmitter.h"
      23             : #include "llvm/CodeGen/Passes.h"
      24             : #include "llvm/CodeGen/TargetLowering.h"
      25             : #include "llvm/CodeGen/TargetPassConfig.h"
      26             : #include "llvm/CodeGen/TargetSubtargetInfo.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"
      47             : #include "llvm/Support/CommandLine.h"
      48             : #include "llvm/Target/TargetMachine.h"
      49             : #include "llvm/Target/TargetOptions.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      101169 : static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
      61      101169 :                                           cl::init(true), cl::Hidden);
      62             : 
      63             : char StackProtector::ID = 0;
      64             : 
      65       26770 : INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
      66             :                       "Insert stack protectors", false, true)
      67       26770 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      68      354374 : INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
      69             :                     "Insert stack protectors", false, true)
      70             : 
      71       22791 : FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
      72             : 
      73             : StackProtector::SSPLayoutKind
      74        1795 : StackProtector::getSSPLayout(const AllocaInst *AI) const {
      75        3590 :   return AI ? Layout.lookup(AI) : SSPLK_None;
      76             : }
      77             : 
      78        9602 : void StackProtector::adjustForColoring(const AllocaInst *From,
      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        9602 :   if (I != Layout.end()) {
      85         170 :     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         170 :     if (I == Layout.end())
      93           0 :       Layout.insert(std::make_pair(To, Kind));
      94         170 :     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
      95           1 :       I->second = Kind;
      96             :   }
      97        9602 : }
      98             : 
      99       22710 : void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
     100             :   AU.addRequired<TargetPassConfig>();
     101             :   AU.addPreserved<DominatorTreeWrapperPass>();
     102       22710 : }
     103             : 
     104      227654 : bool StackProtector::runOnFunction(Function &Fn) {
     105      227654 :   F = &Fn;
     106      227654 :   M = F->getParent();
     107             :   DominatorTreeWrapperPass *DTWP =
     108      227654 :       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
     109      455308 :   DT = DTWP ? &DTWP->getDomTree() : nullptr;
     110      227654 :   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
     111             :   Trip = TM->getTargetTriple();
     112      227654 :   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
     113      227654 :   HasPrologue = false;
     114      227654 :   HasIRCheck = false;
     115             : 
     116      227654 :   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
     117      227654 :   if (Attr.isStringAttribute() &&
     118       45732 :       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
     119             :     return false; // Invalid integer string
     120             : 
     121      227654 :   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         791 :   if (Fn.hasPersonalityFn()) {
     127         137 :     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
     128             :     if (isFuncletEHPersonality(Personality))
     129             :       return false;
     130             :   }
     131             : 
     132             :   ++NumFunProtected;
     133         790 :   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        7301 : bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
     140             :                                               bool Strong,
     141             :                                               bool InStruct) const {
     142        7301 :   if (!Ty)
     143             :     return false;
     144             :   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
     145        1089 :     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         589 :       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         665 :     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
     157         488 :       IsLarge = true;
     158         488 :       return true;
     159             :     }
     160             : 
     161         177 :     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;
     171        5402 :   for (StructType::element_iterator I = ST->element_begin(),
     172        2006 :                                     E = ST->element_end();
     173        5402 :        I != E; ++I)
     174        3904 :     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         682 :       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         353 :     return Id == Intrinsic::lifetime_start || Id == Intrinsic::lifetime_end;
     190             :   }
     191             :   return false;
     192             : }
     193             : 
     194        2007 : bool StackProtector::HasAddressTaken(const Instruction *AI) {
     195        4125 :   for (const User *U : AI->users()) {
     196             :     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
     197         420 :       if (AI == SI->getValueOperand())
     198             :         return true;
     199             :     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
     200          35 :       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         353 :       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          18 :       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          31 :       if (VisitedPHIs.insert(PN).second)
     215          23 :         if (HasAddressTaken(PN))
     216             :           return true;
     217             :     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
     218         251 :       if (HasAddressTaken(GEP))
     219             :         return true;
     220             :     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
     221         854 :       if (HasAddressTaken(BI))
     222             :         return true;
     223             :     }
     224             :   }
     225             :   return false;
     226             : }
     227             : 
     228             : /// 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      227654 : bool StackProtector::RequiresStackProtector() {
     242             :   bool Strong = false;
     243             :   bool NeedsProtector = false;
     244      882223 :   for (const BasicBlock &BB : *F)
     245     3377165 :     for (const Instruction &I : BB)
     246             :       if (const CallInst *CI = dyn_cast<CallInst>(&I))
     247      454580 :         if (CI->getCalledFunction() ==
     248      454580 :             Intrinsic::getDeclaration(F->getParent(),
     249             :                                       Intrinsic::stackprotector))
     250           2 :           HasPrologue = true;
     251             : 
     252      455308 :   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.
     258      227642 :   OptimizationRemarkEmitter ORE(F);
     259             : 
     260      455284 :   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
     261         236 :     ORE.emit([&]() {
     262          16 :       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
     263             :              << "Stack protection applied to function "
     264          12 :              << ore::NV("Function", F)
     265           4 :              << " due to a function attribute or command-line switch";
     266           4 :     });
     267             :     NeedsProtector = true;
     268             :     Strong = true; // Use the same heuristic as strong to determine SSPLayout
     269      454820 :   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
     270             :     Strong = true;
     271      226726 :   else if (HasPrologue)
     272             :     NeedsProtector = true;
     273      453448 :   else if (!F->hasFnAttribute(Attribute::StackProtect))
     274             :     return false;
     275             : 
     276       26792 :   for (const BasicBlock &BB : *F) {
     277      179562 :     for (const Instruction &I : BB) {
     278             :       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
     279        3480 :         if (AI->isArrayAllocation()) {
     280           8 :           auto RemarkBuilder = [&]() {
     281          16 :             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
     282           8 :                                       &I)
     283             :                    << "Stack protection applied to function "
     284          24 :                    << ore::NV("Function", F)
     285             :                    << " due to a call to alloca or use of a variable length "
     286           8 :                       "array";
     287          91 :           };
     288             :           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
     289          56 :             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
     290             :               // A call to alloca with size >= SSPBufferSize requires
     291             :               // stack protectors.
     292          11 :               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
     293          11 :               ORE.emit(RemarkBuilder);
     294             :               NeedsProtector = true;
     295          17 :             } else if (Strong) {
     296             :               // Require protectors for all alloca calls in strong mode.
     297           6 :               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
     298           6 :               ORE.emit(RemarkBuilder);
     299             :               NeedsProtector = true;
     300             :             }
     301             :           } else {
     302             :             // A call to alloca with a variable size requires protectors.
     303          55 :             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
     304          55 :             ORE.emit(RemarkBuilder);
     305             :             NeedsProtector = true;
     306             :           }
     307          83 :           continue;
     308             :         }
     309             : 
     310        3397 :         bool IsLarge = false;
     311        3397 :         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
     312         581 :           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
     313         581 :                                                    : SSPLK_SmallArray));
     314         589 :           ORE.emit([&]() {
     315          24 :             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
     316             :                    << "Stack protection applied to function "
     317          24 :                    << ore::NV("Function", F)
     318             :                    << " due to a stack allocated buffer or struct containing a "
     319           8 :                       "buffer";
     320           8 :           });
     321             :           NeedsProtector = true;
     322         581 :           continue;
     323             :         }
     324             : 
     325        2816 :         if (Strong && HasAddressTaken(AI)) {
     326             :           ++NumAddrTaken;
     327         528 :           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
     328         532 :           ORE.emit([&]() {
     329           8 :             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
     330           4 :                                       &I)
     331             :                    << "Stack protection applied to function "
     332          12 :                    << ore::NV("Function", F)
     333           4 :                    << " due to the address of a local variable being taken";
     334           4 :           });
     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.
     346        1260 : static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
     347             :                             IRBuilder<> &B,
     348             :                             bool *SupportsSelectionDAGSP = nullptr) {
     349        1260 :   if (Value *Guard = TLI->getIRStackGuard(B))
     350         907 :     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         353 :   if (SupportsSelectionDAGSP)
     364         339 :     *SupportsSelectionDAGSP = true;
     365         353 :   TLI->insertSSPDeclarations(*M);
     366         706 :   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         780 : static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
     380             :                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
     381         780 :   bool SupportsSelectionDAGSP = false;
     382         780 :   IRBuilder<> B(&F->getEntryBlock().front());
     383         780 :   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
     384         780 :   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
     385             : 
     386         780 :   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
     387        3120 :   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
     388         780 :                {GuardSlot, AI});
     389        1560 :   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         790 : 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        1445 :       TLI->useStackGuardXorFP() ||
     404         654 :       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
     405         790 :   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
     406             : 
     407        7901 :   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
     408             :     BasicBlock *BB = &*I++;
     409             :     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
     410        5841 :     if (!RI)
     411        5841 :       continue;
     412             : 
     413             :     // Generate prologue instrumentation if not already generated.
     414         807 :     if (!HasPrologue) {
     415         780 :       HasPrologue = true;
     416         780 :       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         807 :     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         480 :     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         480 :     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           0 :       IRBuilder<> B(RI);
     436           0 :       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
     437           0 :       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         480 :       BasicBlock *FailBB = CreateFailBB();
     472             : 
     473             :       // Split the basic block before the return instruction.
     474         480 :       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
     475             : 
     476             :       // Update the dominator tree if we need to.
     477         480 :       if (DT && DT->isReachableFromEntry(BB)) {
     478           0 :         DT->addNewBlock(NewBB, BB);
     479           0 :         DT->addNewBlock(FailBB, BB);
     480             :       }
     481             : 
     482             :       // Remove default branch instruction to the new BB.
     483         480 :       BB->getTerminator()->eraseFromParent();
     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         480 :       NewBB->moveAfter(BB);
     488             : 
     489             :       // Generate the stack protector instructions in the old basic block.
     490             :       IRBuilder<> B(BB);
     491         480 :       Value *Guard = getStackGuard(TLI, M, B);
     492         480 :       LoadInst *LI2 = B.CreateLoad(AI, true);
     493         480 :       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
     494             :       auto SuccessProb =
     495         480 :           BranchProbabilityInfo::getBranchProbStackProtector(true);
     496             :       auto FailureProb =
     497         480 :           BranchProbabilityInfo::getBranchProbStackProtector(false);
     498         960 :       MDNode *Weights = MDBuilder(F->getContext())
     499             :                             .createBranchWeights(SuccessProb.getNumerator(),
     500         480 :                                                  FailureProb.getNumerator());
     501         480 :       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         790 :   return HasPrologue;
     508             : }
     509             : 
     510             : /// CreateFailBB - Create a basic block to jump to when the stack protector
     511             : /// check fails.
     512         480 : BasicBlock *StackProtector::CreateFailBB() {
     513         480 :   LLVMContext &Context = F->getContext();
     514         960 :   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
     515             :   IRBuilder<> B(FailBB);
     516         960 :   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
     517         480 :   if (Trip.isOSOpenBSD()) {
     518             :     Constant *StackChkFail =
     519          62 :         M->getOrInsertFunction("__stack_smash_handler",
     520             :                                Type::getVoidTy(Context),
     521             :                                Type::getInt8PtrTy(Context));
     522             : 
     523         124 :     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
     524             :   } else {
     525             :     Constant *StackChkFail =
     526         418 :         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
     527             : 
     528         418 :     B.CreateCall(StackChkFail, {});
     529             :   }
     530         480 :   B.CreateUnreachable();
     531         480 :   return FailBB;
     532             : }
     533             : 
     534      426448 : bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
     535      852896 :   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
     536      303507 : }

Generated by: LCOV version 1.13