1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
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 // This pass statically checks for common and easily-identified constructs
10 // which produce undefined or likely unintended behavior in LLVM IR.
11 //
12 // It is not a guarantee of correctness, in two ways. First, it isn't
13 // comprehensive. There are checks which could be done statically which are
14 // not yet implemented. Some of these are indicated by TODO comments, but
15 // those aren't comprehensive either. Second, many conditions cannot be
16 // checked statically. This pass does no dynamic instrumentation, so it
17 // can't check for all possible problems.
18 //
19 // Another limitation is that it assumes all code will be executed. A store
20 // through a null pointer in a basic block which is never reached is harmless,
21 // but this pass will warn about it anyway. This is the main reason why most
22 // of these checks live here instead of in the Verifier pass.
23 //
24 // Optimization passes may make conditions that this pass checks for more or
25 // less obvious. If an optimization pass appears to be introducing a warning,
26 // it may be that the optimization pass is merely exposing an existing
27 // condition in the code.
28 //
29 // This code may be run before instcombine. In many cases, instcombine checks
30 // for the same kinds of things and turns instructions with undefined behavior
31 // into unreachable (or equivalent). Because of this, this pass makes some
32 // effort to look through bitcasts and so on.
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "llvm/Analysis/Lint.h"
37 #include "llvm/ADT/APInt.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/InstructionSimplify.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/Analysis/MemoryLocation.h"
47 #include "llvm/Analysis/Passes.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/IR/Argument.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/Constant.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/GlobalVariable.h"
59 #include "llvm/IR/InstVisitor.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/LegacyPassManager.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/InitializePasses.h"
69 #include "llvm/Pass.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <cassert>
76 #include <cstdint>
77 #include <iterator>
78 #include <string>
79 
80 using namespace llvm;
81 
82 namespace {
83   namespace MemRef {
84     static const unsigned Read     = 1;
85     static const unsigned Write    = 2;
86     static const unsigned Callee   = 4;
87     static const unsigned Branchee = 8;
88   } // end namespace MemRef
89 
90   class Lint : public FunctionPass, public InstVisitor<Lint> {
91     friend class InstVisitor<Lint>;
92 
93     void visitFunction(Function &F);
94 
95     void visitCallBase(CallBase &CB);
96     void visitMemoryReference(Instruction &I, Value *Ptr,
97                               uint64_t Size, unsigned Align,
98                               Type *Ty, unsigned Flags);
99     void visitEHBeginCatch(IntrinsicInst *II);
100     void visitEHEndCatch(IntrinsicInst *II);
101 
102     void visitReturnInst(ReturnInst &I);
103     void visitLoadInst(LoadInst &I);
104     void visitStoreInst(StoreInst &I);
105     void visitXor(BinaryOperator &I);
106     void visitSub(BinaryOperator &I);
107     void visitLShr(BinaryOperator &I);
108     void visitAShr(BinaryOperator &I);
109     void visitShl(BinaryOperator &I);
110     void visitSDiv(BinaryOperator &I);
111     void visitUDiv(BinaryOperator &I);
112     void visitSRem(BinaryOperator &I);
113     void visitURem(BinaryOperator &I);
114     void visitAllocaInst(AllocaInst &I);
115     void visitVAArgInst(VAArgInst &I);
116     void visitIndirectBrInst(IndirectBrInst &I);
117     void visitExtractElementInst(ExtractElementInst &I);
118     void visitInsertElementInst(InsertElementInst &I);
119     void visitUnreachableInst(UnreachableInst &I);
120 
121     Value *findValue(Value *V, bool OffsetOk) const;
122     Value *findValueImpl(Value *V, bool OffsetOk,
123                          SmallPtrSetImpl<Value *> &Visited) const;
124 
125   public:
126     Module *Mod;
127     const DataLayout *DL;
128     AliasAnalysis *AA;
129     AssumptionCache *AC;
130     DominatorTree *DT;
131     TargetLibraryInfo *TLI;
132 
133     std::string Messages;
134     raw_string_ostream MessagesStr;
135 
136     static char ID; // Pass identification, replacement for typeid
137     Lint() : FunctionPass(ID), MessagesStr(Messages) {
138       initializeLintPass(*PassRegistry::getPassRegistry());
139     }
140 
141     bool runOnFunction(Function &F) override;
142 
143     void getAnalysisUsage(AnalysisUsage &AU) const override {
144       AU.setPreservesAll();
145       AU.addRequired<AAResultsWrapperPass>();
146       AU.addRequired<AssumptionCacheTracker>();
147       AU.addRequired<TargetLibraryInfoWrapperPass>();
148       AU.addRequired<DominatorTreeWrapperPass>();
149     }
150     void print(raw_ostream &O, const Module *M) const override {}
151 
152     void WriteValues(ArrayRef<const Value *> Vs) {
153       for (const Value *V : Vs) {
154         if (!V)
155           continue;
156         if (isa<Instruction>(V)) {
157           MessagesStr << *V << '\n';
158         } else {
159           V->printAsOperand(MessagesStr, true, Mod);
160           MessagesStr << '\n';
161         }
162       }
163     }
164 
165     /// A check failed, so printout out the condition and the message.
166     ///
167     /// This provides a nice place to put a breakpoint if you want to see why
168     /// something is not correct.
169     void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
170 
171     /// A check failed (with values to print).
172     ///
173     /// This calls the Message-only version so that the above is easier to set
174     /// a breakpoint on.
175     template <typename T1, typename... Ts>
176     void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
177       CheckFailed(Message);
178       WriteValues({V1, Vs...});
179     }
180   };
181 } // end anonymous namespace
182 
183 char Lint::ID = 0;
184 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
185                       false, true)
186 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
187 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
188 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
189 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
190 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
191                     false, true)
192 
193 // Assert - We know that cond should be true, if not print an error message.
194 #define Assert(C, ...) \
195     do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
196 
197 // Lint::run - This is the main Analysis entry point for a
198 // function.
199 //
200 bool Lint::runOnFunction(Function &F) {
201   Mod = F.getParent();
202   DL = &F.getParent()->getDataLayout();
203   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
204   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
205   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
206   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
207   visit(F);
208   dbgs() << MessagesStr.str();
209   Messages.clear();
210   return false;
211 }
212 
213 void Lint::visitFunction(Function &F) {
214   // This isn't undefined behavior, it's just a little unusual, and it's a
215   // fairly common mistake to neglect to name a function.
216   Assert(F.hasName() || F.hasLocalLinkage(),
217          "Unusual: Unnamed function with non-local linkage", &F);
218 
219   // TODO: Check for irreducible control flow.
220 }
221 
222 void Lint::visitCallBase(CallBase &I) {
223   Value *Callee = I.getCalledOperand();
224 
225   visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
226                        MemRef::Callee);
227 
228   if (Function *F = dyn_cast<Function>(findValue(Callee,
229                                                  /*OffsetOk=*/false))) {
230     Assert(I.getCallingConv() == F->getCallingConv(),
231            "Undefined behavior: Caller and callee calling convention differ",
232            &I);
233 
234     FunctionType *FT = F->getFunctionType();
235     unsigned NumActualArgs = I.arg_size();
236 
237     Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
238                           : FT->getNumParams() == NumActualArgs,
239            "Undefined behavior: Call argument count mismatches callee "
240            "argument count",
241            &I);
242 
243     Assert(FT->getReturnType() == I.getType(),
244            "Undefined behavior: Call return type mismatches "
245            "callee return type",
246            &I);
247 
248     // Check argument types (in case the callee was casted) and attributes.
249     // TODO: Verify that caller and callee attributes are compatible.
250     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
251     auto AI = I.arg_begin(), AE = I.arg_end();
252     for (; AI != AE; ++AI) {
253       Value *Actual = *AI;
254       if (PI != PE) {
255         Argument *Formal = &*PI++;
256         Assert(Formal->getType() == Actual->getType(),
257                "Undefined behavior: Call argument type mismatches "
258                "callee parameter type",
259                &I);
260 
261         // Check that noalias arguments don't alias other arguments. This is
262         // not fully precise because we don't know the sizes of the dereferenced
263         // memory regions.
264         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) {
265           AttributeList PAL = I.getAttributes();
266           unsigned ArgNo = 0;
267           for (auto BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
268             // Skip ByVal arguments since they will be memcpy'd to the callee's
269             // stack so we're not really passing the pointer anyway.
270             if (PAL.hasParamAttribute(ArgNo, Attribute::ByVal))
271               continue;
272             // If both arguments are readonly, they have no dependence.
273             if (Formal->onlyReadsMemory() && I.onlyReadsMemory(ArgNo))
274               continue;
275             if (AI != BI && (*BI)->getType()->isPointerTy()) {
276               AliasResult Result = AA->alias(*AI, *BI);
277               Assert(Result != MustAlias && Result != PartialAlias,
278                      "Unusual: noalias argument aliases another argument", &I);
279             }
280           }
281         }
282 
283         // Check that an sret argument points to valid memory.
284         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
285           Type *Ty =
286             cast<PointerType>(Formal->getType())->getElementType();
287           visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
288                                DL->getABITypeAlignment(Ty), Ty,
289                                MemRef::Read | MemRef::Write);
290         }
291       }
292     }
293   }
294 
295   if (const auto *CI = dyn_cast<CallInst>(&I)) {
296     if (CI->isTailCall()) {
297       const AttributeList &PAL = CI->getAttributes();
298       unsigned ArgNo = 0;
299       for (Value *Arg : I.args()) {
300         // Skip ByVal arguments since they will be memcpy'd to the callee's
301         // stack anyway.
302         if (PAL.hasParamAttribute(ArgNo++, Attribute::ByVal))
303           continue;
304         Value *Obj = findValue(Arg, /*OffsetOk=*/true);
305         Assert(!isa<AllocaInst>(Obj),
306                "Undefined behavior: Call with \"tail\" keyword references "
307                "alloca",
308                &I);
309       }
310     }
311   }
312 
313 
314   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
315     switch (II->getIntrinsicID()) {
316     default: break;
317 
318     // TODO: Check more intrinsics
319 
320     case Intrinsic::memcpy: {
321       MemCpyInst *MCI = cast<MemCpyInst>(&I);
322       // TODO: If the size is known, use it.
323       visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
324                            MCI->getDestAlignment(), nullptr, MemRef::Write);
325       visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
326                            MCI->getSourceAlignment(), nullptr, MemRef::Read);
327 
328       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
329       // isn't expressive enough for what we really want to do. Known partial
330       // overlap is not distinguished from the case where nothing is known.
331       auto Size = LocationSize::unknown();
332       if (const ConstantInt *Len =
333               dyn_cast<ConstantInt>(findValue(MCI->getLength(),
334                                               /*OffsetOk=*/false)))
335         if (Len->getValue().isIntN(32))
336           Size = LocationSize::precise(Len->getValue().getZExtValue());
337       Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
338                  MustAlias,
339              "Undefined behavior: memcpy source and destination overlap", &I);
340       break;
341     }
342     case Intrinsic::memcpy_inline: {
343       MemCpyInlineInst *MCII = cast<MemCpyInlineInst>(&I);
344       const uint64_t Size = MCII->getLength()->getValue().getLimitedValue();
345       visitMemoryReference(I, MCII->getDest(), Size, MCII->getDestAlignment(),
346                            nullptr, MemRef::Write);
347       visitMemoryReference(I, MCII->getSource(), Size,
348                            MCII->getSourceAlignment(), nullptr, MemRef::Read);
349 
350       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
351       // isn't expressive enough for what we really want to do. Known partial
352       // overlap is not distinguished from the case where nothing is known.
353       const LocationSize LS = LocationSize::precise(Size);
354       Assert(AA->alias(MCII->getSource(), LS, MCII->getDest(), LS) != MustAlias,
355              "Undefined behavior: memcpy source and destination overlap", &I);
356       break;
357     }
358     case Intrinsic::memmove: {
359       MemMoveInst *MMI = cast<MemMoveInst>(&I);
360       // TODO: If the size is known, use it.
361       visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
362                            MMI->getDestAlignment(), nullptr, MemRef::Write);
363       visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
364                            MMI->getSourceAlignment(), nullptr, MemRef::Read);
365       break;
366     }
367     case Intrinsic::memset: {
368       MemSetInst *MSI = cast<MemSetInst>(&I);
369       // TODO: If the size is known, use it.
370       visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
371                            MSI->getDestAlignment(), nullptr, MemRef::Write);
372       break;
373     }
374 
375     case Intrinsic::vastart:
376       Assert(I.getParent()->getParent()->isVarArg(),
377              "Undefined behavior: va_start called in a non-varargs function",
378              &I);
379 
380       visitMemoryReference(I, I.getArgOperand(0), MemoryLocation::UnknownSize,
381                            0, nullptr, MemRef::Read | MemRef::Write);
382       break;
383     case Intrinsic::vacopy:
384       visitMemoryReference(I, I.getArgOperand(0), MemoryLocation::UnknownSize,
385                            0, nullptr, MemRef::Write);
386       visitMemoryReference(I, I.getArgOperand(1), MemoryLocation::UnknownSize,
387                            0, nullptr, MemRef::Read);
388       break;
389     case Intrinsic::vaend:
390       visitMemoryReference(I, I.getArgOperand(0), MemoryLocation::UnknownSize,
391                            0, nullptr, MemRef::Read | MemRef::Write);
392       break;
393 
394     case Intrinsic::stackrestore:
395       // Stackrestore doesn't read or write memory, but it sets the
396       // stack pointer, which the compiler may read from or write to
397       // at any time, so check it for both readability and writeability.
398       visitMemoryReference(I, I.getArgOperand(0), MemoryLocation::UnknownSize,
399                            0, nullptr, MemRef::Read | MemRef::Write);
400       break;
401     }
402 }
403 
404 void Lint::visitReturnInst(ReturnInst &I) {
405   Function *F = I.getParent()->getParent();
406   Assert(!F->doesNotReturn(),
407          "Unusual: Return statement in function with noreturn attribute", &I);
408 
409   if (Value *V = I.getReturnValue()) {
410     Value *Obj = findValue(V, /*OffsetOk=*/true);
411     Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
412   }
413 }
414 
415 // TODO: Check that the reference is in bounds.
416 // TODO: Check readnone/readonly function attributes.
417 void Lint::visitMemoryReference(Instruction &I,
418                                 Value *Ptr, uint64_t Size, unsigned Align,
419                                 Type *Ty, unsigned Flags) {
420   // If no memory is being referenced, it doesn't matter if the pointer
421   // is valid.
422   if (Size == 0)
423     return;
424 
425   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
426   Assert(!isa<ConstantPointerNull>(UnderlyingObject),
427          "Undefined behavior: Null pointer dereference", &I);
428   Assert(!isa<UndefValue>(UnderlyingObject),
429          "Undefined behavior: Undef pointer dereference", &I);
430   Assert(!isa<ConstantInt>(UnderlyingObject) ||
431              !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
432          "Unusual: All-ones pointer dereference", &I);
433   Assert(!isa<ConstantInt>(UnderlyingObject) ||
434              !cast<ConstantInt>(UnderlyingObject)->isOne(),
435          "Unusual: Address one pointer dereference", &I);
436 
437   if (Flags & MemRef::Write) {
438     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
439       Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
440              &I);
441     Assert(!isa<Function>(UnderlyingObject) &&
442                !isa<BlockAddress>(UnderlyingObject),
443            "Undefined behavior: Write to text section", &I);
444   }
445   if (Flags & MemRef::Read) {
446     Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
447            &I);
448     Assert(!isa<BlockAddress>(UnderlyingObject),
449            "Undefined behavior: Load from block address", &I);
450   }
451   if (Flags & MemRef::Callee) {
452     Assert(!isa<BlockAddress>(UnderlyingObject),
453            "Undefined behavior: Call to block address", &I);
454   }
455   if (Flags & MemRef::Branchee) {
456     Assert(!isa<Constant>(UnderlyingObject) ||
457                isa<BlockAddress>(UnderlyingObject),
458            "Undefined behavior: Branch to non-blockaddress", &I);
459   }
460 
461   // Check for buffer overflows and misalignment.
462   // Only handles memory references that read/write something simple like an
463   // alloca instruction or a global variable.
464   int64_t Offset = 0;
465   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
466     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
467     // something we can handle and if so extract the size of this base object
468     // along with its alignment.
469     uint64_t BaseSize = MemoryLocation::UnknownSize;
470     unsigned BaseAlign = 0;
471 
472     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
473       Type *ATy = AI->getAllocatedType();
474       if (!AI->isArrayAllocation() && ATy->isSized())
475         BaseSize = DL->getTypeAllocSize(ATy);
476       BaseAlign = AI->getAlignment();
477       if (BaseAlign == 0 && ATy->isSized())
478         BaseAlign = DL->getABITypeAlignment(ATy);
479     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
480       // If the global may be defined differently in another compilation unit
481       // then don't warn about funky memory accesses.
482       if (GV->hasDefinitiveInitializer()) {
483         Type *GTy = GV->getValueType();
484         if (GTy->isSized())
485           BaseSize = DL->getTypeAllocSize(GTy);
486         BaseAlign = GV->getAlignment();
487         if (BaseAlign == 0 && GTy->isSized())
488           BaseAlign = DL->getABITypeAlignment(GTy);
489       }
490     }
491 
492     // Accesses from before the start or after the end of the object are not
493     // defined.
494     Assert(Size == MemoryLocation::UnknownSize ||
495                BaseSize == MemoryLocation::UnknownSize ||
496                (Offset >= 0 && Offset + Size <= BaseSize),
497            "Undefined behavior: Buffer overflow", &I);
498 
499     // Accesses that say that the memory is more aligned than it is are not
500     // defined.
501     if (Align == 0 && Ty && Ty->isSized())
502       Align = DL->getABITypeAlignment(Ty);
503     Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
504            "Undefined behavior: Memory reference address is misaligned", &I);
505   }
506 }
507 
508 void Lint::visitLoadInst(LoadInst &I) {
509   visitMemoryReference(I, I.getPointerOperand(),
510                        DL->getTypeStoreSize(I.getType()), I.getAlignment(),
511                        I.getType(), MemRef::Read);
512 }
513 
514 void Lint::visitStoreInst(StoreInst &I) {
515   visitMemoryReference(I, I.getPointerOperand(),
516                        DL->getTypeStoreSize(I.getOperand(0)->getType()),
517                        I.getAlignment(),
518                        I.getOperand(0)->getType(), MemRef::Write);
519 }
520 
521 void Lint::visitXor(BinaryOperator &I) {
522   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
523          "Undefined result: xor(undef, undef)", &I);
524 }
525 
526 void Lint::visitSub(BinaryOperator &I) {
527   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
528          "Undefined result: sub(undef, undef)", &I);
529 }
530 
531 void Lint::visitLShr(BinaryOperator &I) {
532   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
533                                                         /*OffsetOk=*/false)))
534     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
535            "Undefined result: Shift count out of range", &I);
536 }
537 
538 void Lint::visitAShr(BinaryOperator &I) {
539   if (ConstantInt *CI =
540           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
541     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
542            "Undefined result: Shift count out of range", &I);
543 }
544 
545 void Lint::visitShl(BinaryOperator &I) {
546   if (ConstantInt *CI =
547           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
548     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
549            "Undefined result: Shift count out of range", &I);
550 }
551 
552 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
553                    AssumptionCache *AC) {
554   // Assume undef could be zero.
555   if (isa<UndefValue>(V))
556     return true;
557 
558   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
559   if (!VecTy) {
560     KnownBits Known = computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT);
561     return Known.isZero();
562   }
563 
564   // Per-component check doesn't work with zeroinitializer
565   Constant *C = dyn_cast<Constant>(V);
566   if (!C)
567     return false;
568 
569   if (C->isZeroValue())
570     return true;
571 
572   // For a vector, KnownZero will only be true if all values are zero, so check
573   // this per component
574   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
575     Constant *Elem = C->getAggregateElement(I);
576     if (isa<UndefValue>(Elem))
577       return true;
578 
579     KnownBits Known = computeKnownBits(Elem, DL);
580     if (Known.isZero())
581       return true;
582   }
583 
584   return false;
585 }
586 
587 void Lint::visitSDiv(BinaryOperator &I) {
588   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
589          "Undefined behavior: Division by zero", &I);
590 }
591 
592 void Lint::visitUDiv(BinaryOperator &I) {
593   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
594          "Undefined behavior: Division by zero", &I);
595 }
596 
597 void Lint::visitSRem(BinaryOperator &I) {
598   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
599          "Undefined behavior: Division by zero", &I);
600 }
601 
602 void Lint::visitURem(BinaryOperator &I) {
603   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
604          "Undefined behavior: Division by zero", &I);
605 }
606 
607 void Lint::visitAllocaInst(AllocaInst &I) {
608   if (isa<ConstantInt>(I.getArraySize()))
609     // This isn't undefined behavior, it's just an obvious pessimization.
610     Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
611            "Pessimization: Static alloca outside of entry block", &I);
612 
613   // TODO: Check for an unusual size (MSB set?)
614 }
615 
616 void Lint::visitVAArgInst(VAArgInst &I) {
617   visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
618                        nullptr, MemRef::Read | MemRef::Write);
619 }
620 
621 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
622   visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
623                        nullptr, MemRef::Branchee);
624 
625   Assert(I.getNumDestinations() != 0,
626          "Undefined behavior: indirectbr with no destinations", &I);
627 }
628 
629 void Lint::visitExtractElementInst(ExtractElementInst &I) {
630   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
631                                                         /*OffsetOk=*/false)))
632     Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
633            "Undefined result: extractelement index out of range", &I);
634 }
635 
636 void Lint::visitInsertElementInst(InsertElementInst &I) {
637   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
638                                                         /*OffsetOk=*/false)))
639     Assert(CI->getValue().ult(I.getType()->getNumElements()),
640            "Undefined result: insertelement index out of range", &I);
641 }
642 
643 void Lint::visitUnreachableInst(UnreachableInst &I) {
644   // This isn't undefined behavior, it's merely suspicious.
645   Assert(&I == &I.getParent()->front() ||
646              std::prev(I.getIterator())->mayHaveSideEffects(),
647          "Unusual: unreachable immediately preceded by instruction without "
648          "side effects",
649          &I);
650 }
651 
652 /// findValue - Look through bitcasts and simple memory reference patterns
653 /// to identify an equivalent, but more informative, value.  If OffsetOk
654 /// is true, look through getelementptrs with non-zero offsets too.
655 ///
656 /// Most analysis passes don't require this logic, because instcombine
657 /// will simplify most of these kinds of things away. But it's a goal of
658 /// this Lint pass to be useful even on non-optimized IR.
659 Value *Lint::findValue(Value *V, bool OffsetOk) const {
660   SmallPtrSet<Value *, 4> Visited;
661   return findValueImpl(V, OffsetOk, Visited);
662 }
663 
664 /// findValueImpl - Implementation helper for findValue.
665 Value *Lint::findValueImpl(Value *V, bool OffsetOk,
666                            SmallPtrSetImpl<Value *> &Visited) const {
667   // Detect self-referential values.
668   if (!Visited.insert(V).second)
669     return UndefValue::get(V->getType());
670 
671   // TODO: Look through sext or zext cast, when the result is known to
672   // be interpreted as signed or unsigned, respectively.
673   // TODO: Look through eliminable cast pairs.
674   // TODO: Look through calls with unique return values.
675   // TODO: Look through vector insert/extract/shuffle.
676   V = OffsetOk ? GetUnderlyingObject(V, *DL) : V->stripPointerCasts();
677   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
678     BasicBlock::iterator BBI = L->getIterator();
679     BasicBlock *BB = L->getParent();
680     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
681     for (;;) {
682       if (!VisitedBlocks.insert(BB).second)
683         break;
684       if (Value *U =
685           FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA))
686         return findValueImpl(U, OffsetOk, Visited);
687       if (BBI != BB->begin()) break;
688       BB = BB->getUniquePredecessor();
689       if (!BB) break;
690       BBI = BB->end();
691     }
692   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
693     if (Value *W = PN->hasConstantValue())
694       if (W != V)
695         return findValueImpl(W, OffsetOk, Visited);
696   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
697     if (CI->isNoopCast(*DL))
698       return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
699   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
700     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
701                                      Ex->getIndices()))
702       if (W != V)
703         return findValueImpl(W, OffsetOk, Visited);
704   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
705     // Same as above, but for ConstantExpr instead of Instruction.
706     if (Instruction::isCast(CE->getOpcode())) {
707       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
708                                CE->getOperand(0)->getType(), CE->getType(),
709                                *DL))
710         return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
711     } else if (CE->getOpcode() == Instruction::ExtractValue) {
712       ArrayRef<unsigned> Indices = CE->getIndices();
713       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
714         if (W != V)
715           return findValueImpl(W, OffsetOk, Visited);
716     }
717   }
718 
719   // As a last resort, try SimplifyInstruction or constant folding.
720   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
721     if (Value *W = SimplifyInstruction(Inst, {*DL, TLI, DT, AC}))
722       return findValueImpl(W, OffsetOk, Visited);
723   } else if (auto *C = dyn_cast<Constant>(V)) {
724     Value *W = ConstantFoldConstant(C, *DL, TLI);
725     if (W != V)
726       return findValueImpl(W, OffsetOk, Visited);
727   }
728 
729   return V;
730 }
731 
732 //===----------------------------------------------------------------------===//
733 //  Implement the public interfaces to this file...
734 //===----------------------------------------------------------------------===//
735 
736 FunctionPass *llvm::createLintPass() {
737   return new Lint();
738 }
739 
740 /// lintFunction - Check a function for errors, printing messages on stderr.
741 ///
742 void llvm::lintFunction(const Function &f) {
743   Function &F = const_cast<Function&>(f);
744   assert(!F.isDeclaration() && "Cannot lint external functions");
745 
746   legacy::FunctionPassManager FPM(F.getParent());
747   Lint *V = new Lint();
748   FPM.add(V);
749   FPM.run(F);
750 }
751 
752 /// lintModule - Check a module for errors, printing messages on stderr.
753 ///
754 void llvm::lintModule(const Module &M) {
755   legacy::PassManager PM;
756   Lint *V = new Lint();
757   PM.add(V);
758   PM.run(const_cast<Module&>(M));
759 }
760