17a7e6055SDimitry Andric //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This pass inserts stack protectors into functions which need them. A variable
11f22ef01cSRoman Divacky // with a random value in it is stored onto the stack before the local variables
12f22ef01cSRoman Divacky // are allocated. Upon exiting the block, the stored value is checked. If it's
13f22ef01cSRoman Divacky // changed, then there was some sort of violation and the program aborts.
14f22ef01cSRoman Divacky //
15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
16f22ef01cSRoman Divacky 
172cab237bSDimitry Andric #include "llvm/CodeGen/StackProtector.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
2039d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
213ca95b02SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
222cab237bSDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
2391bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h"
242cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
25db17bf38SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
287a7e6055SDimitry Andric #include "llvm/IR/BasicBlock.h"
29139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
30139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
313ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h"
327a7e6055SDimitry Andric #include "llvm/IR/DebugLoc.h"
33139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
34db17bf38SDimitry Andric #include "llvm/IR/Dominators.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
36f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
377a7e6055SDimitry Andric #include "llvm/IR/Instruction.h"
38139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
39139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
4039d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
41139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
427a7e6055SDimitry Andric #include "llvm/IR/Type.h"
437a7e6055SDimitry Andric #include "llvm/IR/User.h"
447a7e6055SDimitry Andric #include "llvm/Pass.h"
457a7e6055SDimitry Andric #include "llvm/Support/Casting.h"
46f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
477a7e6055SDimitry Andric #include "llvm/Target/TargetMachine.h"
487a7e6055SDimitry Andric #include "llvm/Target/TargetOptions.h"
497a7e6055SDimitry Andric #include <utility>
507a7e6055SDimitry Andric 
51f22ef01cSRoman Divacky using namespace llvm;
52f22ef01cSRoman Divacky 
5391bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector"
5491bc56edSDimitry Andric 
55139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
56139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
57139f7f9bSDimitry Andric                         " taken.");
58139f7f9bSDimitry Andric 
59f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
60f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
61f22ef01cSRoman Divacky 
62f22ef01cSRoman Divacky char StackProtector::ID = 0;
63db17bf38SDimitry Andric 
64302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
65d8866befSDimitry Andric                       "Insert stack protectors", false, true)
66d8866befSDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
67302affcbSDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
68d8866befSDimitry Andric                     "Insert stack protectors", false, true)
69f22ef01cSRoman Divacky 
70d8866befSDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
71f785676fSDimitry Andric 
72f785676fSDimitry Andric StackProtector::SSPLayoutKind
73f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
74f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
75f22ef01cSRoman Divacky }
76f22ef01cSRoman Divacky 
7791bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From,
7891bc56edSDimitry Andric                                        const AllocaInst *To) {
7991bc56edSDimitry Andric   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
8091bc56edSDimitry Andric   // tag from the remapped to the target alloca. The remapped alloca should
8191bc56edSDimitry Andric   // have a size smaller than or equal to the replacement alloca.
8291bc56edSDimitry Andric   SSPLayoutMap::iterator I = Layout.find(From);
8391bc56edSDimitry Andric   if (I != Layout.end()) {
8491bc56edSDimitry Andric     SSPLayoutKind Kind = I->second;
8591bc56edSDimitry Andric     Layout.erase(I);
8691bc56edSDimitry Andric 
8791bc56edSDimitry Andric     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
8891bc56edSDimitry Andric     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
8991bc56edSDimitry Andric     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
9091bc56edSDimitry Andric     I = Layout.find(To);
9191bc56edSDimitry Andric     if (I == Layout.end())
9291bc56edSDimitry Andric       Layout.insert(std::make_pair(To, Kind));
9391bc56edSDimitry Andric     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
9491bc56edSDimitry Andric       I->second = Kind;
9591bc56edSDimitry Andric   }
9691bc56edSDimitry Andric }
9791bc56edSDimitry Andric 
98db17bf38SDimitry Andric void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
99db17bf38SDimitry Andric   AU.addRequired<TargetPassConfig>();
100db17bf38SDimitry Andric   AU.addPreserved<DominatorTreeWrapperPass>();
101db17bf38SDimitry Andric }
102db17bf38SDimitry Andric 
103f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
104f22ef01cSRoman Divacky   F = &Fn;
105f22ef01cSRoman Divacky   M = F->getParent();
10691bc56edSDimitry Andric   DominatorTreeWrapperPass *DTWP =
10791bc56edSDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
10891bc56edSDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
109d8866befSDimitry Andric   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
110d8866befSDimitry Andric   Trip = TM->getTargetTriple();
111ff0cc061SDimitry Andric   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
1123ca95b02SDimitry Andric   HasPrologue = false;
1133ca95b02SDimitry Andric   HasIRCheck = false;
114f22ef01cSRoman Divacky 
115ff0cc061SDimitry Andric   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
11691bc56edSDimitry Andric   if (Attr.isStringAttribute() &&
11791bc56edSDimitry Andric       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
11891bc56edSDimitry Andric     return false; // Invalid integer string
11991bc56edSDimitry Andric 
12091bc56edSDimitry Andric   if (!RequiresStackProtector())
12191bc56edSDimitry Andric     return false;
122f22ef01cSRoman Divacky 
1233ca95b02SDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
1243ca95b02SDimitry Andric   // Do nothing if this is funclet-based personality.
1253ca95b02SDimitry Andric   if (Fn.hasPersonalityFn()) {
1263ca95b02SDimitry Andric     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
1273ca95b02SDimitry Andric     if (isFuncletEHPersonality(Personality))
1283ca95b02SDimitry Andric       return false;
1293ca95b02SDimitry Andric   }
1303ca95b02SDimitry Andric 
131139f7f9bSDimitry Andric   ++NumFunProtected;
132f22ef01cSRoman Divacky   return InsertStackProtectors();
133f22ef01cSRoman Divacky }
134f22ef01cSRoman Divacky 
135f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
136f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
137f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
138f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
139f785676fSDimitry Andric                                               bool Strong,
140139f7f9bSDimitry Andric                                               bool InStruct) const {
141f785676fSDimitry Andric   if (!Ty)
142f785676fSDimitry Andric     return false;
1433861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1443861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
1453861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
1463861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
147f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
148f785676fSDimitry Andric       // triggers a protector.
149f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
1503861d79fSDimitry Andric         return false;
1513861d79fSDimitry Andric     }
1523861d79fSDimitry Andric 
1533861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
1543861d79fSDimitry Andric     // emit stack protectors.
155875ed548SDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
156f785676fSDimitry Andric       IsLarge = true;
157f785676fSDimitry Andric       return true;
158f785676fSDimitry Andric     }
159f785676fSDimitry Andric 
160f785676fSDimitry Andric     if (Strong)
161f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1623861d79fSDimitry Andric       return true;
1633861d79fSDimitry Andric   }
1643861d79fSDimitry Andric 
1653861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
166f785676fSDimitry Andric   if (!ST)
1673861d79fSDimitry Andric     return false;
168f785676fSDimitry Andric 
169f785676fSDimitry Andric   bool NeedsProtector = false;
170f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
171f785676fSDimitry Andric                                     E = ST->element_end();
172f785676fSDimitry Andric        I != E; ++I)
173f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
174f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
175f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
176f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
177f785676fSDimitry Andric       if (IsLarge)
178f785676fSDimitry Andric         return true;
179f785676fSDimitry Andric       NeedsProtector = true;
180f785676fSDimitry Andric     }
181f785676fSDimitry Andric 
182f785676fSDimitry Andric   return NeedsProtector;
1833861d79fSDimitry Andric }
1843861d79fSDimitry Andric 
185139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
18691bc56edSDimitry Andric   for (const User *U : AI->users()) {
187139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
188139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
189f22ef01cSRoman Divacky         return true;
190139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
191139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
192139f7f9bSDimitry Andric         return true;
193139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
194139f7f9bSDimitry Andric       return true;
195139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
196139f7f9bSDimitry Andric       return true;
197139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
198139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
199139f7f9bSDimitry Andric         return true;
200139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
201139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
202139f7f9bSDimitry Andric       // they are only visited once.
20339d628a0SDimitry Andric       if (VisitedPHIs.insert(PN).second)
204139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
205139f7f9bSDimitry Andric           return true;
206139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
207139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
208139f7f9bSDimitry Andric         return true;
209139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
210139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
211139f7f9bSDimitry Andric         return true;
212139f7f9bSDimitry Andric     }
213139f7f9bSDimitry Andric   }
214139f7f9bSDimitry Andric   return false;
215139f7f9bSDimitry Andric }
216f22ef01cSRoman Divacky 
217139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
218139f7f9bSDimitry Andric /// upon the stack protector level.
219139f7f9bSDimitry Andric ///
220139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
221139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
222139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
223139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
224139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
225139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
226139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
227139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
228139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
229139f7f9bSDimitry Andric /// address taken.
230139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
231139f7f9bSDimitry Andric   bool Strong = false;
232f785676fSDimitry Andric   bool NeedsProtector = false;
2333ca95b02SDimitry Andric   for (const BasicBlock &BB : *F)
2343ca95b02SDimitry Andric     for (const Instruction &I : BB)
2353ca95b02SDimitry Andric       if (const CallInst *CI = dyn_cast<CallInst>(&I))
2363ca95b02SDimitry Andric         if (CI->getCalledFunction() ==
2373ca95b02SDimitry Andric             Intrinsic::getDeclaration(F->getParent(),
2383ca95b02SDimitry Andric                                       Intrinsic::stackprotector))
2393ca95b02SDimitry Andric           HasPrologue = true;
2403ca95b02SDimitry Andric 
2413ca95b02SDimitry Andric   if (F->hasFnAttribute(Attribute::SafeStack))
2423ca95b02SDimitry Andric     return false;
2433ca95b02SDimitry Andric 
2447a7e6055SDimitry Andric   // We are constructing the OptimizationRemarkEmitter on the fly rather than
2457a7e6055SDimitry Andric   // using the analysis pass to avoid building DominatorTree and LoopInfo which
2467a7e6055SDimitry Andric   // are not available this late in the IR pipeline.
2477a7e6055SDimitry Andric   OptimizationRemarkEmitter ORE(F);
2487a7e6055SDimitry Andric 
249ff0cc061SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
2502cab237bSDimitry Andric     ORE.emit([&]() {
2512cab237bSDimitry Andric       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
2527a7e6055SDimitry Andric              << "Stack protection applied to function "
2537a7e6055SDimitry Andric              << ore::NV("Function", F)
2542cab237bSDimitry Andric              << " due to a function attribute or command-line switch";
2552cab237bSDimitry Andric     });
256f785676fSDimitry Andric     NeedsProtector = true;
257f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
258ff0cc061SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
259139f7f9bSDimitry Andric     Strong = true;
2603ca95b02SDimitry Andric   else if (HasPrologue)
2613ca95b02SDimitry Andric     NeedsProtector = true;
262ff0cc061SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
263f22ef01cSRoman Divacky     return false;
264f22ef01cSRoman Divacky 
26539d628a0SDimitry Andric   for (const BasicBlock &BB : *F) {
26639d628a0SDimitry Andric     for (const Instruction &I : BB) {
26739d628a0SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
268139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
2692cab237bSDimitry Andric           auto RemarkBuilder = [&]() {
2702cab237bSDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
2712cab237bSDimitry Andric                                       &I)
2727a7e6055SDimitry Andric                    << "Stack protection applied to function "
2737a7e6055SDimitry Andric                    << ore::NV("Function", F)
2742cab237bSDimitry Andric                    << " due to a call to alloca or use of a variable length "
2752cab237bSDimitry Andric                       "array";
2762cab237bSDimitry Andric           };
27739d628a0SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
278f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
279139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
280139f7f9bSDimitry Andric               // stack protectors.
281f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2822cab237bSDimitry Andric               ORE.emit(RemarkBuilder);
283f785676fSDimitry Andric               NeedsProtector = true;
284f785676fSDimitry Andric             } else if (Strong) {
285f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
286f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
2872cab237bSDimitry Andric               ORE.emit(RemarkBuilder);
288f785676fSDimitry Andric               NeedsProtector = true;
289f785676fSDimitry Andric             }
290f785676fSDimitry Andric           } else {
291f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
292f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2932cab237bSDimitry Andric             ORE.emit(RemarkBuilder);
294f785676fSDimitry Andric             NeedsProtector = true;
295f785676fSDimitry Andric           }
296f785676fSDimitry Andric           continue;
297139f7f9bSDimitry Andric         }
298139f7f9bSDimitry Andric 
299f785676fSDimitry Andric         bool IsLarge = false;
300f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
301f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
302f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
3032cab237bSDimitry Andric           ORE.emit([&]() {
3042cab237bSDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
3057a7e6055SDimitry Andric                    << "Stack protection applied to function "
3067a7e6055SDimitry Andric                    << ore::NV("Function", F)
3077a7e6055SDimitry Andric                    << " due to a stack allocated buffer or struct containing a "
3082cab237bSDimitry Andric                       "buffer";
3092cab237bSDimitry Andric           });
310f785676fSDimitry Andric           NeedsProtector = true;
311f785676fSDimitry Andric           continue;
312f785676fSDimitry Andric         }
313139f7f9bSDimitry Andric 
314139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
315139f7f9bSDimitry Andric           ++NumAddrTaken;
316f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
3172cab237bSDimitry Andric           ORE.emit([&]() {
3182cab237bSDimitry Andric             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
3192cab237bSDimitry Andric                                       &I)
3207a7e6055SDimitry Andric                    << "Stack protection applied to function "
3217a7e6055SDimitry Andric                    << ore::NV("Function", F)
3222cab237bSDimitry Andric                    << " due to the address of a local variable being taken";
3232cab237bSDimitry Andric           });
324f785676fSDimitry Andric           NeedsProtector = true;
325139f7f9bSDimitry Andric         }
326139f7f9bSDimitry Andric       }
327f22ef01cSRoman Divacky     }
328f22ef01cSRoman Divacky   }
329f22ef01cSRoman Divacky 
330f785676fSDimitry Andric   return NeedsProtector;
331f785676fSDimitry Andric }
332f785676fSDimitry Andric 
3333ca95b02SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is
3343ca95b02SDimitry Andric /// supported.
3353ca95b02SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
3363ca95b02SDimitry Andric                             IRBuilder<> &B,
3373ca95b02SDimitry Andric                             bool *SupportsSelectionDAGSP = nullptr) {
3383ca95b02SDimitry Andric   if (Value *Guard = TLI->getIRStackGuard(B))
3393ca95b02SDimitry Andric     return B.CreateLoad(Guard, true, "StackGuard");
340f785676fSDimitry Andric 
3413ca95b02SDimitry Andric   // Use SelectionDAG SSP handling, since there isn't an IR guard.
342f785676fSDimitry Andric   //
3433ca95b02SDimitry Andric   // This is more or less weird, since we optionally output whether we
3443ca95b02SDimitry Andric   // should perform a SelectionDAG SP here. The reason is that it's strictly
3453ca95b02SDimitry Andric   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
3463ca95b02SDimitry Andric   // mutating. There is no way to get this bit without mutating the IR, so
3473ca95b02SDimitry Andric   // getting this bit has to happen in this right time.
348f785676fSDimitry Andric   //
3493ca95b02SDimitry Andric   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
3503ca95b02SDimitry Andric   // will put more burden on the backends' overriding work, especially when it
3513ca95b02SDimitry Andric   // actually conveys the same information getIRStackGuard() already gives.
3523ca95b02SDimitry Andric   if (SupportsSelectionDAGSP)
3533ca95b02SDimitry Andric     *SupportsSelectionDAGSP = true;
3543ca95b02SDimitry Andric   TLI->insertSSPDeclarations(*M);
3553ca95b02SDimitry Andric   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
356f785676fSDimitry Andric }
357f785676fSDimitry Andric 
3583ca95b02SDimitry Andric /// Insert code into the entry block that stores the stack guard
359f785676fSDimitry Andric /// variable onto the stack:
360f785676fSDimitry Andric ///
361f785676fSDimitry Andric ///   entry:
362f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
3633ca95b02SDimitry Andric ///     StackGuard = <stack guard>
3643ca95b02SDimitry Andric ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
365f785676fSDimitry Andric ///
366f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
367f785676fSDimitry Andric /// node.
368f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
3693ca95b02SDimitry Andric                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
370f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
371f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
3723ca95b02SDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
37391bc56edSDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
374f785676fSDimitry Andric 
3753ca95b02SDimitry Andric   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
3763ca95b02SDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
3773ca95b02SDimitry Andric                {GuardSlot, AI});
378f785676fSDimitry Andric   return SupportsSelectionDAGSP;
379f22ef01cSRoman Divacky }
380f22ef01cSRoman Divacky 
381f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the
382f22ef01cSRoman Divacky /// function.
383f22ef01cSRoman Divacky ///
384f22ef01cSRoman Divacky ///  - The prologue code loads and stores the stack guard onto the stack.
385f22ef01cSRoman Divacky ///  - The epilogue checks the value stored in the prologue against the original
386f22ef01cSRoman Divacky ///    value. It calls __stack_chk_fail if they differ.
387f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() {
3882cab237bSDimitry Andric   // If the target wants to XOR the frame pointer into the guard value, it's
3892cab237bSDimitry Andric   // impossible to emit the check in IR, so the target *must* support stack
3902cab237bSDimitry Andric   // protection in SDAG.
391f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
3922cab237bSDimitry Andric       TLI->useStackGuardXorFP() ||
3932cab237bSDimitry Andric       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
39491bc56edSDimitry Andric   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
395f22ef01cSRoman Divacky 
396f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
3977d523365SDimitry Andric     BasicBlock *BB = &*I++;
398f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
399f785676fSDimitry Andric     if (!RI)
400f785676fSDimitry Andric       continue;
401f22ef01cSRoman Divacky 
4023ca95b02SDimitry Andric     // Generate prologue instrumentation if not already generated.
403f785676fSDimitry Andric     if (!HasPrologue) {
404f785676fSDimitry Andric       HasPrologue = true;
4053ca95b02SDimitry Andric       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
406f785676fSDimitry Andric     }
407ffd1746dSEd Schouten 
4083ca95b02SDimitry Andric     // SelectionDAG based code generation. Nothing else needs to be done here.
4093ca95b02SDimitry Andric     // The epilogue instrumentation is postponed to SelectionDAG.
4103ca95b02SDimitry Andric     if (SupportsSelectionDAGSP)
4113ca95b02SDimitry Andric       break;
412f22ef01cSRoman Divacky 
4133ca95b02SDimitry Andric     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
4143ca95b02SDimitry Andric     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
4153ca95b02SDimitry Andric     // instrumentation has already been generated.
4163ca95b02SDimitry Andric     HasIRCheck = true;
4173ca95b02SDimitry Andric 
4183ca95b02SDimitry Andric     // Generate epilogue instrumentation. The epilogue intrumentation can be
4193ca95b02SDimitry Andric     // function-based or inlined depending on which mechanism the target is
4203ca95b02SDimitry Andric     // providing.
4213ca95b02SDimitry Andric     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
4223ca95b02SDimitry Andric       // Generate the function-based epilogue instrumentation.
4233ca95b02SDimitry Andric       // The target provides a guard check function, generate a call to it.
4243ca95b02SDimitry Andric       IRBuilder<> B(RI);
4253ca95b02SDimitry Andric       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
4263ca95b02SDimitry Andric       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
4273ca95b02SDimitry Andric       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
4283ca95b02SDimitry Andric       Call->setAttributes(Function->getAttributes());
4293ca95b02SDimitry Andric       Call->setCallingConv(Function->getCallingConv());
430f785676fSDimitry Andric     } else {
4313ca95b02SDimitry Andric       // Generate the epilogue with inline instrumentation.
432f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
433f785676fSDimitry Andric       // tail calls.
434f785676fSDimitry Andric       //
435f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
436f22ef01cSRoman Divacky       //
437f22ef01cSRoman Divacky       //   return:
438f22ef01cSRoman Divacky       //     ...
439f22ef01cSRoman Divacky       //     ret ...
440f22ef01cSRoman Divacky       //
441f22ef01cSRoman Divacky       // into this:
442f22ef01cSRoman Divacky       //
443f22ef01cSRoman Divacky       //   return:
444f22ef01cSRoman Divacky       //     ...
4453ca95b02SDimitry Andric       //     %1 = <stack guard>
446f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
447f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
448f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
449f22ef01cSRoman Divacky       //
450f22ef01cSRoman Divacky       //   SP_return:
451f22ef01cSRoman Divacky       //     ret ...
452f22ef01cSRoman Divacky       //
453f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
454f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
455f22ef01cSRoman Divacky       //     unreachable
456f22ef01cSRoman Divacky 
457f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
458f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
459f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
460f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
461f785676fSDimitry Andric 
462f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
4637d523365SDimitry Andric       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
4643b0f4066SDimitry Andric 
465f785676fSDimitry Andric       // Update the dominator tree if we need to.
4663b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4673b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
468f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4692754fe60SDimitry Andric       }
470f22ef01cSRoman Divacky 
471f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
472f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
473f22ef01cSRoman Divacky 
474f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
475f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
476f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
477f22ef01cSRoman Divacky 
478f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
479f785676fSDimitry Andric       IRBuilder<> B(BB);
4803ca95b02SDimitry Andric       Value *Guard = getStackGuard(TLI, M, B);
4813ca95b02SDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI, true);
4823ca95b02SDimitry Andric       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
4837d523365SDimitry Andric       auto SuccessProb =
4847d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(true);
4857d523365SDimitry Andric       auto FailureProb =
4867d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(false);
48739d628a0SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
4887d523365SDimitry Andric                             .createBranchWeights(SuccessProb.getNumerator(),
4897d523365SDimitry Andric                                                  FailureProb.getNumerator());
49039d628a0SDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
491f785676fSDimitry Andric     }
492f22ef01cSRoman Divacky   }
493f22ef01cSRoman Divacky 
49439d628a0SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
495f22ef01cSRoman Divacky   // statements in the function.
4967d523365SDimitry Andric   return HasPrologue;
497f22ef01cSRoman Divacky }
498f22ef01cSRoman Divacky 
499f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
500f22ef01cSRoman Divacky /// check fails.
501f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
502f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
503f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
504f785676fSDimitry Andric   IRBuilder<> B(FailBB);
5053ca95b02SDimitry Andric   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
50639d628a0SDimitry Andric   if (Trip.isOSOpenBSD()) {
50739d628a0SDimitry Andric     Constant *StackChkFail =
50839d628a0SDimitry Andric         M->getOrInsertFunction("__stack_smash_handler",
50939d628a0SDimitry Andric                                Type::getVoidTy(Context),
5107a7e6055SDimitry Andric                                Type::getInt8PtrTy(Context));
511f785676fSDimitry Andric 
512f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
513f785676fSDimitry Andric   } else {
51439d628a0SDimitry Andric     Constant *StackChkFail =
5157a7e6055SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
5167a7e6055SDimitry Andric 
517ff0cc061SDimitry Andric     B.CreateCall(StackChkFail, {});
518f785676fSDimitry Andric   }
519f785676fSDimitry Andric   B.CreateUnreachable();
520f22ef01cSRoman Divacky   return FailBB;
521f22ef01cSRoman Divacky }
5223ca95b02SDimitry Andric 
5233ca95b02SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
5243ca95b02SDimitry Andric   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
5253ca95b02SDimitry Andric }
526