xref: /llvm-project/llvm/lib/CodeGen/StackProtector.cpp (revision b7926ce6d7a83cdf70c68d82bc3389c04009b841)
1 //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass inserts stack protectors into functions which need them. A variable
10 // with a random value in it is stored onto the stack before the local variables
11 // are allocated. Upon exiting the block, the stored value is checked. If it's
12 // changed, then there was some sort of violation and the program aborts.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/StackProtector.h"
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/MemoryLocation.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/InitializePasses.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "stack-protector"
56 
57 STATISTIC(NumFunProtected, "Number of functions protected");
58 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
59                         " taken.");
60 
61 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
62                                           cl::init(true), cl::Hidden);
63 
64 char StackProtector::ID = 0;
65 
66 StackProtector::StackProtector() : FunctionPass(ID), SSPBufferSize(8) {
67   initializeStackProtectorPass(*PassRegistry::getPassRegistry());
68 }
69 
70 INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
71                       "Insert stack protectors", false, true)
72 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
73 INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
74                     "Insert stack protectors", false, true)
75 
76 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
77 
78 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
79   AU.addRequired<TargetPassConfig>();
80   AU.addPreserved<DominatorTreeWrapperPass>();
81 }
82 
83 bool StackProtector::runOnFunction(Function &Fn) {
84   F = &Fn;
85   M = F->getParent();
86   DominatorTreeWrapperPass *DTWP =
87       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
88   DT = DTWP ? &DTWP->getDomTree() : nullptr;
89   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
90   Trip = TM->getTargetTriple();
91   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
92   HasPrologue = false;
93   HasIRCheck = false;
94 
95   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
96   if (Attr.isStringAttribute() &&
97       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
98     return false; // Invalid integer string
99 
100   if (!RequiresStackProtector())
101     return false;
102 
103   // TODO(etienneb): Functions with funclets are not correctly supported now.
104   // Do nothing if this is funclet-based personality.
105   if (Fn.hasPersonalityFn()) {
106     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
107     if (isFuncletEHPersonality(Personality))
108       return false;
109   }
110 
111   ++NumFunProtected;
112   return InsertStackProtectors();
113 }
114 
115 /// \param [out] IsLarge is set to true if a protectable array is found and
116 /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
117 /// multiple arrays, this gets set if any of them is large.
118 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
119                                               bool Strong,
120                                               bool InStruct) const {
121   if (!Ty)
122     return false;
123   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
124     if (!AT->getElementType()->isIntegerTy(8)) {
125       // If we're on a non-Darwin platform or we're inside of a structure, don't
126       // add stack protectors unless the array is a character array.
127       // However, in strong mode any array, regardless of type and size,
128       // triggers a protector.
129       if (!Strong && (InStruct || !Trip.isOSDarwin()))
130         return false;
131     }
132 
133     // If an array has more than SSPBufferSize bytes of allocated space, then we
134     // emit stack protectors.
135     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
136       IsLarge = true;
137       return true;
138     }
139 
140     if (Strong)
141       // Require a protector for all arrays in strong mode
142       return true;
143   }
144 
145   const StructType *ST = dyn_cast<StructType>(Ty);
146   if (!ST)
147     return false;
148 
149   bool NeedsProtector = false;
150   for (StructType::element_iterator I = ST->element_begin(),
151                                     E = ST->element_end();
152        I != E; ++I)
153     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
154       // If the element is a protectable array and is large (>= SSPBufferSize)
155       // then we are done.  If the protectable array is not large, then
156       // keep looking in case a subsequent element is a large array.
157       if (IsLarge)
158         return true;
159       NeedsProtector = true;
160     }
161 
162   return NeedsProtector;
163 }
164 
165 bool StackProtector::HasAddressTaken(const Instruction *AI,
166                                      uint64_t AllocSize) {
167   const DataLayout &DL = M->getDataLayout();
168   for (const User *U : AI->users()) {
169     const auto *I = cast<Instruction>(U);
170     // If this instruction accesses memory make sure it doesn't access beyond
171     // the bounds of the allocated object.
172     Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
173     if (MemLoc.hasValue() && MemLoc->Size.hasValue() &&
174         MemLoc->Size.getValue() > AllocSize)
175       return true;
176     switch (I->getOpcode()) {
177     case Instruction::Store:
178       if (AI == cast<StoreInst>(I)->getValueOperand())
179         return true;
180       break;
181     case Instruction::AtomicCmpXchg:
182       // cmpxchg conceptually includes both a load and store from the same
183       // location. So, like store, the value being stored is what matters.
184       if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
185         return true;
186       break;
187     case Instruction::PtrToInt:
188       if (AI == cast<PtrToIntInst>(I)->getOperand(0))
189         return true;
190       break;
191     case Instruction::Call: {
192       // Ignore intrinsics that do not become real instructions.
193       // TODO: Narrow this to intrinsics that have store-like effects.
194       const auto *CI = cast<CallInst>(I);
195       if (!isa<DbgInfoIntrinsic>(CI) && !CI->isLifetimeStartOrEnd())
196         return true;
197       break;
198     }
199     case Instruction::Invoke:
200       return true;
201     case Instruction::GetElementPtr: {
202       // If the GEP offset is out-of-bounds, or is non-constant and so has to be
203       // assumed to be potentially out-of-bounds, then any memory access that
204       // would use it could also be out-of-bounds meaning stack protection is
205       // required.
206       const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
207       unsigned TypeSize = DL.getIndexTypeSizeInBits(I->getType());
208       APInt Offset(TypeSize, 0);
209       APInt MaxOffset(TypeSize, AllocSize);
210       if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.ugt(MaxOffset))
211         return true;
212       // Adjust AllocSize to be the space remaining after this offset.
213       if (HasAddressTaken(I, AllocSize - Offset.getLimitedValue()))
214         return true;
215       break;
216     }
217     case Instruction::BitCast:
218     case Instruction::Select:
219     case Instruction::AddrSpaceCast:
220       if (HasAddressTaken(I, AllocSize))
221         return true;
222       break;
223     case Instruction::PHI: {
224       // Keep track of what PHI nodes we have already visited to ensure
225       // they are only visited once.
226       const auto *PN = cast<PHINode>(I);
227       if (VisitedPHIs.insert(PN).second)
228         if (HasAddressTaken(PN, AllocSize))
229           return true;
230       break;
231     }
232     case Instruction::Load:
233     case Instruction::AtomicRMW:
234     case Instruction::Ret:
235       // These instructions take an address operand, but have load-like or
236       // other innocuous behavior that should not trigger a stack protector.
237       // atomicrmw conceptually has both load and store semantics, but the
238       // value being stored must be integer; so if a pointer is being stored,
239       // we'll catch it in the PtrToInt case above.
240       break;
241     default:
242       // Conservatively return true for any instruction that takes an address
243       // operand, but is not handled above.
244       return true;
245     }
246   }
247   return false;
248 }
249 
250 /// Search for the first call to the llvm.stackprotector intrinsic and return it
251 /// if present.
252 static const CallInst *findStackProtectorIntrinsic(Function &F) {
253   for (const BasicBlock &BB : F)
254     for (const Instruction &I : BB)
255       if (const auto *II = dyn_cast<IntrinsicInst>(&I))
256         if (II->getIntrinsicID() == Intrinsic::stackprotector)
257           return II;
258   return nullptr;
259 }
260 
261 /// Check whether or not this function needs a stack protector based
262 /// upon the stack protector level.
263 ///
264 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
265 /// The standard heuristic which will add a guard variable to functions that
266 /// call alloca with a either a variable size or a size >= SSPBufferSize,
267 /// functions with character buffers larger than SSPBufferSize, and functions
268 /// with aggregates containing character buffers larger than SSPBufferSize. The
269 /// strong heuristic will add a guard variables to functions that call alloca
270 /// regardless of size, functions with any buffer regardless of type and size,
271 /// functions with aggregates that contain any buffer regardless of type and
272 /// size, and functions that contain stack-based variables that have had their
273 /// address taken. The heuristic will be disregarded for functions explicitly
274 /// marked nossp.
275 bool StackProtector::RequiresStackProtector() {
276   bool Strong = false;
277   bool NeedsProtector = false;
278   HasPrologue = findStackProtectorIntrinsic(*F);
279 
280   if (F->hasFnAttribute(Attribute::SafeStack) ||
281       F->hasFnAttribute(Attribute::NoStackProtect))
282     return false;
283 
284   // We are constructing the OptimizationRemarkEmitter on the fly rather than
285   // using the analysis pass to avoid building DominatorTree and LoopInfo which
286   // are not available this late in the IR pipeline.
287   OptimizationRemarkEmitter ORE(F);
288 
289   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
290     ORE.emit([&]() {
291       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
292              << "Stack protection applied to function "
293              << ore::NV("Function", F)
294              << " due to a function attribute or command-line switch";
295     });
296     NeedsProtector = true;
297     Strong = true; // Use the same heuristic as strong to determine SSPLayout
298   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
299     Strong = true;
300   else if (HasPrologue)
301     NeedsProtector = true;
302   else if (!F->hasFnAttribute(Attribute::StackProtect))
303     return false;
304 
305   for (const BasicBlock &BB : *F) {
306     for (const Instruction &I : BB) {
307       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
308         if (AI->isArrayAllocation()) {
309           auto RemarkBuilder = [&]() {
310             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
311                                       &I)
312                    << "Stack protection applied to function "
313                    << ore::NV("Function", F)
314                    << " due to a call to alloca or use of a variable length "
315                       "array";
316           };
317           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
318             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
319               // A call to alloca with size >= SSPBufferSize requires
320               // stack protectors.
321               Layout.insert(std::make_pair(AI,
322                                            MachineFrameInfo::SSPLK_LargeArray));
323               ORE.emit(RemarkBuilder);
324               NeedsProtector = true;
325             } else if (Strong) {
326               // Require protectors for all alloca calls in strong mode.
327               Layout.insert(std::make_pair(AI,
328                                            MachineFrameInfo::SSPLK_SmallArray));
329               ORE.emit(RemarkBuilder);
330               NeedsProtector = true;
331             }
332           } else {
333             // A call to alloca with a variable size requires protectors.
334             Layout.insert(std::make_pair(AI,
335                                          MachineFrameInfo::SSPLK_LargeArray));
336             ORE.emit(RemarkBuilder);
337             NeedsProtector = true;
338           }
339           continue;
340         }
341 
342         bool IsLarge = false;
343         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
344           Layout.insert(std::make_pair(AI, IsLarge
345                                        ? MachineFrameInfo::SSPLK_LargeArray
346                                        : MachineFrameInfo::SSPLK_SmallArray));
347           ORE.emit([&]() {
348             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
349                    << "Stack protection applied to function "
350                    << ore::NV("Function", F)
351                    << " due to a stack allocated buffer or struct containing a "
352                       "buffer";
353           });
354           NeedsProtector = true;
355           continue;
356         }
357 
358         if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
359                                               AI->getAllocatedType()))) {
360           ++NumAddrTaken;
361           Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
362           ORE.emit([&]() {
363             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
364                                       &I)
365                    << "Stack protection applied to function "
366                    << ore::NV("Function", F)
367                    << " due to the address of a local variable being taken";
368           });
369           NeedsProtector = true;
370         }
371         // Clear any PHIs that we visited, to make sure we examine all uses of
372         // any subsequent allocas that we look at.
373         VisitedPHIs.clear();
374       }
375     }
376   }
377 
378   return NeedsProtector;
379 }
380 
381 /// Create a stack guard loading and populate whether SelectionDAG SSP is
382 /// supported.
383 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
384                             IRBuilder<> &B,
385                             bool *SupportsSelectionDAGSP = nullptr) {
386   Value *Guard = TLI->getIRStackGuard(B);
387   auto GuardMode = TLI->getTargetMachine().Options.StackProtectorGuard;
388   if ((GuardMode == llvm::StackProtectorGuards::TLS ||
389        GuardMode == llvm::StackProtectorGuards::None) && Guard)
390     return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
391 
392   // Use SelectionDAG SSP handling, since there isn't an IR guard.
393   //
394   // This is more or less weird, since we optionally output whether we
395   // should perform a SelectionDAG SP here. The reason is that it's strictly
396   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
397   // mutating. There is no way to get this bit without mutating the IR, so
398   // getting this bit has to happen in this right time.
399   //
400   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
401   // will put more burden on the backends' overriding work, especially when it
402   // actually conveys the same information getIRStackGuard() already gives.
403   if (SupportsSelectionDAGSP)
404     *SupportsSelectionDAGSP = true;
405   TLI->insertSSPDeclarations(*M);
406   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
407 }
408 
409 /// Insert code into the entry block that stores the stack guard
410 /// variable onto the stack:
411 ///
412 ///   entry:
413 ///     StackGuardSlot = alloca i8*
414 ///     StackGuard = <stack guard>
415 ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
416 ///
417 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
418 /// node.
419 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
420                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
421   bool SupportsSelectionDAGSP = false;
422   IRBuilder<> B(&F->getEntryBlock().front());
423   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
424   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
425 
426   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
427   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
428                {GuardSlot, AI});
429   return SupportsSelectionDAGSP;
430 }
431 
432 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
433 /// function.
434 ///
435 ///  - The prologue code loads and stores the stack guard onto the stack.
436 ///  - The epilogue checks the value stored in the prologue against the original
437 ///    value. It calls __stack_chk_fail if they differ.
438 bool StackProtector::InsertStackProtectors() {
439   // If the target wants to XOR the frame pointer into the guard value, it's
440   // impossible to emit the check in IR, so the target *must* support stack
441   // protection in SDAG.
442   bool SupportsSelectionDAGSP =
443       TLI->useStackGuardXorFP() ||
444       (EnableSelectionDAGSP && !TM->Options.EnableFastISel &&
445        !TM->Options.EnableGlobalISel);
446   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
447 
448   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
449     BasicBlock *BB = &*I++;
450     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
451     if (!RI)
452       continue;
453 
454     // Generate prologue instrumentation if not already generated.
455     if (!HasPrologue) {
456       HasPrologue = true;
457       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
458     }
459 
460     // SelectionDAG based code generation. Nothing else needs to be done here.
461     // The epilogue instrumentation is postponed to SelectionDAG.
462     if (SupportsSelectionDAGSP)
463       break;
464 
465     // Find the stack guard slot if the prologue was not created by this pass
466     // itself via a previous call to CreatePrologue().
467     if (!AI) {
468       const CallInst *SPCall = findStackProtectorIntrinsic(*F);
469       assert(SPCall && "Call to llvm.stackprotector is missing");
470       AI = cast<AllocaInst>(SPCall->getArgOperand(1));
471     }
472 
473     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
474     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
475     // instrumentation has already been generated.
476     HasIRCheck = true;
477 
478     // Generate epilogue instrumentation. The epilogue intrumentation can be
479     // function-based or inlined depending on which mechanism the target is
480     // providing.
481     if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
482       // Generate the function-based epilogue instrumentation.
483       // The target provides a guard check function, generate a call to it.
484       IRBuilder<> B(RI);
485       LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
486       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
487       Call->setAttributes(GuardCheck->getAttributes());
488       Call->setCallingConv(GuardCheck->getCallingConv());
489     } else {
490       // Generate the epilogue with inline instrumentation.
491       // If we do not support SelectionDAG based tail calls, generate IR level
492       // tail calls.
493       //
494       // For each block with a return instruction, convert this:
495       //
496       //   return:
497       //     ...
498       //     ret ...
499       //
500       // into this:
501       //
502       //   return:
503       //     ...
504       //     %1 = <stack guard>
505       //     %2 = load StackGuardSlot
506       //     %3 = cmp i1 %1, %2
507       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
508       //
509       //   SP_return:
510       //     ret ...
511       //
512       //   CallStackCheckFailBlk:
513       //     call void @__stack_chk_fail()
514       //     unreachable
515 
516       // Create the FailBB. We duplicate the BB every time since the MI tail
517       // merge pass will merge together all of the various BB into one including
518       // fail BB generated by the stack protector pseudo instruction.
519       BasicBlock *FailBB = CreateFailBB();
520 
521       // Split the basic block before the return instruction.
522       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
523 
524       // Update the dominator tree if we need to.
525       if (DT && DT->isReachableFromEntry(BB)) {
526         DT->addNewBlock(NewBB, BB);
527         DT->addNewBlock(FailBB, BB);
528       }
529 
530       // Remove default branch instruction to the new BB.
531       BB->getTerminator()->eraseFromParent();
532 
533       // Move the newly created basic block to the point right after the old
534       // basic block so that it's in the "fall through" position.
535       NewBB->moveAfter(BB);
536 
537       // Generate the stack protector instructions in the old basic block.
538       IRBuilder<> B(BB);
539       Value *Guard = getStackGuard(TLI, M, B);
540       LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
541       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
542       auto SuccessProb =
543           BranchProbabilityInfo::getBranchProbStackProtector(true);
544       auto FailureProb =
545           BranchProbabilityInfo::getBranchProbStackProtector(false);
546       MDNode *Weights = MDBuilder(F->getContext())
547                             .createBranchWeights(SuccessProb.getNumerator(),
548                                                  FailureProb.getNumerator());
549       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
550     }
551   }
552 
553   // Return if we didn't modify any basic blocks. i.e., there are no return
554   // statements in the function.
555   return HasPrologue;
556 }
557 
558 /// CreateFailBB - Create a basic block to jump to when the stack protector
559 /// check fails.
560 BasicBlock *StackProtector::CreateFailBB() {
561   LLVMContext &Context = F->getContext();
562   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
563   IRBuilder<> B(FailBB);
564   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
565   if (Trip.isOSOpenBSD()) {
566     FunctionCallee StackChkFail = M->getOrInsertFunction(
567         "__stack_smash_handler", Type::getVoidTy(Context),
568         Type::getInt8PtrTy(Context));
569 
570     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
571   } else {
572     FunctionCallee StackChkFail =
573         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
574 
575     B.CreateCall(StackChkFail, {});
576   }
577   B.CreateUnreachable();
578   return FailBB;
579 }
580 
581 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
582   return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
583 }
584 
585 void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
586   if (Layout.empty())
587     return;
588 
589   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
590     if (MFI.isDeadObjectIndex(I))
591       continue;
592 
593     const AllocaInst *AI = MFI.getObjectAllocation(I);
594     if (!AI)
595       continue;
596 
597     SSPLayoutMap::const_iterator LI = Layout.find(AI);
598     if (LI == Layout.end())
599       continue;
600 
601     MFI.setObjectSSPLayout(I, LI->second);
602   }
603 }
604