LCOV - code coverage report
Current view: top level - lib/CodeGen - StackProtector.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 147 153 96.1 %
Date: 2018-10-20 13:21:21 Functions: 14 14 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             : static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
      61             :                                           cl::init(true), cl::Hidden);
      62             : 
      63             : char StackProtector::ID = 0;
      64             : 
      65       31780 : INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
      66             :                       "Insert stack protectors", false, true)
      67       31780 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      68      112604 : INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
      69             :                     "Insert stack protectors", false, true)
      70             : 
      71       27453 : FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
      72             : 
      73       27330 : void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
      74             :   AU.addRequired<TargetPassConfig>();
      75             :   AU.addPreserved<DominatorTreeWrapperPass>();
      76       27330 : }
      77             : 
      78      406474 : bool StackProtector::runOnFunction(Function &Fn) {
      79      406474 :   F = &Fn;
      80      406474 :   M = F->getParent();
      81             :   DominatorTreeWrapperPass *DTWP =
      82      406474 :       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
      83      406474 :   DT = DTWP ? &DTWP->getDomTree() : nullptr;
      84      406474 :   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
      85             :   Trip = TM->getTargetTriple();
      86      406474 :   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
      87      406474 :   HasPrologue = false;
      88      406474 :   HasIRCheck = false;
      89             : 
      90      406474 :   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
      91      406474 :   if (Attr.isStringAttribute() &&
      92      416188 :       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
      93           0 :     return false; // Invalid integer string
      94             : 
      95      406474 :   if (!RequiresStackProtector())
      96             :     return false;
      97             : 
      98             :   // TODO(etienneb): Functions with funclets are not correctly supported now.
      99             :   // Do nothing if this is funclet-based personality.
     100        1267 :   if (Fn.hasPersonalityFn()) {
     101         521 :     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
     102             :     if (isFuncletEHPersonality(Personality))
     103             :       return false;
     104             :   }
     105             : 
     106             :   ++NumFunProtected;
     107        1264 :   return InsertStackProtectors();
     108             : }
     109             : 
     110             : /// \param [out] IsLarge is set to true if a protectable array is found and
     111             : /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
     112             : /// multiple arrays, this gets set if any of them is large.
     113       14088 : bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
     114             :                                               bool Strong,
     115             :                                               bool InStruct) const {
     116       14088 :   if (!Ty)
     117             :     return false;
     118             :   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
     119        1293 :     if (!AT->getElementType()->isIntegerTy(8)) {
     120             :       // If we're on a non-Darwin platform or we're inside of a structure, don't
     121             :       // add stack protectors unless the array is a character array.
     122             :       // However, in strong mode any array, regardless of type and size,
     123             :       // triggers a protector.
     124         680 :       if (!Strong && (InStruct || !Trip.isOSDarwin()))
     125             :         return false;
     126             :     }
     127             : 
     128             :     // If an array has more than SSPBufferSize bytes of allocated space, then we
     129             :     // emit stack protectors.
     130         869 :     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
     131         644 :       IsLarge = true;
     132         644 :       return true;
     133             :     }
     134             : 
     135         225 :     if (Strong)
     136             :       // Require a protector for all arrays in strong mode
     137             :       return true;
     138             :   }
     139             : 
     140             :   const StructType *ST = dyn_cast<StructType>(Ty);
     141             :   if (!ST)
     142             :     return false;
     143             : 
     144             :   bool NeedsProtector = false;
     145        8573 :   for (StructType::element_iterator I = ST->element_begin(),
     146        5411 :                                     E = ST->element_end();
     147       13984 :        I != E; ++I)
     148        9123 :     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
     149             :       // If the element is a protectable array and is large (>= SSPBufferSize)
     150             :       // then we are done.  If the protectable array is not large, then
     151             :       // keep looking in case a subsequent element is a large array.
     152         756 :       if (IsLarge)
     153             :         return true;
     154             :       NeedsProtector = true;
     155             :     }
     156             : 
     157             :   return NeedsProtector;
     158             : }
     159             : 
     160             : static bool isLifetimeInst(const Instruction *I) {
     161             :   if (const auto Intrinsic = dyn_cast<IntrinsicInst>(I)) {
     162             :     const auto Id = Intrinsic->getIntrinsicID();
     163        2464 :     return Id == Intrinsic::lifetime_start || Id == Intrinsic::lifetime_end;
     164             :   }
     165             :   return false;
     166             : }
     167             : 
     168        8939 : bool StackProtector::HasAddressTaken(const Instruction *AI) {
     169       21087 :   for (const User *U : AI->users()) {
     170             :     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
     171        1603 :       if (AI == SI->getValueOperand())
     172             :         return true;
     173             :     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
     174          40 :       if (AI == SI->getOperand(0))
     175             :         return true;
     176             :     } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
     177             :       // Ignore intrinsics that are not calls. TODO: Use isLoweredToCall().
     178        2464 :       if (!isa<DbgInfoIntrinsic>(CI) && !isLifetimeInst(CI))
     179             :         return true;
     180             :     } else if (isa<InvokeInst>(U)) {
     181             :       return true;
     182             :     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
     183          80 :       if (HasAddressTaken(SI))
     184             :         return true;
     185             :     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
     186             :       // Keep track of what PHI nodes we have already visited to ensure
     187             :       // they are only visited once.
     188         125 :       if (VisitedPHIs.insert(PN).second)
     189          57 :         if (HasAddressTaken(PN))
     190             :           return true;
     191             :     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
     192        1214 :       if (HasAddressTaken(GEP))
     193             :         return true;
     194             :     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
     195        5381 :       if (HasAddressTaken(BI))
     196             :         return true;
     197             :     }
     198             :   }
     199             :   return false;
     200             : }
     201             : 
     202             : /// Check whether or not this function needs a stack protector based
     203             : /// upon the stack protector level.
     204             : ///
     205             : /// We use two heuristics: a standard (ssp) and strong (sspstrong).
     206             : /// The standard heuristic which will add a guard variable to functions that
     207             : /// call alloca with a either a variable size or a size >= SSPBufferSize,
     208             : /// functions with character buffers larger than SSPBufferSize, and functions
     209             : /// with aggregates containing character buffers larger than SSPBufferSize. The
     210             : /// strong heuristic will add a guard variables to functions that call alloca
     211             : /// regardless of size, functions with any buffer regardless of type and size,
     212             : /// functions with aggregates that contain any buffer regardless of type and
     213             : /// size, and functions that contain stack-based variables that have had their
     214             : /// address taken.
     215      406474 : bool StackProtector::RequiresStackProtector() {
     216             :   bool Strong = false;
     217             :   bool NeedsProtector = false;
     218     3624113 :   for (const BasicBlock &BB : *F)
     219    40389517 :     for (const Instruction &I : BB)
     220             :       if (const CallInst *CI = dyn_cast<CallInst>(&I))
     221     2445842 :         if (CI->getCalledFunction() ==
     222     2445842 :             Intrinsic::getDeclaration(F->getParent(),
     223             :                                       Intrinsic::stackprotector))
     224           2 :           HasPrologue = true;
     225             : 
     226      406474 :   if (F->hasFnAttribute(Attribute::SafeStack))
     227             :     return false;
     228             : 
     229             :   // We are constructing the OptimizationRemarkEmitter on the fly rather than
     230             :   // using the analysis pass to avoid building DominatorTree and LoopInfo which
     231             :   // are not available this late in the IR pipeline.
     232      406462 :   OptimizationRemarkEmitter ORE(F);
     233             : 
     234      406462 :   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
     235         232 :     ORE.emit([&]() {
     236             :       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
     237             :              << "Stack protection applied to function "
     238             :              << ore::NV("Function", F)
     239             :              << " due to a function attribute or command-line switch";
     240             :     });
     241             :     NeedsProtector = true;
     242             :     Strong = true; // Use the same heuristic as strong to determine SSPLayout
     243      406230 :   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
     244             :     Strong = true;
     245      402921 :   else if (HasPrologue)
     246             :     NeedsProtector = true;
     247      402919 :   else if (!F->hasFnAttribute(Attribute::StackProtect))
     248             :     return false;
     249             : 
     250       55064 :   for (const BasicBlock &BB : *F) {
     251      475423 :     for (const Instruction &I : BB) {
     252             :       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
     253        5065 :         if (AI->isArrayAllocation()) {
     254             :           auto RemarkBuilder = [&]() {
     255             :             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
     256             :                                       &I)
     257             :                    << "Stack protection applied to function "
     258             :                    << ore::NV("Function", F)
     259             :                    << " due to a call to alloca or use of a variable length "
     260             :                       "array";
     261         100 :           };
     262             :           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
     263          53 :             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
     264             :               // A call to alloca with size >= SSPBufferSize requires
     265             :               // stack protectors.
     266          22 :               Layout.insert(std::make_pair(AI,
     267          11 :                                            MachineFrameInfo::SSPLK_LargeArray));
     268          11 :               ORE.emit(RemarkBuilder);
     269             :               NeedsProtector = true;
     270          17 :             } else if (Strong) {
     271             :               // Require protectors for all alloca calls in strong mode.
     272          12 :               Layout.insert(std::make_pair(AI,
     273           6 :                                            MachineFrameInfo::SSPLK_SmallArray));
     274           6 :               ORE.emit(RemarkBuilder);
     275             :               NeedsProtector = true;
     276             :             }
     277             :           } else {
     278             :             // A call to alloca with a variable size requires protectors.
     279         144 :             Layout.insert(std::make_pair(AI,
     280          72 :                                          MachineFrameInfo::SSPLK_LargeArray));
     281          72 :             ORE.emit(RemarkBuilder);
     282             :             NeedsProtector = true;
     283             :           }
     284             :           continue;
     285             :         }
     286             : 
     287        4965 :         bool IsLarge = false;
     288        4965 :         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
     289        1568 :           Layout.insert(std::make_pair(AI, IsLarge
     290         784 :                                        ? MachineFrameInfo::SSPLK_LargeArray
     291         784 :                                        : MachineFrameInfo::SSPLK_SmallArray));
     292         784 :           ORE.emit([&]() {
     293             :             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
     294             :                    << "Stack protection applied to function "
     295             :                    << ore::NV("Function", F)
     296             :                    << " due to a stack allocated buffer or struct containing a "
     297             :                       "buffer";
     298             :           });
     299             :           NeedsProtector = true;
     300         784 :           continue;
     301             :         }
     302             : 
     303        4181 :         if (Strong && HasAddressTaken(AI)) {
     304             :           ++NumAddrTaken;
     305        1871 :           Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
     306        1871 :           ORE.emit([&]() {
     307             :             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
     308             :                                       &I)
     309             :                    << "Stack protection applied to function "
     310             :                    << ore::NV("Function", F)
     311             :                    << " due to the address of a local variable being taken";
     312             :           });
     313             :           NeedsProtector = true;
     314             :         }
     315             :       }
     316             :     }
     317             :   }
     318             : 
     319             :   return NeedsProtector;
     320             : }
     321             : 
     322             : /// Create a stack guard loading and populate whether SelectionDAG SSP is
     323             : /// supported.
     324        2205 : static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
     325             :                             IRBuilder<> &B,
     326             :                             bool *SupportsSelectionDAGSP = nullptr) {
     327        2205 :   if (Value *Guard = TLI->getIRStackGuard(B))
     328        1851 :     return B.CreateLoad(Guard, true, "StackGuard");
     329             : 
     330             :   // Use SelectionDAG SSP handling, since there isn't an IR guard.
     331             :   //
     332             :   // This is more or less weird, since we optionally output whether we
     333             :   // should perform a SelectionDAG SP here. The reason is that it's strictly
     334             :   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
     335             :   // mutating. There is no way to get this bit without mutating the IR, so
     336             :   // getting this bit has to happen in this right time.
     337             :   //
     338             :   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
     339             :   // will put more burden on the backends' overriding work, especially when it
     340             :   // actually conveys the same information getIRStackGuard() already gives.
     341         354 :   if (SupportsSelectionDAGSP)
     342         340 :     *SupportsSelectionDAGSP = true;
     343         354 :   TLI->insertSSPDeclarations(*M);
     344         708 :   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
     345             : }
     346             : 
     347             : /// Insert code into the entry block that stores the stack guard
     348             : /// variable onto the stack:
     349             : ///
     350             : ///   entry:
     351             : ///     StackGuardSlot = alloca i8*
     352             : ///     StackGuard = <stack guard>
     353             : ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
     354             : ///
     355             : /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
     356             : /// node.
     357        1249 : static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
     358             :                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
     359        1249 :   bool SupportsSelectionDAGSP = false;
     360        1249 :   IRBuilder<> B(&F->getEntryBlock().front());
     361        1249 :   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
     362        1249 :   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
     363             : 
     364        1249 :   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
     365        1249 :   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
     366        1249 :                {GuardSlot, AI});
     367        1249 :   return SupportsSelectionDAGSP;
     368             : }
     369             : 
     370             : /// InsertStackProtectors - Insert code into the prologue and epilogue of the
     371             : /// function.
     372             : ///
     373             : ///  - The prologue code loads and stores the stack guard onto the stack.
     374             : ///  - The epilogue checks the value stored in the prologue against the original
     375             : ///    value. It calls __stack_chk_fail if they differ.
     376        1264 : bool StackProtector::InsertStackProtectors() {
     377             :   // If the target wants to XOR the frame pointer into the guard value, it's
     378             :   // impossible to emit the check in IR, so the target *must* support stack
     379             :   // protection in SDAG.
     380             :   bool SupportsSelectionDAGSP =
     381        1264 :       TLI->useStackGuardXorFP() ||
     382        1126 :       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
     383        1264 :   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
     384             : 
     385       21888 :   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
     386             :     BasicBlock *BB = &*I++;
     387             :     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
     388             :     if (!RI)
     389             :       continue;
     390             : 
     391             :     // Generate prologue instrumentation if not already generated.
     392        1284 :     if (!HasPrologue) {
     393        1249 :       HasPrologue = true;
     394        1249 :       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
     395             :     }
     396             : 
     397             :     // SelectionDAG based code generation. Nothing else needs to be done here.
     398             :     // The epilogue instrumentation is postponed to SelectionDAG.
     399        1284 :     if (SupportsSelectionDAGSP)
     400             :       break;
     401             : 
     402             :     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
     403             :     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
     404             :     // instrumentation has already been generated.
     405         956 :     HasIRCheck = true;
     406             : 
     407             :     // Generate epilogue instrumentation. The epilogue intrumentation can be
     408             :     // function-based or inlined depending on which mechanism the target is
     409             :     // providing.
     410         956 :     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
     411             :       // Generate the function-based epilogue instrumentation.
     412             :       // The target provides a guard check function, generate a call to it.
     413           0 :       IRBuilder<> B(RI);
     414           0 :       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
     415           0 :       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
     416             :       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
     417             :       Call->setAttributes(Function->getAttributes());
     418             :       Call->setCallingConv(Function->getCallingConv());
     419             :     } else {
     420             :       // Generate the epilogue with inline instrumentation.
     421             :       // If we do not support SelectionDAG based tail calls, generate IR level
     422             :       // tail calls.
     423             :       //
     424             :       // For each block with a return instruction, convert this:
     425             :       //
     426             :       //   return:
     427             :       //     ...
     428             :       //     ret ...
     429             :       //
     430             :       // into this:
     431             :       //
     432             :       //   return:
     433             :       //     ...
     434             :       //     %1 = <stack guard>
     435             :       //     %2 = load StackGuardSlot
     436             :       //     %3 = cmp i1 %1, %2
     437             :       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
     438             :       //
     439             :       //   SP_return:
     440             :       //     ret ...
     441             :       //
     442             :       //   CallStackCheckFailBlk:
     443             :       //     call void @__stack_chk_fail()
     444             :       //     unreachable
     445             : 
     446             :       // Create the FailBB. We duplicate the BB every time since the MI tail
     447             :       // merge pass will merge together all of the various BB into one including
     448             :       // fail BB generated by the stack protector pseudo instruction.
     449         956 :       BasicBlock *FailBB = CreateFailBB();
     450             : 
     451             :       // Split the basic block before the return instruction.
     452         956 :       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
     453             : 
     454             :       // Update the dominator tree if we need to.
     455         956 :       if (DT && DT->isReachableFromEntry(BB)) {
     456           0 :         DT->addNewBlock(NewBB, BB);
     457           0 :         DT->addNewBlock(FailBB, BB);
     458             :       }
     459             : 
     460             :       // Remove default branch instruction to the new BB.
     461         956 :       BB->getTerminator()->eraseFromParent();
     462             : 
     463             :       // Move the newly created basic block to the point right after the old
     464             :       // basic block so that it's in the "fall through" position.
     465         956 :       NewBB->moveAfter(BB);
     466             : 
     467             :       // Generate the stack protector instructions in the old basic block.
     468             :       IRBuilder<> B(BB);
     469         956 :       Value *Guard = getStackGuard(TLI, M, B);
     470         956 :       LoadInst *LI2 = B.CreateLoad(AI, true);
     471         956 :       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
     472             :       auto SuccessProb =
     473         956 :           BranchProbabilityInfo::getBranchProbStackProtector(true);
     474             :       auto FailureProb =
     475         956 :           BranchProbabilityInfo::getBranchProbStackProtector(false);
     476         956 :       MDNode *Weights = MDBuilder(F->getContext())
     477         956 :                             .createBranchWeights(SuccessProb.getNumerator(),
     478             :                                                  FailureProb.getNumerator());
     479         956 :       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
     480             :     }
     481             :   }
     482             : 
     483             :   // Return if we didn't modify any basic blocks. i.e., there are no return
     484             :   // statements in the function.
     485        1264 :   return HasPrologue;
     486             : }
     487             : 
     488             : /// CreateFailBB - Create a basic block to jump to when the stack protector
     489             : /// check fails.
     490         956 : BasicBlock *StackProtector::CreateFailBB() {
     491         956 :   LLVMContext &Context = F->getContext();
     492        1912 :   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
     493             :   IRBuilder<> B(FailBB);
     494        1912 :   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
     495         956 :   if (Trip.isOSOpenBSD()) {
     496             :     Constant *StackChkFail =
     497         124 :         M->getOrInsertFunction("__stack_smash_handler",
     498             :                                Type::getVoidTy(Context),
     499             :                                Type::getInt8PtrTy(Context));
     500             : 
     501          62 :     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
     502             :   } else {
     503             :     Constant *StackChkFail =
     504        1788 :         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
     505             : 
     506         894 :     B.CreateCall(StackChkFail, {});
     507             :   }
     508         956 :   B.CreateUnreachable();
     509         956 :   return FailBB;
     510             : }
     511             : 
     512     3218092 : bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
     513     3218092 :   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
     514             : }
     515             : 
     516      406398 : void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
     517      406398 :   if (Layout.empty())
     518             :     return;
     519             : 
     520        8824 :   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
     521        5224 :     if (MFI.isDeadObjectIndex(I))
     522        2480 :       continue;
     523             : 
     524             :     const AllocaInst *AI = MFI.getObjectAllocation(I);
     525        5194 :     if (!AI)
     526             :       continue;
     527             : 
     528        5180 :     SSPLayoutMap::const_iterator LI = Layout.find(AI);
     529        5180 :     if (LI == Layout.end())
     530             :       continue;
     531             : 
     532        2744 :     MFI.setObjectSSPLayout(I, LI->second);
     533             :   }
     534             : }

Generated by: LCOV version 1.13