xref: /llvm-project/llvm/lib/CodeGen/SafeStack.cpp (revision a5a272a491406874e5147ba474182d30098ddfd4)
1 //===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass splits the stack into the safe stack (kept as-is for LLVM backend)
10 // and the unsafe stack (explicitly allocated and managed through the runtime
11 // support library).
12 //
13 // http://clang.llvm.org/docs/SafeStack.html
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "SafeStackLayout.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/DomTreeUpdater.h"
26 #include "llvm/Analysis/InlineCost.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/StackLifetime.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/CodeGen/TargetLowering.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/ConstantRange.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DIBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/InstIterator.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Use.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/InitializePasses.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/MathExtras.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Target/TargetMachine.h"
63 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
64 #include "llvm/Transforms/Utils/Cloning.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <string>
70 #include <utility>
71 
72 using namespace llvm;
73 using namespace llvm::safestack;
74 
75 #define DEBUG_TYPE "safe-stack"
76 
77 namespace llvm {
78 
79 STATISTIC(NumFunctions, "Total number of functions");
80 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
81 STATISTIC(NumUnsafeStackRestorePointsFunctions,
82           "Number of functions that use setjmp or exceptions");
83 
84 STATISTIC(NumAllocas, "Total number of allocas");
85 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
86 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
87 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
88 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
89 
90 } // namespace llvm
91 
92 /// Use __safestack_pointer_address even if the platform has a faster way of
93 /// access safe stack pointer.
94 static cl::opt<bool>
95     SafeStackUsePointerAddress("safestack-use-pointer-address",
96                                   cl::init(false), cl::Hidden);
97 
98 static cl::opt<bool> ClColoring("safe-stack-coloring",
99                                 cl::desc("enable safe stack coloring"),
100                                 cl::Hidden, cl::init(true));
101 
102 namespace {
103 
104 /// The SafeStack pass splits the stack of each function into the safe
105 /// stack, which is only accessed through memory safe dereferences (as
106 /// determined statically), and the unsafe stack, which contains all
107 /// local variables that are accessed in ways that we can't prove to
108 /// be safe.
109 class SafeStack {
110   Function &F;
111   const TargetLoweringBase &TL;
112   const DataLayout &DL;
113   DomTreeUpdater *DTU;
114   ScalarEvolution &SE;
115 
116   Type *StackPtrTy;
117   Type *IntPtrTy;
118   Type *Int32Ty;
119   Type *Int8Ty;
120 
121   Value *UnsafeStackPtr = nullptr;
122 
123   /// Unsafe stack alignment. Each stack frame must ensure that the stack is
124   /// aligned to this value. We need to re-align the unsafe stack if the
125   /// alignment of any object on the stack exceeds this value.
126   ///
127   /// 16 seems like a reasonable upper bound on the alignment of objects that we
128   /// might expect to appear on the stack on most common targets.
129   static constexpr uint64_t StackAlignment = 16;
130 
131   /// Return the value of the stack canary.
132   Value *getStackGuard(IRBuilder<> &IRB, Function &F);
133 
134   /// Load stack guard from the frame and check if it has changed.
135   void checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
136                        AllocaInst *StackGuardSlot, Value *StackGuard);
137 
138   /// Find all static allocas, dynamic allocas, return instructions and
139   /// stack restore points (exception unwind blocks and setjmp calls) in the
140   /// given function and append them to the respective vectors.
141   void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
142                  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
143                  SmallVectorImpl<Argument *> &ByValArguments,
144                  SmallVectorImpl<Instruction *> &Returns,
145                  SmallVectorImpl<Instruction *> &StackRestorePoints);
146 
147   /// Calculate the allocation size of a given alloca. Returns 0 if the
148   /// size can not be statically determined.
149   uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
150 
151   /// Allocate space for all static allocas in \p StaticAllocas,
152   /// replace allocas with pointers into the unsafe stack.
153   ///
154   /// \returns A pointer to the top of the unsafe stack after all unsafe static
155   /// allocas are allocated.
156   Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
157                                         ArrayRef<AllocaInst *> StaticAllocas,
158                                         ArrayRef<Argument *> ByValArguments,
159                                         Instruction *BasePointer,
160                                         AllocaInst *StackGuardSlot);
161 
162   /// Generate code to restore the stack after all stack restore points
163   /// in \p StackRestorePoints.
164   ///
165   /// \returns A local variable in which to maintain the dynamic top of the
166   /// unsafe stack if needed.
167   AllocaInst *
168   createStackRestorePoints(IRBuilder<> &IRB, Function &F,
169                            ArrayRef<Instruction *> StackRestorePoints,
170                            Value *StaticTop, bool NeedDynamicTop);
171 
172   /// Replace all allocas in \p DynamicAllocas with code to allocate
173   /// space dynamically on the unsafe stack and store the dynamic unsafe stack
174   /// top to \p DynamicTop if non-null.
175   void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
176                                        AllocaInst *DynamicTop,
177                                        ArrayRef<AllocaInst *> DynamicAllocas);
178 
179   bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
180 
181   bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
182                           const Value *AllocaPtr, uint64_t AllocaSize);
183   bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
184                     uint64_t AllocaSize);
185 
186   bool ShouldInlinePointerAddress(CallInst &CI);
187   void TryInlinePointerAddress();
188 
189 public:
190   SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
191             DomTreeUpdater *DTU, ScalarEvolution &SE)
192       : F(F), TL(TL), DL(DL), DTU(DTU), SE(SE),
193         StackPtrTy(Type::getInt8PtrTy(F.getContext())),
194         IntPtrTy(DL.getIntPtrType(F.getContext())),
195         Int32Ty(Type::getInt32Ty(F.getContext())),
196         Int8Ty(Type::getInt8Ty(F.getContext())) {}
197 
198   // Run the transformation on the associated function.
199   // Returns whether the function was changed.
200   bool run();
201 };
202 
203 constexpr uint64_t SafeStack::StackAlignment;
204 
205 uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
206   uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
207   if (AI->isArrayAllocation()) {
208     auto C = dyn_cast<ConstantInt>(AI->getArraySize());
209     if (!C)
210       return 0;
211     Size *= C->getZExtValue();
212   }
213   return Size;
214 }
215 
216 bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
217                              const Value *AllocaPtr, uint64_t AllocaSize) {
218   const SCEV *AddrExpr = SE.getSCEV(Addr);
219   const auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(AddrExpr));
220   if (!Base || Base->getValue() != AllocaPtr) {
221     LLVM_DEBUG(
222         dbgs() << "[SafeStack] "
223                << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
224                << *AllocaPtr << "\n"
225                << "SCEV " << *AddrExpr << " not directly based on alloca\n");
226     return false;
227   }
228 
229   const SCEV *Expr = SE.removePointerBase(AddrExpr);
230   uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
231   ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
232   ConstantRange SizeRange =
233       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
234   ConstantRange AccessRange = AccessStartRange.add(SizeRange);
235   ConstantRange AllocaRange =
236       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
237   bool Safe = AllocaRange.contains(AccessRange);
238 
239   LLVM_DEBUG(
240       dbgs() << "[SafeStack] "
241              << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
242              << *AllocaPtr << "\n"
243              << "            Access " << *Addr << "\n"
244              << "            SCEV " << *Expr
245              << " U: " << SE.getUnsignedRange(Expr)
246              << ", S: " << SE.getSignedRange(Expr) << "\n"
247              << "            Range " << AccessRange << "\n"
248              << "            AllocaRange " << AllocaRange << "\n"
249              << "            " << (Safe ? "safe" : "unsafe") << "\n");
250 
251   return Safe;
252 }
253 
254 bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
255                                    const Value *AllocaPtr,
256                                    uint64_t AllocaSize) {
257   if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
258     if (MTI->getRawSource() != U && MTI->getRawDest() != U)
259       return true;
260   } else {
261     if (MI->getRawDest() != U)
262       return true;
263   }
264 
265   const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
266   // Non-constant size => unsafe. FIXME: try SCEV getRange.
267   if (!Len) return false;
268   return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
269 }
270 
271 /// Check whether a given allocation must be put on the safe
272 /// stack or not. The function analyzes all uses of AI and checks whether it is
273 /// only accessed in a memory safe way (as decided statically).
274 bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
275   // Go through all uses of this alloca and check whether all accesses to the
276   // allocated object are statically known to be memory safe and, hence, the
277   // object can be placed on the safe stack.
278   SmallPtrSet<const Value *, 16> Visited;
279   SmallVector<const Value *, 8> WorkList;
280   WorkList.push_back(AllocaPtr);
281 
282   // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
283   while (!WorkList.empty()) {
284     const Value *V = WorkList.pop_back_val();
285     for (const Use &UI : V->uses()) {
286       auto I = cast<const Instruction>(UI.getUser());
287       assert(V == UI.get());
288 
289       switch (I->getOpcode()) {
290       case Instruction::Load:
291         if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
292                           AllocaSize))
293           return false;
294         break;
295 
296       case Instruction::VAArg:
297         // "va-arg" from a pointer is safe.
298         break;
299       case Instruction::Store:
300         if (V == I->getOperand(0)) {
301           // Stored the pointer - conservatively assume it may be unsafe.
302           LLVM_DEBUG(dbgs()
303                      << "[SafeStack] Unsafe alloca: " << *AllocaPtr
304                      << "\n            store of address: " << *I << "\n");
305           return false;
306         }
307 
308         if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
309                           AllocaPtr, AllocaSize))
310           return false;
311         break;
312 
313       case Instruction::Ret:
314         // Information leak.
315         return false;
316 
317       case Instruction::Call:
318       case Instruction::Invoke: {
319         const CallBase &CS = *cast<CallBase>(I);
320 
321         if (I->isLifetimeStartOrEnd())
322           continue;
323 
324         if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
325           if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
326             LLVM_DEBUG(dbgs()
327                        << "[SafeStack] Unsafe alloca: " << *AllocaPtr
328                        << "\n            unsafe memintrinsic: " << *I << "\n");
329             return false;
330           }
331           continue;
332         }
333 
334         // LLVM 'nocapture' attribute is only set for arguments whose address
335         // is not stored, passed around, or used in any other non-trivial way.
336         // We assume that passing a pointer to an object as a 'nocapture
337         // readnone' argument is safe.
338         // FIXME: a more precise solution would require an interprocedural
339         // analysis here, which would look at all uses of an argument inside
340         // the function being called.
341         auto B = CS.arg_begin(), E = CS.arg_end();
342         for (auto A = B; A != E; ++A)
343           if (A->get() == V)
344             if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
345                                                CS.doesNotAccessMemory()))) {
346               LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
347                                 << "\n            unsafe call: " << *I << "\n");
348               return false;
349             }
350         continue;
351       }
352 
353       default:
354         if (Visited.insert(I).second)
355           WorkList.push_back(cast<const Instruction>(I));
356       }
357     }
358   }
359 
360   // All uses of the alloca are safe, we can place it on the safe stack.
361   return true;
362 }
363 
364 Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
365   Value *StackGuardVar = TL.getIRStackGuard(IRB);
366   Module *M = F.getParent();
367 
368   if (!StackGuardVar) {
369     TL.insertSSPDeclarations(*M);
370     return IRB.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
371   }
372 
373   return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
374 }
375 
376 void SafeStack::findInsts(Function &F,
377                           SmallVectorImpl<AllocaInst *> &StaticAllocas,
378                           SmallVectorImpl<AllocaInst *> &DynamicAllocas,
379                           SmallVectorImpl<Argument *> &ByValArguments,
380                           SmallVectorImpl<Instruction *> &Returns,
381                           SmallVectorImpl<Instruction *> &StackRestorePoints) {
382   for (Instruction &I : instructions(&F)) {
383     if (auto AI = dyn_cast<AllocaInst>(&I)) {
384       ++NumAllocas;
385 
386       uint64_t Size = getStaticAllocaAllocationSize(AI);
387       if (IsSafeStackAlloca(AI, Size))
388         continue;
389 
390       if (AI->isStaticAlloca()) {
391         ++NumUnsafeStaticAllocas;
392         StaticAllocas.push_back(AI);
393       } else {
394         ++NumUnsafeDynamicAllocas;
395         DynamicAllocas.push_back(AI);
396       }
397     } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
398       if (CallInst *CI = I.getParent()->getTerminatingMustTailCall())
399         Returns.push_back(CI);
400       else
401         Returns.push_back(RI);
402     } else if (auto CI = dyn_cast<CallInst>(&I)) {
403       // setjmps require stack restore.
404       if (CI->getCalledFunction() && CI->canReturnTwice())
405         StackRestorePoints.push_back(CI);
406     } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
407       // Exception landing pads require stack restore.
408       StackRestorePoints.push_back(LP);
409     } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
410       if (II->getIntrinsicID() == Intrinsic::gcroot)
411         report_fatal_error(
412             "gcroot intrinsic not compatible with safestack attribute");
413     }
414   }
415   for (Argument &Arg : F.args()) {
416     if (!Arg.hasByValAttr())
417       continue;
418     uint64_t Size = DL.getTypeStoreSize(Arg.getParamByValType());
419     if (IsSafeStackAlloca(&Arg, Size))
420       continue;
421 
422     ++NumUnsafeByValArguments;
423     ByValArguments.push_back(&Arg);
424   }
425 }
426 
427 AllocaInst *
428 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
429                                     ArrayRef<Instruction *> StackRestorePoints,
430                                     Value *StaticTop, bool NeedDynamicTop) {
431   assert(StaticTop && "The stack top isn't set.");
432 
433   if (StackRestorePoints.empty())
434     return nullptr;
435 
436   // We need the current value of the shadow stack pointer to restore
437   // after longjmp or exception catching.
438 
439   // FIXME: On some platforms this could be handled by the longjmp/exception
440   // runtime itself.
441 
442   AllocaInst *DynamicTop = nullptr;
443   if (NeedDynamicTop) {
444     // If we also have dynamic alloca's, the stack pointer value changes
445     // throughout the function. For now we store it in an alloca.
446     DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
447                                   "unsafe_stack_dynamic_ptr");
448     IRB.CreateStore(StaticTop, DynamicTop);
449   }
450 
451   // Restore current stack pointer after longjmp/exception catch.
452   for (Instruction *I : StackRestorePoints) {
453     ++NumUnsafeStackRestorePoints;
454 
455     IRB.SetInsertPoint(I->getNextNode());
456     Value *CurrentTop =
457         DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
458     IRB.CreateStore(CurrentTop, UnsafeStackPtr);
459   }
460 
461   return DynamicTop;
462 }
463 
464 void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
465                                 AllocaInst *StackGuardSlot, Value *StackGuard) {
466   Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
467   Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
468 
469   auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
470   auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
471   MDNode *Weights = MDBuilder(F.getContext())
472                         .createBranchWeights(SuccessProb.getNumerator(),
473                                              FailureProb.getNumerator());
474   Instruction *CheckTerm =
475       SplitBlockAndInsertIfThen(Cmp, &RI, /* Unreachable */ true, Weights, DTU);
476   IRBuilder<> IRBFail(CheckTerm);
477   // FIXME: respect -fsanitize-trap / -ftrap-function here?
478   FunctionCallee StackChkFail =
479       F.getParent()->getOrInsertFunction("__stack_chk_fail", IRB.getVoidTy());
480   IRBFail.CreateCall(StackChkFail, {});
481 }
482 
483 /// We explicitly compute and set the unsafe stack layout for all unsafe
484 /// static alloca instructions. We save the unsafe "base pointer" in the
485 /// prologue into a local variable and restore it in the epilogue.
486 Value *SafeStack::moveStaticAllocasToUnsafeStack(
487     IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
488     ArrayRef<Argument *> ByValArguments, Instruction *BasePointer,
489     AllocaInst *StackGuardSlot) {
490   if (StaticAllocas.empty() && ByValArguments.empty())
491     return BasePointer;
492 
493   DIBuilder DIB(*F.getParent());
494 
495   StackLifetime SSC(F, StaticAllocas, StackLifetime::LivenessType::May);
496   static const StackLifetime::LiveRange NoColoringRange(1, true);
497   if (ClColoring)
498     SSC.run();
499 
500   for (auto *I : SSC.getMarkers()) {
501     auto *Op = dyn_cast<Instruction>(I->getOperand(1));
502     const_cast<IntrinsicInst *>(I)->eraseFromParent();
503     // Remove the operand bitcast, too, if it has no more uses left.
504     if (Op && Op->use_empty())
505       Op->eraseFromParent();
506   }
507 
508   // Unsafe stack always grows down.
509   StackLayout SSL(StackAlignment);
510   if (StackGuardSlot) {
511     Type *Ty = StackGuardSlot->getAllocatedType();
512     Align Align = std::max(DL.getPrefTypeAlign(Ty), StackGuardSlot->getAlign());
513     SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
514                   Align, SSC.getFullLiveRange());
515   }
516 
517   for (Argument *Arg : ByValArguments) {
518     Type *Ty = Arg->getParamByValType();
519     uint64_t Size = DL.getTypeStoreSize(Ty);
520     if (Size == 0)
521       Size = 1; // Don't create zero-sized stack objects.
522 
523     // Ensure the object is properly aligned.
524     Align Align = DL.getPrefTypeAlign(Ty);
525     if (auto A = Arg->getParamAlign())
526       Align = std::max(Align, *A);
527     SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
528   }
529 
530   for (AllocaInst *AI : StaticAllocas) {
531     Type *Ty = AI->getAllocatedType();
532     uint64_t Size = getStaticAllocaAllocationSize(AI);
533     if (Size == 0)
534       Size = 1; // Don't create zero-sized stack objects.
535 
536     // Ensure the object is properly aligned.
537     Align Align = std::max(DL.getPrefTypeAlign(Ty), AI->getAlign());
538 
539     SSL.addObject(AI, Size, Align,
540                   ClColoring ? SSC.getLiveRange(AI) : NoColoringRange);
541   }
542 
543   SSL.computeLayout();
544   Align FrameAlignment = SSL.getFrameAlignment();
545 
546   // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
547   // (AlignmentSkew).
548   if (FrameAlignment > StackAlignment) {
549     // Re-align the base pointer according to the max requested alignment.
550     IRB.SetInsertPoint(BasePointer->getNextNode());
551     BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
552         IRB.CreateAnd(
553             IRB.CreatePtrToInt(BasePointer, IntPtrTy),
554             ConstantInt::get(IntPtrTy, ~(FrameAlignment.value() - 1))),
555         StackPtrTy));
556   }
557 
558   IRB.SetInsertPoint(BasePointer->getNextNode());
559 
560   if (StackGuardSlot) {
561     unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
562     Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
563                                ConstantInt::get(Int32Ty, -Offset));
564     Value *NewAI =
565         IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
566 
567     // Replace alloc with the new location.
568     StackGuardSlot->replaceAllUsesWith(NewAI);
569     StackGuardSlot->eraseFromParent();
570   }
571 
572   for (Argument *Arg : ByValArguments) {
573     unsigned Offset = SSL.getObjectOffset(Arg);
574     MaybeAlign Align(SSL.getObjectAlignment(Arg));
575     Type *Ty = Arg->getParamByValType();
576 
577     uint64_t Size = DL.getTypeStoreSize(Ty);
578     if (Size == 0)
579       Size = 1; // Don't create zero-sized stack objects.
580 
581     Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
582                                ConstantInt::get(Int32Ty, -Offset));
583     Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
584                                      Arg->getName() + ".unsafe-byval");
585 
586     // Replace alloc with the new location.
587     replaceDbgDeclare(Arg, BasePointer, DIB, DIExpression::ApplyOffset,
588                       -Offset);
589     Arg->replaceAllUsesWith(NewArg);
590     IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
591     IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlign(), Size);
592   }
593 
594   // Allocate space for every unsafe static AllocaInst on the unsafe stack.
595   for (AllocaInst *AI : StaticAllocas) {
596     IRB.SetInsertPoint(AI);
597     unsigned Offset = SSL.getObjectOffset(AI);
598 
599     replaceDbgDeclare(AI, BasePointer, DIB, DIExpression::ApplyOffset, -Offset);
600     replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
601 
602     // Replace uses of the alloca with the new location.
603     // Insert address calculation close to each use to work around PR27844.
604     std::string Name = std::string(AI->getName()) + ".unsafe";
605     while (!AI->use_empty()) {
606       Use &U = *AI->use_begin();
607       Instruction *User = cast<Instruction>(U.getUser());
608 
609       Instruction *InsertBefore;
610       if (auto *PHI = dyn_cast<PHINode>(User))
611         InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
612       else
613         InsertBefore = User;
614 
615       IRBuilder<> IRBUser(InsertBefore);
616       Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
617                                      ConstantInt::get(Int32Ty, -Offset));
618       Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
619 
620       if (auto *PHI = dyn_cast<PHINode>(User))
621         // PHI nodes may have multiple incoming edges from the same BB (why??),
622         // all must be updated at once with the same incoming value.
623         PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
624       else
625         U.set(Replacement);
626     }
627 
628     AI->eraseFromParent();
629   }
630 
631   // Re-align BasePointer so that our callees would see it aligned as
632   // expected.
633   // FIXME: no need to update BasePointer in leaf functions.
634   unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
635 
636   // Update shadow stack pointer in the function epilogue.
637   IRB.SetInsertPoint(BasePointer->getNextNode());
638 
639   Value *StaticTop =
640       IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
641                     "unsafe_stack_static_top");
642   IRB.CreateStore(StaticTop, UnsafeStackPtr);
643   return StaticTop;
644 }
645 
646 void SafeStack::moveDynamicAllocasToUnsafeStack(
647     Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
648     ArrayRef<AllocaInst *> DynamicAllocas) {
649   DIBuilder DIB(*F.getParent());
650 
651   for (AllocaInst *AI : DynamicAllocas) {
652     IRBuilder<> IRB(AI);
653 
654     // Compute the new SP value (after AI).
655     Value *ArraySize = AI->getArraySize();
656     if (ArraySize->getType() != IntPtrTy)
657       ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
658 
659     Type *Ty = AI->getAllocatedType();
660     uint64_t TySize = DL.getTypeAllocSize(Ty);
661     Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
662 
663     Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
664                                    IntPtrTy);
665     SP = IRB.CreateSub(SP, Size);
666 
667     // Align the SP value to satisfy the AllocaInst, type and stack alignments.
668     uint64_t Align =
669         std::max(std::max(DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
670                  StackAlignment);
671 
672     assert(isPowerOf2_32(Align));
673     Value *NewTop = IRB.CreateIntToPtr(
674         IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
675         StackPtrTy);
676 
677     // Save the stack pointer.
678     IRB.CreateStore(NewTop, UnsafeStackPtr);
679     if (DynamicTop)
680       IRB.CreateStore(NewTop, DynamicTop);
681 
682     Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
683     if (AI->hasName() && isa<Instruction>(NewAI))
684       NewAI->takeName(AI);
685 
686     replaceDbgDeclare(AI, NewAI, DIB, DIExpression::ApplyOffset, 0);
687     AI->replaceAllUsesWith(NewAI);
688     AI->eraseFromParent();
689   }
690 
691   if (!DynamicAllocas.empty()) {
692     // Now go through the instructions again, replacing stacksave/stackrestore.
693     for (Instruction &I : llvm::make_early_inc_range(instructions(&F))) {
694       auto *II = dyn_cast<IntrinsicInst>(&I);
695       if (!II)
696         continue;
697 
698       if (II->getIntrinsicID() == Intrinsic::stacksave) {
699         IRBuilder<> IRB(II);
700         Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
701         LI->takeName(II);
702         II->replaceAllUsesWith(LI);
703         II->eraseFromParent();
704       } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
705         IRBuilder<> IRB(II);
706         Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
707         SI->takeName(II);
708         assert(II->use_empty());
709         II->eraseFromParent();
710       }
711     }
712   }
713 }
714 
715 bool SafeStack::ShouldInlinePointerAddress(CallInst &CI) {
716   Function *Callee = CI.getCalledFunction();
717   if (CI.hasFnAttr(Attribute::AlwaysInline) &&
718       isInlineViable(*Callee).isSuccess())
719     return true;
720   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
721       CI.isNoInline())
722     return false;
723   return true;
724 }
725 
726 void SafeStack::TryInlinePointerAddress() {
727   auto *CI = dyn_cast<CallInst>(UnsafeStackPtr);
728   if (!CI)
729     return;
730 
731   if(F.hasOptNone())
732     return;
733 
734   Function *Callee = CI->getCalledFunction();
735   if (!Callee || Callee->isDeclaration())
736     return;
737 
738   if (!ShouldInlinePointerAddress(*CI))
739     return;
740 
741   InlineFunctionInfo IFI;
742   InlineFunction(*CI, IFI);
743 }
744 
745 bool SafeStack::run() {
746   assert(F.hasFnAttribute(Attribute::SafeStack) &&
747          "Can't run SafeStack on a function without the attribute");
748   assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
749 
750   ++NumFunctions;
751 
752   SmallVector<AllocaInst *, 16> StaticAllocas;
753   SmallVector<AllocaInst *, 4> DynamicAllocas;
754   SmallVector<Argument *, 4> ByValArguments;
755   SmallVector<Instruction *, 4> Returns;
756 
757   // Collect all points where stack gets unwound and needs to be restored
758   // This is only necessary because the runtime (setjmp and unwind code) is
759   // not aware of the unsafe stack and won't unwind/restore it properly.
760   // To work around this problem without changing the runtime, we insert
761   // instrumentation to restore the unsafe stack pointer when necessary.
762   SmallVector<Instruction *, 4> StackRestorePoints;
763 
764   // Find all static and dynamic alloca instructions that must be moved to the
765   // unsafe stack, all return instructions and stack restore points.
766   findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
767             StackRestorePoints);
768 
769   if (StaticAllocas.empty() && DynamicAllocas.empty() &&
770       ByValArguments.empty() && StackRestorePoints.empty())
771     return false; // Nothing to do in this function.
772 
773   if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
774       !ByValArguments.empty())
775     ++NumUnsafeStackFunctions; // This function has the unsafe stack.
776 
777   if (!StackRestorePoints.empty())
778     ++NumUnsafeStackRestorePointsFunctions;
779 
780   IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
781   // Calls must always have a debug location, or else inlining breaks. So
782   // we explicitly set a artificial debug location here.
783   if (DISubprogram *SP = F.getSubprogram())
784     IRB.SetCurrentDebugLocation(
785         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP));
786   if (SafeStackUsePointerAddress) {
787     FunctionCallee Fn = F.getParent()->getOrInsertFunction(
788         "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
789     UnsafeStackPtr = IRB.CreateCall(Fn);
790   } else {
791     UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
792   }
793 
794   // Load the current stack pointer (we'll also use it as a base pointer).
795   // FIXME: use a dedicated register for it ?
796   Instruction *BasePointer =
797       IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
798   assert(BasePointer->getType() == StackPtrTy);
799 
800   AllocaInst *StackGuardSlot = nullptr;
801   // FIXME: implement weaker forms of stack protector.
802   if (F.hasFnAttribute(Attribute::StackProtect) ||
803       F.hasFnAttribute(Attribute::StackProtectStrong) ||
804       F.hasFnAttribute(Attribute::StackProtectReq)) {
805     Value *StackGuard = getStackGuard(IRB, F);
806     StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
807     IRB.CreateStore(StackGuard, StackGuardSlot);
808 
809     for (Instruction *RI : Returns) {
810       IRBuilder<> IRBRet(RI);
811       checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
812     }
813   }
814 
815   // The top of the unsafe stack after all unsafe static allocas are
816   // allocated.
817   Value *StaticTop = moveStaticAllocasToUnsafeStack(
818       IRB, F, StaticAllocas, ByValArguments, BasePointer, StackGuardSlot);
819 
820   // Safe stack object that stores the current unsafe stack top. It is updated
821   // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
822   // This is only needed if we need to restore stack pointer after longjmp
823   // or exceptions, and we have dynamic allocations.
824   // FIXME: a better alternative might be to store the unsafe stack pointer
825   // before setjmp / invoke instructions.
826   AllocaInst *DynamicTop = createStackRestorePoints(
827       IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
828 
829   // Handle dynamic allocas.
830   moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
831                                   DynamicAllocas);
832 
833   // Restore the unsafe stack pointer before each return.
834   for (Instruction *RI : Returns) {
835     IRB.SetInsertPoint(RI);
836     IRB.CreateStore(BasePointer, UnsafeStackPtr);
837   }
838 
839   TryInlinePointerAddress();
840 
841   LLVM_DEBUG(dbgs() << "[SafeStack]     safestack applied\n");
842   return true;
843 }
844 
845 class SafeStackLegacyPass : public FunctionPass {
846   const TargetMachine *TM = nullptr;
847 
848 public:
849   static char ID; // Pass identification, replacement for typeid..
850 
851   SafeStackLegacyPass() : FunctionPass(ID) {
852     initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
853   }
854 
855   void getAnalysisUsage(AnalysisUsage &AU) const override {
856     AU.addRequired<TargetPassConfig>();
857     AU.addRequired<TargetLibraryInfoWrapperPass>();
858     AU.addRequired<AssumptionCacheTracker>();
859     AU.addPreserved<DominatorTreeWrapperPass>();
860   }
861 
862   bool runOnFunction(Function &F) override {
863     LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
864 
865     if (!F.hasFnAttribute(Attribute::SafeStack)) {
866       LLVM_DEBUG(dbgs() << "[SafeStack]     safestack is not requested"
867                            " for this function\n");
868       return false;
869     }
870 
871     if (F.isDeclaration()) {
872       LLVM_DEBUG(dbgs() << "[SafeStack]     function definition"
873                            " is not available\n");
874       return false;
875     }
876 
877     TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
878     auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
879     if (!TL)
880       report_fatal_error("TargetLowering instance is required");
881 
882     auto *DL = &F.getParent()->getDataLayout();
883     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
884     auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
885 
886     // Compute DT and LI only for functions that have the attribute.
887     // This is only useful because the legacy pass manager doesn't let us
888     // compute analyzes lazily.
889 
890     DominatorTree *DT;
891     bool ShouldPreserveDominatorTree;
892     Optional<DominatorTree> LazilyComputedDomTree;
893 
894     // Do we already have a DominatorTree avaliable from the previous pass?
895     // Note that we should *NOT* require it, to avoid the case where we end up
896     // not needing it, but the legacy PM would have computed it for us anyways.
897     if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
898       DT = &DTWP->getDomTree();
899       ShouldPreserveDominatorTree = true;
900     } else {
901       // Otherwise, we need to compute it.
902       LazilyComputedDomTree.emplace(F);
903       DT = LazilyComputedDomTree.getPointer();
904       ShouldPreserveDominatorTree = false;
905     }
906 
907     // Likewise, lazily compute loop info.
908     LoopInfo LI(*DT);
909 
910     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
911 
912     ScalarEvolution SE(F, TLI, ACT, *DT, LI);
913 
914     return SafeStack(F, *TL, *DL, ShouldPreserveDominatorTree ? &DTU : nullptr,
915                      SE)
916         .run();
917   }
918 };
919 
920 } // end anonymous namespace
921 
922 char SafeStackLegacyPass::ID = 0;
923 
924 INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
925                       "Safe Stack instrumentation pass", false, false)
926 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
927 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
928 INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
929                     "Safe Stack instrumentation pass", false, false)
930 
931 FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }
932