1f22ef01cSRoman Divacky //===-- 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 
17f785676fSDimitry 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"
22f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
2391bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h"
24139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
26139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
273ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h"
28139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
29139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
30f785676fSDimitry Andric #include "llvm/IR/GlobalValue.h"
31f785676fSDimitry Andric #include "llvm/IR/GlobalVariable.h"
32f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
33139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
34f785676fSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
3639d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
38f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
3939d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
40f785676fSDimitry Andric #include <cstdlib>
41f22ef01cSRoman Divacky using namespace llvm;
42f22ef01cSRoman Divacky 
4391bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector"
4491bc56edSDimitry Andric 
45139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
46139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
47139f7f9bSDimitry Andric                         " taken.");
48139f7f9bSDimitry Andric 
49f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
50f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
51f22ef01cSRoman Divacky 
52f22ef01cSRoman Divacky char StackProtector::ID = 0;
53f785676fSDimitry Andric INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
54f785676fSDimitry Andric                 false, true)
55f22ef01cSRoman Divacky 
56f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
57f785676fSDimitry Andric   return new StackProtector(TM);
58f785676fSDimitry Andric }
59f785676fSDimitry Andric 
60f785676fSDimitry Andric StackProtector::SSPLayoutKind
61f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
62f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
63f22ef01cSRoman Divacky }
64f22ef01cSRoman Divacky 
6591bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From,
6691bc56edSDimitry Andric                                        const AllocaInst *To) {
6791bc56edSDimitry Andric   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
6891bc56edSDimitry Andric   // tag from the remapped to the target alloca. The remapped alloca should
6991bc56edSDimitry Andric   // have a size smaller than or equal to the replacement alloca.
7091bc56edSDimitry Andric   SSPLayoutMap::iterator I = Layout.find(From);
7191bc56edSDimitry Andric   if (I != Layout.end()) {
7291bc56edSDimitry Andric     SSPLayoutKind Kind = I->second;
7391bc56edSDimitry Andric     Layout.erase(I);
7491bc56edSDimitry Andric 
7591bc56edSDimitry Andric     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
7691bc56edSDimitry Andric     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
7791bc56edSDimitry Andric     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
7891bc56edSDimitry Andric     I = Layout.find(To);
7991bc56edSDimitry Andric     if (I == Layout.end())
8091bc56edSDimitry Andric       Layout.insert(std::make_pair(To, Kind));
8191bc56edSDimitry Andric     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
8291bc56edSDimitry Andric       I->second = Kind;
8391bc56edSDimitry Andric   }
8491bc56edSDimitry Andric }
8591bc56edSDimitry Andric 
86f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
87f22ef01cSRoman Divacky   F = &Fn;
88f22ef01cSRoman Divacky   M = F->getParent();
8991bc56edSDimitry Andric   DominatorTreeWrapperPass *DTWP =
9091bc56edSDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
9191bc56edSDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
92ff0cc061SDimitry Andric   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
933ca95b02SDimitry Andric   HasPrologue = false;
943ca95b02SDimitry Andric   HasIRCheck = false;
95f22ef01cSRoman Divacky 
96ff0cc061SDimitry Andric   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
9791bc56edSDimitry Andric   if (Attr.isStringAttribute() &&
9891bc56edSDimitry Andric       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
9991bc56edSDimitry Andric     return false; // Invalid integer string
10091bc56edSDimitry Andric 
10191bc56edSDimitry Andric   if (!RequiresStackProtector())
10291bc56edSDimitry Andric     return false;
103f22ef01cSRoman Divacky 
1043ca95b02SDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
1053ca95b02SDimitry Andric   // Do nothing if this is funclet-based personality.
1063ca95b02SDimitry Andric   if (Fn.hasPersonalityFn()) {
1073ca95b02SDimitry Andric     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
1083ca95b02SDimitry Andric     if (isFuncletEHPersonality(Personality))
1093ca95b02SDimitry Andric       return false;
1103ca95b02SDimitry Andric   }
1113ca95b02SDimitry Andric 
112139f7f9bSDimitry Andric   ++NumFunProtected;
113f22ef01cSRoman Divacky   return InsertStackProtectors();
114f22ef01cSRoman Divacky }
115f22ef01cSRoman Divacky 
116f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
117f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
118f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
119f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
120f785676fSDimitry Andric                                               bool Strong,
121139f7f9bSDimitry Andric                                               bool InStruct) const {
122f785676fSDimitry Andric   if (!Ty)
123f785676fSDimitry Andric     return false;
1243861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1253861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
1263861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
1273861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
128f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
129f785676fSDimitry Andric       // triggers a protector.
130f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
1313861d79fSDimitry Andric         return false;
1323861d79fSDimitry Andric     }
1333861d79fSDimitry Andric 
1343861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
1353861d79fSDimitry Andric     // emit stack protectors.
136875ed548SDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
137f785676fSDimitry Andric       IsLarge = true;
138f785676fSDimitry Andric       return true;
139f785676fSDimitry Andric     }
140f785676fSDimitry Andric 
141f785676fSDimitry Andric     if (Strong)
142f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1433861d79fSDimitry Andric       return true;
1443861d79fSDimitry Andric   }
1453861d79fSDimitry Andric 
1463861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
147f785676fSDimitry Andric   if (!ST)
1483861d79fSDimitry Andric     return false;
149f785676fSDimitry Andric 
150f785676fSDimitry Andric   bool NeedsProtector = false;
151f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
152f785676fSDimitry Andric                                     E = ST->element_end();
153f785676fSDimitry Andric        I != E; ++I)
154f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
155f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
156f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
157f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
158f785676fSDimitry Andric       if (IsLarge)
159f785676fSDimitry Andric         return true;
160f785676fSDimitry Andric       NeedsProtector = true;
161f785676fSDimitry Andric     }
162f785676fSDimitry Andric 
163f785676fSDimitry Andric   return NeedsProtector;
1643861d79fSDimitry Andric }
1653861d79fSDimitry Andric 
166139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
16791bc56edSDimitry Andric   for (const User *U : AI->users()) {
168139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
169139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
170f22ef01cSRoman Divacky         return true;
171139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
172139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
173139f7f9bSDimitry Andric         return true;
174139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
175139f7f9bSDimitry Andric       return true;
176139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
177139f7f9bSDimitry Andric       return true;
178139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
179139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
180139f7f9bSDimitry Andric         return true;
181139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
182139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
183139f7f9bSDimitry Andric       // they are only visited once.
18439d628a0SDimitry Andric       if (VisitedPHIs.insert(PN).second)
185139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
186139f7f9bSDimitry Andric           return true;
187139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
188139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
189139f7f9bSDimitry Andric         return true;
190139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
191139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
192139f7f9bSDimitry Andric         return true;
193139f7f9bSDimitry Andric     }
194139f7f9bSDimitry Andric   }
195139f7f9bSDimitry Andric   return false;
196139f7f9bSDimitry Andric }
197f22ef01cSRoman Divacky 
198139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
199139f7f9bSDimitry Andric /// upon the stack protector level.
200139f7f9bSDimitry Andric ///
201139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
202139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
203139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
204139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
205139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
206139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
207139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
208139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
209139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
210139f7f9bSDimitry Andric /// address taken.
211139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
212139f7f9bSDimitry Andric   bool Strong = false;
213f785676fSDimitry Andric   bool NeedsProtector = false;
2143ca95b02SDimitry Andric   for (const BasicBlock &BB : *F)
2153ca95b02SDimitry Andric     for (const Instruction &I : BB)
2163ca95b02SDimitry Andric       if (const CallInst *CI = dyn_cast<CallInst>(&I))
2173ca95b02SDimitry Andric         if (CI->getCalledFunction() ==
2183ca95b02SDimitry Andric             Intrinsic::getDeclaration(F->getParent(),
2193ca95b02SDimitry Andric                                       Intrinsic::stackprotector))
2203ca95b02SDimitry Andric           HasPrologue = true;
2213ca95b02SDimitry Andric 
2223ca95b02SDimitry Andric   if (F->hasFnAttribute(Attribute::SafeStack))
2233ca95b02SDimitry Andric     return false;
2243ca95b02SDimitry Andric 
225ff0cc061SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
226f785676fSDimitry Andric     NeedsProtector = true;
227f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
228ff0cc061SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
229139f7f9bSDimitry Andric     Strong = true;
2303ca95b02SDimitry Andric   else if (HasPrologue)
2313ca95b02SDimitry Andric     NeedsProtector = true;
232ff0cc061SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
233f22ef01cSRoman Divacky     return false;
234f22ef01cSRoman Divacky 
23539d628a0SDimitry Andric   for (const BasicBlock &BB : *F) {
23639d628a0SDimitry Andric     for (const Instruction &I : BB) {
23739d628a0SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
238139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
239139f7f9bSDimitry Andric           // SSP-Strong: Enable protectors for any call to alloca, regardless
240139f7f9bSDimitry Andric           // of size.
241139f7f9bSDimitry Andric           if (Strong)
242f22ef01cSRoman Divacky             return true;
243f22ef01cSRoman Divacky 
24439d628a0SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
245f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
246139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
247139f7f9bSDimitry Andric               // stack protectors.
248f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
249f785676fSDimitry Andric               NeedsProtector = true;
250f785676fSDimitry Andric             } else if (Strong) {
251f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
252f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
253f785676fSDimitry Andric               NeedsProtector = true;
254f785676fSDimitry Andric             }
255f785676fSDimitry Andric           } else {
256f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
257f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
258f785676fSDimitry Andric             NeedsProtector = true;
259f785676fSDimitry Andric           }
260f785676fSDimitry Andric           continue;
261139f7f9bSDimitry Andric         }
262139f7f9bSDimitry Andric 
263f785676fSDimitry Andric         bool IsLarge = false;
264f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
265f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
266f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
267f785676fSDimitry Andric           NeedsProtector = true;
268f785676fSDimitry Andric           continue;
269f785676fSDimitry Andric         }
270139f7f9bSDimitry Andric 
271139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
272139f7f9bSDimitry Andric           ++NumAddrTaken;
273f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
274f785676fSDimitry Andric           NeedsProtector = true;
275139f7f9bSDimitry Andric         }
276139f7f9bSDimitry Andric       }
277f22ef01cSRoman Divacky     }
278f22ef01cSRoman Divacky   }
279f22ef01cSRoman Divacky 
280f785676fSDimitry Andric   return NeedsProtector;
281f785676fSDimitry Andric }
282f785676fSDimitry Andric 
2833ca95b02SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is
2843ca95b02SDimitry Andric /// supported.
2853ca95b02SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
2863ca95b02SDimitry Andric                             IRBuilder<> &B,
2873ca95b02SDimitry Andric                             bool *SupportsSelectionDAGSP = nullptr) {
2883ca95b02SDimitry Andric   if (Value *Guard = TLI->getIRStackGuard(B))
2893ca95b02SDimitry Andric     return B.CreateLoad(Guard, true, "StackGuard");
290f785676fSDimitry Andric 
2913ca95b02SDimitry Andric   // Use SelectionDAG SSP handling, since there isn't an IR guard.
292f785676fSDimitry Andric   //
2933ca95b02SDimitry Andric   // This is more or less weird, since we optionally output whether we
2943ca95b02SDimitry Andric   // should perform a SelectionDAG SP here. The reason is that it's strictly
2953ca95b02SDimitry Andric   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
2963ca95b02SDimitry Andric   // mutating. There is no way to get this bit without mutating the IR, so
2973ca95b02SDimitry Andric   // getting this bit has to happen in this right time.
298f785676fSDimitry Andric   //
2993ca95b02SDimitry Andric   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
3003ca95b02SDimitry Andric   // will put more burden on the backends' overriding work, especially when it
3013ca95b02SDimitry Andric   // actually conveys the same information getIRStackGuard() already gives.
3023ca95b02SDimitry Andric   if (SupportsSelectionDAGSP)
3033ca95b02SDimitry Andric     *SupportsSelectionDAGSP = true;
3043ca95b02SDimitry Andric   TLI->insertSSPDeclarations(*M);
3053ca95b02SDimitry Andric   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
306f785676fSDimitry Andric }
307f785676fSDimitry Andric 
3083ca95b02SDimitry Andric /// Insert code into the entry block that stores the stack guard
309f785676fSDimitry Andric /// variable onto the stack:
310f785676fSDimitry Andric ///
311f785676fSDimitry Andric ///   entry:
312f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
3133ca95b02SDimitry Andric ///     StackGuard = <stack guard>
3143ca95b02SDimitry Andric ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
315f785676fSDimitry Andric ///
316f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
317f785676fSDimitry Andric /// node.
318f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
3193ca95b02SDimitry Andric                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
320f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
321f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
3223ca95b02SDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
32391bc56edSDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
324f785676fSDimitry Andric 
3253ca95b02SDimitry Andric   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
3263ca95b02SDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
3273ca95b02SDimitry Andric                {GuardSlot, AI});
328f785676fSDimitry Andric   return SupportsSelectionDAGSP;
329f22ef01cSRoman Divacky }
330f22ef01cSRoman Divacky 
331f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the
332f22ef01cSRoman Divacky /// function.
333f22ef01cSRoman Divacky ///
334f22ef01cSRoman Divacky ///  - The prologue code loads and stores the stack guard onto the stack.
335f22ef01cSRoman Divacky ///  - The epilogue checks the value stored in the prologue against the original
336f22ef01cSRoman Divacky ///    value. It calls __stack_chk_fail if they differ.
337f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() {
338f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
339f785676fSDimitry Andric       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
34091bc56edSDimitry Andric   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
341f22ef01cSRoman Divacky 
342f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
3437d523365SDimitry Andric     BasicBlock *BB = &*I++;
344f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
345f785676fSDimitry Andric     if (!RI)
346f785676fSDimitry Andric       continue;
347f22ef01cSRoman Divacky 
3483ca95b02SDimitry Andric     // Generate prologue instrumentation if not already generated.
349f785676fSDimitry Andric     if (!HasPrologue) {
350f785676fSDimitry Andric       HasPrologue = true;
3513ca95b02SDimitry Andric       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
352f785676fSDimitry Andric     }
353ffd1746dSEd Schouten 
3543ca95b02SDimitry Andric     // SelectionDAG based code generation. Nothing else needs to be done here.
3553ca95b02SDimitry Andric     // The epilogue instrumentation is postponed to SelectionDAG.
3563ca95b02SDimitry Andric     if (SupportsSelectionDAGSP)
3573ca95b02SDimitry Andric       break;
358f22ef01cSRoman Divacky 
3593ca95b02SDimitry Andric     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
3603ca95b02SDimitry Andric     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
3613ca95b02SDimitry Andric     // instrumentation has already been generated.
3623ca95b02SDimitry Andric     HasIRCheck = true;
3633ca95b02SDimitry Andric 
3643ca95b02SDimitry Andric     // Generate epilogue instrumentation. The epilogue intrumentation can be
3653ca95b02SDimitry Andric     // function-based or inlined depending on which mechanism the target is
3663ca95b02SDimitry Andric     // providing.
3673ca95b02SDimitry Andric     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
3683ca95b02SDimitry Andric       // Generate the function-based epilogue instrumentation.
3693ca95b02SDimitry Andric       // The target provides a guard check function, generate a call to it.
3703ca95b02SDimitry Andric       IRBuilder<> B(RI);
3713ca95b02SDimitry Andric       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
3723ca95b02SDimitry Andric       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
3733ca95b02SDimitry Andric       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
3743ca95b02SDimitry Andric       Call->setAttributes(Function->getAttributes());
3753ca95b02SDimitry Andric       Call->setCallingConv(Function->getCallingConv());
376f785676fSDimitry Andric     } else {
3773ca95b02SDimitry Andric       // Generate the epilogue with inline instrumentation.
378f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
379f785676fSDimitry Andric       // tail calls.
380f785676fSDimitry Andric       //
381f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
382f22ef01cSRoman Divacky       //
383f22ef01cSRoman Divacky       //   return:
384f22ef01cSRoman Divacky       //     ...
385f22ef01cSRoman Divacky       //     ret ...
386f22ef01cSRoman Divacky       //
387f22ef01cSRoman Divacky       // into this:
388f22ef01cSRoman Divacky       //
389f22ef01cSRoman Divacky       //   return:
390f22ef01cSRoman Divacky       //     ...
3913ca95b02SDimitry Andric       //     %1 = <stack guard>
392f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
393f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
394f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
395f22ef01cSRoman Divacky       //
396f22ef01cSRoman Divacky       //   SP_return:
397f22ef01cSRoman Divacky       //     ret ...
398f22ef01cSRoman Divacky       //
399f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
400f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
401f22ef01cSRoman Divacky       //     unreachable
402f22ef01cSRoman Divacky 
403f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
404f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
405f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
406f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
407f785676fSDimitry Andric 
408f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
4097d523365SDimitry Andric       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
4103b0f4066SDimitry Andric 
411f785676fSDimitry Andric       // Update the dominator tree if we need to.
4123b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4133b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
414f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4152754fe60SDimitry Andric       }
416f22ef01cSRoman Divacky 
417f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
418f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
419f22ef01cSRoman Divacky 
420f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
421f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
422f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
423f22ef01cSRoman Divacky 
424f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
425f785676fSDimitry Andric       IRBuilder<> B(BB);
4263ca95b02SDimitry Andric       Value *Guard = getStackGuard(TLI, M, B);
4273ca95b02SDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI, true);
4283ca95b02SDimitry Andric       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
4297d523365SDimitry Andric       auto SuccessProb =
4307d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(true);
4317d523365SDimitry Andric       auto FailureProb =
4327d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(false);
43339d628a0SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
4347d523365SDimitry Andric                             .createBranchWeights(SuccessProb.getNumerator(),
4357d523365SDimitry Andric                                                  FailureProb.getNumerator());
43639d628a0SDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
437f785676fSDimitry Andric     }
438f22ef01cSRoman Divacky   }
439f22ef01cSRoman Divacky 
44039d628a0SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
441f22ef01cSRoman Divacky   // statements in the function.
4427d523365SDimitry Andric   return HasPrologue;
443f22ef01cSRoman Divacky }
444f22ef01cSRoman Divacky 
445f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
446f22ef01cSRoman Divacky /// check fails.
447f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
448f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
449f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
450f785676fSDimitry Andric   IRBuilder<> B(FailBB);
4513ca95b02SDimitry Andric   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
45239d628a0SDimitry Andric   if (Trip.isOSOpenBSD()) {
45339d628a0SDimitry Andric     Constant *StackChkFail =
45439d628a0SDimitry Andric         M->getOrInsertFunction("__stack_smash_handler",
45539d628a0SDimitry Andric                                Type::getVoidTy(Context),
45639d628a0SDimitry Andric                                Type::getInt8PtrTy(Context), nullptr);
457f785676fSDimitry Andric 
458f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
459f785676fSDimitry Andric   } else {
46039d628a0SDimitry Andric     Constant *StackChkFail =
46139d628a0SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
46239d628a0SDimitry Andric                                nullptr);
463ff0cc061SDimitry Andric     B.CreateCall(StackChkFail, {});
464f785676fSDimitry Andric   }
465f785676fSDimitry Andric   B.CreateUnreachable();
466f22ef01cSRoman Divacky   return FailBB;
467f22ef01cSRoman Divacky }
4683ca95b02SDimitry Andric 
4693ca95b02SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
4703ca95b02SDimitry Andric   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
4713ca95b02SDimitry Andric }
472