xref: /openbsd-src/gnu/llvm/llvm/lib/Analysis/Lint.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This pass statically checks for common and easily-identified constructs
1009467b48Spatrick // which produce undefined or likely unintended behavior in LLVM IR.
1109467b48Spatrick //
1209467b48Spatrick // It is not a guarantee of correctness, in two ways. First, it isn't
1309467b48Spatrick // comprehensive. There are checks which could be done statically which are
1409467b48Spatrick // not yet implemented. Some of these are indicated by TODO comments, but
1509467b48Spatrick // those aren't comprehensive either. Second, many conditions cannot be
1609467b48Spatrick // checked statically. This pass does no dynamic instrumentation, so it
1709467b48Spatrick // can't check for all possible problems.
1809467b48Spatrick //
1909467b48Spatrick // Another limitation is that it assumes all code will be executed. A store
2009467b48Spatrick // through a null pointer in a basic block which is never reached is harmless,
2109467b48Spatrick // but this pass will warn about it anyway. This is the main reason why most
2209467b48Spatrick // of these checks live here instead of in the Verifier pass.
2309467b48Spatrick //
2409467b48Spatrick // Optimization passes may make conditions that this pass checks for more or
2509467b48Spatrick // less obvious. If an optimization pass appears to be introducing a warning,
2609467b48Spatrick // it may be that the optimization pass is merely exposing an existing
2709467b48Spatrick // condition in the code.
2809467b48Spatrick //
2909467b48Spatrick // This code may be run before instcombine. In many cases, instcombine checks
3009467b48Spatrick // for the same kinds of things and turns instructions with undefined behavior
3109467b48Spatrick // into unreachable (or equivalent). Because of this, this pass makes some
3209467b48Spatrick // effort to look through bitcasts and so on.
3309467b48Spatrick //
3409467b48Spatrick //===----------------------------------------------------------------------===//
3509467b48Spatrick 
3609467b48Spatrick #include "llvm/Analysis/Lint.h"
3709467b48Spatrick #include "llvm/ADT/APInt.h"
3809467b48Spatrick #include "llvm/ADT/ArrayRef.h"
3909467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
4009467b48Spatrick #include "llvm/ADT/Twine.h"
4109467b48Spatrick #include "llvm/Analysis/AliasAnalysis.h"
4209467b48Spatrick #include "llvm/Analysis/AssumptionCache.h"
4309467b48Spatrick #include "llvm/Analysis/ConstantFolding.h"
4409467b48Spatrick #include "llvm/Analysis/InstructionSimplify.h"
4509467b48Spatrick #include "llvm/Analysis/Loads.h"
4609467b48Spatrick #include "llvm/Analysis/MemoryLocation.h"
4709467b48Spatrick #include "llvm/Analysis/TargetLibraryInfo.h"
4809467b48Spatrick #include "llvm/Analysis/ValueTracking.h"
4909467b48Spatrick #include "llvm/IR/Argument.h"
5009467b48Spatrick #include "llvm/IR/BasicBlock.h"
5109467b48Spatrick #include "llvm/IR/Constant.h"
5209467b48Spatrick #include "llvm/IR/Constants.h"
5309467b48Spatrick #include "llvm/IR/DataLayout.h"
5409467b48Spatrick #include "llvm/IR/DerivedTypes.h"
5509467b48Spatrick #include "llvm/IR/Dominators.h"
5609467b48Spatrick #include "llvm/IR/Function.h"
5709467b48Spatrick #include "llvm/IR/GlobalVariable.h"
5809467b48Spatrick #include "llvm/IR/InstVisitor.h"
5909467b48Spatrick #include "llvm/IR/InstrTypes.h"
6009467b48Spatrick #include "llvm/IR/Instruction.h"
6109467b48Spatrick #include "llvm/IR/Instructions.h"
6209467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
6309467b48Spatrick #include "llvm/IR/LegacyPassManager.h"
6409467b48Spatrick #include "llvm/IR/Module.h"
6573471bf0Spatrick #include "llvm/IR/PassManager.h"
6609467b48Spatrick #include "llvm/IR/Type.h"
6709467b48Spatrick #include "llvm/IR/Value.h"
6809467b48Spatrick #include "llvm/InitializePasses.h"
6909467b48Spatrick #include "llvm/Pass.h"
7009467b48Spatrick #include "llvm/Support/Casting.h"
7109467b48Spatrick #include "llvm/Support/KnownBits.h"
7209467b48Spatrick #include "llvm/Support/raw_ostream.h"
7309467b48Spatrick #include <cassert>
7409467b48Spatrick #include <cstdint>
7509467b48Spatrick #include <iterator>
7609467b48Spatrick #include <string>
7709467b48Spatrick 
7809467b48Spatrick using namespace llvm;
7909467b48Spatrick 
8009467b48Spatrick namespace {
8109467b48Spatrick namespace MemRef {
8209467b48Spatrick static const unsigned Read = 1;
8309467b48Spatrick static const unsigned Write = 2;
8409467b48Spatrick static const unsigned Callee = 4;
8509467b48Spatrick static const unsigned Branchee = 8;
8609467b48Spatrick } // end namespace MemRef
8709467b48Spatrick 
8873471bf0Spatrick class Lint : public InstVisitor<Lint> {
8909467b48Spatrick   friend class InstVisitor<Lint>;
9009467b48Spatrick 
9109467b48Spatrick   void visitFunction(Function &F);
9209467b48Spatrick 
93097a140dSpatrick   void visitCallBase(CallBase &CB);
9473471bf0Spatrick   void visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
95097a140dSpatrick                             MaybeAlign Alignment, Type *Ty, unsigned Flags);
9609467b48Spatrick   void visitEHBeginCatch(IntrinsicInst *II);
9709467b48Spatrick   void visitEHEndCatch(IntrinsicInst *II);
9809467b48Spatrick 
9909467b48Spatrick   void visitReturnInst(ReturnInst &I);
10009467b48Spatrick   void visitLoadInst(LoadInst &I);
10109467b48Spatrick   void visitStoreInst(StoreInst &I);
10209467b48Spatrick   void visitXor(BinaryOperator &I);
10309467b48Spatrick   void visitSub(BinaryOperator &I);
10409467b48Spatrick   void visitLShr(BinaryOperator &I);
10509467b48Spatrick   void visitAShr(BinaryOperator &I);
10609467b48Spatrick   void visitShl(BinaryOperator &I);
10709467b48Spatrick   void visitSDiv(BinaryOperator &I);
10809467b48Spatrick   void visitUDiv(BinaryOperator &I);
10909467b48Spatrick   void visitSRem(BinaryOperator &I);
11009467b48Spatrick   void visitURem(BinaryOperator &I);
11109467b48Spatrick   void visitAllocaInst(AllocaInst &I);
11209467b48Spatrick   void visitVAArgInst(VAArgInst &I);
11309467b48Spatrick   void visitIndirectBrInst(IndirectBrInst &I);
11409467b48Spatrick   void visitExtractElementInst(ExtractElementInst &I);
11509467b48Spatrick   void visitInsertElementInst(InsertElementInst &I);
11609467b48Spatrick   void visitUnreachableInst(UnreachableInst &I);
11709467b48Spatrick 
11809467b48Spatrick   Value *findValue(Value *V, bool OffsetOk) const;
11909467b48Spatrick   Value *findValueImpl(Value *V, bool OffsetOk,
12009467b48Spatrick                        SmallPtrSetImpl<Value *> &Visited) const;
12109467b48Spatrick 
12209467b48Spatrick public:
12309467b48Spatrick   Module *Mod;
12409467b48Spatrick   const DataLayout *DL;
12509467b48Spatrick   AliasAnalysis *AA;
12609467b48Spatrick   AssumptionCache *AC;
12709467b48Spatrick   DominatorTree *DT;
12809467b48Spatrick   TargetLibraryInfo *TLI;
12909467b48Spatrick 
13009467b48Spatrick   std::string Messages;
13109467b48Spatrick   raw_string_ostream MessagesStr;
13209467b48Spatrick 
Lint(Module * Mod,const DataLayout * DL,AliasAnalysis * AA,AssumptionCache * AC,DominatorTree * DT,TargetLibraryInfo * TLI)13373471bf0Spatrick   Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
13473471bf0Spatrick        AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI)
13573471bf0Spatrick       : Mod(Mod), DL(DL), AA(AA), AC(AC), DT(DT), TLI(TLI),
13673471bf0Spatrick         MessagesStr(Messages) {}
13709467b48Spatrick 
WriteValues(ArrayRef<const Value * > Vs)13809467b48Spatrick   void WriteValues(ArrayRef<const Value *> Vs) {
13909467b48Spatrick     for (const Value *V : Vs) {
14009467b48Spatrick       if (!V)
14109467b48Spatrick         continue;
14209467b48Spatrick       if (isa<Instruction>(V)) {
14309467b48Spatrick         MessagesStr << *V << '\n';
14409467b48Spatrick       } else {
14509467b48Spatrick         V->printAsOperand(MessagesStr, true, Mod);
14609467b48Spatrick         MessagesStr << '\n';
14709467b48Spatrick       }
14809467b48Spatrick     }
14909467b48Spatrick   }
15009467b48Spatrick 
15109467b48Spatrick   /// A check failed, so printout out the condition and the message.
15209467b48Spatrick   ///
15309467b48Spatrick   /// This provides a nice place to put a breakpoint if you want to see why
15409467b48Spatrick   /// something is not correct.
CheckFailed(const Twine & Message)15509467b48Spatrick   void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
15609467b48Spatrick 
15709467b48Spatrick   /// A check failed (with values to print).
15809467b48Spatrick   ///
15909467b48Spatrick   /// This calls the Message-only version so that the above is easier to set
16009467b48Spatrick   /// a breakpoint on.
16109467b48Spatrick   template <typename T1, typename... Ts>
CheckFailed(const Twine & Message,const T1 & V1,const Ts &...Vs)16209467b48Spatrick   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
16309467b48Spatrick     CheckFailed(Message);
16409467b48Spatrick     WriteValues({V1, Vs...});
16509467b48Spatrick   }
16609467b48Spatrick };
16709467b48Spatrick } // end anonymous namespace
16809467b48Spatrick 
169*d415bd75Srobert // Check - We know that cond should be true, if not print an error message.
170*d415bd75Srobert #define Check(C, ...)                                                          \
17173471bf0Spatrick   do {                                                                         \
17273471bf0Spatrick     if (!(C)) {                                                                \
17373471bf0Spatrick       CheckFailed(__VA_ARGS__);                                                \
17473471bf0Spatrick       return;                                                                  \
17573471bf0Spatrick     }                                                                          \
17673471bf0Spatrick   } while (false)
17709467b48Spatrick 
visitFunction(Function & F)17809467b48Spatrick void Lint::visitFunction(Function &F) {
17909467b48Spatrick   // This isn't undefined behavior, it's just a little unusual, and it's a
18009467b48Spatrick   // fairly common mistake to neglect to name a function.
181*d415bd75Srobert   Check(F.hasName() || F.hasLocalLinkage(),
18209467b48Spatrick         "Unusual: Unnamed function with non-local linkage", &F);
18309467b48Spatrick 
18409467b48Spatrick   // TODO: Check for irreducible control flow.
18509467b48Spatrick }
18609467b48Spatrick 
visitCallBase(CallBase & I)187097a140dSpatrick void Lint::visitCallBase(CallBase &I) {
188097a140dSpatrick   Value *Callee = I.getCalledOperand();
18909467b48Spatrick 
190*d415bd75Srobert   visitMemoryReference(I, MemoryLocation::getAfter(Callee), std::nullopt,
191*d415bd75Srobert                        nullptr, MemRef::Callee);
19209467b48Spatrick 
19309467b48Spatrick   if (Function *F = dyn_cast<Function>(findValue(Callee,
19409467b48Spatrick                                                  /*OffsetOk=*/false))) {
195*d415bd75Srobert     Check(I.getCallingConv() == F->getCallingConv(),
19609467b48Spatrick           "Undefined behavior: Caller and callee calling convention differ",
19709467b48Spatrick           &I);
19809467b48Spatrick 
19909467b48Spatrick     FunctionType *FT = F->getFunctionType();
200097a140dSpatrick     unsigned NumActualArgs = I.arg_size();
20109467b48Spatrick 
202*d415bd75Srobert     Check(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
20309467b48Spatrick                          : FT->getNumParams() == NumActualArgs,
20409467b48Spatrick           "Undefined behavior: Call argument count mismatches callee "
20509467b48Spatrick           "argument count",
20609467b48Spatrick           &I);
20709467b48Spatrick 
208*d415bd75Srobert     Check(FT->getReturnType() == I.getType(),
20909467b48Spatrick           "Undefined behavior: Call return type mismatches "
21009467b48Spatrick           "callee return type",
21109467b48Spatrick           &I);
21209467b48Spatrick 
21309467b48Spatrick     // Check argument types (in case the callee was casted) and attributes.
21409467b48Spatrick     // TODO: Verify that caller and callee attributes are compatible.
21509467b48Spatrick     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
216097a140dSpatrick     auto AI = I.arg_begin(), AE = I.arg_end();
21709467b48Spatrick     for (; AI != AE; ++AI) {
21809467b48Spatrick       Value *Actual = *AI;
21909467b48Spatrick       if (PI != PE) {
22009467b48Spatrick         Argument *Formal = &*PI++;
221*d415bd75Srobert         Check(Formal->getType() == Actual->getType(),
22209467b48Spatrick               "Undefined behavior: Call argument type mismatches "
22309467b48Spatrick               "callee parameter type",
22409467b48Spatrick               &I);
22509467b48Spatrick 
22609467b48Spatrick         // Check that noalias arguments don't alias other arguments. This is
22709467b48Spatrick         // not fully precise because we don't know the sizes of the dereferenced
22809467b48Spatrick         // memory regions.
22909467b48Spatrick         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) {
230097a140dSpatrick           AttributeList PAL = I.getAttributes();
23109467b48Spatrick           unsigned ArgNo = 0;
232*d415bd75Srobert           for (auto *BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
23309467b48Spatrick             // Skip ByVal arguments since they will be memcpy'd to the callee's
23409467b48Spatrick             // stack so we're not really passing the pointer anyway.
235*d415bd75Srobert             if (PAL.hasParamAttr(ArgNo, Attribute::ByVal))
23609467b48Spatrick               continue;
23709467b48Spatrick             // If both arguments are readonly, they have no dependence.
238097a140dSpatrick             if (Formal->onlyReadsMemory() && I.onlyReadsMemory(ArgNo))
23909467b48Spatrick               continue;
24009467b48Spatrick             if (AI != BI && (*BI)->getType()->isPointerTy()) {
24109467b48Spatrick               AliasResult Result = AA->alias(*AI, *BI);
242*d415bd75Srobert               Check(Result != AliasResult::MustAlias &&
24373471bf0Spatrick                         Result != AliasResult::PartialAlias,
24409467b48Spatrick                     "Unusual: noalias argument aliases another argument", &I);
24509467b48Spatrick             }
24609467b48Spatrick           }
24709467b48Spatrick         }
24809467b48Spatrick 
24909467b48Spatrick         // Check that an sret argument points to valid memory.
25009467b48Spatrick         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
25173471bf0Spatrick           Type *Ty = Formal->getParamStructRetType();
25273471bf0Spatrick           MemoryLocation Loc(
25373471bf0Spatrick               Actual, LocationSize::precise(DL->getTypeStoreSize(Ty)));
25473471bf0Spatrick           visitMemoryReference(I, Loc, DL->getABITypeAlign(Ty), Ty,
25509467b48Spatrick                                MemRef::Read | MemRef::Write);
25609467b48Spatrick         }
25709467b48Spatrick       }
25809467b48Spatrick     }
25909467b48Spatrick   }
26009467b48Spatrick 
261097a140dSpatrick   if (const auto *CI = dyn_cast<CallInst>(&I)) {
26209467b48Spatrick     if (CI->isTailCall()) {
26309467b48Spatrick       const AttributeList &PAL = CI->getAttributes();
26409467b48Spatrick       unsigned ArgNo = 0;
265097a140dSpatrick       for (Value *Arg : I.args()) {
26609467b48Spatrick         // Skip ByVal arguments since they will be memcpy'd to the callee's
26709467b48Spatrick         // stack anyway.
268*d415bd75Srobert         if (PAL.hasParamAttr(ArgNo++, Attribute::ByVal))
26909467b48Spatrick           continue;
27009467b48Spatrick         Value *Obj = findValue(Arg, /*OffsetOk=*/true);
271*d415bd75Srobert         Check(!isa<AllocaInst>(Obj),
27209467b48Spatrick               "Undefined behavior: Call with \"tail\" keyword references "
27309467b48Spatrick               "alloca",
27409467b48Spatrick               &I);
27509467b48Spatrick       }
27609467b48Spatrick     }
27709467b48Spatrick   }
27809467b48Spatrick 
27909467b48Spatrick   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
28009467b48Spatrick     switch (II->getIntrinsicID()) {
28173471bf0Spatrick     default:
28273471bf0Spatrick       break;
28309467b48Spatrick 
28409467b48Spatrick       // TODO: Check more intrinsics
28509467b48Spatrick 
28609467b48Spatrick     case Intrinsic::memcpy: {
28709467b48Spatrick       MemCpyInst *MCI = cast<MemCpyInst>(&I);
28873471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForDest(MCI),
289097a140dSpatrick                            MCI->getDestAlign(), nullptr, MemRef::Write);
29073471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForSource(MCI),
291097a140dSpatrick                            MCI->getSourceAlign(), nullptr, MemRef::Read);
29209467b48Spatrick 
29309467b48Spatrick       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
29409467b48Spatrick       // isn't expressive enough for what we really want to do. Known partial
29509467b48Spatrick       // overlap is not distinguished from the case where nothing is known.
29673471bf0Spatrick       auto Size = LocationSize::afterPointer();
29709467b48Spatrick       if (const ConstantInt *Len =
29809467b48Spatrick               dyn_cast<ConstantInt>(findValue(MCI->getLength(),
29909467b48Spatrick                                               /*OffsetOk=*/false)))
30009467b48Spatrick         if (Len->getValue().isIntN(32))
30109467b48Spatrick           Size = LocationSize::precise(Len->getValue().getZExtValue());
302*d415bd75Srobert       Check(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
30373471bf0Spatrick                 AliasResult::MustAlias,
30409467b48Spatrick             "Undefined behavior: memcpy source and destination overlap", &I);
30509467b48Spatrick       break;
30609467b48Spatrick     }
307097a140dSpatrick     case Intrinsic::memcpy_inline: {
308097a140dSpatrick       MemCpyInlineInst *MCII = cast<MemCpyInlineInst>(&I);
309097a140dSpatrick       const uint64_t Size = MCII->getLength()->getValue().getLimitedValue();
31073471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForDest(MCII),
31173471bf0Spatrick                            MCII->getDestAlign(), nullptr, MemRef::Write);
31273471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForSource(MCII),
31373471bf0Spatrick                            MCII->getSourceAlign(), nullptr, MemRef::Read);
314097a140dSpatrick 
315097a140dSpatrick       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
316097a140dSpatrick       // isn't expressive enough for what we really want to do. Known partial
317097a140dSpatrick       // overlap is not distinguished from the case where nothing is known.
318097a140dSpatrick       const LocationSize LS = LocationSize::precise(Size);
319*d415bd75Srobert       Check(AA->alias(MCII->getSource(), LS, MCII->getDest(), LS) !=
32073471bf0Spatrick                 AliasResult::MustAlias,
321097a140dSpatrick             "Undefined behavior: memcpy source and destination overlap", &I);
322097a140dSpatrick       break;
323097a140dSpatrick     }
32409467b48Spatrick     case Intrinsic::memmove: {
32509467b48Spatrick       MemMoveInst *MMI = cast<MemMoveInst>(&I);
32673471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForDest(MMI),
327097a140dSpatrick                            MMI->getDestAlign(), nullptr, MemRef::Write);
32873471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForSource(MMI),
329097a140dSpatrick                            MMI->getSourceAlign(), nullptr, MemRef::Read);
33009467b48Spatrick       break;
33109467b48Spatrick     }
33209467b48Spatrick     case Intrinsic::memset: {
33309467b48Spatrick       MemSetInst *MSI = cast<MemSetInst>(&I);
33473471bf0Spatrick       visitMemoryReference(I, MemoryLocation::getForDest(MSI),
335097a140dSpatrick                            MSI->getDestAlign(), nullptr, MemRef::Write);
33609467b48Spatrick       break;
33709467b48Spatrick     }
338*d415bd75Srobert     case Intrinsic::memset_inline: {
339*d415bd75Srobert       MemSetInlineInst *MSII = cast<MemSetInlineInst>(&I);
340*d415bd75Srobert       visitMemoryReference(I, MemoryLocation::getForDest(MSII),
341*d415bd75Srobert                            MSII->getDestAlign(), nullptr, MemRef::Write);
342*d415bd75Srobert       break;
343*d415bd75Srobert     }
34409467b48Spatrick 
34509467b48Spatrick     case Intrinsic::vastart:
346*d415bd75Srobert       Check(I.getParent()->getParent()->isVarArg(),
34709467b48Spatrick             "Undefined behavior: va_start called in a non-varargs function",
34809467b48Spatrick             &I);
34909467b48Spatrick 
350*d415bd75Srobert       visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
351*d415bd75Srobert                            std::nullopt, nullptr, MemRef::Read | MemRef::Write);
35209467b48Spatrick       break;
35309467b48Spatrick     case Intrinsic::vacopy:
354*d415bd75Srobert       visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
355*d415bd75Srobert                            std::nullopt, nullptr, MemRef::Write);
356*d415bd75Srobert       visitMemoryReference(I, MemoryLocation::getForArgument(&I, 1, TLI),
357*d415bd75Srobert                            std::nullopt, nullptr, MemRef::Read);
35809467b48Spatrick       break;
35909467b48Spatrick     case Intrinsic::vaend:
360*d415bd75Srobert       visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
361*d415bd75Srobert                            std::nullopt, nullptr, MemRef::Read | MemRef::Write);
36209467b48Spatrick       break;
36309467b48Spatrick 
36409467b48Spatrick     case Intrinsic::stackrestore:
36509467b48Spatrick       // Stackrestore doesn't read or write memory, but it sets the
36609467b48Spatrick       // stack pointer, which the compiler may read from or write to
36709467b48Spatrick       // at any time, so check it for both readability and writeability.
368*d415bd75Srobert       visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
369*d415bd75Srobert                            std::nullopt, nullptr, MemRef::Read | MemRef::Write);
37073471bf0Spatrick       break;
37173471bf0Spatrick     case Intrinsic::get_active_lane_mask:
37273471bf0Spatrick       if (auto *TripCount = dyn_cast<ConstantInt>(I.getArgOperand(1)))
373*d415bd75Srobert         Check(!TripCount->isZero(),
374*d415bd75Srobert               "get_active_lane_mask: operand #2 "
375*d415bd75Srobert               "must be greater than 0",
376*d415bd75Srobert               &I);
37709467b48Spatrick       break;
37809467b48Spatrick     }
37909467b48Spatrick }
38009467b48Spatrick 
visitReturnInst(ReturnInst & I)38109467b48Spatrick void Lint::visitReturnInst(ReturnInst &I) {
38209467b48Spatrick   Function *F = I.getParent()->getParent();
383*d415bd75Srobert   Check(!F->doesNotReturn(),
38409467b48Spatrick         "Unusual: Return statement in function with noreturn attribute", &I);
38509467b48Spatrick 
38609467b48Spatrick   if (Value *V = I.getReturnValue()) {
38709467b48Spatrick     Value *Obj = findValue(V, /*OffsetOk=*/true);
388*d415bd75Srobert     Check(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
38909467b48Spatrick   }
39009467b48Spatrick }
39109467b48Spatrick 
39209467b48Spatrick // TODO: Check that the reference is in bounds.
39309467b48Spatrick // TODO: Check readnone/readonly function attributes.
visitMemoryReference(Instruction & I,const MemoryLocation & Loc,MaybeAlign Align,Type * Ty,unsigned Flags)39473471bf0Spatrick void Lint::visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
395097a140dSpatrick                                 MaybeAlign Align, Type *Ty, unsigned Flags) {
39609467b48Spatrick   // If no memory is being referenced, it doesn't matter if the pointer
39709467b48Spatrick   // is valid.
39873471bf0Spatrick   if (Loc.Size.isZero())
39909467b48Spatrick     return;
40009467b48Spatrick 
40173471bf0Spatrick   Value *Ptr = const_cast<Value *>(Loc.Ptr);
40209467b48Spatrick   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
403*d415bd75Srobert   Check(!isa<ConstantPointerNull>(UnderlyingObject),
40409467b48Spatrick         "Undefined behavior: Null pointer dereference", &I);
405*d415bd75Srobert   Check(!isa<UndefValue>(UnderlyingObject),
40609467b48Spatrick         "Undefined behavior: Undef pointer dereference", &I);
407*d415bd75Srobert   Check(!isa<ConstantInt>(UnderlyingObject) ||
40809467b48Spatrick             !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
40909467b48Spatrick         "Unusual: All-ones pointer dereference", &I);
410*d415bd75Srobert   Check(!isa<ConstantInt>(UnderlyingObject) ||
41109467b48Spatrick             !cast<ConstantInt>(UnderlyingObject)->isOne(),
41209467b48Spatrick         "Unusual: Address one pointer dereference", &I);
41309467b48Spatrick 
41409467b48Spatrick   if (Flags & MemRef::Write) {
41509467b48Spatrick     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
416*d415bd75Srobert       Check(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
41709467b48Spatrick             &I);
418*d415bd75Srobert     Check(!isa<Function>(UnderlyingObject) &&
41909467b48Spatrick               !isa<BlockAddress>(UnderlyingObject),
42009467b48Spatrick           "Undefined behavior: Write to text section", &I);
42109467b48Spatrick   }
42209467b48Spatrick   if (Flags & MemRef::Read) {
423*d415bd75Srobert     Check(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
42409467b48Spatrick           &I);
425*d415bd75Srobert     Check(!isa<BlockAddress>(UnderlyingObject),
42609467b48Spatrick           "Undefined behavior: Load from block address", &I);
42709467b48Spatrick   }
42809467b48Spatrick   if (Flags & MemRef::Callee) {
429*d415bd75Srobert     Check(!isa<BlockAddress>(UnderlyingObject),
43009467b48Spatrick           "Undefined behavior: Call to block address", &I);
43109467b48Spatrick   }
43209467b48Spatrick   if (Flags & MemRef::Branchee) {
433*d415bd75Srobert     Check(!isa<Constant>(UnderlyingObject) ||
43409467b48Spatrick               isa<BlockAddress>(UnderlyingObject),
43509467b48Spatrick           "Undefined behavior: Branch to non-blockaddress", &I);
43609467b48Spatrick   }
43709467b48Spatrick 
43809467b48Spatrick   // Check for buffer overflows and misalignment.
43909467b48Spatrick   // Only handles memory references that read/write something simple like an
44009467b48Spatrick   // alloca instruction or a global variable.
44109467b48Spatrick   int64_t Offset = 0;
44209467b48Spatrick   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
44309467b48Spatrick     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
44409467b48Spatrick     // something we can handle and if so extract the size of this base object
44509467b48Spatrick     // along with its alignment.
44609467b48Spatrick     uint64_t BaseSize = MemoryLocation::UnknownSize;
447097a140dSpatrick     MaybeAlign BaseAlign;
44809467b48Spatrick 
44909467b48Spatrick     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
45009467b48Spatrick       Type *ATy = AI->getAllocatedType();
45109467b48Spatrick       if (!AI->isArrayAllocation() && ATy->isSized())
45209467b48Spatrick         BaseSize = DL->getTypeAllocSize(ATy);
453097a140dSpatrick       BaseAlign = AI->getAlign();
45409467b48Spatrick     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
45509467b48Spatrick       // If the global may be defined differently in another compilation unit
45609467b48Spatrick       // then don't warn about funky memory accesses.
45709467b48Spatrick       if (GV->hasDefinitiveInitializer()) {
45809467b48Spatrick         Type *GTy = GV->getValueType();
45909467b48Spatrick         if (GTy->isSized())
46009467b48Spatrick           BaseSize = DL->getTypeAllocSize(GTy);
461097a140dSpatrick         BaseAlign = GV->getAlign();
462097a140dSpatrick         if (!BaseAlign && GTy->isSized())
463097a140dSpatrick           BaseAlign = DL->getABITypeAlign(GTy);
46409467b48Spatrick       }
46509467b48Spatrick     }
46609467b48Spatrick 
46709467b48Spatrick     // Accesses from before the start or after the end of the object are not
46809467b48Spatrick     // defined.
469*d415bd75Srobert     Check(!Loc.Size.hasValue() || BaseSize == MemoryLocation::UnknownSize ||
47073471bf0Spatrick               (Offset >= 0 && Offset + Loc.Size.getValue() <= BaseSize),
47109467b48Spatrick           "Undefined behavior: Buffer overflow", &I);
47209467b48Spatrick 
47309467b48Spatrick     // Accesses that say that the memory is more aligned than it is are not
47409467b48Spatrick     // defined.
475097a140dSpatrick     if (!Align && Ty && Ty->isSized())
476097a140dSpatrick       Align = DL->getABITypeAlign(Ty);
477097a140dSpatrick     if (BaseAlign && Align)
478*d415bd75Srobert       Check(*Align <= commonAlignment(*BaseAlign, Offset),
47909467b48Spatrick             "Undefined behavior: Memory reference address is misaligned", &I);
48009467b48Spatrick   }
48109467b48Spatrick }
48209467b48Spatrick 
visitLoadInst(LoadInst & I)48309467b48Spatrick void Lint::visitLoadInst(LoadInst &I) {
48473471bf0Spatrick   visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), I.getType(),
48573471bf0Spatrick                        MemRef::Read);
48609467b48Spatrick }
48709467b48Spatrick 
visitStoreInst(StoreInst & I)48809467b48Spatrick void Lint::visitStoreInst(StoreInst &I) {
48973471bf0Spatrick   visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(),
49073471bf0Spatrick                        I.getOperand(0)->getType(), MemRef::Write);
49109467b48Spatrick }
49209467b48Spatrick 
visitXor(BinaryOperator & I)49309467b48Spatrick void Lint::visitXor(BinaryOperator &I) {
494*d415bd75Srobert   Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
49509467b48Spatrick         "Undefined result: xor(undef, undef)", &I);
49609467b48Spatrick }
49709467b48Spatrick 
visitSub(BinaryOperator & I)49809467b48Spatrick void Lint::visitSub(BinaryOperator &I) {
499*d415bd75Srobert   Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
50009467b48Spatrick         "Undefined result: sub(undef, undef)", &I);
50109467b48Spatrick }
50209467b48Spatrick 
visitLShr(BinaryOperator & I)50309467b48Spatrick void Lint::visitLShr(BinaryOperator &I) {
50409467b48Spatrick   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
50509467b48Spatrick                                                         /*OffsetOk=*/false)))
506*d415bd75Srobert     Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
50709467b48Spatrick           "Undefined result: Shift count out of range", &I);
50809467b48Spatrick }
50909467b48Spatrick 
visitAShr(BinaryOperator & I)51009467b48Spatrick void Lint::visitAShr(BinaryOperator &I) {
51109467b48Spatrick   if (ConstantInt *CI =
51209467b48Spatrick           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
513*d415bd75Srobert     Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
51409467b48Spatrick           "Undefined result: Shift count out of range", &I);
51509467b48Spatrick }
51609467b48Spatrick 
visitShl(BinaryOperator & I)51709467b48Spatrick void Lint::visitShl(BinaryOperator &I) {
51809467b48Spatrick   if (ConstantInt *CI =
51909467b48Spatrick           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
520*d415bd75Srobert     Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
52109467b48Spatrick           "Undefined result: Shift count out of range", &I);
52209467b48Spatrick }
52309467b48Spatrick 
isZero(Value * V,const DataLayout & DL,DominatorTree * DT,AssumptionCache * AC)52409467b48Spatrick static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
52509467b48Spatrick                    AssumptionCache *AC) {
52609467b48Spatrick   // Assume undef could be zero.
52709467b48Spatrick   if (isa<UndefValue>(V))
52809467b48Spatrick     return true;
52909467b48Spatrick 
53009467b48Spatrick   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
53109467b48Spatrick   if (!VecTy) {
53273471bf0Spatrick     KnownBits Known =
53373471bf0Spatrick         computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT);
53409467b48Spatrick     return Known.isZero();
53509467b48Spatrick   }
53609467b48Spatrick 
53709467b48Spatrick   // Per-component check doesn't work with zeroinitializer
53809467b48Spatrick   Constant *C = dyn_cast<Constant>(V);
53909467b48Spatrick   if (!C)
54009467b48Spatrick     return false;
54109467b48Spatrick 
54209467b48Spatrick   if (C->isZeroValue())
54309467b48Spatrick     return true;
54409467b48Spatrick 
54509467b48Spatrick   // For a vector, KnownZero will only be true if all values are zero, so check
54609467b48Spatrick   // this per component
54773471bf0Spatrick   for (unsigned I = 0, N = cast<FixedVectorType>(VecTy)->getNumElements();
54873471bf0Spatrick        I != N; ++I) {
54909467b48Spatrick     Constant *Elem = C->getAggregateElement(I);
55009467b48Spatrick     if (isa<UndefValue>(Elem))
55109467b48Spatrick       return true;
55209467b48Spatrick 
55309467b48Spatrick     KnownBits Known = computeKnownBits(Elem, DL);
55409467b48Spatrick     if (Known.isZero())
55509467b48Spatrick       return true;
55609467b48Spatrick   }
55709467b48Spatrick 
55809467b48Spatrick   return false;
55909467b48Spatrick }
56009467b48Spatrick 
visitSDiv(BinaryOperator & I)56109467b48Spatrick void Lint::visitSDiv(BinaryOperator &I) {
562*d415bd75Srobert   Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
56309467b48Spatrick         "Undefined behavior: Division by zero", &I);
56409467b48Spatrick }
56509467b48Spatrick 
visitUDiv(BinaryOperator & I)56609467b48Spatrick void Lint::visitUDiv(BinaryOperator &I) {
567*d415bd75Srobert   Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
56809467b48Spatrick         "Undefined behavior: Division by zero", &I);
56909467b48Spatrick }
57009467b48Spatrick 
visitSRem(BinaryOperator & I)57109467b48Spatrick void Lint::visitSRem(BinaryOperator &I) {
572*d415bd75Srobert   Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
57309467b48Spatrick         "Undefined behavior: Division by zero", &I);
57409467b48Spatrick }
57509467b48Spatrick 
visitURem(BinaryOperator & I)57609467b48Spatrick void Lint::visitURem(BinaryOperator &I) {
577*d415bd75Srobert   Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
57809467b48Spatrick         "Undefined behavior: Division by zero", &I);
57909467b48Spatrick }
58009467b48Spatrick 
visitAllocaInst(AllocaInst & I)58109467b48Spatrick void Lint::visitAllocaInst(AllocaInst &I) {
58209467b48Spatrick   if (isa<ConstantInt>(I.getArraySize()))
58309467b48Spatrick     // This isn't undefined behavior, it's just an obvious pessimization.
584*d415bd75Srobert     Check(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
58509467b48Spatrick           "Pessimization: Static alloca outside of entry block", &I);
58609467b48Spatrick 
58709467b48Spatrick   // TODO: Check for an unusual size (MSB set?)
58809467b48Spatrick }
58909467b48Spatrick 
visitVAArgInst(VAArgInst & I)59009467b48Spatrick void Lint::visitVAArgInst(VAArgInst &I) {
591*d415bd75Srobert   visitMemoryReference(I, MemoryLocation::get(&I), std::nullopt, nullptr,
59273471bf0Spatrick                        MemRef::Read | MemRef::Write);
59309467b48Spatrick }
59409467b48Spatrick 
visitIndirectBrInst(IndirectBrInst & I)59509467b48Spatrick void Lint::visitIndirectBrInst(IndirectBrInst &I) {
596*d415bd75Srobert   visitMemoryReference(I, MemoryLocation::getAfter(I.getAddress()),
597*d415bd75Srobert                        std::nullopt, nullptr, MemRef::Branchee);
59809467b48Spatrick 
599*d415bd75Srobert   Check(I.getNumDestinations() != 0,
60009467b48Spatrick         "Undefined behavior: indirectbr with no destinations", &I);
60109467b48Spatrick }
60209467b48Spatrick 
visitExtractElementInst(ExtractElementInst & I)60309467b48Spatrick void Lint::visitExtractElementInst(ExtractElementInst &I) {
60409467b48Spatrick   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
60509467b48Spatrick                                                         /*OffsetOk=*/false)))
606*d415bd75Srobert     Check(
60773471bf0Spatrick         CI->getValue().ult(
60873471bf0Spatrick             cast<FixedVectorType>(I.getVectorOperandType())->getNumElements()),
60909467b48Spatrick         "Undefined result: extractelement index out of range", &I);
61009467b48Spatrick }
61109467b48Spatrick 
visitInsertElementInst(InsertElementInst & I)61209467b48Spatrick void Lint::visitInsertElementInst(InsertElementInst &I) {
61309467b48Spatrick   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
61409467b48Spatrick                                                         /*OffsetOk=*/false)))
615*d415bd75Srobert     Check(CI->getValue().ult(
61673471bf0Spatrick               cast<FixedVectorType>(I.getType())->getNumElements()),
61709467b48Spatrick           "Undefined result: insertelement index out of range", &I);
61809467b48Spatrick }
61909467b48Spatrick 
visitUnreachableInst(UnreachableInst & I)62009467b48Spatrick void Lint::visitUnreachableInst(UnreachableInst &I) {
62109467b48Spatrick   // This isn't undefined behavior, it's merely suspicious.
622*d415bd75Srobert   Check(&I == &I.getParent()->front() ||
62309467b48Spatrick             std::prev(I.getIterator())->mayHaveSideEffects(),
62409467b48Spatrick         "Unusual: unreachable immediately preceded by instruction without "
62509467b48Spatrick         "side effects",
62609467b48Spatrick         &I);
62709467b48Spatrick }
62809467b48Spatrick 
62909467b48Spatrick /// findValue - Look through bitcasts and simple memory reference patterns
63009467b48Spatrick /// to identify an equivalent, but more informative, value.  If OffsetOk
63109467b48Spatrick /// is true, look through getelementptrs with non-zero offsets too.
63209467b48Spatrick ///
63309467b48Spatrick /// Most analysis passes don't require this logic, because instcombine
63409467b48Spatrick /// will simplify most of these kinds of things away. But it's a goal of
63509467b48Spatrick /// this Lint pass to be useful even on non-optimized IR.
findValue(Value * V,bool OffsetOk) const63609467b48Spatrick Value *Lint::findValue(Value *V, bool OffsetOk) const {
63709467b48Spatrick   SmallPtrSet<Value *, 4> Visited;
63809467b48Spatrick   return findValueImpl(V, OffsetOk, Visited);
63909467b48Spatrick }
64009467b48Spatrick 
64109467b48Spatrick /// findValueImpl - Implementation helper for findValue.
findValueImpl(Value * V,bool OffsetOk,SmallPtrSetImpl<Value * > & Visited) const64209467b48Spatrick Value *Lint::findValueImpl(Value *V, bool OffsetOk,
64309467b48Spatrick                            SmallPtrSetImpl<Value *> &Visited) const {
64409467b48Spatrick   // Detect self-referential values.
64509467b48Spatrick   if (!Visited.insert(V).second)
64609467b48Spatrick     return UndefValue::get(V->getType());
64709467b48Spatrick 
64809467b48Spatrick   // TODO: Look through sext or zext cast, when the result is known to
64909467b48Spatrick   // be interpreted as signed or unsigned, respectively.
65009467b48Spatrick   // TODO: Look through eliminable cast pairs.
65109467b48Spatrick   // TODO: Look through calls with unique return values.
65209467b48Spatrick   // TODO: Look through vector insert/extract/shuffle.
65373471bf0Spatrick   V = OffsetOk ? getUnderlyingObject(V) : V->stripPointerCasts();
65409467b48Spatrick   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
65509467b48Spatrick     BasicBlock::iterator BBI = L->getIterator();
65609467b48Spatrick     BasicBlock *BB = L->getParent();
65709467b48Spatrick     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
65809467b48Spatrick     for (;;) {
65909467b48Spatrick       if (!VisitedBlocks.insert(BB).second)
66009467b48Spatrick         break;
66109467b48Spatrick       if (Value *U =
66209467b48Spatrick               FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA))
66309467b48Spatrick         return findValueImpl(U, OffsetOk, Visited);
66473471bf0Spatrick       if (BBI != BB->begin())
66573471bf0Spatrick         break;
66609467b48Spatrick       BB = BB->getUniquePredecessor();
66773471bf0Spatrick       if (!BB)
66873471bf0Spatrick         break;
66909467b48Spatrick       BBI = BB->end();
67009467b48Spatrick     }
67109467b48Spatrick   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
67209467b48Spatrick     if (Value *W = PN->hasConstantValue())
67309467b48Spatrick       return findValueImpl(W, OffsetOk, Visited);
67409467b48Spatrick   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
67509467b48Spatrick     if (CI->isNoopCast(*DL))
67609467b48Spatrick       return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
67709467b48Spatrick   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
67873471bf0Spatrick     if (Value *W =
67973471bf0Spatrick             FindInsertedValue(Ex->getAggregateOperand(), Ex->getIndices()))
68009467b48Spatrick       if (W != V)
68109467b48Spatrick         return findValueImpl(W, OffsetOk, Visited);
68209467b48Spatrick   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
68309467b48Spatrick     // Same as above, but for ConstantExpr instead of Instruction.
68409467b48Spatrick     if (Instruction::isCast(CE->getOpcode())) {
68509467b48Spatrick       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
68609467b48Spatrick                                CE->getOperand(0)->getType(), CE->getType(),
68709467b48Spatrick                                *DL))
68809467b48Spatrick         return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
68909467b48Spatrick     }
69009467b48Spatrick   }
69109467b48Spatrick 
69209467b48Spatrick   // As a last resort, try SimplifyInstruction or constant folding.
69309467b48Spatrick   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
694*d415bd75Srobert     if (Value *W = simplifyInstruction(Inst, {*DL, TLI, DT, AC}))
69509467b48Spatrick       return findValueImpl(W, OffsetOk, Visited);
69609467b48Spatrick   } else if (auto *C = dyn_cast<Constant>(V)) {
697097a140dSpatrick     Value *W = ConstantFoldConstant(C, *DL, TLI);
698097a140dSpatrick     if (W != V)
69909467b48Spatrick       return findValueImpl(W, OffsetOk, Visited);
70009467b48Spatrick   }
70109467b48Spatrick 
70209467b48Spatrick   return V;
70309467b48Spatrick }
70409467b48Spatrick 
run(Function & F,FunctionAnalysisManager & AM)70573471bf0Spatrick PreservedAnalyses LintPass::run(Function &F, FunctionAnalysisManager &AM) {
70673471bf0Spatrick   auto *Mod = F.getParent();
70773471bf0Spatrick   auto *DL = &F.getParent()->getDataLayout();
70873471bf0Spatrick   auto *AA = &AM.getResult<AAManager>(F);
70973471bf0Spatrick   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
71073471bf0Spatrick   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
71173471bf0Spatrick   auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
71273471bf0Spatrick   Lint L(Mod, DL, AA, AC, DT, TLI);
71373471bf0Spatrick   L.visit(F);
71473471bf0Spatrick   dbgs() << L.MessagesStr.str();
71573471bf0Spatrick   return PreservedAnalyses::all();
71673471bf0Spatrick }
71773471bf0Spatrick 
718*d415bd75Srobert namespace {
71973471bf0Spatrick class LintLegacyPass : public FunctionPass {
72073471bf0Spatrick public:
72173471bf0Spatrick   static char ID; // Pass identification, replacement for typeid
LintLegacyPass()72273471bf0Spatrick   LintLegacyPass() : FunctionPass(ID) {
72373471bf0Spatrick     initializeLintLegacyPassPass(*PassRegistry::getPassRegistry());
72473471bf0Spatrick   }
72573471bf0Spatrick 
72673471bf0Spatrick   bool runOnFunction(Function &F) override;
72773471bf0Spatrick 
getAnalysisUsage(AnalysisUsage & AU) const72873471bf0Spatrick   void getAnalysisUsage(AnalysisUsage &AU) const override {
72973471bf0Spatrick     AU.setPreservesAll();
73073471bf0Spatrick     AU.addRequired<AAResultsWrapperPass>();
73173471bf0Spatrick     AU.addRequired<AssumptionCacheTracker>();
73273471bf0Spatrick     AU.addRequired<TargetLibraryInfoWrapperPass>();
73373471bf0Spatrick     AU.addRequired<DominatorTreeWrapperPass>();
73473471bf0Spatrick   }
print(raw_ostream & O,const Module * M) const73573471bf0Spatrick   void print(raw_ostream &O, const Module *M) const override {}
73673471bf0Spatrick };
737*d415bd75Srobert } // namespace
73873471bf0Spatrick 
73973471bf0Spatrick char LintLegacyPass::ID = 0;
74073471bf0Spatrick INITIALIZE_PASS_BEGIN(LintLegacyPass, "lint", "Statically lint-checks LLVM IR",
74173471bf0Spatrick                       false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)74273471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
74373471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
74473471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
74573471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
74673471bf0Spatrick INITIALIZE_PASS_END(LintLegacyPass, "lint", "Statically lint-checks LLVM IR",
74773471bf0Spatrick                     false, true)
74873471bf0Spatrick 
74973471bf0Spatrick bool LintLegacyPass::runOnFunction(Function &F) {
75073471bf0Spatrick   auto *Mod = F.getParent();
75173471bf0Spatrick   auto *DL = &F.getParent()->getDataLayout();
75273471bf0Spatrick   auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
75373471bf0Spatrick   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
75473471bf0Spatrick   auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
75573471bf0Spatrick   auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
75673471bf0Spatrick   Lint L(Mod, DL, AA, AC, DT, TLI);
75773471bf0Spatrick   L.visit(F);
75873471bf0Spatrick   dbgs() << L.MessagesStr.str();
75973471bf0Spatrick   return false;
76073471bf0Spatrick }
76173471bf0Spatrick 
76209467b48Spatrick //===----------------------------------------------------------------------===//
76309467b48Spatrick //  Implement the public interfaces to this file...
76409467b48Spatrick //===----------------------------------------------------------------------===//
76509467b48Spatrick 
createLintLegacyPassPass()76673471bf0Spatrick FunctionPass *llvm::createLintLegacyPassPass() { return new LintLegacyPass(); }
76709467b48Spatrick 
76809467b48Spatrick /// lintFunction - Check a function for errors, printing messages on stderr.
76909467b48Spatrick ///
lintFunction(const Function & f)77009467b48Spatrick void llvm::lintFunction(const Function &f) {
77109467b48Spatrick   Function &F = const_cast<Function &>(f);
77209467b48Spatrick   assert(!F.isDeclaration() && "Cannot lint external functions");
77309467b48Spatrick 
77409467b48Spatrick   legacy::FunctionPassManager FPM(F.getParent());
77573471bf0Spatrick   auto *V = new LintLegacyPass();
77609467b48Spatrick   FPM.add(V);
77709467b48Spatrick   FPM.run(F);
77809467b48Spatrick }
77909467b48Spatrick 
78009467b48Spatrick /// lintModule - Check a module for errors, printing messages on stderr.
78109467b48Spatrick ///
lintModule(const Module & M)78209467b48Spatrick void llvm::lintModule(const Module &M) {
78309467b48Spatrick   legacy::PassManager PM;
78473471bf0Spatrick   auto *V = new LintLegacyPass();
78509467b48Spatrick   PM.add(V);
78609467b48Spatrick   PM.run(const_cast<Module &>(M));
78709467b48Spatrick }
788