blob: 547c43c5ddd4a5fa5cdd14fcee0d0b9ec26a1ea7 [file] [log] [blame]
Nuno Lopesa2f6cec2012-05-22 17:19:09 +00001//===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Nuno Lopesa2f6cec2012-05-22 17:19:09 +00006//
7//===----------------------------------------------------------------------===//
Nuno Lopesa2f6cec2012-05-22 17:19:09 +00008
Chandler Carruth00a301d2017-11-14 01:30:04 +00009#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000010#include "llvm/ADT/Statistic.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000011#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000012#include "llvm/Analysis/MemoryBuiltins.h"
Joel Galenson8dbcc582018-07-24 15:21:54 +000013#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth452a0072014-03-04 11:59:06 +000014#include "llvm/Analysis/TargetFolder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000016#include "llvm/IR/BasicBlock.h"
17#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000019#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000021#include "llvm/IR/InstIterator.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000022#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Intrinsics.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000026#include "llvm/IR/Value.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000027#include "llvm/Pass.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000028#include "llvm/Support/Casting.h"
Nuno Lopes288e86ff62012-05-31 22:58:48 +000029#include "llvm/Support/CommandLine.h"
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000030#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000031#include "llvm/Support/ErrorHandling.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000032#include "llvm/Support/raw_ostream.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000033#include <cstdint>
34#include <vector>
35
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000036using namespace llvm;
37
Chandler Carruth964daaa2014-04-22 02:55:47 +000038#define DEBUG_TYPE "bounds-checking"
39
Nuno Lopes0e967e02012-06-21 15:59:53 +000040static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
41 cl::desc("Use one trap block per function"));
Nuno Lopes288e86ff62012-05-31 22:58:48 +000042
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000043STATISTIC(ChecksAdded, "Bounds checks added");
44STATISTIC(ChecksSkipped, "Bounds checks skipped");
45STATISTIC(ChecksUnable, "Bounds checks unable to add");
46
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000047using BuilderTy = IRBuilder<TargetFolder>;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000048
Joel Galensoncfe5bc12018-08-03 17:12:23 +000049/// Gets the conditions under which memory accessing instructions will overflow.
Chandler Carruth1594fee2017-11-14 01:13:59 +000050///
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///
Joel Galensoncfe5bc12018-08-03 17:12:23 +000055/// Returns the condition under which the access will overflow.
56static Value *getBoundsCheckCond(Value *Ptr, Value *InstVal,
57 const DataLayout &DL, TargetLibraryInfo &TLI,
58 ObjectSizeOffsetEvaluator &ObjSizeEval,
59 BuilderTy &IRB, ScalarEvolution &SE) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000060 uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +000061 LLVM_DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
62 << " bytes\n");
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000063
Chandler Carruth1594fee2017-11-14 01:13:59 +000064 SizeOffsetEvalType SizeOffset = ObjSizeEval.compute(Ptr);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000065
Chandler Carruth1594fee2017-11-14 01:13:59 +000066 if (!ObjSizeEval.bothKnown(SizeOffset)) {
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000067 ++ChecksUnable;
Joel Galensoncfe5bc12018-08-03 17:12:23 +000068 return nullptr;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000069 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000070
Nuno Lopes0e967e02012-06-21 15:59:53 +000071 Value *Size = SizeOffset.first;
72 Value *Offset = SizeOffset.second;
Nuno Lopes1e8dffd2012-07-03 17:30:18 +000073 ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
Nuno Lopes0e967e02012-06-21 15:59:53 +000074
Mehdi Aminia28d91d2015-03-10 02:37:25 +000075 Type *IntTy = DL.getIntPtrType(Ptr->getType());
Nuno Lopes0e967e02012-06-21 15:59:53 +000076 Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
77
Joel Galenson8dbcc582018-07-24 15:21:54 +000078 auto SizeRange = SE.getUnsignedRange(SE.getSCEV(Size));
79 auto OffsetRange = SE.getUnsignedRange(SE.getSCEV(Offset));
80 auto NeededSizeRange = SE.getUnsignedRange(SE.getSCEV(NeededSizeVal));
81
Nuno Lopes7d000612012-05-31 22:45:40 +000082 // 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)
Nuno Lopes1e8dffd2012-07-03 17:30:18 +000086 //
87 // optimization: if Size >= 0 (signed), skip 1st check
Nuno Lopes7d000612012-05-31 22:45:40 +000088 // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
Chandler Carruth1594fee2017-11-14 01:13:59 +000089 Value *ObjSize = IRB.CreateSub(Size, Offset);
Joel Galenson8dbcc582018-07-24 15:21:54 +000090 Value *Cmp2 = SizeRange.getUnsignedMin().uge(OffsetRange.getUnsignedMax())
91 ? ConstantInt::getFalse(Ptr->getContext())
92 : IRB.CreateICmpULT(Size, Offset);
93 Value *Cmp3 = SizeRange.sub(OffsetRange)
94 .getUnsignedMin()
95 .uge(NeededSizeRange.getUnsignedMax())
96 ? ConstantInt::getFalse(Ptr->getContext())
97 : IRB.CreateICmpULT(ObjSize, NeededSizeVal);
Chandler Carruth1594fee2017-11-14 01:13:59 +000098 Value *Or = IRB.CreateOr(Cmp2, Cmp3);
Joel Galenson8dbcc582018-07-24 15:21:54 +000099 if ((!SizeCI || SizeCI->getValue().slt(0)) &&
100 !SizeRange.getSignedMin().isNonNegative()) {
Chandler Carruth1594fee2017-11-14 01:13:59 +0000101 Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
102 Or = IRB.CreateOr(Cmp1, Or);
Nuno Lopes1e8dffd2012-07-03 17:30:18 +0000103 }
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000104
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000105 return Or;
106}
107
108/// Adds run-time bounds checks to memory accessing instructions.
109///
110/// \p Or is the condition that should guard the trap.
111///
112/// \p GetTrapBB is a callable that returns the trap BB to use on failure.
113template <typename GetTrapBBT>
114static void insertBoundsCheck(Value *Or, BuilderTy IRB, GetTrapBBT GetTrapBB) {
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000115 // check if the comparison is always false
116 ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
117 if (C) {
118 ++ChecksSkipped;
119 // If non-zero, nothing to do.
120 if (!C->getZExtValue())
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000121 return;
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000122 }
123 ++ChecksAdded;
124
Chandler Carruth1594fee2017-11-14 01:13:59 +0000125 BasicBlock::iterator SplitI = IRB.GetInsertPoint();
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000126 BasicBlock *OldBB = SplitI->getParent();
127 BasicBlock *Cont = OldBB->splitBasicBlock(SplitI);
128 OldBB->getTerminator()->eraseFromParent();
129
130 if (C) {
131 // If we have a constant zero, unconditionally branch.
132 // FIXME: We should really handle this differently to bypass the splitting
133 // the block.
Chandler Carruth1594fee2017-11-14 01:13:59 +0000134 BranchInst::Create(GetTrapBB(IRB), OldBB);
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000135 return;
Chandler Carruth3f0e0562017-10-18 22:42:36 +0000136 }
137
138 // Create the conditional branch.
Chandler Carruth1594fee2017-11-14 01:13:59 +0000139 BranchInst::Create(GetTrapBB(IRB), Cont, Or, OldBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000140}
141
Joel Galenson8dbcc582018-07-24 15:21:54 +0000142static bool addBoundsChecking(Function &F, TargetLibraryInfo &TLI,
143 ScalarEvolution &SE) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000144 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruth1594fee2017-11-14 01:13:59 +0000145 ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(),
Nuno Lopes340b0462013-10-24 09:17:24 +0000146 /*RoundToAlign=*/true);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000147
148 // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
149 // touching instructions
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000150 SmallVector<std::pair<Instruction *, Value *>, 4> TrapInfo;
Chandler Carruth1594fee2017-11-14 01:13:59 +0000151 for (Instruction &I : instructions(F)) {
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000152 Value *Or = nullptr;
153 BuilderTy IRB(I.getParent(), BasicBlock::iterator(&I), TargetFolder(DL));
154 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
155 Or = getBoundsCheckCond(LI->getPointerOperand(), LI, DL, TLI,
156 ObjSizeEval, IRB, SE);
157 } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
158 Or = getBoundsCheckCond(SI->getPointerOperand(), SI->getValueOperand(),
159 DL, TLI, ObjSizeEval, IRB, SE);
160 } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
161 Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getCompareOperand(),
162 DL, TLI, ObjSizeEval, IRB, SE);
163 } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
164 Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getValOperand(), DL,
165 TLI, ObjSizeEval, IRB, SE);
166 }
167 if (Or)
168 TrapInfo.push_back(std::make_pair(&I, Or));
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000169 }
170
Chandler Carruth1594fee2017-11-14 01:13:59 +0000171 // Create a trapping basic block on demand using a callback. Depending on
172 // flags, this will either create a single block for the entire function or
173 // will create a fresh block every time it is called.
174 BasicBlock *TrapBB = nullptr;
175 auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
176 if (TrapBB && SingleTrapBB)
177 return TrapBB;
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000178
Chandler Carruth1594fee2017-11-14 01:13:59 +0000179 Function *Fn = IRB.GetInsertBlock()->getParent();
180 // FIXME: This debug location doesn't make a lot of sense in the
181 // `SingleTrapBB` case.
182 auto DebugLoc = IRB.getCurrentDebugLocation();
183 IRBuilder<>::InsertPointGuard Guard(IRB);
184 TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
185 IRB.SetInsertPoint(TrapBB);
186
187 auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
188 CallInst *TrapCall = IRB.CreateCall(F, {});
189 TrapCall->setDoesNotReturn();
190 TrapCall->setDoesNotThrow();
191 TrapCall->setDebugLoc(DebugLoc);
192 IRB.CreateUnreachable();
193
194 return TrapBB;
195 };
196
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000197 // Add the checks.
198 for (const auto &Entry : TrapInfo) {
199 Instruction *Inst = Entry.first;
Chandler Carruth1594fee2017-11-14 01:13:59 +0000200 BuilderTy IRB(Inst->getParent(), BasicBlock::iterator(Inst), TargetFolder(DL));
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000201 insertBoundsCheck(Entry.second, IRB, GetTrapBB);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000202 }
Joel Galensoncfe5bc12018-08-03 17:12:23 +0000203
204 return !TrapInfo.empty();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000205}
206
Chandler Carruth00a301d2017-11-14 01:30:04 +0000207PreservedAnalyses BoundsCheckingPass::run(Function &F, FunctionAnalysisManager &AM) {
208 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Joel Galenson8dbcc582018-07-24 15:21:54 +0000209 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
Chandler Carruth00a301d2017-11-14 01:30:04 +0000210
Joel Galenson8dbcc582018-07-24 15:21:54 +0000211 if (!addBoundsChecking(F, TLI, SE))
Chandler Carruth00a301d2017-11-14 01:30:04 +0000212 return PreservedAnalyses::all();
213
214 return PreservedAnalyses::none();
215}
216
217namespace {
218struct BoundsCheckingLegacyPass : public FunctionPass {
219 static char ID;
220
221 BoundsCheckingLegacyPass() : FunctionPass(ID) {
222 initializeBoundsCheckingLegacyPassPass(*PassRegistry::getPassRegistry());
223 }
224
225 bool runOnFunction(Function &F) override {
226 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Joel Galenson8dbcc582018-07-24 15:21:54 +0000227 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
228 return addBoundsChecking(F, TLI, SE);
Chandler Carruth00a301d2017-11-14 01:30:04 +0000229 }
230
231 void getAnalysisUsage(AnalysisUsage &AU) const override {
232 AU.addRequired<TargetLibraryInfoWrapperPass>();
Joel Galenson8dbcc582018-07-24 15:21:54 +0000233 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth00a301d2017-11-14 01:30:04 +0000234 }
235};
236} // namespace
237
238char BoundsCheckingLegacyPass::ID = 0;
239INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking",
240 "Run-time bounds checking", false, false)
241INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
242INITIALIZE_PASS_END(BoundsCheckingLegacyPass, "bounds-checking",
243 "Run-time bounds checking", false, false)
244
245FunctionPass *llvm::createBoundsCheckingLegacyPass() {
246 return new BoundsCheckingLegacyPass();
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000247}