LLVM  14.0.0git
BoundsChecking.cpp
Go to the documentation of this file.
1 //===- BoundsChecking.cpp - Instrumentation for run-time bounds checking --===//
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 
10 #include "llvm/ADT/Statistic.h"
11 #include "llvm/ADT/Twine.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/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
34 #include <cstdint>
35 #include <utility>
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "bounds-checking"
40 
41 static cl::opt<bool> SingleTrapBB("bounds-checking-single-trap",
42  cl::desc("Use one trap block per function"));
43 
44 STATISTIC(ChecksAdded, "Bounds checks added");
45 STATISTIC(ChecksSkipped, "Bounds checks skipped");
46 STATISTIC(ChecksUnable, "Bounds checks unable to add");
47 
49 
50 /// Gets the conditions under which memory accessing instructions will overflow.
51 ///
52 /// \p Ptr is the pointer that will be read/written, and \p InstVal is either
53 /// the result from the load or the value being stored. It is used to determine
54 /// the size of memory block that is touched.
55 ///
56 /// Returns the condition under which the access will overflow.
57 static Value *getBoundsCheckCond(Value *Ptr, Value *InstVal,
58  const DataLayout &DL, TargetLibraryInfo &TLI,
59  ObjectSizeOffsetEvaluator &ObjSizeEval,
60  BuilderTy &IRB, ScalarEvolution &SE) {
61  uint64_t NeededSize = DL.getTypeStoreSize(InstVal->getType());
62  LLVM_DEBUG(dbgs() << "Instrument " << *Ptr << " for " << Twine(NeededSize)
63  << " bytes\n");
64 
65  SizeOffsetEvalType SizeOffset = ObjSizeEval.compute(Ptr);
66 
67  if (!ObjSizeEval.bothKnown(SizeOffset)) {
68  ++ChecksUnable;
69  return nullptr;
70  }
71 
72  Value *Size = SizeOffset.first;
73  Value *Offset = SizeOffset.second;
74  ConstantInt *SizeCI = dyn_cast<ConstantInt>(Size);
75 
76  Type *IntTy = DL.getIntPtrType(Ptr->getType());
77  Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize);
78 
79  auto SizeRange = SE.getUnsignedRange(SE.getSCEV(Size));
80  auto OffsetRange = SE.getUnsignedRange(SE.getSCEV(Offset));
81  auto NeededSizeRange = SE.getUnsignedRange(SE.getSCEV(NeededSizeVal));
82 
83  // three checks are required to ensure safety:
84  // . Offset >= 0 (since the offset is given from the base ptr)
85  // . Size >= Offset (unsigned)
86  // . Size - Offset >= NeededSize (unsigned)
87  //
88  // optimization: if Size >= 0 (signed), skip 1st check
89  // FIXME: add NSW/NUW here? -- we dont care if the subtraction overflows
90  Value *ObjSize = IRB.CreateSub(Size, Offset);
91  Value *Cmp2 = SizeRange.getUnsignedMin().uge(OffsetRange.getUnsignedMax())
93  : IRB.CreateICmpULT(Size, Offset);
94  Value *Cmp3 = SizeRange.sub(OffsetRange)
95  .getUnsignedMin()
96  .uge(NeededSizeRange.getUnsignedMax())
98  : IRB.CreateICmpULT(ObjSize, NeededSizeVal);
99  Value *Or = IRB.CreateOr(Cmp2, Cmp3);
100  if ((!SizeCI || SizeCI->getValue().slt(0)) &&
101  !SizeRange.getSignedMin().isNonNegative()) {
102  Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0));
103  Or = IRB.CreateOr(Cmp1, Or);
104  }
105 
106  return Or;
107 }
108 
109 /// Adds run-time bounds checks to memory accessing instructions.
110 ///
111 /// \p Or is the condition that should guard the trap.
112 ///
113 /// \p GetTrapBB is a callable that returns the trap BB to use on failure.
114 template <typename GetTrapBBT>
115 static void insertBoundsCheck(Value *Or, BuilderTy &IRB, GetTrapBBT GetTrapBB) {
116  // check if the comparison is always false
117  ConstantInt *C = dyn_cast_or_null<ConstantInt>(Or);
118  if (C) {
119  ++ChecksSkipped;
120  // If non-zero, nothing to do.
121  if (!C->getZExtValue())
122  return;
123  }
124  ++ChecksAdded;
125 
126  BasicBlock::iterator SplitI = IRB.GetInsertPoint();
127  BasicBlock *OldBB = SplitI->getParent();
128  BasicBlock *Cont = OldBB->splitBasicBlock(SplitI);
129  OldBB->getTerminator()->eraseFromParent();
130 
131  if (C) {
132  // If we have a constant zero, unconditionally branch.
133  // FIXME: We should really handle this differently to bypass the splitting
134  // the block.
135  BranchInst::Create(GetTrapBB(IRB), OldBB);
136  return;
137  }
138 
139  // Create the conditional branch.
140  BranchInst::Create(GetTrapBB(IRB), Cont, Or, OldBB);
141 }
142 
144  ScalarEvolution &SE) {
145  const DataLayout &DL = F.getParent()->getDataLayout();
146  ObjectSizeOpts EvalOpts;
147  EvalOpts.RoundToAlign = true;
148  ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(), EvalOpts);
149 
150  // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
151  // touching instructions
153  for (Instruction &I : instructions(F)) {
154  Value *Or = nullptr;
155  BuilderTy IRB(I.getParent(), BasicBlock::iterator(&I), TargetFolder(DL));
156  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
157  if (!LI->isVolatile())
158  Or = getBoundsCheckCond(LI->getPointerOperand(), LI, DL, TLI,
159  ObjSizeEval, IRB, SE);
160  } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
161  if (!SI->isVolatile())
162  Or = getBoundsCheckCond(SI->getPointerOperand(), SI->getValueOperand(),
163  DL, TLI, ObjSizeEval, IRB, SE);
164  } else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
165  if (!AI->isVolatile())
166  Or =
167  getBoundsCheckCond(AI->getPointerOperand(), AI->getCompareOperand(),
168  DL, TLI, ObjSizeEval, IRB, SE);
169  } else if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
170  if (!AI->isVolatile())
171  Or = getBoundsCheckCond(AI->getPointerOperand(), AI->getValOperand(),
172  DL, TLI, ObjSizeEval, IRB, SE);
173  }
174  if (Or)
175  TrapInfo.push_back(std::make_pair(&I, Or));
176  }
177 
178  // Create a trapping basic block on demand using a callback. Depending on
179  // flags, this will either create a single block for the entire function or
180  // will create a fresh block every time it is called.
181  BasicBlock *TrapBB = nullptr;
182  auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
183  if (TrapBB && SingleTrapBB)
184  return TrapBB;
185 
186  Function *Fn = IRB.GetInsertBlock()->getParent();
187  // FIXME: This debug location doesn't make a lot of sense in the
188  // `SingleTrapBB` case.
189  auto DebugLoc = IRB.getCurrentDebugLocation();
191  TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
192  IRB.SetInsertPoint(TrapBB);
193 
194  auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
195  CallInst *TrapCall = IRB.CreateCall(F, {});
196  TrapCall->setDoesNotReturn();
197  TrapCall->setDoesNotThrow();
198  TrapCall->setDebugLoc(DebugLoc);
199  IRB.CreateUnreachable();
200 
201  return TrapBB;
202  };
203 
204  // Add the checks.
205  for (const auto &Entry : TrapInfo) {
206  Instruction *Inst = Entry.first;
208  insertBoundsCheck(Entry.second, IRB, GetTrapBB);
209  }
210 
211  return !TrapInfo.empty();
212 }
213 
215  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
216  auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
217 
218  if (!addBoundsChecking(F, TLI, SE))
219  return PreservedAnalyses::all();
220 
221  return PreservedAnalyses::none();
222 }
223 
224 namespace {
225 struct BoundsCheckingLegacyPass : public FunctionPass {
226  static char ID;
227 
228  BoundsCheckingLegacyPass() : FunctionPass(ID) {
230  }
231 
232  bool runOnFunction(Function &F) override {
233  auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
234  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
235  return addBoundsChecking(F, TLI, SE);
236  }
237 
238  void getAnalysisUsage(AnalysisUsage &AU) const override {
241  }
242 };
243 } // namespace
244 
246 INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking",
247  "Run-time bounds checking", false, false)
249 INITIALIZE_PASS_END(BoundsCheckingLegacyPass, "bounds-checking",
250  "Run-time bounds checking", false, false)
251 
253  return new BoundsCheckingLegacyPass();
254 }
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
llvm::ScalarEvolutionAnalysis
Analysis pass that exposes the ScalarEvolution for a function.
Definition: ScalarEvolution.h:2093
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::initializeBoundsCheckingLegacyPassPass
void initializeBoundsCheckingLegacyPassPass(PassRegistry &)
llvm::createBoundsCheckingLegacyPass
FunctionPass * createBoundsCheckingLegacyPass()
Legacy pass creation function for the above pass.
Definition: BoundsChecking.cpp:252
llvm::RecurKind::Or
@ Or
Bitwise or logical OR of integers.
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:113
llvm::Intrinsic::getDeclaration
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1384
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:90
llvm::BasicBlock::getParent
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
llvm::AnalysisManager::getResult
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:783
InstIterator.h
llvm::Function
Definition: Function.h:62
TargetFolder.h
Pass.h
llvm::ConstantInt::getValue
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:133
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
Statistic.h
llvm::ObjectSizeOffsetEvaluator::compute
SizeOffsetEvalType compute(Value *V)
Definition: MemoryBuiltins.cpp:871
ErrorHandling.h
llvm::BoundsCheckingPass::run
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: BoundsChecking.cpp:214
llvm::IRBuilder
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2532
llvm::ScalarEvolution
The main scalar evolution driver.
Definition: ScalarEvolution.h:460
llvm::IRBuilderBase::CreateOr
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1388
llvm::PreservedAnalyses::none
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:158
llvm::Function::getContext
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:321
ScalarEvolution.h
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
MemoryBuiltins.h
llvm::BasicBlock::splitBasicBlock
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:385
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::ObjectSizeOpts::RoundToAlign
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
Definition: MemoryBuiltins.h:204
checking
bounds checking
Definition: BoundsChecking.cpp:249
llvm::CallBase::setDoesNotThrow
void setDoesNotThrow()
Definition: InstrTypes.h:1865
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
F
#define F(x, y, z)
Definition: MD5.cpp:56
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(BoundsCheckingLegacyPass, "bounds-checking", "Run-time bounds checking", false, false) INITIALIZE_PASS_END(BoundsCheckingLegacyPass
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Instruction.h
CommandLine.h
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::CallBase::setDoesNotReturn
void setDoesNotReturn()
Definition: InstrTypes.h:1858
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
Constants.h
Intrinsics.h
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
Twine.h
InstrTypes.h
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
TargetLibraryInfo.h
insertBoundsCheck
static void insertBoundsCheck(Value *Or, BuilderTy &IRB, GetTrapBBT GetTrapBB)
Adds run-time bounds checks to memory accessing instructions.
Definition: BoundsChecking.cpp:115
false
Definition: StackSlotColoring.cpp:142
llvm::Instruction
Definition: Instruction.h:45
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::ConstantInt::get
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:925
llvm::ObjectSizeOffsetEvaluator
Evaluate the size and offset of an object pointed to by a Value*.
Definition: MemoryBuiltins.h:294
llvm::ScalarEvolutionWrapperPass
Definition: ScalarEvolution.h:2123
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
llvm::ScalarEvolution::getSCEV
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
Definition: ScalarEvolution.cpp:4110
BasicBlock.h
llvm::cl::opt< bool >
llvm::APInt::slt
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1063
llvm::instructions
inst_range instructions(Function *F)
Definition: InstIterator.h:133
llvm::StoreInst
An instruction for storing to memory.
Definition: Instructions.h:304
SingleTrapBB
static cl::opt< bool > SingleTrapBB("bounds-checking-single-trap", cl::desc("Use one trap block per function"))
llvm::IRBuilderBase::GetInsertPoint
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:179
llvm::Instruction::eraseFromParent
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:78
llvm::TargetLibraryInfoWrapperPass
Definition: TargetLibraryInfo.h:465
uint64_t
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:578
BoundsChecking.h
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
llvm::BranchInst::Create
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
Definition: Instructions.h:3139
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::Instruction::setDebugLoc
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:367
llvm::ScalarEvolution::getUnsignedRange
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
Definition: ScalarEvolution.h:946
addBoundsChecking
static bool addBoundsChecking(Function &F, TargetLibraryInfo &TLI, ScalarEvolution &SE)
Definition: BoundsChecking.cpp:143
IRBuilder.h
SI
StandardInstrumentations SI(Debug, VerifyEach)
llvm::IRBuilderBase::CreateICmpSLT
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2138
DataLayout.h
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
llvm::BasicBlock::Create
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:100
llvm::Value::getContext
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:991
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
llvm::ObjectSizeOpts
Various options to control the behavior of getObjectSize.
Definition: MemoryBuiltins.h:188
llvm::LoadInst
An instruction for reading from memory.
Definition: Instructions.h:175
llvm::BasicBlock::getTerminator
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:152
llvm::AtomicRMWInst
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:726
llvm::ConstantInt::getFalse
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:880
runOnFunction
static bool runOnFunction(Function &F, bool PostInlining)
Definition: EntryExitInstrumenter.cpp:69
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:83
llvm::TargetFolder
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:32
llvm::PreservedAnalyses::all
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
llvm::IRBuilderBase::CreateICmpULT
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2122
llvm::SizeOffsetEvalType
std::pair< Value *, Value * > SizeOffsetEvalType
Definition: MemoryBuiltins.h:290
Casting.h
Function.h
llvm::TargetLibraryInfo
Provides information about what library functions are available for the current target.
Definition: TargetLibraryInfo.h:221
getBoundsCheckCond
static Value * getBoundsCheckCond(Value *Ptr, Value *InstVal, const DataLayout &DL, TargetLibraryInfo &TLI, ObjectSizeOffsetEvaluator &ObjSizeEval, BuilderTy &IRB, ScalarEvolution &SE)
Gets the conditions under which memory accessing instructions will overflow.
Definition: BoundsChecking.cpp:57
Instructions.h
llvm::Instruction::getParent
const BasicBlock * getParent() const
Definition: Instruction.h:94
llvm::ObjectSizeOffsetEvaluator::bothKnown
bool bothKnown(SizeOffsetEvalType SizeOffset)
Definition: MemoryBuiltins.h:336
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition: InstructionSimplify.h:44
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
llvm::CallInst
This class represents a function call, abstracting a target machine's calling convention.
Definition: Instructions.h:1469
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
llvm::IRBuilderBase::CreateSub
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1229
llvm::DebugLoc
A debug info location.
Definition: DebugLoc.h:33
llvm::cl::desc
Definition: CommandLine.h:412
raw_ostream.h
Value.h
InitializePasses.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::AtomicCmpXchgInst
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:521
Debug.h
llvm::TargetLibraryAnalysis
Analysis pass providing the TargetLibraryInfo.
Definition: TargetLibraryInfo.h:440
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38