1 //===- PoisonChecking.cpp - -----------------------------------------------===// 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 // 9 // Implements a transform pass which instruments IR such that poison semantics 10 // are made explicit. That is, it provides a (possibly partial) executable 11 // semantics for every instruction w.r.t. poison as specified in the LLVM 12 // LangRef. There are obvious parallels to the sanitizer tools, but this pass 13 // is focused purely on the semantics of LLVM IR, not any particular source 14 // language. If you're looking for something to see if your C/C++ contains 15 // UB, this is not it. 16 // 17 // The rewritten semantics of each instruction will include the following 18 // components: 19 // 20 // 1) The original instruction, unmodified. 21 // 2) A propagation rule which translates dynamic information about the poison 22 // state of each input to whether the dynamic output of the instruction 23 // produces poison. 24 // 3) A flag validation rule which validates any poison producing flags on the 25 // instruction itself (e.g. checks for overflow on nsw). 26 // 4) A check rule which traps (to a handler function) if this instruction must 27 // execute undefined behavior given the poison state of it's inputs. 28 // 29 // At the moment, the UB detection is done in a best effort manner; that is, 30 // the resulting code may produce a false negative result (not report UB when 31 // it actually exists according to the LangRef spec), but should never produce 32 // a false positive (report UB where it doesn't exist). The intention is to 33 // eventually support a "strict" mode which never dynamically reports a false 34 // negative at the cost of rejecting some valid inputs to translation. 35 // 36 // Use cases for this pass include: 37 // - Understanding (and testing!) the implications of the definition of poison 38 // from the LangRef. 39 // - Validating the output of a IR fuzzer to ensure that all programs produced 40 // are well defined on the specific input used. 41 // - Finding/confirming poison specific miscompiles by checking the poison 42 // status of an input/IR pair is the same before and after an optimization 43 // transform. 44 // - Checking that a bugpoint reduction does not introduce UB which didn't 45 // exist in the original program being reduced. 46 // 47 // The major sources of inaccuracy are currently: 48 // - Most validation rules not yet implemented for instructions with poison 49 // relavant flags. At the moment, only nsw/nuw on add/sub are supported. 50 // - UB which is control dependent on a branch on poison is not yet 51 // reported. Currently, only data flow dependence is modeled. 52 // - Poison which is propagated through memory is not modeled. As such, 53 // storing poison to memory and then reloading it will cause a false negative 54 // as we consider the reloaded value to not be poisoned. 55 // - Poison propagation across function boundaries is not modeled. At the 56 // moment, all arguments and return values are assumed not to be poison. 57 // - Undef is not modeled. In particular, the optimizer's freedom to pick 58 // concrete values for undef bits so as to maximize potential for producing 59 // poison is not modeled. 60 // 61 //===----------------------------------------------------------------------===// 62 63 #include "llvm/Transforms/Instrumentation/PoisonChecking.h" 64 #include "llvm/ADT/DenseMap.h" 65 #include "llvm/ADT/Statistic.h" 66 #include "llvm/Analysis/MemoryBuiltins.h" 67 #include "llvm/Analysis/ValueTracking.h" 68 #include "llvm/IR/IRBuilder.h" 69 #include "llvm/IR/InstVisitor.h" 70 #include "llvm/IR/IntrinsicInst.h" 71 #include "llvm/IR/PatternMatch.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Debug.h" 74 75 using namespace llvm; 76 77 #define DEBUG_TYPE "poison-checking" 78 79 static cl::opt<bool> 80 LocalCheck("poison-checking-function-local", 81 cl::init(false), 82 cl::desc("Check that returns are non-poison (for testing)")); 83 84 85 static bool isConstantFalse(Value* V) { 86 assert(V->getType()->isIntegerTy(1)); 87 if (auto *CI = dyn_cast<ConstantInt>(V)) 88 return CI->isZero(); 89 return false; 90 } 91 92 static Value *buildOrChain(IRBuilder<> &B, ArrayRef<Value*> Ops) { 93 if (Ops.size() == 0) 94 return B.getFalse(); 95 unsigned i = 0; 96 for (; i < Ops.size() && isConstantFalse(Ops[i]); i++) {} 97 if (i == Ops.size()) 98 return B.getFalse(); 99 Value *Accum = Ops[i++]; 100 for (; i < Ops.size(); i++) 101 if (!isConstantFalse(Ops[i])) 102 Accum = B.CreateOr(Accum, Ops[i]); 103 return Accum; 104 } 105 106 static void generatePoisonChecksForBinOp(Instruction &I, 107 SmallVector<Value*, 2> &Checks) { 108 assert(isa<BinaryOperator>(I)); 109 110 IRBuilder<> B(&I); 111 Value *LHS = I.getOperand(0); 112 Value *RHS = I.getOperand(1); 113 switch (I.getOpcode()) { 114 default: 115 return; 116 case Instruction::Add: { 117 if (I.hasNoSignedWrap()) { 118 auto *OverflowOp = 119 B.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow, LHS, RHS); 120 Checks.push_back(B.CreateExtractValue(OverflowOp, 1)); 121 } 122 if (I.hasNoUnsignedWrap()) { 123 auto *OverflowOp = 124 B.CreateBinaryIntrinsic(Intrinsic::uadd_with_overflow, LHS, RHS); 125 Checks.push_back(B.CreateExtractValue(OverflowOp, 1)); 126 } 127 break; 128 } 129 case Instruction::Sub: { 130 if (I.hasNoSignedWrap()) { 131 auto *OverflowOp = 132 B.CreateBinaryIntrinsic(Intrinsic::ssub_with_overflow, LHS, RHS); 133 Checks.push_back(B.CreateExtractValue(OverflowOp, 1)); 134 } 135 if (I.hasNoUnsignedWrap()) { 136 auto *OverflowOp = 137 B.CreateBinaryIntrinsic(Intrinsic::usub_with_overflow, LHS, RHS); 138 Checks.push_back(B.CreateExtractValue(OverflowOp, 1)); 139 } 140 break; 141 } 142 case Instruction::Mul: { 143 if (I.hasNoSignedWrap()) { 144 auto *OverflowOp = 145 B.CreateBinaryIntrinsic(Intrinsic::smul_with_overflow, LHS, RHS); 146 Checks.push_back(B.CreateExtractValue(OverflowOp, 1)); 147 } 148 if (I.hasNoUnsignedWrap()) { 149 auto *OverflowOp = 150 B.CreateBinaryIntrinsic(Intrinsic::umul_with_overflow, LHS, RHS); 151 Checks.push_back(B.CreateExtractValue(OverflowOp, 1)); 152 } 153 break; 154 } 155 case Instruction::UDiv: { 156 if (I.isExact()) { 157 auto *Check = 158 B.CreateICmp(ICmpInst::ICMP_NE, B.CreateURem(LHS, RHS), 159 ConstantInt::get(LHS->getType(), 0)); 160 Checks.push_back(Check); 161 } 162 break; 163 } 164 case Instruction::SDiv: { 165 if (I.isExact()) { 166 auto *Check = 167 B.CreateICmp(ICmpInst::ICMP_NE, B.CreateSRem(LHS, RHS), 168 ConstantInt::get(LHS->getType(), 0)); 169 Checks.push_back(Check); 170 } 171 break; 172 } 173 case Instruction::AShr: 174 case Instruction::LShr: 175 case Instruction::Shl: { 176 Value *ShiftCheck = 177 B.CreateICmp(ICmpInst::ICMP_UGE, RHS, 178 ConstantInt::get(RHS->getType(), 179 LHS->getType()->getScalarSizeInBits())); 180 Checks.push_back(ShiftCheck); 181 break; 182 } 183 }; 184 } 185 186 static Value* generatePoisonChecks(Instruction &I) { 187 IRBuilder<> B(&I); 188 SmallVector<Value*, 2> Checks; 189 if (isa<BinaryOperator>(I) && !I.getType()->isVectorTy()) 190 generatePoisonChecksForBinOp(I, Checks); 191 192 // Handle non-binops seperately 193 switch (I.getOpcode()) { 194 default: 195 // Note there are a couple of missing cases here, once implemented, this 196 // should become an llvm_unreachable. 197 break; 198 case Instruction::ExtractElement: { 199 Value *Vec = I.getOperand(0); 200 auto *VecVTy = cast<VectorType>(Vec->getType()); 201 if (VecVTy->isScalable()) 202 break; 203 Value *Idx = I.getOperand(1); 204 unsigned NumElts = VecVTy->getNumElements(); 205 Value *Check = 206 B.CreateICmp(ICmpInst::ICMP_UGE, Idx, 207 ConstantInt::get(Idx->getType(), NumElts)); 208 Checks.push_back(Check); 209 break; 210 } 211 case Instruction::InsertElement: { 212 Value *Vec = I.getOperand(0); 213 auto *VecVTy = cast<VectorType>(Vec->getType()); 214 if (VecVTy->isScalable()) 215 break; 216 Value *Idx = I.getOperand(2); 217 unsigned NumElts = VecVTy->getNumElements(); 218 Value *Check = 219 B.CreateICmp(ICmpInst::ICMP_UGE, Idx, 220 ConstantInt::get(Idx->getType(), NumElts)); 221 Checks.push_back(Check); 222 break; 223 } 224 }; 225 return buildOrChain(B, Checks); 226 } 227 228 static Value *getPoisonFor(DenseMap<Value *, Value *> &ValToPoison, Value *V) { 229 auto Itr = ValToPoison.find(V); 230 if (Itr != ValToPoison.end()) 231 return Itr->second; 232 if (isa<Constant>(V)) { 233 return ConstantInt::getFalse(V->getContext()); 234 } 235 // Return false for unknwon values - this implements a non-strict mode where 236 // unhandled IR constructs are simply considered to never produce poison. At 237 // some point in the future, we probably want a "strict mode" for testing if 238 // nothing else. 239 return ConstantInt::getFalse(V->getContext()); 240 } 241 242 static void CreateAssert(IRBuilder<> &B, Value *Cond) { 243 assert(Cond->getType()->isIntegerTy(1)); 244 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 245 if (CI->isAllOnesValue()) 246 return; 247 248 Module *M = B.GetInsertBlock()->getModule(); 249 M->getOrInsertFunction("__poison_checker_assert", 250 Type::getVoidTy(M->getContext()), 251 Type::getInt1Ty(M->getContext())); 252 Function *TrapFunc = M->getFunction("__poison_checker_assert"); 253 B.CreateCall(TrapFunc, Cond); 254 } 255 256 static void CreateAssertNot(IRBuilder<> &B, Value *Cond) { 257 assert(Cond->getType()->isIntegerTy(1)); 258 CreateAssert(B, B.CreateNot(Cond)); 259 } 260 261 static bool rewrite(Function &F) { 262 auto * const Int1Ty = Type::getInt1Ty(F.getContext()); 263 264 DenseMap<Value *, Value *> ValToPoison; 265 266 for (BasicBlock &BB : F) 267 for (auto I = BB.begin(); isa<PHINode>(&*I); I++) { 268 auto *OldPHI = cast<PHINode>(&*I); 269 auto *NewPHI = PHINode::Create(Int1Ty, 270 OldPHI->getNumIncomingValues()); 271 for (unsigned i = 0; i < OldPHI->getNumIncomingValues(); i++) 272 NewPHI->addIncoming(UndefValue::get(Int1Ty), 273 OldPHI->getIncomingBlock(i)); 274 NewPHI->insertBefore(OldPHI); 275 ValToPoison[OldPHI] = NewPHI; 276 } 277 278 for (BasicBlock &BB : F) 279 for (Instruction &I : BB) { 280 if (isa<PHINode>(I)) continue; 281 282 IRBuilder<> B(cast<Instruction>(&I)); 283 284 // Note: There are many more sources of documented UB, but this pass only 285 // attempts to find UB triggered by propagation of poison. 286 if (Value *Op = const_cast<Value*>(getGuaranteedNonFullPoisonOp(&I))) 287 CreateAssertNot(B, getPoisonFor(ValToPoison, Op)); 288 289 if (LocalCheck) 290 if (auto *RI = dyn_cast<ReturnInst>(&I)) 291 if (RI->getNumOperands() != 0) { 292 Value *Op = RI->getOperand(0); 293 CreateAssertNot(B, getPoisonFor(ValToPoison, Op)); 294 } 295 296 SmallVector<Value*, 4> Checks; 297 if (propagatesFullPoison(&I)) 298 for (Value *V : I.operands()) 299 Checks.push_back(getPoisonFor(ValToPoison, V)); 300 301 if (canCreatePoison(&I)) 302 if (auto *Check = generatePoisonChecks(I)) 303 Checks.push_back(Check); 304 ValToPoison[&I] = buildOrChain(B, Checks); 305 } 306 307 for (BasicBlock &BB : F) 308 for (auto I = BB.begin(); isa<PHINode>(&*I); I++) { 309 auto *OldPHI = cast<PHINode>(&*I); 310 if (!ValToPoison.count(OldPHI)) 311 continue; // skip the newly inserted phis 312 auto *NewPHI = cast<PHINode>(ValToPoison[OldPHI]); 313 for (unsigned i = 0; i < OldPHI->getNumIncomingValues(); i++) { 314 auto *OldVal = OldPHI->getIncomingValue(i); 315 NewPHI->setIncomingValue(i, getPoisonFor(ValToPoison, OldVal)); 316 } 317 } 318 return true; 319 } 320 321 322 PreservedAnalyses PoisonCheckingPass::run(Module &M, 323 ModuleAnalysisManager &AM) { 324 bool Changed = false; 325 for (auto &F : M) 326 Changed |= rewrite(F); 327 328 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all(); 329 } 330 331 PreservedAnalyses PoisonCheckingPass::run(Function &F, 332 FunctionAnalysisManager &AM) { 333 return rewrite(F) ? PreservedAnalyses::none() : PreservedAnalyses::all(); 334 } 335 336 337 /* Major TODO Items: 338 - Control dependent poison UB 339 - Strict mode - (i.e. must analyze every operand) 340 - Poison through memory 341 - Function ABIs 342 - Full coverage of intrinsics, etc.. (ouch) 343 344 Instructions w/Unclear Semantics: 345 - shufflevector - It would seem reasonable for an out of bounds mask element 346 to produce poison, but the LangRef does not state. 347 - and/or - It would seem reasonable for poison to propagate from both 348 arguments, but LangRef doesn't state and propagatesFullPoison doesn't 349 include these two. 350 - all binary ops w/vector operands - The likely interpretation would be that 351 any element overflowing should produce poison for the entire result, but 352 the LangRef does not state. 353 - Floating point binary ops w/fmf flags other than (nnan, noinfs). It seems 354 strange that only certian flags should be documented as producing poison. 355 356 Cases of clear poison semantics not yet implemented: 357 - Exact flags on ashr/lshr produce poison 358 - NSW/NUW flags on shl produce poison 359 - Inbounds flag on getelementptr produce poison 360 - fptosi/fptoui (out of bounds input) produce poison 361 - Scalable vector types for insertelement/extractelement 362 - Floating point binary ops w/fmf nnan/noinfs flags produce poison 363 */ 364