xref: /src/contrib/llvm-project/llvm/lib/CodeGen/StackProtector.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
171d5a254SDimitry Andric //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This pass inserts stack protectors into functions which need them. A variable
10009b1c42SEd Schouten // with a random value in it is stored onto the stack before the local variables
11009b1c42SEd Schouten // are allocated. Upon exiting the block, the stored value is checked. If it's
12009b1c42SEd Schouten // changed, then there was some sort of violation and the program aborts.
13009b1c42SEd Schouten //
14009b1c42SEd Schouten //===----------------------------------------------------------------------===//
15009b1c42SEd Schouten 
16044eb2f6SDimitry Andric #include "llvm/CodeGen/StackProtector.h"
174a16efa3SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
187fa27ce4SDimitry Andric #include "llvm/ADT/SmallVector.h"
194a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
2067c32a98SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
21cfca06d7SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
22044eb2f6SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
235ca98fd9SDimitry Andric #include "llvm/CodeGen/Passes.h"
24044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
257ab83427SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
274a16efa3SDimitry Andric #include "llvm/IR/Attributes.h"
2871d5a254SDimitry Andric #include "llvm/IR/BasicBlock.h"
294a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
304a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
314a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
327ab83427SDimitry Andric #include "llvm/IR/Dominators.h"
337fa27ce4SDimitry Andric #include "llvm/IR/EHPersonalities.h"
344a16efa3SDimitry Andric #include "llvm/IR/Function.h"
35f8af5cf6SDimitry Andric #include "llvm/IR/IRBuilder.h"
3671d5a254SDimitry Andric #include "llvm/IR/Instruction.h"
374a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
38eb11fae6SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
394a16efa3SDimitry Andric #include "llvm/IR/Intrinsics.h"
4067c32a98SDimitry Andric #include "llvm/IR/MDBuilder.h"
414a16efa3SDimitry Andric #include "llvm/IR/Module.h"
4271d5a254SDimitry Andric #include "llvm/IR/Type.h"
4371d5a254SDimitry Andric #include "llvm/IR/User.h"
44706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
4571d5a254SDimitry Andric #include "llvm/Pass.h"
4671d5a254SDimitry Andric #include "llvm/Support/Casting.h"
47009b1c42SEd Schouten #include "llvm/Support/CommandLine.h"
4871d5a254SDimitry Andric #include "llvm/Target/TargetMachine.h"
4971d5a254SDimitry Andric #include "llvm/Target/TargetOptions.h"
50e3b55780SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51e3b55780SDimitry Andric #include <optional>
5271d5a254SDimitry Andric #include <utility>
5371d5a254SDimitry Andric 
54009b1c42SEd Schouten using namespace llvm;
55009b1c42SEd Schouten 
565ca98fd9SDimitry Andric #define DEBUG_TYPE "stack-protector"
575ca98fd9SDimitry Andric 
584a16efa3SDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
594a16efa3SDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
604a16efa3SDimitry Andric                         " taken.");
614a16efa3SDimitry Andric 
62f8af5cf6SDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
63f8af5cf6SDimitry Andric                                           cl::init(true), cl::Hidden);
64e3b55780SDimitry Andric static cl::opt<bool> DisableCheckNoReturn("disable-check-noreturn-call",
65e3b55780SDimitry Andric                                           cl::init(false), cl::Hidden);
66009b1c42SEd Schouten 
67aca2e42cSDimitry Andric /// InsertStackProtectors - Insert code into the prologue and epilogue of the
68aca2e42cSDimitry Andric /// function.
69aca2e42cSDimitry Andric ///
70aca2e42cSDimitry Andric ///  - The prologue code loads and stores the stack guard onto the stack.
71aca2e42cSDimitry Andric ///  - The epilogue checks the value stored in the prologue against the original
72aca2e42cSDimitry Andric ///    value. It calls __stack_chk_fail if they differ.
73aca2e42cSDimitry Andric static bool InsertStackProtectors(const TargetMachine *TM, Function *F,
74aca2e42cSDimitry Andric                                   DomTreeUpdater *DTU, bool &HasPrologue,
75aca2e42cSDimitry Andric                                   bool &HasIRCheck);
76aca2e42cSDimitry Andric 
77aca2e42cSDimitry Andric /// CreateFailBB - Create a basic block to jump to when the stack protector
78aca2e42cSDimitry Andric /// check fails.
79aca2e42cSDimitry Andric static BasicBlock *CreateFailBB(Function *F, const Triple &Trip);
80aca2e42cSDimitry Andric 
shouldEmitSDCheck(const BasicBlock & BB) const81aca2e42cSDimitry Andric bool SSPLayoutInfo::shouldEmitSDCheck(const BasicBlock &BB) const {
82aca2e42cSDimitry Andric   return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
83aca2e42cSDimitry Andric }
84aca2e42cSDimitry Andric 
copyToMachineFrameInfo(MachineFrameInfo & MFI) const85aca2e42cSDimitry Andric void SSPLayoutInfo::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
86aca2e42cSDimitry Andric   if (Layout.empty())
87aca2e42cSDimitry Andric     return;
88aca2e42cSDimitry Andric 
89aca2e42cSDimitry Andric   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
90aca2e42cSDimitry Andric     if (MFI.isDeadObjectIndex(I))
91aca2e42cSDimitry Andric       continue;
92aca2e42cSDimitry Andric 
93aca2e42cSDimitry Andric     const AllocaInst *AI = MFI.getObjectAllocation(I);
94aca2e42cSDimitry Andric     if (!AI)
95aca2e42cSDimitry Andric       continue;
96aca2e42cSDimitry Andric 
97aca2e42cSDimitry Andric     SSPLayoutMap::const_iterator LI = Layout.find(AI);
98aca2e42cSDimitry Andric     if (LI == Layout.end())
99aca2e42cSDimitry Andric       continue;
100aca2e42cSDimitry Andric 
101aca2e42cSDimitry Andric     MFI.setObjectSSPLayout(I, LI->second);
102aca2e42cSDimitry Andric   }
103aca2e42cSDimitry Andric }
104aca2e42cSDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)105aca2e42cSDimitry Andric SSPLayoutInfo SSPLayoutAnalysis::run(Function &F,
106aca2e42cSDimitry Andric                                      FunctionAnalysisManager &FAM) {
107aca2e42cSDimitry Andric 
108aca2e42cSDimitry Andric   SSPLayoutInfo Info;
109aca2e42cSDimitry Andric   Info.RequireStackProtector =
110aca2e42cSDimitry Andric       SSPLayoutAnalysis::requiresStackProtector(&F, &Info.Layout);
111aca2e42cSDimitry Andric   Info.SSPBufferSize = F.getFnAttributeAsParsedInteger(
112aca2e42cSDimitry Andric       "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
113aca2e42cSDimitry Andric   return Info;
114aca2e42cSDimitry Andric }
115aca2e42cSDimitry Andric 
116aca2e42cSDimitry Andric AnalysisKey SSPLayoutAnalysis::Key;
117aca2e42cSDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)118aca2e42cSDimitry Andric PreservedAnalyses StackProtectorPass::run(Function &F,
119aca2e42cSDimitry Andric                                           FunctionAnalysisManager &FAM) {
120aca2e42cSDimitry Andric   auto &Info = FAM.getResult<SSPLayoutAnalysis>(F);
121aca2e42cSDimitry Andric   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
122aca2e42cSDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
123aca2e42cSDimitry Andric 
124aca2e42cSDimitry Andric   if (!Info.RequireStackProtector)
125aca2e42cSDimitry Andric     return PreservedAnalyses::all();
126aca2e42cSDimitry Andric 
127aca2e42cSDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
128aca2e42cSDimitry Andric   // Do nothing if this is funclet-based personality.
129aca2e42cSDimitry Andric   if (F.hasPersonalityFn()) {
130aca2e42cSDimitry Andric     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
131aca2e42cSDimitry Andric     if (isFuncletEHPersonality(Personality))
132aca2e42cSDimitry Andric       return PreservedAnalyses::all();
133aca2e42cSDimitry Andric   }
134aca2e42cSDimitry Andric 
135aca2e42cSDimitry Andric   ++NumFunProtected;
136aca2e42cSDimitry Andric   bool Changed = InsertStackProtectors(TM, &F, DT ? &DTU : nullptr,
137aca2e42cSDimitry Andric                                        Info.HasPrologue, Info.HasIRCheck);
138aca2e42cSDimitry Andric #ifdef EXPENSIVE_CHECKS
139aca2e42cSDimitry Andric   assert((!DT || DT->verify(DominatorTree::VerificationLevel::Full)) &&
140aca2e42cSDimitry Andric          "Failed to maintain validity of domtree!");
141aca2e42cSDimitry Andric #endif
142aca2e42cSDimitry Andric 
143aca2e42cSDimitry Andric   if (!Changed)
144aca2e42cSDimitry Andric     return PreservedAnalyses::all();
145aca2e42cSDimitry Andric   PreservedAnalyses PA;
146aca2e42cSDimitry Andric   PA.preserve<SSPLayoutAnalysis>();
147aca2e42cSDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
148aca2e42cSDimitry Andric   return PA;
149aca2e42cSDimitry Andric }
150aca2e42cSDimitry Andric 
151009b1c42SEd Schouten char StackProtector::ID = 0;
1527ab83427SDimitry Andric 
StackProtector()153e3b55780SDimitry Andric StackProtector::StackProtector() : FunctionPass(ID) {
154706b4fc4SDimitry Andric   initializeStackProtectorPass(*PassRegistry::getPassRegistry());
155706b4fc4SDimitry Andric }
156706b4fc4SDimitry Andric 
157ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
158b5630dbaSDimitry Andric                       "Insert stack protectors", false, true)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)159b5630dbaSDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
160344a3780SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
161ab44ce3dSDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
162b5630dbaSDimitry Andric                     "Insert stack protectors", false, true)
163009b1c42SEd Schouten 
164b5630dbaSDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
165f8af5cf6SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1667ab83427SDimitry Andric void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
1677ab83427SDimitry Andric   AU.addRequired<TargetPassConfig>();
1687ab83427SDimitry Andric   AU.addPreserved<DominatorTreeWrapperPass>();
1697ab83427SDimitry Andric }
1707ab83427SDimitry Andric 
runOnFunction(Function & Fn)171009b1c42SEd Schouten bool StackProtector::runOnFunction(Function &Fn) {
172009b1c42SEd Schouten   F = &Fn;
173009b1c42SEd Schouten   M = F->getParent();
174e3b55780SDimitry Andric   if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
175e3b55780SDimitry Andric     DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
176b5630dbaSDimitry Andric   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
177aca2e42cSDimitry Andric   LayoutInfo.HasPrologue = false;
178aca2e42cSDimitry Andric   LayoutInfo.HasIRCheck = false;
179009b1c42SEd Schouten 
180aca2e42cSDimitry Andric   LayoutInfo.SSPBufferSize = Fn.getFnAttributeAsParsedInteger(
181aca2e42cSDimitry Andric       "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
182aca2e42cSDimitry Andric   if (!requiresStackProtector(F, &LayoutInfo.Layout))
1835ca98fd9SDimitry Andric     return false;
184009b1c42SEd Schouten 
18501095a5dSDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
18601095a5dSDimitry Andric   // Do nothing if this is funclet-based personality.
18701095a5dSDimitry Andric   if (Fn.hasPersonalityFn()) {
18801095a5dSDimitry Andric     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
18901095a5dSDimitry Andric     if (isFuncletEHPersonality(Personality))
19001095a5dSDimitry Andric       return false;
19101095a5dSDimitry Andric   }
19201095a5dSDimitry Andric 
1934a16efa3SDimitry Andric   ++NumFunProtected;
194aca2e42cSDimitry Andric   bool Changed =
195aca2e42cSDimitry Andric       InsertStackProtectors(TM, F, DTU ? &*DTU : nullptr,
196aca2e42cSDimitry Andric                             LayoutInfo.HasPrologue, LayoutInfo.HasIRCheck);
197e3b55780SDimitry Andric #ifdef EXPENSIVE_CHECKS
198e3b55780SDimitry Andric   assert((!DTU ||
199e3b55780SDimitry Andric           DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
200e3b55780SDimitry Andric          "Failed to maintain validity of domtree!");
201e3b55780SDimitry Andric #endif
202e3b55780SDimitry Andric   DTU.reset();
203e3b55780SDimitry Andric   return Changed;
204009b1c42SEd Schouten }
205009b1c42SEd Schouten 
206f8af5cf6SDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
207f8af5cf6SDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
208f8af5cf6SDimitry Andric /// multiple arrays, this gets set if any of them is large.
ContainsProtectableArray(Type * Ty,Module * M,unsigned SSPBufferSize,bool & IsLarge,bool Strong,bool InStruct)2097fa27ce4SDimitry Andric static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize,
2107fa27ce4SDimitry Andric                                      bool &IsLarge, bool Strong,
2117fa27ce4SDimitry Andric                                      bool InStruct) {
212f8af5cf6SDimitry Andric   if (!Ty)
213f8af5cf6SDimitry Andric     return false;
214522600a2SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
215522600a2SDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
216522600a2SDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
217522600a2SDimitry Andric       // add stack protectors unless the array is a character array.
218f8af5cf6SDimitry Andric       // However, in strong mode any array, regardless of type and size,
219f8af5cf6SDimitry Andric       // triggers a protector.
2207fa27ce4SDimitry Andric       if (!Strong && (InStruct || !Triple(M->getTargetTriple()).isOSDarwin()))
221522600a2SDimitry Andric         return false;
222522600a2SDimitry Andric     }
223522600a2SDimitry Andric 
224522600a2SDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
225522600a2SDimitry Andric     // emit stack protectors.
226ee8648bdSDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
227f8af5cf6SDimitry Andric       IsLarge = true;
228f8af5cf6SDimitry Andric       return true;
229f8af5cf6SDimitry Andric     }
230f8af5cf6SDimitry Andric 
231f8af5cf6SDimitry Andric     if (Strong)
232f8af5cf6SDimitry Andric       // Require a protector for all arrays in strong mode
233522600a2SDimitry Andric       return true;
234522600a2SDimitry Andric   }
235522600a2SDimitry Andric 
236522600a2SDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
237f8af5cf6SDimitry Andric   if (!ST)
238522600a2SDimitry Andric     return false;
239f8af5cf6SDimitry Andric 
240f8af5cf6SDimitry Andric   bool NeedsProtector = false;
241c0981da4SDimitry Andric   for (Type *ET : ST->elements())
2427fa27ce4SDimitry Andric     if (ContainsProtectableArray(ET, M, SSPBufferSize, IsLarge, Strong, true)) {
243f8af5cf6SDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
244f8af5cf6SDimitry Andric       // then we are done.  If the protectable array is not large, then
245f8af5cf6SDimitry Andric       // keep looking in case a subsequent element is a large array.
246f8af5cf6SDimitry Andric       if (IsLarge)
247f8af5cf6SDimitry Andric         return true;
248f8af5cf6SDimitry Andric       NeedsProtector = true;
249f8af5cf6SDimitry Andric     }
250f8af5cf6SDimitry Andric 
251f8af5cf6SDimitry Andric   return NeedsProtector;
252522600a2SDimitry Andric }
253522600a2SDimitry Andric 
2547fa27ce4SDimitry Andric /// Check whether a stack allocation has its address taken.
HasAddressTaken(const Instruction * AI,TypeSize AllocSize,Module * M,SmallPtrSet<const PHINode *,16> & VisitedPHIs)2557fa27ce4SDimitry Andric static bool HasAddressTaken(const Instruction *AI, TypeSize AllocSize,
2567fa27ce4SDimitry Andric                             Module *M,
2577fa27ce4SDimitry Andric                             SmallPtrSet<const PHINode *, 16> &VisitedPHIs) {
258cfca06d7SDimitry Andric   const DataLayout &DL = M->getDataLayout();
2591d5ae102SDimitry Andric   for (const User *U : AI->users()) {
2601d5ae102SDimitry Andric     const auto *I = cast<Instruction>(U);
261cfca06d7SDimitry Andric     // If this instruction accesses memory make sure it doesn't access beyond
262cfca06d7SDimitry Andric     // the bounds of the allocated object.
263e3b55780SDimitry Andric     std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
264145449b1SDimitry Andric     if (MemLoc && MemLoc->Size.hasValue() &&
265b1c73532SDimitry Andric         !TypeSize::isKnownGE(AllocSize, MemLoc->Size.getValue()))
266cfca06d7SDimitry Andric       return true;
2671d5ae102SDimitry Andric     switch (I->getOpcode()) {
2681d5ae102SDimitry Andric     case Instruction::Store:
2691d5ae102SDimitry Andric       if (AI == cast<StoreInst>(I)->getValueOperand())
2701d5ae102SDimitry Andric         return true;
2711d5ae102SDimitry Andric       break;
2721d5ae102SDimitry Andric     case Instruction::AtomicCmpXchg:
2731d5ae102SDimitry Andric       // cmpxchg conceptually includes both a load and store from the same
2741d5ae102SDimitry Andric       // location. So, like store, the value being stored is what matters.
2751d5ae102SDimitry Andric       if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
2761d5ae102SDimitry Andric         return true;
2771d5ae102SDimitry Andric       break;
2781d5ae102SDimitry Andric     case Instruction::PtrToInt:
2791d5ae102SDimitry Andric       if (AI == cast<PtrToIntInst>(I)->getOperand(0))
2801d5ae102SDimitry Andric         return true;
2811d5ae102SDimitry Andric       break;
2821d5ae102SDimitry Andric     case Instruction::Call: {
2831d5ae102SDimitry Andric       // Ignore intrinsics that do not become real instructions.
2841d5ae102SDimitry Andric       // TODO: Narrow this to intrinsics that have store-like effects.
2851d5ae102SDimitry Andric       const auto *CI = cast<CallInst>(I);
286344a3780SDimitry Andric       if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
2871d5ae102SDimitry Andric         return true;
2881d5ae102SDimitry Andric       break;
2891d5ae102SDimitry Andric     }
2901d5ae102SDimitry Andric     case Instruction::Invoke:
2911d5ae102SDimitry Andric       return true;
292cfca06d7SDimitry Andric     case Instruction::GetElementPtr: {
293cfca06d7SDimitry Andric       // If the GEP offset is out-of-bounds, or is non-constant and so has to be
294cfca06d7SDimitry Andric       // assumed to be potentially out-of-bounds, then any memory access that
295cfca06d7SDimitry Andric       // would use it could also be out-of-bounds meaning stack protection is
296cfca06d7SDimitry Andric       // required.
297cfca06d7SDimitry Andric       const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
29877fc4c14SDimitry Andric       unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
29977fc4c14SDimitry Andric       APInt Offset(IndexSize, 0);
30077fc4c14SDimitry Andric       if (!GEP->accumulateConstantOffset(DL, Offset))
30177fc4c14SDimitry Andric         return true;
302b1c73532SDimitry Andric       TypeSize OffsetSize = TypeSize::getFixed(Offset.getLimitedValue());
30377fc4c14SDimitry Andric       if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
304cfca06d7SDimitry Andric         return true;
305cfca06d7SDimitry Andric       // Adjust AllocSize to be the space remaining after this offset.
30677fc4c14SDimitry Andric       // We can't subtract a fixed size from a scalable one, so in that case
30777fc4c14SDimitry Andric       // assume the scalable value is of minimum size.
30877fc4c14SDimitry Andric       TypeSize NewAllocSize =
309b1c73532SDimitry Andric           TypeSize::getFixed(AllocSize.getKnownMinValue()) - OffsetSize;
3107fa27ce4SDimitry Andric       if (HasAddressTaken(I, NewAllocSize, M, VisitedPHIs))
311cfca06d7SDimitry Andric         return true;
312cfca06d7SDimitry Andric       break;
313cfca06d7SDimitry Andric     }
3141d5ae102SDimitry Andric     case Instruction::BitCast:
3151d5ae102SDimitry Andric     case Instruction::Select:
3161d5ae102SDimitry Andric     case Instruction::AddrSpaceCast:
3177fa27ce4SDimitry Andric       if (HasAddressTaken(I, AllocSize, M, VisitedPHIs))
3181d5ae102SDimitry Andric         return true;
3191d5ae102SDimitry Andric       break;
3201d5ae102SDimitry Andric     case Instruction::PHI: {
3211d5ae102SDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
3221d5ae102SDimitry Andric       // they are only visited once.
3231d5ae102SDimitry Andric       const auto *PN = cast<PHINode>(I);
3241d5ae102SDimitry Andric       if (VisitedPHIs.insert(PN).second)
3257fa27ce4SDimitry Andric         if (HasAddressTaken(PN, AllocSize, M, VisitedPHIs))
3261d5ae102SDimitry Andric           return true;
3271d5ae102SDimitry Andric       break;
3281d5ae102SDimitry Andric     }
3291d5ae102SDimitry Andric     case Instruction::Load:
3301d5ae102SDimitry Andric     case Instruction::AtomicRMW:
3311d5ae102SDimitry Andric     case Instruction::Ret:
3321d5ae102SDimitry Andric       // These instructions take an address operand, but have load-like or
3331d5ae102SDimitry Andric       // other innocuous behavior that should not trigger a stack protector.
3341d5ae102SDimitry Andric       // atomicrmw conceptually has both load and store semantics, but the
3351d5ae102SDimitry Andric       // value being stored must be integer; so if a pointer is being stored,
3361d5ae102SDimitry Andric       // we'll catch it in the PtrToInt case above.
3371d5ae102SDimitry Andric       break;
3381d5ae102SDimitry Andric     default:
3391d5ae102SDimitry Andric       // Conservatively return true for any instruction that takes an address
3401d5ae102SDimitry Andric       // operand, but is not handled above.
3411d5ae102SDimitry Andric       return true;
3421d5ae102SDimitry Andric     }
3431d5ae102SDimitry Andric   }
3441d5ae102SDimitry Andric   return false;
3451d5ae102SDimitry Andric }
3461d5ae102SDimitry Andric 
347d8e91e46SDimitry Andric /// Search for the first call to the llvm.stackprotector intrinsic and return it
348d8e91e46SDimitry Andric /// if present.
findStackProtectorIntrinsic(Function & F)349d8e91e46SDimitry Andric static const CallInst *findStackProtectorIntrinsic(Function &F) {
350d8e91e46SDimitry Andric   for (const BasicBlock &BB : F)
351d8e91e46SDimitry Andric     for (const Instruction &I : BB)
352b60736ecSDimitry Andric       if (const auto *II = dyn_cast<IntrinsicInst>(&I))
353b60736ecSDimitry Andric         if (II->getIntrinsicID() == Intrinsic::stackprotector)
354b60736ecSDimitry Andric           return II;
355d8e91e46SDimitry Andric   return nullptr;
356d8e91e46SDimitry Andric }
357d8e91e46SDimitry Andric 
358eb11fae6SDimitry Andric /// Check whether or not this function needs a stack protector based
3594a16efa3SDimitry Andric /// upon the stack protector level.
3604a16efa3SDimitry Andric ///
3614a16efa3SDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
3624a16efa3SDimitry Andric /// The standard heuristic which will add a guard variable to functions that
3634a16efa3SDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
3644a16efa3SDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
3654a16efa3SDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
3664a16efa3SDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
3674a16efa3SDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
3684a16efa3SDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
3694a16efa3SDimitry Andric /// size, and functions that contain stack-based variables that have had their
3704a16efa3SDimitry Andric /// address taken.
requiresStackProtector(Function * F,SSPLayoutMap * Layout)371aca2e42cSDimitry Andric bool SSPLayoutAnalysis::requiresStackProtector(Function *F,
372aca2e42cSDimitry Andric                                                SSPLayoutMap *Layout) {
3737fa27ce4SDimitry Andric   Module *M = F->getParent();
3744a16efa3SDimitry Andric   bool Strong = false;
375f8af5cf6SDimitry Andric   bool NeedsProtector = false;
37601095a5dSDimitry Andric 
3777fa27ce4SDimitry Andric   // The set of PHI nodes visited when determining if a variable's reference has
3787fa27ce4SDimitry Andric   // been taken.  This set is maintained to ensure we don't visit the same PHI
3797fa27ce4SDimitry Andric   // node multiple times.
3807fa27ce4SDimitry Andric   SmallPtrSet<const PHINode *, 16> VisitedPHIs;
3817fa27ce4SDimitry Andric 
3827fa27ce4SDimitry Andric   unsigned SSPBufferSize = F->getFnAttributeAsParsedInteger(
383aca2e42cSDimitry Andric       "stack-protector-buffer-size", SSPLayoutInfo::DefaultSSPBufferSize);
3847fa27ce4SDimitry Andric 
38501095a5dSDimitry Andric   if (F->hasFnAttribute(Attribute::SafeStack))
38601095a5dSDimitry Andric     return false;
38701095a5dSDimitry Andric 
38871d5a254SDimitry Andric   // We are constructing the OptimizationRemarkEmitter on the fly rather than
38971d5a254SDimitry Andric   // using the analysis pass to avoid building DominatorTree and LoopInfo which
39071d5a254SDimitry Andric   // are not available this late in the IR pipeline.
39171d5a254SDimitry Andric   OptimizationRemarkEmitter ORE(F);
39271d5a254SDimitry Andric 
3935a5ac124SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
3947fa27ce4SDimitry Andric     if (!Layout)
3957fa27ce4SDimitry Andric       return true;
396044eb2f6SDimitry Andric     ORE.emit([&]() {
397044eb2f6SDimitry Andric       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
39871d5a254SDimitry Andric              << "Stack protection applied to function "
39971d5a254SDimitry Andric              << ore::NV("Function", F)
400044eb2f6SDimitry Andric              << " due to a function attribute or command-line switch";
401044eb2f6SDimitry Andric     });
402f8af5cf6SDimitry Andric     NeedsProtector = true;
403f8af5cf6SDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
4045a5ac124SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
4054a16efa3SDimitry Andric     Strong = true;
4065a5ac124SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
407009b1c42SEd Schouten     return false;
408009b1c42SEd Schouten 
40967c32a98SDimitry Andric   for (const BasicBlock &BB : *F) {
41067c32a98SDimitry Andric     for (const Instruction &I : BB) {
41167c32a98SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4124a16efa3SDimitry Andric         if (AI->isArrayAllocation()) {
413044eb2f6SDimitry Andric           auto RemarkBuilder = [&]() {
414044eb2f6SDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
415044eb2f6SDimitry Andric                                       &I)
41671d5a254SDimitry Andric                    << "Stack protection applied to function "
41771d5a254SDimitry Andric                    << ore::NV("Function", F)
418044eb2f6SDimitry Andric                    << " due to a call to alloca or use of a variable length "
419044eb2f6SDimitry Andric                       "array";
420044eb2f6SDimitry Andric           };
42167c32a98SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
422f8af5cf6SDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
4234a16efa3SDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
4244a16efa3SDimitry Andric               // stack protectors.
4257fa27ce4SDimitry Andric               if (!Layout)
4267fa27ce4SDimitry Andric                 return true;
4277fa27ce4SDimitry Andric               Layout->insert(
4287fa27ce4SDimitry Andric                   std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
429044eb2f6SDimitry Andric               ORE.emit(RemarkBuilder);
430f8af5cf6SDimitry Andric               NeedsProtector = true;
431f8af5cf6SDimitry Andric             } else if (Strong) {
432f8af5cf6SDimitry Andric               // Require protectors for all alloca calls in strong mode.
4337fa27ce4SDimitry Andric               if (!Layout)
4347fa27ce4SDimitry Andric                 return true;
4357fa27ce4SDimitry Andric               Layout->insert(
4367fa27ce4SDimitry Andric                   std::make_pair(AI, MachineFrameInfo::SSPLK_SmallArray));
437044eb2f6SDimitry Andric               ORE.emit(RemarkBuilder);
438f8af5cf6SDimitry Andric               NeedsProtector = true;
439f8af5cf6SDimitry Andric             }
440f8af5cf6SDimitry Andric           } else {
441f8af5cf6SDimitry Andric             // A call to alloca with a variable size requires protectors.
4427fa27ce4SDimitry Andric             if (!Layout)
4437fa27ce4SDimitry Andric               return true;
4447fa27ce4SDimitry Andric             Layout->insert(
4457fa27ce4SDimitry Andric                 std::make_pair(AI, MachineFrameInfo::SSPLK_LargeArray));
446044eb2f6SDimitry Andric             ORE.emit(RemarkBuilder);
447f8af5cf6SDimitry Andric             NeedsProtector = true;
448f8af5cf6SDimitry Andric           }
449f8af5cf6SDimitry Andric           continue;
4504a16efa3SDimitry Andric         }
4514a16efa3SDimitry Andric 
452f8af5cf6SDimitry Andric         bool IsLarge = false;
4537fa27ce4SDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), M, SSPBufferSize,
4547fa27ce4SDimitry Andric                                      IsLarge, Strong, false)) {
4557fa27ce4SDimitry Andric           if (!Layout)
4567fa27ce4SDimitry Andric             return true;
4577fa27ce4SDimitry Andric           Layout->insert(std::make_pair(
4587fa27ce4SDimitry Andric               AI, IsLarge ? MachineFrameInfo::SSPLK_LargeArray
459eb11fae6SDimitry Andric                           : MachineFrameInfo::SSPLK_SmallArray));
460044eb2f6SDimitry Andric           ORE.emit([&]() {
461044eb2f6SDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
46271d5a254SDimitry Andric                    << "Stack protection applied to function "
46371d5a254SDimitry Andric                    << ore::NV("Function", F)
46471d5a254SDimitry Andric                    << " due to a stack allocated buffer or struct containing a "
465044eb2f6SDimitry Andric                       "buffer";
466044eb2f6SDimitry Andric           });
467f8af5cf6SDimitry Andric           NeedsProtector = true;
468f8af5cf6SDimitry Andric           continue;
469f8af5cf6SDimitry Andric         }
4704a16efa3SDimitry Andric 
4717fa27ce4SDimitry Andric         if (Strong &&
4727fa27ce4SDimitry Andric             HasAddressTaken(
4737fa27ce4SDimitry Andric                 AI, M->getDataLayout().getTypeAllocSize(AI->getAllocatedType()),
4747fa27ce4SDimitry Andric                 M, VisitedPHIs)) {
4754a16efa3SDimitry Andric           ++NumAddrTaken;
4767fa27ce4SDimitry Andric           if (!Layout)
4777fa27ce4SDimitry Andric             return true;
4787fa27ce4SDimitry Andric           Layout->insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
479044eb2f6SDimitry Andric           ORE.emit([&]() {
480044eb2f6SDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
481044eb2f6SDimitry Andric                                       &I)
48271d5a254SDimitry Andric                    << "Stack protection applied to function "
48371d5a254SDimitry Andric                    << ore::NV("Function", F)
484044eb2f6SDimitry Andric                    << " due to the address of a local variable being taken";
485044eb2f6SDimitry Andric           });
486f8af5cf6SDimitry Andric           NeedsProtector = true;
4874a16efa3SDimitry Andric         }
488cfca06d7SDimitry Andric         // Clear any PHIs that we visited, to make sure we examine all uses of
489cfca06d7SDimitry Andric         // any subsequent allocas that we look at.
490cfca06d7SDimitry Andric         VisitedPHIs.clear();
4914a16efa3SDimitry Andric       }
492009b1c42SEd Schouten     }
493009b1c42SEd Schouten   }
494009b1c42SEd Schouten 
495f8af5cf6SDimitry Andric   return NeedsProtector;
496f8af5cf6SDimitry Andric }
497f8af5cf6SDimitry Andric 
49801095a5dSDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is
49901095a5dSDimitry Andric /// supported.
getStackGuard(const TargetLoweringBase * TLI,Module * M,IRBuilder<> & B,bool * SupportsSelectionDAGSP=nullptr)50001095a5dSDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
50101095a5dSDimitry Andric                             IRBuilder<> &B,
50201095a5dSDimitry Andric                             bool *SupportsSelectionDAGSP = nullptr) {
503b60736ecSDimitry Andric   Value *Guard = TLI->getIRStackGuard(B);
504344a3780SDimitry Andric   StringRef GuardMode = M->getStackProtectorGuard();
505344a3780SDimitry Andric   if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
506b1c73532SDimitry Andric     return B.CreateLoad(B.getPtrTy(), Guard, true, "StackGuard");
507f8af5cf6SDimitry Andric 
50801095a5dSDimitry Andric   // Use SelectionDAG SSP handling, since there isn't an IR guard.
509f8af5cf6SDimitry Andric   //
51001095a5dSDimitry Andric   // This is more or less weird, since we optionally output whether we
51101095a5dSDimitry Andric   // should perform a SelectionDAG SP here. The reason is that it's strictly
51201095a5dSDimitry Andric   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
51301095a5dSDimitry Andric   // mutating. There is no way to get this bit without mutating the IR, so
51401095a5dSDimitry Andric   // getting this bit has to happen in this right time.
515f8af5cf6SDimitry Andric   //
51601095a5dSDimitry Andric   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
51701095a5dSDimitry Andric   // will put more burden on the backends' overriding work, especially when it
51801095a5dSDimitry Andric   // actually conveys the same information getIRStackGuard() already gives.
51901095a5dSDimitry Andric   if (SupportsSelectionDAGSP)
52001095a5dSDimitry Andric     *SupportsSelectionDAGSP = true;
52101095a5dSDimitry Andric   TLI->insertSSPDeclarations(*M);
52201095a5dSDimitry Andric   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
523f8af5cf6SDimitry Andric }
524f8af5cf6SDimitry Andric 
52501095a5dSDimitry Andric /// Insert code into the entry block that stores the stack guard
526f8af5cf6SDimitry Andric /// variable onto the stack:
527f8af5cf6SDimitry Andric ///
528f8af5cf6SDimitry Andric ///   entry:
529f8af5cf6SDimitry Andric ///     StackGuardSlot = alloca i8*
53001095a5dSDimitry Andric ///     StackGuard = <stack guard>
53101095a5dSDimitry Andric ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
532f8af5cf6SDimitry Andric ///
533f8af5cf6SDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
534f8af5cf6SDimitry Andric /// node.
CreatePrologue(Function * F,Module * M,Instruction * CheckLoc,const TargetLoweringBase * TLI,AllocaInst * & AI)535e3b55780SDimitry Andric static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
53601095a5dSDimitry Andric                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
537f8af5cf6SDimitry Andric   bool SupportsSelectionDAGSP = false;
538f8af5cf6SDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
539b1c73532SDimitry Andric   PointerType *PtrTy = PointerType::getUnqual(CheckLoc->getContext());
5405ca98fd9SDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
541f8af5cf6SDimitry Andric 
54201095a5dSDimitry Andric   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
54301095a5dSDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
54401095a5dSDimitry Andric                {GuardSlot, AI});
545f8af5cf6SDimitry Andric   return SupportsSelectionDAGSP;
546009b1c42SEd Schouten }
547009b1c42SEd Schouten 
InsertStackProtectors(const TargetMachine * TM,Function * F,DomTreeUpdater * DTU,bool & HasPrologue,bool & HasIRCheck)548aca2e42cSDimitry Andric bool InsertStackProtectors(const TargetMachine *TM, Function *F,
549aca2e42cSDimitry Andric                            DomTreeUpdater *DTU, bool &HasPrologue,
550aca2e42cSDimitry Andric                            bool &HasIRCheck) {
551aca2e42cSDimitry Andric   auto *M = F->getParent();
552aca2e42cSDimitry Andric   auto *TLI = TM->getSubtargetImpl(*F)->getTargetLowering();
553aca2e42cSDimitry Andric 
554044eb2f6SDimitry Andric   // If the target wants to XOR the frame pointer into the guard value, it's
555044eb2f6SDimitry Andric   // impossible to emit the check in IR, so the target *must* support stack
556044eb2f6SDimitry Andric   // protection in SDAG.
557f8af5cf6SDimitry Andric   bool SupportsSelectionDAGSP =
558044eb2f6SDimitry Andric       TLI->useStackGuardXorFP() ||
559c0981da4SDimitry Andric       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
5605ca98fd9SDimitry Andric   AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
561e3b55780SDimitry Andric   BasicBlock *FailBB = nullptr;
562009b1c42SEd Schouten 
563c0981da4SDimitry Andric   for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
564e3b55780SDimitry Andric     // This is stack protector auto generated check BB, skip it.
565e3b55780SDimitry Andric     if (&BB == FailBB)
566e3b55780SDimitry Andric       continue;
567e3b55780SDimitry Andric     Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
5687fa27ce4SDimitry Andric     if (!CheckLoc && !DisableCheckNoReturn)
5697fa27ce4SDimitry Andric       for (auto &Inst : BB)
5707fa27ce4SDimitry Andric         if (auto *CB = dyn_cast<CallBase>(&Inst))
5717fa27ce4SDimitry Andric           // Do stack check before noreturn calls that aren't nounwind (e.g:
5727fa27ce4SDimitry Andric           // __cxa_throw).
5737fa27ce4SDimitry Andric           if (CB->doesNotReturn() && !CB->doesNotThrow()) {
574e3b55780SDimitry Andric             CheckLoc = CB;
575e3b55780SDimitry Andric             break;
576e3b55780SDimitry Andric           }
577e3b55780SDimitry Andric 
578e3b55780SDimitry Andric     if (!CheckLoc)
579f8af5cf6SDimitry Andric       continue;
580009b1c42SEd Schouten 
58101095a5dSDimitry Andric     // Generate prologue instrumentation if not already generated.
582f8af5cf6SDimitry Andric     if (!HasPrologue) {
583f8af5cf6SDimitry Andric       HasPrologue = true;
584e3b55780SDimitry Andric       SupportsSelectionDAGSP &= CreatePrologue(F, M, CheckLoc, TLI, AI);
585f8af5cf6SDimitry Andric     }
58666e41e3cSRoman Divacky 
58701095a5dSDimitry Andric     // SelectionDAG based code generation. Nothing else needs to be done here.
58801095a5dSDimitry Andric     // The epilogue instrumentation is postponed to SelectionDAG.
58901095a5dSDimitry Andric     if (SupportsSelectionDAGSP)
59001095a5dSDimitry Andric       break;
591009b1c42SEd Schouten 
592d8e91e46SDimitry Andric     // Find the stack guard slot if the prologue was not created by this pass
593d8e91e46SDimitry Andric     // itself via a previous call to CreatePrologue().
594d8e91e46SDimitry Andric     if (!AI) {
595d8e91e46SDimitry Andric       const CallInst *SPCall = findStackProtectorIntrinsic(*F);
596d8e91e46SDimitry Andric       assert(SPCall && "Call to llvm.stackprotector is missing");
597d8e91e46SDimitry Andric       AI = cast<AllocaInst>(SPCall->getArgOperand(1));
598d8e91e46SDimitry Andric     }
599d8e91e46SDimitry Andric 
60001095a5dSDimitry Andric     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
60101095a5dSDimitry Andric     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
60201095a5dSDimitry Andric     // instrumentation has already been generated.
60301095a5dSDimitry Andric     HasIRCheck = true;
60401095a5dSDimitry Andric 
605e3b55780SDimitry Andric     // If we're instrumenting a block with a tail call, the check has to be
606344a3780SDimitry Andric     // inserted before the call rather than between it and the return. The
607e3b55780SDimitry Andric     // verifier guarantees that a tail call is either directly before the
608344a3780SDimitry Andric     // return or with a single correct bitcast of the return value in between so
609344a3780SDimitry Andric     // we don't need to worry about many situations here.
610e3b55780SDimitry Andric     Instruction *Prev = CheckLoc->getPrevNonDebugInstruction();
611e3b55780SDimitry Andric     if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
612344a3780SDimitry Andric       CheckLoc = Prev;
613344a3780SDimitry Andric     else if (Prev) {
614344a3780SDimitry Andric       Prev = Prev->getPrevNonDebugInstruction();
615e3b55780SDimitry Andric       if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
616344a3780SDimitry Andric         CheckLoc = Prev;
617344a3780SDimitry Andric     }
618344a3780SDimitry Andric 
61901095a5dSDimitry Andric     // Generate epilogue instrumentation. The epilogue intrumentation can be
62001095a5dSDimitry Andric     // function-based or inlined depending on which mechanism the target is
62101095a5dSDimitry Andric     // providing.
622e6d15924SDimitry Andric     if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
62301095a5dSDimitry Andric       // Generate the function-based epilogue instrumentation.
62401095a5dSDimitry Andric       // The target provides a guard check function, generate a call to it.
625344a3780SDimitry Andric       IRBuilder<> B(CheckLoc);
626b1c73532SDimitry Andric       LoadInst *Guard = B.CreateLoad(B.getPtrTy(), AI, true, "Guard");
62701095a5dSDimitry Andric       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
628e6d15924SDimitry Andric       Call->setAttributes(GuardCheck->getAttributes());
629e6d15924SDimitry Andric       Call->setCallingConv(GuardCheck->getCallingConv());
630f8af5cf6SDimitry Andric     } else {
63101095a5dSDimitry Andric       // Generate the epilogue with inline instrumentation.
632344a3780SDimitry Andric       // If we do not support SelectionDAG based calls, generate IR level
633344a3780SDimitry Andric       // calls.
634f8af5cf6SDimitry Andric       //
635009b1c42SEd Schouten       // For each block with a return instruction, convert this:
636009b1c42SEd Schouten       //
637009b1c42SEd Schouten       //   return:
638009b1c42SEd Schouten       //     ...
639009b1c42SEd Schouten       //     ret ...
640009b1c42SEd Schouten       //
641009b1c42SEd Schouten       // into this:
642009b1c42SEd Schouten       //
643009b1c42SEd Schouten       //   return:
644009b1c42SEd Schouten       //     ...
64501095a5dSDimitry Andric       //     %1 = <stack guard>
646009b1c42SEd Schouten       //     %2 = load StackGuardSlot
647e3b55780SDimitry Andric       //     %3 = icmp ne i1 %1, %2
648e3b55780SDimitry Andric       //     br i1 %3, label %CallStackCheckFailBlk, label %SP_return
649009b1c42SEd Schouten       //
650009b1c42SEd Schouten       //   SP_return:
651009b1c42SEd Schouten       //     ret ...
652009b1c42SEd Schouten       //
653009b1c42SEd Schouten       //   CallStackCheckFailBlk:
654009b1c42SEd Schouten       //     call void @__stack_chk_fail()
655009b1c42SEd Schouten       //     unreachable
656009b1c42SEd Schouten 
657f8af5cf6SDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
658f8af5cf6SDimitry Andric       // merge pass will merge together all of the various BB into one including
659f8af5cf6SDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
660e3b55780SDimitry Andric       if (!FailBB)
661aca2e42cSDimitry Andric         FailBB = CreateFailBB(F, TM->getTargetTriple());
662f8af5cf6SDimitry Andric 
663e3b55780SDimitry Andric       IRBuilder<> B(CheckLoc);
66401095a5dSDimitry Andric       Value *Guard = getStackGuard(TLI, M, B);
665b1c73532SDimitry Andric       LoadInst *LI2 = B.CreateLoad(B.getPtrTy(), AI, true);
666e3b55780SDimitry Andric       auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
667dd58ef01SDimitry Andric       auto SuccessProb =
668dd58ef01SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(true);
669dd58ef01SDimitry Andric       auto FailureProb =
670dd58ef01SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(false);
67167c32a98SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
672e3b55780SDimitry Andric                             .createBranchWeights(FailureProb.getNumerator(),
673e3b55780SDimitry Andric                                                  SuccessProb.getNumerator());
674e3b55780SDimitry Andric 
675e3b55780SDimitry Andric       SplitBlockAndInsertIfThen(Cmp, CheckLoc,
676aca2e42cSDimitry Andric                                 /*Unreachable=*/false, Weights, DTU,
677e3b55780SDimitry Andric                                 /*LI=*/nullptr, /*ThenBlock=*/FailBB);
678e3b55780SDimitry Andric 
679e3b55780SDimitry Andric       auto *BI = cast<BranchInst>(Cmp->getParent()->getTerminator());
680e3b55780SDimitry Andric       BasicBlock *NewBB = BI->getSuccessor(1);
681e3b55780SDimitry Andric       NewBB->setName("SP_return");
682e3b55780SDimitry Andric       NewBB->moveAfter(&BB);
683e3b55780SDimitry Andric 
684e3b55780SDimitry Andric       Cmp->setPredicate(Cmp->getInversePredicate());
685e3b55780SDimitry Andric       BI->swapSuccessors();
686f8af5cf6SDimitry Andric     }
687009b1c42SEd Schouten   }
688009b1c42SEd Schouten 
68967c32a98SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
690009b1c42SEd Schouten   // statements in the function.
691dd58ef01SDimitry Andric   return HasPrologue;
692009b1c42SEd Schouten }
693009b1c42SEd Schouten 
CreateFailBB(Function * F,const Triple & Trip)694aca2e42cSDimitry Andric BasicBlock *CreateFailBB(Function *F, const Triple &Trip) {
695aca2e42cSDimitry Andric   auto *M = F->getParent();
696f8af5cf6SDimitry Andric   LLVMContext &Context = F->getContext();
697f8af5cf6SDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
698f8af5cf6SDimitry Andric   IRBuilder<> B(FailBB);
699b60736ecSDimitry Andric   if (F->getSubprogram())
700b60736ecSDimitry Andric     B.SetCurrentDebugLocation(
701b60736ecSDimitry Andric         DILocation::get(Context, 0, 0, F->getSubprogram()));
7027fa27ce4SDimitry Andric   FunctionCallee StackChkFail;
7037fa27ce4SDimitry Andric   SmallVector<Value *, 1> Args;
70467c32a98SDimitry Andric   if (Trip.isOSOpenBSD()) {
7057fa27ce4SDimitry Andric     StackChkFail = M->getOrInsertFunction("__stack_smash_handler",
7067fa27ce4SDimitry Andric                                           Type::getVoidTy(Context),
707b1c73532SDimitry Andric                                           PointerType::getUnqual(Context));
7087fa27ce4SDimitry Andric     Args.push_back(B.CreateGlobalStringPtr(F->getName(), "SSH"));
709f8af5cf6SDimitry Andric   } else {
7107fa27ce4SDimitry Andric     StackChkFail =
71171d5a254SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
712f8af5cf6SDimitry Andric   }
7137fa27ce4SDimitry Andric   cast<Function>(StackChkFail.getCallee())->addFnAttr(Attribute::NoReturn);
7147fa27ce4SDimitry Andric   B.CreateCall(StackChkFail, Args);
715f8af5cf6SDimitry Andric   B.CreateUnreachable();
716009b1c42SEd Schouten   return FailBB;
717009b1c42SEd Schouten }
718