1 //===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
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 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Analysis/MemoryBuiltins.h"
14 #include "llvm/Analysis/TargetFolder.h"
15 #include "llvm/Analysis/TargetLibraryInfo.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/InstIterator.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cstdint>
34 #include <vector>
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "bounds-checking"
39 
40 static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
41                                   cl::desc("Use one trap block per function"));
42 
43 STATISTIC(ChecksAdded, "Bounds checks added");
44 STATISTIC(ChecksSkipped, "Bounds checks skipped");
45 STATISTIC(ChecksUnable, "Bounds checks unable to add");
46 
47 using BuilderTy = IRBuilder<TargetFolder>;
48 
49 /// Adds run-time bounds checks to memory accessing instructions.
50 ///
51 /// \p Ptr is the pointer that will be read/written, and \p InstVal is either
52 /// the result from the load or the value being stored. It is used to determine
53 /// the size of memory block that is touched.
54 ///
55 /// \p GetTrapBB is a callable that returns the trap BB to use on failure.
56 ///
57 /// Returns true if any change was made to the IR, false otherwise.
58 template <typename GetTrapBBT>
59 static bool instrumentMemAccess(Value *Ptr, Value *InstVal,
60                                 const DataLayout &DL, TargetLibraryInfo &TLI,
61                                 ObjectSizeOffsetEvaluator &ObjSizeEval,
62                                 BuilderTy &IRB,
63                                 GetTrapBBT GetTrapBB) {
64   uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
65   DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
66               << " bytes\n");
67 
68   SizeOffsetEvalType SizeOffset = ObjSizeEval.compute(Ptr);
69 
70   if (!ObjSizeEval.bothKnown(SizeOffset)) {
71     ++ChecksUnable;
72     return false;
73   }
74 
75   Value *Size   = SizeOffset.first;
76   Value *Offset = SizeOffset.second;
77   ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
78 
79   Type *IntTy = DL.getIntPtrType(Ptr->getType());
80   Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
81 
82   // three checks are required to ensure safety:
83   // . Offset >= 0  (since the offset is given from the base ptr)
84   // . Size >= Offset  (unsigned)
85   // . Size - Offset >= NeededSize  (unsigned)
86   //
87   // optimization: if Size >= 0 (signed), skip 1st check
88   // FIXME: add NSW/NUW here?  -- we dont care if the subtraction overflows
89   Value *ObjSize = IRB.CreateSub(Size, Offset);
90   Value *Cmp2 = IRB.CreateICmpULT(Size, Offset);
91   Value *Cmp3 = IRB.CreateICmpULT(ObjSize, NeededSizeVal);
92   Value *Or = IRB.CreateOr(Cmp2, Cmp3);
93   if (!SizeCI || SizeCI->getValue().slt(0)) {
94     Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
95     Or = IRB.CreateOr(Cmp1, Or);
96   }
97 
98   // check if the comparison is always false
99   ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
100   if (C) {
101     ++ChecksSkipped;
102     // If non-zero, nothing to do.
103     if (!C->getZExtValue())
104       return true;
105   }
106   ++ChecksAdded;
107 
108   BasicBlock::iterator SplitI = IRB.GetInsertPoint();
109   BasicBlock *OldBB = SplitI->getParent();
110   BasicBlock *Cont = OldBB->splitBasicBlock(SplitI);
111   OldBB->getTerminator()->eraseFromParent();
112 
113   if (C) {
114     // If we have a constant zero, unconditionally branch.
115     // FIXME: We should really handle this differently to bypass the splitting
116     // the block.
117     BranchInst::Create(GetTrapBB(IRB), OldBB);
118     return true;
119   }
120 
121   // Create the conditional branch.
122   BranchInst::Create(GetTrapBB(IRB), Cont, Or, OldBB);
123   return true;
124 }
125 
126 static bool addBoundsChecking(Function &F, TargetLibraryInfo &TLI) {
127   const DataLayout &DL = F.getParent()->getDataLayout();
128   ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(),
129                                            /*RoundToAlign=*/true);
130 
131   // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
132   // touching instructions
133   std::vector<Instruction *> WorkList;
134   for (Instruction &I : instructions(F)) {
135     if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
136         isa<AtomicRMWInst>(I))
137         WorkList.push_back(&I);
138   }
139 
140   // Create a trapping basic block on demand using a callback. Depending on
141   // flags, this will either create a single block for the entire function or
142   // will create a fresh block every time it is called.
143   BasicBlock *TrapBB = nullptr;
144   auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
145     if (TrapBB && SingleTrapBB)
146       return TrapBB;
147 
148     Function *Fn = IRB.GetInsertBlock()->getParent();
149     // FIXME: This debug location doesn't make a lot of sense in the
150     // `SingleTrapBB` case.
151     auto DebugLoc = IRB.getCurrentDebugLocation();
152     IRBuilder<>::InsertPointGuard Guard(IRB);
153     TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
154     IRB.SetInsertPoint(TrapBB);
155 
156     auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
157     CallInst *TrapCall = IRB.CreateCall(F, {});
158     TrapCall->setDoesNotReturn();
159     TrapCall->setDoesNotThrow();
160     TrapCall->setDebugLoc(DebugLoc);
161     IRB.CreateUnreachable();
162 
163     return TrapBB;
164   };
165 
166   bool MadeChange = false;
167   for (Instruction *Inst : WorkList) {
168     BuilderTy IRB(Inst->getParent(), BasicBlock::iterator(Inst), TargetFolder(DL));
169     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
170       MadeChange |= instrumentMemAccess(LI->getPointerOperand(), LI, DL, TLI,
171                                         ObjSizeEval, IRB, GetTrapBB);
172     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
173       MadeChange |=
174           instrumentMemAccess(SI->getPointerOperand(), SI->getValueOperand(),
175                               DL, TLI, ObjSizeEval, IRB, GetTrapBB);
176     } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
177       MadeChange |=
178           instrumentMemAccess(AI->getPointerOperand(), AI->getCompareOperand(),
179                               DL, TLI, ObjSizeEval, IRB, GetTrapBB);
180     } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
181       MadeChange |=
182           instrumentMemAccess(AI->getPointerOperand(), AI->getValOperand(), DL,
183                               TLI, ObjSizeEval, IRB, GetTrapBB);
184     } else {
185       llvm_unreachable("unknown Instruction type");
186     }
187   }
188   return MadeChange;
189 }
190 
191 PreservedAnalyses BoundsCheckingPass::run(Function &F, FunctionAnalysisManager &AM) {
192   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
193 
194   if (!addBoundsChecking(F, TLI))
195     return PreservedAnalyses::all();
196 
197   return PreservedAnalyses::none();
198 }
199 
200 namespace {
201 struct BoundsCheckingLegacyPass : public FunctionPass {
202   static char ID;
203 
204   BoundsCheckingLegacyPass() : FunctionPass(ID) {
205     initializeBoundsCheckingLegacyPassPass(*PassRegistry::getPassRegistry());
206   }
207 
208   bool runOnFunction(Function &F) override {
209     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
210     return addBoundsChecking(F, TLI);
211   }
212 
213   void getAnalysisUsage(AnalysisUsage &AU) const override {
214     AU.addRequired<TargetLibraryInfoWrapperPass>();
215   }
216 };
217 } // namespace
218 
219 char BoundsCheckingLegacyPass::ID = 0;
220 INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking",
221                       "Run-time bounds checking", false, false)
222 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
223 INITIALIZE_PASS_END(BoundsCheckingLegacyPass, "bounds-checking",
224                     "Run-time bounds checking", false, false)
225 
226 FunctionPass *llvm::createBoundsCheckingLegacyPass() {
227   return new BoundsCheckingLegacyPass();
228 }
229