4441663fc6de522bb30d53da446864ea8c03dea9
[oota-llvm.git] / lib / Transforms / Instrumentation / SafeStack.cpp
1 //===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass splits the stack into the safe stack (kept as-is for LLVM backend)
11 // and the unsafe stack (explicitly allocated and managed through the runtime
12 // support library).
13 //
14 // http://clang.llvm.org/docs/SafeStack.html
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/InstIterator.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_os_ostream.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
45
46 using namespace llvm;
47
48 #define DEBUG_TYPE "safestack"
49
50 namespace llvm {
51
52 STATISTIC(NumFunctions, "Total number of functions");
53 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
54 STATISTIC(NumUnsafeStackRestorePointsFunctions,
55           "Number of functions that use setjmp or exceptions");
56
57 STATISTIC(NumAllocas, "Total number of allocas");
58 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
59 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
60 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
61 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
62
63 } // namespace llvm
64
65 namespace {
66
67 /// Rewrite an SCEV expression for a memory access address to an expression that
68 /// represents offset from the given alloca.
69 ///
70 /// The implementation simply replaces all mentions of the alloca with zero.
71 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
72   const Value *AllocaPtr;
73
74 public:
75   AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
76       : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
77
78   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
79     if (Expr->getValue() == AllocaPtr)
80       return SE.getZero(Expr->getType());
81     return Expr;
82   }
83 };
84
85 /// The SafeStack pass splits the stack of each function into the safe
86 /// stack, which is only accessed through memory safe dereferences (as
87 /// determined statically), and the unsafe stack, which contains all
88 /// local variables that are accessed in ways that we can't prove to
89 /// be safe.
90 class SafeStack : public FunctionPass {
91   const TargetMachine *TM;
92   const TargetLoweringBase *TL;
93   const DataLayout *DL;
94   ScalarEvolution *SE;
95
96   Type *StackPtrTy;
97   Type *IntPtrTy;
98   Type *Int32Ty;
99   Type *Int8Ty;
100
101   Value *UnsafeStackPtr = nullptr;
102
103   /// Unsafe stack alignment. Each stack frame must ensure that the stack is
104   /// aligned to this value. We need to re-align the unsafe stack if the
105   /// alignment of any object on the stack exceeds this value.
106   ///
107   /// 16 seems like a reasonable upper bound on the alignment of objects that we
108   /// might expect to appear on the stack on most common targets.
109   enum { StackAlignment = 16 };
110
111   /// \brief Build a value representing a pointer to the unsafe stack pointer.
112   Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
113
114   /// \brief Find all static allocas, dynamic allocas, return instructions and
115   /// stack restore points (exception unwind blocks and setjmp calls) in the
116   /// given function and append them to the respective vectors.
117   void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
118                  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
119                  SmallVectorImpl<Argument *> &ByValArguments,
120                  SmallVectorImpl<ReturnInst *> &Returns,
121                  SmallVectorImpl<Instruction *> &StackRestorePoints);
122
123   /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
124   /// size can not be statically determined.
125   uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
126
127   /// \brief Allocate space for all static allocas in \p StaticAllocas,
128   /// replace allocas with pointers into the unsafe stack and generate code to
129   /// restore the stack pointer before all return instructions in \p Returns.
130   ///
131   /// \returns A pointer to the top of the unsafe stack after all unsafe static
132   /// allocas are allocated.
133   Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
134                                         ArrayRef<AllocaInst *> StaticAllocas,
135                                         ArrayRef<Argument *> ByValArguments,
136                                         ArrayRef<ReturnInst *> Returns);
137
138   /// \brief Generate code to restore the stack after all stack restore points
139   /// in \p StackRestorePoints.
140   ///
141   /// \returns A local variable in which to maintain the dynamic top of the
142   /// unsafe stack if needed.
143   AllocaInst *
144   createStackRestorePoints(IRBuilder<> &IRB, Function &F,
145                            ArrayRef<Instruction *> StackRestorePoints,
146                            Value *StaticTop, bool NeedDynamicTop);
147
148   /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
149   /// space dynamically on the unsafe stack and store the dynamic unsafe stack
150   /// top to \p DynamicTop if non-null.
151   void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
152                                        AllocaInst *DynamicTop,
153                                        ArrayRef<AllocaInst *> DynamicAllocas);
154
155   bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
156
157   bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
158                           const Value *AllocaPtr, uint64_t AllocaSize);
159   bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
160                     uint64_t AllocaSize);
161
162 public:
163   static char ID; // Pass identification, replacement for typeid.
164   SafeStack(const TargetMachine *TM)
165       : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) {
166     initializeSafeStackPass(*PassRegistry::getPassRegistry());
167   }
168   SafeStack() : SafeStack(nullptr) {}
169
170   void getAnalysisUsage(AnalysisUsage &AU) const override {
171     AU.addRequired<ScalarEvolutionWrapperPass>();
172   }
173
174   bool doInitialization(Module &M) override {
175     DL = &M.getDataLayout();
176
177     StackPtrTy = Type::getInt8PtrTy(M.getContext());
178     IntPtrTy = DL->getIntPtrType(M.getContext());
179     Int32Ty = Type::getInt32Ty(M.getContext());
180     Int8Ty = Type::getInt8Ty(M.getContext());
181
182     return false;
183   }
184
185   bool runOnFunction(Function &F) override;
186 }; // class SafeStack
187
188 uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
189   uint64_t Size = DL->getTypeAllocSize(AI->getAllocatedType());
190   if (AI->isArrayAllocation()) {
191     auto C = dyn_cast<ConstantInt>(AI->getArraySize());
192     if (!C)
193       return 0;
194     Size *= C->getZExtValue();
195   }
196   return Size;
197 }
198
199 bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
200                              const Value *AllocaPtr, uint64_t AllocaSize) {
201   AllocaOffsetRewriter Rewriter(*SE, AllocaPtr);
202   const SCEV *Expr = Rewriter.visit(SE->getSCEV(Addr));
203
204   uint64_t BitWidth = SE->getTypeSizeInBits(Expr->getType());
205   ConstantRange AccessStartRange = SE->getUnsignedRange(Expr);
206   ConstantRange SizeRange =
207       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
208   ConstantRange AccessRange = AccessStartRange.add(SizeRange);
209   ConstantRange AllocaRange =
210       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
211   bool Safe = AllocaRange.contains(AccessRange);
212
213   DEBUG(dbgs() << "[SafeStack] "
214                << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
215                << *AllocaPtr << "\n"
216                << "            Access " << *Addr << "\n"
217                << "            SCEV " << *Expr
218                << " U: " << SE->getUnsignedRange(Expr)
219                << ", S: " << SE->getSignedRange(Expr) << "\n"
220                << "            Range " << AccessRange << "\n"
221                << "            AllocaRange " << AllocaRange << "\n"
222                << "            " << (Safe ? "safe" : "unsafe") << "\n");
223
224   return Safe;
225 }
226
227 bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
228                                    const Value *AllocaPtr,
229                                    uint64_t AllocaSize) {
230   // All MemIntrinsics have destination address in Arg0 and size in Arg2.
231   if (MI->getRawDest() != U) return true;
232   const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
233   // Non-constant size => unsafe. FIXME: try SCEV getRange.
234   if (!Len) return false;
235   return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
236 }
237
238 /// Check whether a given allocation must be put on the safe
239 /// stack or not. The function analyzes all uses of AI and checks whether it is
240 /// only accessed in a memory safe way (as decided statically).
241 bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
242   // Go through all uses of this alloca and check whether all accesses to the
243   // allocated object are statically known to be memory safe and, hence, the
244   // object can be placed on the safe stack.
245   SmallPtrSet<const Value *, 16> Visited;
246   SmallVector<const Value *, 8> WorkList;
247   WorkList.push_back(AllocaPtr);
248
249   // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
250   while (!WorkList.empty()) {
251     const Value *V = WorkList.pop_back_val();
252     for (const Use &UI : V->uses()) {
253       auto I = cast<const Instruction>(UI.getUser());
254       assert(V == UI.get());
255
256       switch (I->getOpcode()) {
257       case Instruction::Load: {
258         if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr,
259                           AllocaSize))
260           return false;
261         break;
262       }
263       case Instruction::VAArg:
264         // "va-arg" from a pointer is safe.
265         break;
266       case Instruction::Store: {
267         if (V == I->getOperand(0)) {
268           // Stored the pointer - conservatively assume it may be unsafe.
269           DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
270                        << "\n            store of address: " << *I << "\n");
271           return false;
272         }
273
274         if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()),
275                           AllocaPtr, AllocaSize))
276           return false;
277         break;
278       }
279       case Instruction::Ret: {
280         // Information leak.
281         return false;
282       }
283
284       case Instruction::Call:
285       case Instruction::Invoke: {
286         ImmutableCallSite CS(I);
287
288         if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
289           if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
290               II->getIntrinsicID() == Intrinsic::lifetime_end)
291             continue;
292         }
293
294         if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
295           if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
296             DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
297                          << "\n            unsafe memintrinsic: " << *I
298                          << "\n");
299             return false;
300           }
301           continue;
302         }
303
304         // LLVM 'nocapture' attribute is only set for arguments whose address
305         // is not stored, passed around, or used in any other non-trivial way.
306         // We assume that passing a pointer to an object as a 'nocapture
307         // readnone' argument is safe.
308         // FIXME: a more precise solution would require an interprocedural
309         // analysis here, which would look at all uses of an argument inside
310         // the function being called.
311         ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
312         for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
313           if (A->get() == V)
314             if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
315                                                CS.doesNotAccessMemory()))) {
316               DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
317                            << "\n            unsafe call: " << *I << "\n");
318               return false;
319             }
320         continue;
321       }
322
323       default:
324         if (Visited.insert(I).second)
325           WorkList.push_back(cast<const Instruction>(I));
326       }
327     }
328   }
329
330   // All uses of the alloca are safe, we can place it on the safe stack.
331   return true;
332 }
333
334 Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
335   // Check if there is a target-specific location for the unsafe stack pointer.
336   if (TL)
337     if (Value *V = TL->getSafeStackPointerLocation(IRB))
338       return V;
339
340   // Otherwise, assume the target links with compiler-rt, which provides a
341   // thread-local variable with a magic name.
342   Module &M = *F.getParent();
343   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
344   auto UnsafeStackPtr =
345       dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
346
347   if (!UnsafeStackPtr) {
348     // The global variable is not defined yet, define it ourselves.
349     // We use the initial-exec TLS model because we do not support the
350     // variable living anywhere other than in the main executable.
351     UnsafeStackPtr = new GlobalVariable(
352         M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
353         UnsafeStackPtrVar, nullptr, GlobalValue::InitialExecTLSModel);
354   } else {
355     // The variable exists, check its type and attributes.
356     if (UnsafeStackPtr->getValueType() != StackPtrTy)
357       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
358     if (!UnsafeStackPtr->isThreadLocal())
359       report_fatal_error(Twine(UnsafeStackPtrVar) + " must be thread-local");
360   }
361   return UnsafeStackPtr;
362 }
363
364 void SafeStack::findInsts(Function &F,
365                           SmallVectorImpl<AllocaInst *> &StaticAllocas,
366                           SmallVectorImpl<AllocaInst *> &DynamicAllocas,
367                           SmallVectorImpl<Argument *> &ByValArguments,
368                           SmallVectorImpl<ReturnInst *> &Returns,
369                           SmallVectorImpl<Instruction *> &StackRestorePoints) {
370   for (Instruction &I : instructions(&F)) {
371     if (auto AI = dyn_cast<AllocaInst>(&I)) {
372       ++NumAllocas;
373
374       uint64_t Size = getStaticAllocaAllocationSize(AI);
375       if (IsSafeStackAlloca(AI, Size))
376         continue;
377
378       if (AI->isStaticAlloca()) {
379         ++NumUnsafeStaticAllocas;
380         StaticAllocas.push_back(AI);
381       } else {
382         ++NumUnsafeDynamicAllocas;
383         DynamicAllocas.push_back(AI);
384       }
385     } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
386       Returns.push_back(RI);
387     } else if (auto CI = dyn_cast<CallInst>(&I)) {
388       // setjmps require stack restore.
389       if (CI->getCalledFunction() && CI->canReturnTwice())
390         StackRestorePoints.push_back(CI);
391     } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
392       // Exception landing pads require stack restore.
393       StackRestorePoints.push_back(LP);
394     } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
395       if (II->getIntrinsicID() == Intrinsic::gcroot)
396         llvm::report_fatal_error(
397             "gcroot intrinsic not compatible with safestack attribute");
398     }
399   }
400   for (Argument &Arg : F.args()) {
401     if (!Arg.hasByValAttr())
402       continue;
403     uint64_t Size =
404         DL->getTypeStoreSize(Arg.getType()->getPointerElementType());
405     if (IsSafeStackAlloca(&Arg, Size))
406       continue;
407
408     ++NumUnsafeByValArguments;
409     ByValArguments.push_back(&Arg);
410   }
411 }
412
413 AllocaInst *
414 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
415                                     ArrayRef<Instruction *> StackRestorePoints,
416                                     Value *StaticTop, bool NeedDynamicTop) {
417   if (StackRestorePoints.empty())
418     return nullptr;
419
420   // We need the current value of the shadow stack pointer to restore
421   // after longjmp or exception catching.
422
423   // FIXME: On some platforms this could be handled by the longjmp/exception
424   // runtime itself.
425
426   AllocaInst *DynamicTop = nullptr;
427   if (NeedDynamicTop)
428     // If we also have dynamic alloca's, the stack pointer value changes
429     // throughout the function. For now we store it in an alloca.
430     DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
431                                   "unsafe_stack_dynamic_ptr");
432
433   if (!StaticTop)
434     // We need the original unsafe stack pointer value, even if there are
435     // no unsafe static allocas.
436     StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
437
438   if (NeedDynamicTop)
439     IRB.CreateStore(StaticTop, DynamicTop);
440
441   // Restore current stack pointer after longjmp/exception catch.
442   for (Instruction *I : StackRestorePoints) {
443     ++NumUnsafeStackRestorePoints;
444
445     IRB.SetInsertPoint(I->getNextNode());
446     Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
447     IRB.CreateStore(CurrentTop, UnsafeStackPtr);
448   }
449
450   return DynamicTop;
451 }
452
453 Value *SafeStack::moveStaticAllocasToUnsafeStack(
454     IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
455     ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns) {
456   if (StaticAllocas.empty() && ByValArguments.empty())
457     return nullptr;
458
459   DIBuilder DIB(*F.getParent());
460
461   // We explicitly compute and set the unsafe stack layout for all unsafe
462   // static alloca instructions. We save the unsafe "base pointer" in the
463   // prologue into a local variable and restore it in the epilogue.
464
465   // Load the current stack pointer (we'll also use it as a base pointer).
466   // FIXME: use a dedicated register for it ?
467   Instruction *BasePointer =
468       IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
469   assert(BasePointer->getType() == StackPtrTy);
470
471   for (ReturnInst *RI : Returns) {
472     IRB.SetInsertPoint(RI);
473     IRB.CreateStore(BasePointer, UnsafeStackPtr);
474   }
475
476   // Compute maximum alignment among static objects on the unsafe stack.
477   unsigned MaxAlignment = 0;
478   for (Argument *Arg : ByValArguments) {
479     Type *Ty = Arg->getType()->getPointerElementType();
480     unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
481                               Arg->getParamAlignment());
482     if (Align > MaxAlignment)
483       MaxAlignment = Align;
484   }
485   for (AllocaInst *AI : StaticAllocas) {
486     Type *Ty = AI->getAllocatedType();
487     unsigned Align =
488         std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
489     if (Align > MaxAlignment)
490       MaxAlignment = Align;
491   }
492
493   if (MaxAlignment > StackAlignment) {
494     // Re-align the base pointer according to the max requested alignment.
495     assert(isPowerOf2_32(MaxAlignment));
496     IRB.SetInsertPoint(BasePointer->getNextNode());
497     BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
498         IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
499                       ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
500         StackPtrTy));
501   }
502
503   int64_t StaticOffset = 0; // Current stack top.
504   IRB.SetInsertPoint(BasePointer->getNextNode());
505
506   for (Argument *Arg : ByValArguments) {
507     Type *Ty = Arg->getType()->getPointerElementType();
508
509     uint64_t Size = DL->getTypeStoreSize(Ty);
510     if (Size == 0)
511       Size = 1; // Don't create zero-sized stack objects.
512
513     // Ensure the object is properly aligned.
514     unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
515                               Arg->getParamAlignment());
516
517     // Add alignment.
518     // NOTE: we ensure that BasePointer itself is aligned to >= Align.
519     StaticOffset += Size;
520     StaticOffset = RoundUpToAlignment(StaticOffset, Align);
521
522     Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
523                                ConstantInt::get(Int32Ty, -StaticOffset));
524     Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
525                                      Arg->getName() + ".unsafe-byval");
526
527     // Replace alloc with the new location.
528     replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
529                       /*Deref=*/true, -StaticOffset);
530     Arg->replaceAllUsesWith(NewArg);
531     IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
532     IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
533   }
534
535   // Allocate space for every unsafe static AllocaInst on the unsafe stack.
536   for (AllocaInst *AI : StaticAllocas) {
537     IRB.SetInsertPoint(AI);
538
539     Type *Ty = AI->getAllocatedType();
540     uint64_t Size = getStaticAllocaAllocationSize(AI);
541     if (Size == 0)
542       Size = 1; // Don't create zero-sized stack objects.
543
544     // Ensure the object is properly aligned.
545     unsigned Align =
546         std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
547
548     // Add alignment.
549     // NOTE: we ensure that BasePointer itself is aligned to >= Align.
550     StaticOffset += Size;
551     StaticOffset = RoundUpToAlignment(StaticOffset, Align);
552
553     Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
554                                ConstantInt::get(Int32Ty, -StaticOffset));
555     Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
556     if (AI->hasName() && isa<Instruction>(NewAI))
557       cast<Instruction>(NewAI)->takeName(AI);
558
559     // Replace alloc with the new location.
560     replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
561     AI->replaceAllUsesWith(NewAI);
562     AI->eraseFromParent();
563   }
564
565   // Re-align BasePointer so that our callees would see it aligned as
566   // expected.
567   // FIXME: no need to update BasePointer in leaf functions.
568   StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
569
570   // Update shadow stack pointer in the function epilogue.
571   IRB.SetInsertPoint(BasePointer->getNextNode());
572
573   Value *StaticTop =
574       IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
575                     "unsafe_stack_static_top");
576   IRB.CreateStore(StaticTop, UnsafeStackPtr);
577   return StaticTop;
578 }
579
580 void SafeStack::moveDynamicAllocasToUnsafeStack(
581     Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
582     ArrayRef<AllocaInst *> DynamicAllocas) {
583   DIBuilder DIB(*F.getParent());
584
585   for (AllocaInst *AI : DynamicAllocas) {
586     IRBuilder<> IRB(AI);
587
588     // Compute the new SP value (after AI).
589     Value *ArraySize = AI->getArraySize();
590     if (ArraySize->getType() != IntPtrTy)
591       ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
592
593     Type *Ty = AI->getAllocatedType();
594     uint64_t TySize = DL->getTypeAllocSize(Ty);
595     Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
596
597     Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
598     SP = IRB.CreateSub(SP, Size);
599
600     // Align the SP value to satisfy the AllocaInst, type and stack alignments.
601     unsigned Align = std::max(
602         std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
603         (unsigned)StackAlignment);
604
605     assert(isPowerOf2_32(Align));
606     Value *NewTop = IRB.CreateIntToPtr(
607         IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
608         StackPtrTy);
609
610     // Save the stack pointer.
611     IRB.CreateStore(NewTop, UnsafeStackPtr);
612     if (DynamicTop)
613       IRB.CreateStore(NewTop, DynamicTop);
614
615     Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
616     if (AI->hasName() && isa<Instruction>(NewAI))
617       NewAI->takeName(AI);
618
619     replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
620     AI->replaceAllUsesWith(NewAI);
621     AI->eraseFromParent();
622   }
623
624   if (!DynamicAllocas.empty()) {
625     // Now go through the instructions again, replacing stacksave/stackrestore.
626     for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
627       Instruction *I = &*(It++);
628       auto II = dyn_cast<IntrinsicInst>(I);
629       if (!II)
630         continue;
631
632       if (II->getIntrinsicID() == Intrinsic::stacksave) {
633         IRBuilder<> IRB(II);
634         Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
635         LI->takeName(II);
636         II->replaceAllUsesWith(LI);
637         II->eraseFromParent();
638       } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
639         IRBuilder<> IRB(II);
640         Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
641         SI->takeName(II);
642         assert(II->use_empty());
643         II->eraseFromParent();
644       }
645     }
646   }
647 }
648
649 bool SafeStack::runOnFunction(Function &F) {
650   DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
651
652   if (!F.hasFnAttribute(Attribute::SafeStack)) {
653     DEBUG(dbgs() << "[SafeStack]     safestack is not requested"
654                     " for this function\n");
655     return false;
656   }
657
658   if (F.isDeclaration()) {
659     DEBUG(dbgs() << "[SafeStack]     function definition"
660                     " is not available\n");
661     return false;
662   }
663
664   TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
665   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
666
667   {
668     // Make sure the regular stack protector won't run on this function
669     // (safestack attribute takes precedence).
670     AttrBuilder B;
671     B.addAttribute(Attribute::StackProtect)
672         .addAttribute(Attribute::StackProtectReq)
673         .addAttribute(Attribute::StackProtectStrong);
674     F.removeAttributes(
675         AttributeSet::FunctionIndex,
676         AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
677   }
678
679   ++NumFunctions;
680
681   SmallVector<AllocaInst *, 16> StaticAllocas;
682   SmallVector<AllocaInst *, 4> DynamicAllocas;
683   SmallVector<Argument *, 4> ByValArguments;
684   SmallVector<ReturnInst *, 4> Returns;
685
686   // Collect all points where stack gets unwound and needs to be restored
687   // This is only necessary because the runtime (setjmp and unwind code) is
688   // not aware of the unsafe stack and won't unwind/restore it prorerly.
689   // To work around this problem without changing the runtime, we insert
690   // instrumentation to restore the unsafe stack pointer when necessary.
691   SmallVector<Instruction *, 4> StackRestorePoints;
692
693   // Find all static and dynamic alloca instructions that must be moved to the
694   // unsafe stack, all return instructions and stack restore points.
695   findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
696             StackRestorePoints);
697
698   if (StaticAllocas.empty() && DynamicAllocas.empty() &&
699       ByValArguments.empty() && StackRestorePoints.empty())
700     return false; // Nothing to do in this function.
701
702   if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
703       !ByValArguments.empty())
704     ++NumUnsafeStackFunctions; // This function has the unsafe stack.
705
706   if (!StackRestorePoints.empty())
707     ++NumUnsafeStackRestorePointsFunctions;
708
709   IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
710   UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
711
712   // The top of the unsafe stack after all unsafe static allocas are allocated.
713   Value *StaticTop = moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas,
714                                                     ByValArguments, Returns);
715
716   // Safe stack object that stores the current unsafe stack top. It is updated
717   // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
718   // This is only needed if we need to restore stack pointer after longjmp
719   // or exceptions, and we have dynamic allocations.
720   // FIXME: a better alternative might be to store the unsafe stack pointer
721   // before setjmp / invoke instructions.
722   AllocaInst *DynamicTop = createStackRestorePoints(
723       IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
724
725   // Handle dynamic allocas.
726   moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
727                                   DynamicAllocas);
728
729   DEBUG(dbgs() << "[SafeStack]     safestack applied\n");
730   return true;
731 }
732
733 } // anonymous namespace
734
735 char SafeStack::ID = 0;
736 INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
737                          "Safe Stack instrumentation pass", false, false)
738 INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
739                        "Safe Stack instrumentation pass", false, false)
740
741 FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
742   return new SafeStack(TM);
743 }