blob: 6415f7ae53b655aa252dc7f3f810cf42a96f338e [file] [log] [blame]
Nuno Lopes5c525b52012-05-22 17:19:09 +00001//===- 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// This file implements a pass that instruments the code to perform run-time
11// bounds checking on loads, stores, and other memory intrinsics.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "bounds-checking"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000016#include "llvm/IRBuilder.h"
17#include "llvm/Intrinsics.h"
18#include "llvm/Pass.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000019#include "llvm/ADT/Statistic.h"
Nuno Lopes7f584722012-06-21 15:59:53 +000020#include "llvm/Analysis/MemoryBuiltins.h"
Nuno Lopes1cbf2be2012-05-31 22:58:48 +000021#include "llvm/Support/CommandLine.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Support/InstIterator.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000024#include "llvm/Support/TargetFolder.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000025#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000026#include "llvm/DataLayout.h"
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000027#include "llvm/Target/TargetLibraryInfo.h"
Nuno Lopes78435f62012-07-20 22:39:33 +000028#include "llvm/Transforms/Instrumentation.h"
Nuno Lopes5c525b52012-05-22 17:19:09 +000029using namespace llvm;
30
Nuno Lopes7f584722012-06-21 15:59:53 +000031static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
32 cl::desc("Use one trap block per function"));
Nuno Lopes1cbf2be2012-05-31 22:58:48 +000033
Nuno Lopes5c525b52012-05-22 17:19:09 +000034STATISTIC(ChecksAdded, "Bounds checks added");
35STATISTIC(ChecksSkipped, "Bounds checks skipped");
36STATISTIC(ChecksUnable, "Bounds checks unable to add");
37
38typedef IRBuilder<true, TargetFolder> BuilderTy;
39
40namespace {
Nuno Lopes5c525b52012-05-22 17:19:09 +000041 struct BoundsChecking : public FunctionPass {
Nuno Lopes5c525b52012-05-22 17:19:09 +000042 static char ID;
43
Joey Goulyf284aef2012-11-23 10:47:35 +000044 BoundsChecking() : FunctionPass(ID) {
Nuno Lopes5c525b52012-05-22 17:19:09 +000045 initializeBoundsCheckingPass(*PassRegistry::getPassRegistry());
46 }
47
Nuno Lopes5c525b52012-05-22 17:19:09 +000048 virtual bool runOnFunction(Function &F);
49
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Micah Villmow3574eca2012-10-08 16:38:25 +000051 AU.addRequired<DataLayout>();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000052 AU.addRequired<TargetLibraryInfo>();
Nuno Lopes5c525b52012-05-22 17:19:09 +000053 }
Nuno Lopes2f0a7482012-05-22 22:02:19 +000054
55 private:
Micah Villmow3574eca2012-10-08 16:38:25 +000056 const DataLayout *TD;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000057 const TargetLibraryInfo *TLI;
Nuno Lopes7f584722012-06-21 15:59:53 +000058 ObjectSizeOffsetEvaluator *ObjSizeEval;
Nuno Lopes2f0a7482012-05-22 22:02:19 +000059 BuilderTy *Builder;
Nuno Lopes512be1f2012-06-23 00:12:34 +000060 Instruction *Inst;
Nuno Lopes2f0a7482012-05-22 22:02:19 +000061 BasicBlock *TrapBB;
Nuno Lopes2f0a7482012-05-22 22:02:19 +000062
63 BasicBlock *getTrapBB();
Nuno Lopes2b526302012-05-23 16:24:52 +000064 void emitBranchToTrap(Value *Cmp = 0);
Nuno Lopes0463cce2012-05-31 22:45:40 +000065 bool computeAllocSize(Value *Ptr, APInt &Offset, Value* &OffsetValue,
66 APInt &Size, Value* &SizeValue);
Nuno Lopes2f0a7482012-05-22 22:02:19 +000067 bool instrument(Value *Ptr, Value *Val);
Nuno Lopes5c525b52012-05-22 17:19:09 +000068 };
69}
70
71char BoundsChecking::ID = 0;
Nuno Lopes42d80c72012-07-03 17:30:18 +000072INITIALIZE_PASS(BoundsChecking, "bounds-checking", "Run-time bounds checking",
73 false, false)
Nuno Lopes5c525b52012-05-22 17:19:09 +000074
75
76/// getTrapBB - create a basic block that traps. All overflowing conditions
77/// branch to this block. There's only one trap block per function.
78BasicBlock *BoundsChecking::getTrapBB() {
Nuno Lopes7f584722012-06-21 15:59:53 +000079 if (TrapBB && SingleTrapBB)
Nuno Lopes5c525b52012-05-22 17:19:09 +000080 return TrapBB;
81
Nuno Lopes512be1f2012-06-23 00:12:34 +000082 Function *Fn = Inst->getParent()->getParent();
Nuno Lopes5c525b52012-05-22 17:19:09 +000083 BasicBlock::iterator PrevInsertPoint = Builder->GetInsertPoint();
84 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
85 Builder->SetInsertPoint(TrapBB);
86
87 llvm::Value *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
88 CallInst *TrapCall = Builder->CreateCall(F);
89 TrapCall->setDoesNotReturn();
90 TrapCall->setDoesNotThrow();
Nuno Lopes512be1f2012-06-23 00:12:34 +000091 TrapCall->setDebugLoc(Inst->getDebugLoc());
Nuno Lopes5c525b52012-05-22 17:19:09 +000092 Builder->CreateUnreachable();
93
94 Builder->SetInsertPoint(PrevInsertPoint);
95 return TrapBB;
96}
97
98
Nuno Lopes2b526302012-05-23 16:24:52 +000099/// emitBranchToTrap - emit a branch instruction to a trap block.
100/// If Cmp is non-null, perform a jump only if its value evaluates to true.
101void BoundsChecking::emitBranchToTrap(Value *Cmp) {
Nuno Lopes7f584722012-06-21 15:59:53 +0000102 // check if the comparison is always false
103 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Cmp);
104 if (C) {
105 ++ChecksSkipped;
106 if (!C->getZExtValue())
107 return;
108 else
109 Cmp = 0; // unconditional branch
110 }
Nuno Lopes53916aa2012-12-03 10:15:03 +0000111 ++ChecksAdded;
Nuno Lopes7f584722012-06-21 15:59:53 +0000112
Nuno Lopes2b526302012-05-23 16:24:52 +0000113 Instruction *Inst = Builder->GetInsertPoint();
114 BasicBlock *OldBB = Inst->getParent();
115 BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
116 OldBB->getTerminator()->eraseFromParent();
117
Nuno Lopes2b526302012-05-23 16:24:52 +0000118 if (Cmp)
119 BranchInst::Create(getTrapBB(), Cont, Cmp, OldBB);
120 else
121 BranchInst::Create(getTrapBB(), OldBB);
122}
123
124
Nuno Lopes2f0a7482012-05-22 22:02:19 +0000125/// instrument - adds run-time bounds checks to memory accessing instructions.
126/// Ptr is the pointer that will be read/written, and InstVal is either the
127/// result from the load or the value being stored. It is used to determine the
128/// size of memory block that is touched.
129/// Returns true if any change was made to the IR, false otherwise.
Nuno Lopes5c525b52012-05-22 17:19:09 +0000130bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
131 uint64_t NeededSize = TD->getTypeStoreSize(InstVal->getType());
132 DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
133 << " bytes\n");
134
Nuno Lopes7f584722012-06-21 15:59:53 +0000135 SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Ptr);
Nuno Lopes5c525b52012-05-22 17:19:09 +0000136
Nuno Lopes7f584722012-06-21 15:59:53 +0000137 if (!ObjSizeEval->bothKnown(SizeOffset)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000138 ++ChecksUnable;
139 return false;
140 }
Nuno Lopes5c525b52012-05-22 17:19:09 +0000141
Nuno Lopes7f584722012-06-21 15:59:53 +0000142 Value *Size = SizeOffset.first;
143 Value *Offset = SizeOffset.second;
Nuno Lopes42d80c72012-07-03 17:30:18 +0000144 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Nuno Lopes7f584722012-06-21 15:59:53 +0000145
Duncan Sands7ed4f942012-10-29 17:31:46 +0000146 Type *IntTy = TD->getIntPtrType(Ptr->getType());
Nuno Lopes7f584722012-06-21 15:59:53 +0000147 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
148
Nuno Lopes0463cce2012-05-31 22:45:40 +0000149 // three checks are required to ensure safety:
150 // . Offset >= 0 (since the offset is given from the base ptr)
151 // . Size >= Offset (unsigned)
152 // . Size - Offset >= NeededSize (unsigned)
Nuno Lopes42d80c72012-07-03 17:30:18 +0000153 //
154 // optimization: if Size >= 0 (signed), skip 1st check
Nuno Lopes0463cce2012-05-31 22:45:40 +0000155 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Nuno Lopes7f584722012-06-21 15:59:53 +0000156 Value *ObjSize = Builder->CreateSub(Size, Offset);
Nuno Lopes7f584722012-06-21 15:59:53 +0000157 Value *Cmp2 = Builder->CreateICmpULT(Size, Offset);
158 Value *Cmp3 = Builder->CreateICmpULT(ObjSize, NeededSizeVal);
Nuno Lopes42d80c72012-07-03 17:30:18 +0000159 Value *Or = Builder->CreateOr(Cmp2, Cmp3);
160 if (!SizeCI || SizeCI->getValue().slt(0)) {
161 Value *Cmp1 = Builder->CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
162 Or = Builder->CreateOr(Cmp1, Or);
163 }
Nuno Lopes2b526302012-05-23 16:24:52 +0000164 emitBranchToTrap(Or);
Nuno Lopes5c525b52012-05-22 17:19:09 +0000165
Nuno Lopes5c525b52012-05-22 17:19:09 +0000166 return true;
167}
168
169bool BoundsChecking::runOnFunction(Function &F) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000170 TD = &getAnalysis<DataLayout>();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000171 TLI = &getAnalysis<TargetLibraryInfo>();
Nuno Lopes5c525b52012-05-22 17:19:09 +0000172
173 TrapBB = 0;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000174 BuilderTy TheBuilder(F.getContext(), TargetFolder(TD));
175 Builder = &TheBuilder;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000176 ObjectSizeOffsetEvaluator TheObjSizeEval(TD, TLI, F.getContext());
Nuno Lopes7f584722012-06-21 15:59:53 +0000177 ObjSizeEval = &TheObjSizeEval;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000178
179 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
180 // touching instructions
181 std::vector<Instruction*> WorkList;
182 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
183 Instruction *I = &*i;
184 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<AtomicCmpXchgInst>(I) ||
185 isa<AtomicRMWInst>(I))
186 WorkList.push_back(I);
187 }
188
189 bool MadeChange = false;
Nuno Lopes2f0a7482012-05-22 22:02:19 +0000190 for (std::vector<Instruction*>::iterator i = WorkList.begin(),
191 e = WorkList.end(); i != e; ++i) {
Nuno Lopes512be1f2012-06-23 00:12:34 +0000192 Inst = *i;
Nuno Lopes5c525b52012-05-22 17:19:09 +0000193
Nuno Lopes512be1f2012-06-23 00:12:34 +0000194 Builder->SetInsertPoint(Inst);
195 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000196 MadeChange |= instrument(LI->getPointerOperand(), LI);
Nuno Lopes512be1f2012-06-23 00:12:34 +0000197 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000198 MadeChange |= instrument(SI->getPointerOperand(), SI->getValueOperand());
Nuno Lopes512be1f2012-06-23 00:12:34 +0000199 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000200 MadeChange |= instrument(AI->getPointerOperand(),AI->getCompareOperand());
Nuno Lopes512be1f2012-06-23 00:12:34 +0000201 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst)) {
Nuno Lopes5c525b52012-05-22 17:19:09 +0000202 MadeChange |= instrument(AI->getPointerOperand(), AI->getValOperand());
203 } else {
204 llvm_unreachable("unknown Instruction type");
205 }
206 }
207 return MadeChange;
208}
209
Joey Goulyf284aef2012-11-23 10:47:35 +0000210FunctionPass *llvm::createBoundsCheckingPass() {
211 return new BoundsChecking();
Nuno Lopes5c525b52012-05-22 17:19:09 +0000212}