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