LCOV - code coverage report
Current view: top level - lib/CodeGen - StackProtector.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 198 201 98.5 %
Date: 2017-09-14 15:23:50 Functions: 17 17 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/ADT/SmallPtrSet.h"
      18             : #include "llvm/ADT/Statistic.h"
      19             : #include "llvm/Analysis/BranchProbabilityInfo.h"
      20             : #include "llvm/Analysis/EHPersonalities.h"
      21             : #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
      22             : #include "llvm/CodeGen/Passes.h"
      23             : #include "llvm/CodeGen/StackProtector.h"
      24             : #include "llvm/CodeGen/TargetPassConfig.h"
      25             : #include "llvm/IR/Attributes.h"
      26             : #include "llvm/IR/BasicBlock.h"
      27             : #include "llvm/IR/Constants.h"
      28             : #include "llvm/IR/DataLayout.h"
      29             : #include "llvm/IR/DebugInfo.h"
      30             : #include "llvm/IR/DebugLoc.h"
      31             : #include "llvm/IR/DerivedTypes.h"
      32             : #include "llvm/IR/Dominators.h"
      33             : #include "llvm/IR/Function.h"
      34             : #include "llvm/IR/IRBuilder.h"
      35             : #include "llvm/IR/Instruction.h"
      36             : #include "llvm/IR/Instructions.h"
      37             : #include "llvm/IR/Intrinsics.h"
      38             : #include "llvm/IR/MDBuilder.h"
      39             : #include "llvm/IR/Module.h"
      40             : #include "llvm/IR/Type.h"
      41             : #include "llvm/IR/User.h"
      42             : #include "llvm/Pass.h"
      43             : #include "llvm/Support/Casting.h"
      44             : #include "llvm/Support/CommandLine.h"
      45             : #include "llvm/Target/TargetLowering.h"
      46             : #include "llvm/Target/TargetMachine.h"
      47             : #include "llvm/Target/TargetOptions.h"
      48             : #include "llvm/Target/TargetSubtargetInfo.h"
      49             : #include <utility>
      50             : 
      51             : using namespace llvm;
      52             : 
      53             : #define DEBUG_TYPE "stack-protector"
      54             : 
      55             : STATISTIC(NumFunProtected, "Number of functions protected");
      56             : STATISTIC(NumAddrTaken, "Number of local variables that have their address"
      57             :                         " taken.");
      58             : 
      59       72306 : static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
      60      144612 :                                           cl::init(true), cl::Hidden);
      61             : 
      62             : char StackProtector::ID = 0;
      63             : 
      64       20212 : INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
      65             :                       "Insert stack protectors", false, true)
      66       20212 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      67      383903 : INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
      68             :                     "Insert stack protectors", false, true)
      69             : 
      70       16923 : FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
      71             : 
      72             : StackProtector::SSPLayoutKind
      73        1455 : StackProtector::getSSPLayout(const AllocaInst *AI) const {
      74        2714 :   return AI ? Layout.lookup(AI) : SSPLK_None;
      75             : }
      76             : 
      77        9259 : void StackProtector::adjustForColoring(const AllocaInst *From,
      78             :                                        const AllocaInst *To) {
      79             :   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
      80             :   // tag from the remapped to the target alloca. The remapped alloca should
      81             :   // have a size smaller than or equal to the replacement alloca.
      82       18518 :   SSPLayoutMap::iterator I = Layout.find(From);
      83       27777 :   if (I != Layout.end()) {
      84         134 :     SSPLayoutKind Kind = I->second;
      85         268 :     Layout.erase(I);
      86             : 
      87             :     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
      88             :     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
      89             :     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
      90         268 :     I = Layout.find(To);
      91         402 :     if (I == Layout.end())
      92           0 :       Layout.insert(std::make_pair(To, Kind));
      93         134 :     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
      94           1 :       I->second = Kind;
      95             :   }
      96        9259 : }
      97             : 
      98       16898 : void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
      99       16898 :   AU.addRequired<TargetPassConfig>();
     100       16898 :   AU.addPreserved<DominatorTreeWrapperPass>();
     101       16898 : }
     102             : 
     103      143201 : bool StackProtector::runOnFunction(Function &Fn) {
     104      143201 :   F = &Fn;
     105      143201 :   M = F->getParent();
     106             :   DominatorTreeWrapperPass *DTWP =
     107      143201 :       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
     108      143210 :   DT = DTWP ? &DTWP->getDomTree() : nullptr;
     109      143201 :   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
     110      286402 :   Trip = TM->getTargetTriple();
     111      143201 :   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
     112      143201 :   HasPrologue = false;
     113      143201 :   HasIRCheck = false;
     114             : 
     115      286402 :   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
     116      143201 :   if (Attr.isStringAttribute() &&
     117       14066 :       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
     118             :     return false; // Invalid integer string
     119             : 
     120      143201 :   if (!RequiresStackProtector())
     121             :     return false;
     122             : 
     123             :   // TODO(etienneb): Functions with funclets are not correctly supported now.
     124             :   // Do nothing if this is funclet-based personality.
     125         625 :   if (Fn.hasPersonalityFn()) {
     126         106 :     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
     127             :     if (isFuncletEHPersonality(Personality))
     128             :       return false;
     129             :   }
     130             : 
     131         624 :   ++NumFunProtected;
     132         624 :   return InsertStackProtectors();
     133             : }
     134             : 
     135             : /// \param [out] IsLarge is set to true if a protectable array is found and
     136             : /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
     137             : /// multiple arrays, this gets set if any of them is large.
     138        6206 : bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
     139             :                                               bool Strong,
     140             :                                               bool InStruct) const {
     141        6206 :   if (!Ty)
     142             :     return false;
     143         993 :   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
     144         993 :     if (!AT->getElementType()->isIntegerTy(8)) {
     145             :       // If we're on a non-Darwin platform or we're inside of a structure, don't
     146             :       // add stack protectors unless the array is a character array.
     147             :       // However, in strong mode any array, regardless of type and size,
     148             :       // triggers a protector.
     149         573 :       if (!Strong && (InStruct || !Trip.isOSDarwin()))
     150             :         return false;
     151             :     }
     152             : 
     153             :     // If an array has more than SSPBufferSize bytes of allocated space, then we
     154             :     // emit stack protectors.
     155         571 :     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
     156         427 :       IsLarge = true;
     157         427 :       return true;
     158             :     }
     159             : 
     160         144 :     if (Strong)
     161             :       // Require a protector for all arrays in strong mode
     162             :       return true;
     163             :   }
     164             : 
     165        1726 :   const StructType *ST = dyn_cast<StructType>(Ty);
     166             :   if (!ST)
     167             :     return false;
     168             : 
     169        1726 :   bool NeedsProtector = false;
     170        4554 :   for (StructType::element_iterator I = ST->element_begin(),
     171        1726 :                                     E = ST->element_end();
     172        4554 :        I != E; ++I)
     173        3259 :     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
     174             :       // If the element is a protectable array and is large (>= SSPBufferSize)
     175             :       // then we are done.  If the protectable array is not large, then
     176             :       // keep looking in case a subsequent element is a large array.
     177         564 :       if (IsLarge)
     178             :         return true;
     179             :       NeedsProtector = true;
     180             :     }
     181             : 
     182             :   return NeedsProtector;
     183             : }
     184             : 
     185        1471 : bool StackProtector::HasAddressTaken(const Instruction *AI) {
     186        7408 :   for (const User *U : AI->users()) {
     187        2183 :     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
     188         323 :       if (AI == SI->getValueOperand())
     189             :         return true;
     190        1561 :     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
     191          48 :       if (AI == SI->getOperand(0))
     192             :         return true;
     193        1513 :     } else if (isa<CallInst>(U)) {
     194             :       return true;
     195        1230 :     } else if (isa<InvokeInst>(U)) {
     196             :       return true;
     197        1210 :     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
     198          12 :       if (HasAddressTaken(SI))
     199             :         return true;
     200        1208 :     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
     201             :       // Keep track of what PHI nodes we have already visited to ensure
     202             :       // they are only visited once.
     203          22 :       if (VisitedPHIs.insert(PN).second)
     204          18 :         if (HasAddressTaken(PN))
     205             :           return true;
     206        1341 :     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
     207         177 :       if (HasAddressTaken(GEP))
     208             :         return true;
     209        1595 :     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
     210         608 :       if (HasAddressTaken(BI))
     211             :         return true;
     212             :     }
     213             :   }
     214             :   return false;
     215             : }
     216             : 
     217             : /// \brief Check whether or not this function needs a stack protector based
     218             : /// upon the stack protector level.
     219             : ///
     220             : /// We use two heuristics: a standard (ssp) and strong (sspstrong).
     221             : /// The standard heuristic which will add a guard variable to functions that
     222             : /// call alloca with a either a variable size or a size >= SSPBufferSize,
     223             : /// functions with character buffers larger than SSPBufferSize, and functions
     224             : /// with aggregates containing character buffers larger than SSPBufferSize. The
     225             : /// strong heuristic will add a guard variables to functions that call alloca
     226             : /// regardless of size, functions with any buffer regardless of type and size,
     227             : /// functions with aggregates that contain any buffer regardless of type and
     228             : /// size, and functions that contain stack-based variables that have had their
     229             : /// address taken.
     230      143201 : bool StackProtector::RequiresStackProtector() {
     231      143201 :   bool Strong = false;
     232      143201 :   bool NeedsProtector = false;
     233      709580 :   for (const BasicBlock &BB : *F)
     234     2845111 :     for (const Instruction &I : BB)
     235      305679 :       if (const CallInst *CI = dyn_cast<CallInst>(&I))
     236      611358 :         if (CI->getCalledFunction() ==
     237      305679 :             Intrinsic::getDeclaration(F->getParent(),
     238             :                                       Intrinsic::stackprotector))
     239           2 :           HasPrologue = true;
     240             : 
     241      286402 :   if (F->hasFnAttribute(Attribute::SafeStack))
     242             :     return false;
     243             : 
     244             :   // We are constructing the OptimizationRemarkEmitter on the fly rather than
     245             :   // using the analysis pass to avoid building DominatorTree and LoopInfo which
     246             :   // are not available this late in the IR pipeline.
     247      143192 :   OptimizationRemarkEmitter ORE(F);
     248             : 
     249      286384 :   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
     250         724 :     ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
     251         362 :              << "Stack protection applied to function "
     252         543 :              << ore::NV("Function", F)
     253             :              << " due to a function attribute or command-line switch");
     254         181 :     NeedsProtector = true;
     255         181 :     Strong = true; // Use the same heuristic as strong to determine SSPLayout
     256      286022 :   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
     257             :     Strong = true;
     258      142470 :   else if (HasPrologue)
     259             :     NeedsProtector = true;
     260      284936 :   else if (!F->hasFnAttribute(Attribute::StackProtect))
     261             :     return false;
     262             : 
     263       27977 :   for (const BasicBlock &BB : *F) {
     264      173209 :     for (const Instruction &I : BB) {
     265        3010 :       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
     266        3010 :         if (AI->isArrayAllocation()) {
     267             :           OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
     268         126 :                                     &I);
     269             :           Remark
     270         126 :               << "Stack protection applied to function "
     271         189 :               << ore::NV("Function", F)
     272          63 :               << " due to a call to alloca or use of a variable length array";
     273         150 :           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
     274          48 :             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
     275             :               // A call to alloca with size >= SSPBufferSize requires
     276             :               // stack protectors.
     277          18 :               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
     278           9 :               ORE.emit(Remark);
     279           9 :               NeedsProtector = true;
     280          15 :             } else if (Strong) {
     281             :               // Require protectors for all alloca calls in strong mode.
     282          12 :               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
     283           6 :               ORE.emit(Remark);
     284           6 :               NeedsProtector = true;
     285             :             }
     286             :           } else {
     287             :             // A call to alloca with a variable size requires protectors.
     288          78 :             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
     289          39 :             ORE.emit(Remark);
     290          39 :             NeedsProtector = true;
     291             :           }
     292             :           continue;
     293             :         }
     294             : 
     295        2947 :         bool IsLarge = false;
     296        3450 :         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
     297        1006 :           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
     298         503 :                                                    : SSPLK_SmallArray));
     299        1509 :           ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
     300        1006 :                    << "Stack protection applied to function "
     301        1509 :                    << ore::NV("Function", F)
     302             :                    << " due to a stack allocated buffer or struct containing a "
     303             :                       "buffer");
     304         503 :           NeedsProtector = true;
     305         503 :           continue;
     306             :         }
     307             : 
     308        2444 :         if (Strong && HasAddressTaken(AI)) {
     309         407 :           ++NumAddrTaken;
     310         814 :           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
     311         407 :           ORE.emit(
     312         814 :               OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I)
     313         814 :               << "Stack protection applied to function "
     314        1221 :               << ore::NV("Function", F)
     315             :               << " due to the address of a local variable being taken");
     316         407 :           NeedsProtector = true;
     317             :         }
     318             :       }
     319             :     }
     320             :   }
     321             : 
     322             :   return NeedsProtector;
     323             : }
     324             : 
     325             : /// Create a stack guard loading and populate whether SelectionDAG SSP is
     326             : /// supported.
     327        1003 : static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
     328             :                             IRBuilder<> &B,
     329             :                             bool *SupportsSelectionDAGSP = nullptr) {
     330        1003 :   if (Value *Guard = TLI->getIRStackGuard(B))
     331         730 :     return B.CreateLoad(Guard, true, "StackGuard");
     332             : 
     333             :   // Use SelectionDAG SSP handling, since there isn't an IR guard.
     334             :   //
     335             :   // This is more or less weird, since we optionally output whether we
     336             :   // should perform a SelectionDAG SP here. The reason is that it's strictly
     337             :   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
     338             :   // mutating. There is no way to get this bit without mutating the IR, so
     339             :   // getting this bit has to happen in this right time.
     340             :   //
     341             :   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
     342             :   // will put more burden on the backends' overriding work, especially when it
     343             :   // actually conveys the same information getIRStackGuard() already gives.
     344         273 :   if (SupportsSelectionDAGSP)
     345         259 :     *SupportsSelectionDAGSP = true;
     346         273 :   TLI->insertSSPDeclarations(*M);
     347         819 :   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
     348             : }
     349             : 
     350             : /// Insert code into the entry block that stores the stack guard
     351             : /// variable onto the stack:
     352             : ///
     353             : ///   entry:
     354             : ///     StackGuardSlot = alloca i8*
     355             : ///     StackGuard = <stack guard>
     356             : ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
     357             : ///
     358             : /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
     359             : /// node.
     360         614 : static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
     361             :                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
     362         614 :   bool SupportsSelectionDAGSP = false;
     363        2456 :   IRBuilder<> B(&F->getEntryBlock().front());
     364         614 :   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
     365         614 :   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
     366             : 
     367         614 :   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
     368        3070 :   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
     369         614 :                {GuardSlot, AI});
     370        1228 :   return SupportsSelectionDAGSP;
     371             : }
     372             : 
     373             : /// InsertStackProtectors - Insert code into the prologue and epilogue of the
     374             : /// function.
     375             : ///
     376             : ///  - The prologue code loads and stores the stack guard onto the stack.
     377             : ///  - The epilogue checks the value stored in the prologue against the original
     378             : ///    value. It calls __stack_chk_fail if they differ.
     379         624 : bool StackProtector::InsertStackProtectors() {
     380             :   bool SupportsSelectionDAGSP =
     381         624 :       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
     382         624 :   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
     383             : 
     384        1872 :   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
     385       16056 :     BasicBlock *BB = &*I++;
     386        5988 :     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
     387        4716 :     if (!RI)
     388        4716 :       continue;
     389             : 
     390             :     // Generate prologue instrumentation if not already generated.
     391         636 :     if (!HasPrologue) {
     392         614 :       HasPrologue = true;
     393         614 :       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
     394             :     }
     395             : 
     396             :     // SelectionDAG based code generation. Nothing else needs to be done here.
     397             :     // The epilogue instrumentation is postponed to SelectionDAG.
     398         636 :     if (SupportsSelectionDAGSP)
     399             :       break;
     400             : 
     401             :     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
     402             :     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
     403             :     // instrumentation has already been generated.
     404         390 :     HasIRCheck = true;
     405             : 
     406             :     // Generate epilogue instrumentation. The epilogue intrumentation can be
     407             :     // function-based or inlined depending on which mechanism the target is
     408             :     // providing.
     409         390 :     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
     410             :       // Generate the function-based epilogue instrumentation.
     411             :       // The target provides a guard check function, generate a call to it.
     412           2 :       IRBuilder<> B(RI);
     413           1 :       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
     414           3 :       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
     415           1 :       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
     416           1 :       Call->setAttributes(Function->getAttributes());
     417           2 :       Call->setCallingConv(Function->getCallingConv());
     418             :     } else {
     419             :       // Generate the epilogue with inline instrumentation.
     420             :       // If we do not support SelectionDAG based tail calls, generate IR level
     421             :       // tail calls.
     422             :       //
     423             :       // For each block with a return instruction, convert this:
     424             :       //
     425             :       //   return:
     426             :       //     ...
     427             :       //     ret ...
     428             :       //
     429             :       // into this:
     430             :       //
     431             :       //   return:
     432             :       //     ...
     433             :       //     %1 = <stack guard>
     434             :       //     %2 = load StackGuardSlot
     435             :       //     %3 = cmp i1 %1, %2
     436             :       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
     437             :       //
     438             :       //   SP_return:
     439             :       //     ret ...
     440             :       //
     441             :       //   CallStackCheckFailBlk:
     442             :       //     call void @__stack_chk_fail()
     443             :       //     unreachable
     444             : 
     445             :       // Create the FailBB. We duplicate the BB every time since the MI tail
     446             :       // merge pass will merge together all of the various BB into one including
     447             :       // fail BB generated by the stack protector pseudo instruction.
     448         389 :       BasicBlock *FailBB = CreateFailBB();
     449             : 
     450             :       // Split the basic block before the return instruction.
     451         778 :       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
     452             : 
     453             :       // Update the dominator tree if we need to.
     454         389 :       if (DT && DT->isReachableFromEntry(BB)) {
     455           0 :         DT->addNewBlock(NewBB, BB);
     456           0 :         DT->addNewBlock(FailBB, BB);
     457             :       }
     458             : 
     459             :       // Remove default branch instruction to the new BB.
     460         389 :       BB->getTerminator()->eraseFromParent();
     461             : 
     462             :       // Move the newly created basic block to the point right after the old
     463             :       // basic block so that it's in the "fall through" position.
     464         389 :       NewBB->moveAfter(BB);
     465             : 
     466             :       // Generate the stack protector instructions in the old basic block.
     467        1167 :       IRBuilder<> B(BB);
     468         389 :       Value *Guard = getStackGuard(TLI, M, B);
     469         389 :       LoadInst *LI2 = B.CreateLoad(AI, true);
     470         778 :       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
     471             :       auto SuccessProb =
     472         389 :           BranchProbabilityInfo::getBranchProbStackProtector(true);
     473             :       auto FailureProb =
     474         389 :           BranchProbabilityInfo::getBranchProbStackProtector(false);
     475        1167 :       MDNode *Weights = MDBuilder(F->getContext())
     476         778 :                             .createBranchWeights(SuccessProb.getNumerator(),
     477         389 :                                                  FailureProb.getNumerator());
     478         389 :       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
     479             :     }
     480             :   }
     481             : 
     482             :   // Return if we didn't modify any basic blocks. i.e., there are no return
     483             :   // statements in the function.
     484         624 :   return HasPrologue;
     485             : }
     486             : 
     487             : /// CreateFailBB - Create a basic block to jump to when the stack protector
     488             : /// check fails.
     489         389 : BasicBlock *StackProtector::CreateFailBB() {
     490         389 :   LLVMContext &Context = F->getContext();
     491        1167 :   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
     492        1167 :   IRBuilder<> B(FailBB);
     493        1167 :   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
     494         778 :   if (Trip.isOSOpenBSD()) {
     495             :     Constant *StackChkFail =
     496         124 :         M->getOrInsertFunction("__stack_smash_handler",
     497             :                                Type::getVoidTy(Context),
     498          62 :                                Type::getInt8PtrTy(Context));
     499             : 
     500         186 :     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
     501             :   } else {
     502             :     Constant *StackChkFail =
     503         654 :         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
     504             : 
     505         654 :     B.CreateCall(StackChkFail, {});
     506             :   }
     507         389 :   B.CreateUnreachable();
     508         778 :   return FailBB;
     509             : }
     510             : 
     511      279650 : bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
     512      559300 :   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
     513      216918 : }

Generated by: LCOV version 1.13