LLVM  mainline
Lint.cpp
Go to the documentation of this file.
00001 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass statically checks for common and easily-identified constructs
00011 // which produce undefined or likely unintended behavior in LLVM IR.
00012 //
00013 // It is not a guarantee of correctness, in two ways. First, it isn't
00014 // comprehensive. There are checks which could be done statically which are
00015 // not yet implemented. Some of these are indicated by TODO comments, but
00016 // those aren't comprehensive either. Second, many conditions cannot be
00017 // checked statically. This pass does no dynamic instrumentation, so it
00018 // can't check for all possible problems.
00019 //
00020 // Another limitation is that it assumes all code will be executed. A store
00021 // through a null pointer in a basic block which is never reached is harmless,
00022 // but this pass will warn about it anyway. This is the main reason why most
00023 // of these checks live here instead of in the Verifier pass.
00024 //
00025 // Optimization passes may make conditions that this pass checks for more or
00026 // less obvious. If an optimization pass appears to be introducing a warning,
00027 // it may be that the optimization pass is merely exposing an existing
00028 // condition in the code.
00029 //
00030 // This code may be run before instcombine. In many cases, instcombine checks
00031 // for the same kinds of things and turns instructions with undefined behavior
00032 // into unreachable (or equivalent). Because of this, this pass makes some
00033 // effort to look through bitcasts and so on.
00034 //
00035 //===----------------------------------------------------------------------===//
00036 
00037 #include "llvm/Analysis/Lint.h"
00038 #include "llvm/ADT/STLExtras.h"
00039 #include "llvm/ADT/SmallSet.h"
00040 #include "llvm/Analysis/AliasAnalysis.h"
00041 #include "llvm/Analysis/AssumptionCache.h"
00042 #include "llvm/Analysis/ConstantFolding.h"
00043 #include "llvm/Analysis/InstructionSimplify.h"
00044 #include "llvm/Analysis/Loads.h"
00045 #include "llvm/Analysis/Passes.h"
00046 #include "llvm/Analysis/TargetLibraryInfo.h"
00047 #include "llvm/Analysis/ValueTracking.h"
00048 #include "llvm/IR/CallSite.h"
00049 #include "llvm/IR/DataLayout.h"
00050 #include "llvm/IR/Dominators.h"
00051 #include "llvm/IR/Function.h"
00052 #include "llvm/IR/InstVisitor.h"
00053 #include "llvm/IR/IntrinsicInst.h"
00054 #include "llvm/IR/LegacyPassManager.h"
00055 #include "llvm/Pass.h"
00056 #include "llvm/Support/Debug.h"
00057 #include "llvm/Support/raw_ostream.h"
00058 using namespace llvm;
00059 
00060 namespace {
00061   namespace MemRef {
00062     static const unsigned Read     = 1;
00063     static const unsigned Write    = 2;
00064     static const unsigned Callee   = 4;
00065     static const unsigned Branchee = 8;
00066   }
00067 
00068   class Lint : public FunctionPass, public InstVisitor<Lint> {
00069     friend class InstVisitor<Lint>;
00070 
00071     void visitFunction(Function &F);
00072 
00073     void visitCallSite(CallSite CS);
00074     void visitMemoryReference(Instruction &I, Value *Ptr,
00075                               uint64_t Size, unsigned Align,
00076                               Type *Ty, unsigned Flags);
00077     void visitEHBeginCatch(IntrinsicInst *II);
00078     void visitEHEndCatch(IntrinsicInst *II);
00079 
00080     void visitCallInst(CallInst &I);
00081     void visitInvokeInst(InvokeInst &I);
00082     void visitReturnInst(ReturnInst &I);
00083     void visitLoadInst(LoadInst &I);
00084     void visitStoreInst(StoreInst &I);
00085     void visitXor(BinaryOperator &I);
00086     void visitSub(BinaryOperator &I);
00087     void visitLShr(BinaryOperator &I);
00088     void visitAShr(BinaryOperator &I);
00089     void visitShl(BinaryOperator &I);
00090     void visitSDiv(BinaryOperator &I);
00091     void visitUDiv(BinaryOperator &I);
00092     void visitSRem(BinaryOperator &I);
00093     void visitURem(BinaryOperator &I);
00094     void visitAllocaInst(AllocaInst &I);
00095     void visitVAArgInst(VAArgInst &I);
00096     void visitIndirectBrInst(IndirectBrInst &I);
00097     void visitExtractElementInst(ExtractElementInst &I);
00098     void visitInsertElementInst(InsertElementInst &I);
00099     void visitUnreachableInst(UnreachableInst &I);
00100 
00101     Value *findValue(Value *V, const DataLayout &DL, bool OffsetOk) const;
00102     Value *findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
00103                          SmallPtrSetImpl<Value *> &Visited) const;
00104 
00105   public:
00106     Module *Mod;
00107     AliasAnalysis *AA;
00108     AssumptionCache *AC;
00109     DominatorTree *DT;
00110     TargetLibraryInfo *TLI;
00111 
00112     std::string Messages;
00113     raw_string_ostream MessagesStr;
00114 
00115     static char ID; // Pass identification, replacement for typeid
00116     Lint() : FunctionPass(ID), MessagesStr(Messages) {
00117       initializeLintPass(*PassRegistry::getPassRegistry());
00118     }
00119 
00120     bool runOnFunction(Function &F) override;
00121 
00122     void getAnalysisUsage(AnalysisUsage &AU) const override {
00123       AU.setPreservesAll();
00124       AU.addRequired<AliasAnalysis>();
00125       AU.addRequired<AssumptionCacheTracker>();
00126       AU.addRequired<TargetLibraryInfoWrapperPass>();
00127       AU.addRequired<DominatorTreeWrapperPass>();
00128     }
00129     void print(raw_ostream &O, const Module *M) const override {}
00130 
00131     void WriteValues(ArrayRef<const Value *> Vs) {
00132       for (const Value *V : Vs) {
00133         if (!V)
00134           continue;
00135         if (isa<Instruction>(V)) {
00136           MessagesStr << *V << '\n';
00137         } else {
00138           V->printAsOperand(MessagesStr, true, Mod);
00139           MessagesStr << '\n';
00140         }
00141       }
00142     }
00143 
00144     /// \brief A check failed, so printout out the condition and the message.
00145     ///
00146     /// This provides a nice place to put a breakpoint if you want to see why
00147     /// something is not correct.
00148     void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
00149 
00150     /// \brief A check failed (with values to print).
00151     ///
00152     /// This calls the Message-only version so that the above is easier to set
00153     /// a breakpoint on.
00154     template <typename T1, typename... Ts>
00155     void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
00156       CheckFailed(Message);
00157       WriteValues({V1, Vs...});
00158     }
00159   };
00160 }
00161 
00162 char Lint::ID = 0;
00163 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
00164                       false, true)
00165 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00166 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00167 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00168 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00169 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
00170                     false, true)
00171 
00172 // Assert - We know that cond should be true, if not print an error message.
00173 #define Assert(C, ...) \
00174     do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
00175 
00176 // Lint::run - This is the main Analysis entry point for a
00177 // function.
00178 //
00179 bool Lint::runOnFunction(Function &F) {
00180   Mod = F.getParent();
00181   AA = &getAnalysis<AliasAnalysis>();
00182   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00183   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00184   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00185   visit(F);
00186   dbgs() << MessagesStr.str();
00187   Messages.clear();
00188   return false;
00189 }
00190 
00191 void Lint::visitFunction(Function &F) {
00192   // This isn't undefined behavior, it's just a little unusual, and it's a
00193   // fairly common mistake to neglect to name a function.
00194   Assert(F.hasName() || F.hasLocalLinkage(),
00195          "Unusual: Unnamed function with non-local linkage", &F);
00196 
00197   // TODO: Check for irreducible control flow.
00198 }
00199 
00200 void Lint::visitCallSite(CallSite CS) {
00201   Instruction &I = *CS.getInstruction();
00202   Value *Callee = CS.getCalledValue();
00203   const DataLayout &DL = CS->getModule()->getDataLayout();
00204 
00205   visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
00206                        0, nullptr, MemRef::Callee);
00207 
00208   if (Function *F = dyn_cast<Function>(findValue(Callee, DL,
00209                                                  /*OffsetOk=*/false))) {
00210     Assert(CS.getCallingConv() == F->getCallingConv(),
00211            "Undefined behavior: Caller and callee calling convention differ",
00212            &I);
00213 
00214     FunctionType *FT = F->getFunctionType();
00215     unsigned NumActualArgs = CS.arg_size();
00216 
00217     Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
00218                           : FT->getNumParams() == NumActualArgs,
00219            "Undefined behavior: Call argument count mismatches callee "
00220            "argument count",
00221            &I);
00222 
00223     Assert(FT->getReturnType() == I.getType(),
00224            "Undefined behavior: Call return type mismatches "
00225            "callee return type",
00226            &I);
00227 
00228     // Check argument types (in case the callee was casted) and attributes.
00229     // TODO: Verify that caller and callee attributes are compatible.
00230     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
00231     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
00232     for (; AI != AE; ++AI) {
00233       Value *Actual = *AI;
00234       if (PI != PE) {
00235         Argument *Formal = PI++;
00236         Assert(Formal->getType() == Actual->getType(),
00237                "Undefined behavior: Call argument type mismatches "
00238                "callee parameter type",
00239                &I);
00240 
00241         // Check that noalias arguments don't alias other arguments. This is
00242         // not fully precise because we don't know the sizes of the dereferenced
00243         // memory regions.
00244         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
00245           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
00246             if (AI != BI && (*BI)->getType()->isPointerTy()) {
00247               AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
00248               Assert(Result != AliasAnalysis::MustAlias &&
00249                          Result != AliasAnalysis::PartialAlias,
00250                      "Unusual: noalias argument aliases another argument", &I);
00251             }
00252 
00253         // Check that an sret argument points to valid memory.
00254         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
00255           Type *Ty =
00256             cast<PointerType>(Formal->getType())->getElementType();
00257           visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
00258                                DL.getABITypeAlignment(Ty), Ty,
00259                                MemRef::Read | MemRef::Write);
00260         }
00261       }
00262     }
00263   }
00264 
00265   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
00266     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
00267          AI != AE; ++AI) {
00268       Value *Obj = findValue(*AI, DL, /*OffsetOk=*/true);
00269       Assert(!isa<AllocaInst>(Obj),
00270              "Undefined behavior: Call with \"tail\" keyword references "
00271              "alloca",
00272              &I);
00273     }
00274 
00275 
00276   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
00277     switch (II->getIntrinsicID()) {
00278     default: break;
00279 
00280     // TODO: Check more intrinsics
00281 
00282     case Intrinsic::memcpy: {
00283       MemCpyInst *MCI = cast<MemCpyInst>(&I);
00284       // TODO: If the size is known, use it.
00285       visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
00286                            MCI->getAlignment(), nullptr,
00287                            MemRef::Write);
00288       visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
00289                            MCI->getAlignment(), nullptr,
00290                            MemRef::Read);
00291 
00292       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
00293       // isn't expressive enough for what we really want to do. Known partial
00294       // overlap is not distinguished from the case where nothing is known.
00295       uint64_t Size = 0;
00296       if (const ConstantInt *Len =
00297               dyn_cast<ConstantInt>(findValue(MCI->getLength(), DL,
00298                                               /*OffsetOk=*/false)))
00299         if (Len->getValue().isIntN(32))
00300           Size = Len->getValue().getZExtValue();
00301       Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
00302                  AliasAnalysis::MustAlias,
00303              "Undefined behavior: memcpy source and destination overlap", &I);
00304       break;
00305     }
00306     case Intrinsic::memmove: {
00307       MemMoveInst *MMI = cast<MemMoveInst>(&I);
00308       // TODO: If the size is known, use it.
00309       visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
00310                            MMI->getAlignment(), nullptr,
00311                            MemRef::Write);
00312       visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
00313                            MMI->getAlignment(), nullptr,
00314                            MemRef::Read);
00315       break;
00316     }
00317     case Intrinsic::memset: {
00318       MemSetInst *MSI = cast<MemSetInst>(&I);
00319       // TODO: If the size is known, use it.
00320       visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
00321                            MSI->getAlignment(), nullptr,
00322                            MemRef::Write);
00323       break;
00324     }
00325 
00326     case Intrinsic::vastart:
00327       Assert(I.getParent()->getParent()->isVarArg(),
00328              "Undefined behavior: va_start called in a non-varargs function",
00329              &I);
00330 
00331       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
00332                            0, nullptr, MemRef::Read | MemRef::Write);
00333       break;
00334     case Intrinsic::vacopy:
00335       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
00336                            0, nullptr, MemRef::Write);
00337       visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
00338                            0, nullptr, MemRef::Read);
00339       break;
00340     case Intrinsic::vaend:
00341       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
00342                            0, nullptr, MemRef::Read | MemRef::Write);
00343       break;
00344 
00345     case Intrinsic::stackrestore:
00346       // Stackrestore doesn't read or write memory, but it sets the
00347       // stack pointer, which the compiler may read from or write to
00348       // at any time, so check it for both readability and writeability.
00349       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
00350                            0, nullptr, MemRef::Read | MemRef::Write);
00351       break;
00352 
00353     case Intrinsic::eh_begincatch:
00354       visitEHBeginCatch(II);
00355       break;
00356     case Intrinsic::eh_endcatch:
00357       visitEHEndCatch(II);
00358       break;
00359     }
00360 }
00361 
00362 void Lint::visitCallInst(CallInst &I) {
00363   return visitCallSite(&I);
00364 }
00365 
00366 void Lint::visitInvokeInst(InvokeInst &I) {
00367   return visitCallSite(&I);
00368 }
00369 
00370 void Lint::visitReturnInst(ReturnInst &I) {
00371   Function *F = I.getParent()->getParent();
00372   Assert(!F->doesNotReturn(),
00373          "Unusual: Return statement in function with noreturn attribute", &I);
00374 
00375   if (Value *V = I.getReturnValue()) {
00376     Value *Obj =
00377         findValue(V, F->getParent()->getDataLayout(), /*OffsetOk=*/true);
00378     Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
00379   }
00380 }
00381 
00382 // TODO: Check that the reference is in bounds.
00383 // TODO: Check readnone/readonly function attributes.
00384 void Lint::visitMemoryReference(Instruction &I,
00385                                 Value *Ptr, uint64_t Size, unsigned Align,
00386                                 Type *Ty, unsigned Flags) {
00387   // If no memory is being referenced, it doesn't matter if the pointer
00388   // is valid.
00389   if (Size == 0)
00390     return;
00391 
00392   Value *UnderlyingObject =
00393       findValue(Ptr, I.getModule()->getDataLayout(), /*OffsetOk=*/true);
00394   Assert(!isa<ConstantPointerNull>(UnderlyingObject),
00395          "Undefined behavior: Null pointer dereference", &I);
00396   Assert(!isa<UndefValue>(UnderlyingObject),
00397          "Undefined behavior: Undef pointer dereference", &I);
00398   Assert(!isa<ConstantInt>(UnderlyingObject) ||
00399              !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
00400          "Unusual: All-ones pointer dereference", &I);
00401   Assert(!isa<ConstantInt>(UnderlyingObject) ||
00402              !cast<ConstantInt>(UnderlyingObject)->isOne(),
00403          "Unusual: Address one pointer dereference", &I);
00404 
00405   if (Flags & MemRef::Write) {
00406     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
00407       Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
00408              &I);
00409     Assert(!isa<Function>(UnderlyingObject) &&
00410                !isa<BlockAddress>(UnderlyingObject),
00411            "Undefined behavior: Write to text section", &I);
00412   }
00413   if (Flags & MemRef::Read) {
00414     Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
00415            &I);
00416     Assert(!isa<BlockAddress>(UnderlyingObject),
00417            "Undefined behavior: Load from block address", &I);
00418   }
00419   if (Flags & MemRef::Callee) {
00420     Assert(!isa<BlockAddress>(UnderlyingObject),
00421            "Undefined behavior: Call to block address", &I);
00422   }
00423   if (Flags & MemRef::Branchee) {
00424     Assert(!isa<Constant>(UnderlyingObject) ||
00425                isa<BlockAddress>(UnderlyingObject),
00426            "Undefined behavior: Branch to non-blockaddress", &I);
00427   }
00428 
00429   // Check for buffer overflows and misalignment.
00430   // Only handles memory references that read/write something simple like an
00431   // alloca instruction or a global variable.
00432   auto &DL = I.getModule()->getDataLayout();
00433   int64_t Offset = 0;
00434   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
00435     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
00436     // something we can handle and if so extract the size of this base object
00437     // along with its alignment.
00438     uint64_t BaseSize = AliasAnalysis::UnknownSize;
00439     unsigned BaseAlign = 0;
00440 
00441     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
00442       Type *ATy = AI->getAllocatedType();
00443       if (!AI->isArrayAllocation() && ATy->isSized())
00444         BaseSize = DL.getTypeAllocSize(ATy);
00445       BaseAlign = AI->getAlignment();
00446       if (BaseAlign == 0 && ATy->isSized())
00447         BaseAlign = DL.getABITypeAlignment(ATy);
00448     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
00449       // If the global may be defined differently in another compilation unit
00450       // then don't warn about funky memory accesses.
00451       if (GV->hasDefinitiveInitializer()) {
00452         Type *GTy = GV->getType()->getElementType();
00453         if (GTy->isSized())
00454           BaseSize = DL.getTypeAllocSize(GTy);
00455         BaseAlign = GV->getAlignment();
00456         if (BaseAlign == 0 && GTy->isSized())
00457           BaseAlign = DL.getABITypeAlignment(GTy);
00458       }
00459     }
00460 
00461     // Accesses from before the start or after the end of the object are not
00462     // defined.
00463     Assert(Size == AliasAnalysis::UnknownSize ||
00464                BaseSize == AliasAnalysis::UnknownSize ||
00465                (Offset >= 0 && Offset + Size <= BaseSize),
00466            "Undefined behavior: Buffer overflow", &I);
00467 
00468     // Accesses that say that the memory is more aligned than it is are not
00469     // defined.
00470     if (Align == 0 && Ty && Ty->isSized())
00471       Align = DL.getABITypeAlignment(Ty);
00472     Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
00473            "Undefined behavior: Memory reference address is misaligned", &I);
00474   }
00475 }
00476 
00477 void Lint::visitLoadInst(LoadInst &I) {
00478   visitMemoryReference(I, I.getPointerOperand(),
00479                        AA->getTypeStoreSize(I.getType()), I.getAlignment(),
00480                        I.getType(), MemRef::Read);
00481 }
00482 
00483 void Lint::visitStoreInst(StoreInst &I) {
00484   visitMemoryReference(I, I.getPointerOperand(),
00485                        AA->getTypeStoreSize(I.getOperand(0)->getType()),
00486                        I.getAlignment(),
00487                        I.getOperand(0)->getType(), MemRef::Write);
00488 }
00489 
00490 void Lint::visitXor(BinaryOperator &I) {
00491   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
00492          "Undefined result: xor(undef, undef)", &I);
00493 }
00494 
00495 void Lint::visitSub(BinaryOperator &I) {
00496   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
00497          "Undefined result: sub(undef, undef)", &I);
00498 }
00499 
00500 void Lint::visitLShr(BinaryOperator &I) {
00501   if (ConstantInt *CI = dyn_cast<ConstantInt>(
00502           findValue(I.getOperand(1), I.getModule()->getDataLayout(),
00503                     /*OffsetOk=*/false)))
00504     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00505            "Undefined result: Shift count out of range", &I);
00506 }
00507 
00508 void Lint::visitAShr(BinaryOperator &I) {
00509   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
00510           I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
00511     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00512            "Undefined result: Shift count out of range", &I);
00513 }
00514 
00515 void Lint::visitShl(BinaryOperator &I) {
00516   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
00517           I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
00518     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00519            "Undefined result: Shift count out of range", &I);
00520 }
00521 
00522 static bool
00523 allPredsCameFromLandingPad(BasicBlock *BB,
00524                            SmallSet<BasicBlock *, 4> &VisitedBlocks) {
00525   VisitedBlocks.insert(BB);
00526   if (BB->isLandingPad())
00527     return true;
00528   // If we find a block with no predecessors, the search failed.
00529   if (pred_empty(BB))
00530     return false;
00531   for (BasicBlock *Pred : predecessors(BB)) {
00532     if (VisitedBlocks.count(Pred))
00533       continue;
00534     if (!allPredsCameFromLandingPad(Pred, VisitedBlocks))
00535       return false;
00536   }
00537   return true;
00538 }
00539 
00540 static bool
00541 allSuccessorsReachEndCatch(BasicBlock *BB, BasicBlock::iterator InstBegin,
00542                            IntrinsicInst **SecondBeginCatch,
00543                            SmallSet<BasicBlock *, 4> &VisitedBlocks) {
00544   VisitedBlocks.insert(BB);
00545   for (BasicBlock::iterator I = InstBegin, E = BB->end(); I != E; ++I) {
00546     IntrinsicInst *IC = dyn_cast<IntrinsicInst>(I);
00547     if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch)
00548       return true;
00549     // If we find another begincatch while looking for an endcatch,
00550     // that's also an error.
00551     if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch) {
00552       *SecondBeginCatch = IC;
00553       return false;
00554     }
00555   }
00556 
00557   // If we reach a block with no successors while searching, the
00558   // search has failed.
00559   if (succ_empty(BB))
00560     return false;
00561   // Otherwise, search all of the successors.
00562   for (BasicBlock *Succ : successors(BB)) {
00563     if (VisitedBlocks.count(Succ))
00564       continue;
00565     if (!allSuccessorsReachEndCatch(Succ, Succ->begin(), SecondBeginCatch,
00566                                     VisitedBlocks))
00567       return false;
00568   }
00569   return true;
00570 }
00571 
00572 void Lint::visitEHBeginCatch(IntrinsicInst *II) {
00573   // The checks in this function make a potentially dubious assumption about
00574   // the CFG, namely that any block involved in a catch is only used for the
00575   // catch.  This will very likely be true of IR generated by a front end,
00576   // but it may cease to be true, for example, if the IR is run through a
00577   // pass which combines similar blocks.
00578   //
00579   // In general, if we encounter a block the isn't dominated by the catch
00580   // block while we are searching the catch block's successors for a call
00581   // to end catch intrinsic, then it is possible that it will be legal for
00582   // a path through this block to never reach a call to llvm.eh.endcatch.
00583   // An analogous statement could be made about our search for a landing
00584   // pad among the catch block's predecessors.
00585   //
00586   // What is actually required is that no path is possible at runtime that
00587   // reaches a call to llvm.eh.begincatch without having previously visited
00588   // a landingpad instruction and that no path is possible at runtime that
00589   // calls llvm.eh.begincatch and does not subsequently call llvm.eh.endcatch
00590   // (mentally adjusting for the fact that in reality these calls will be
00591   // removed before code generation).
00592   //
00593   // Because this is a lint check, we take a pessimistic approach and warn if
00594   // the control flow is potentially incorrect.
00595 
00596   SmallSet<BasicBlock *, 4> VisitedBlocks;
00597   BasicBlock *CatchBB = II->getParent();
00598 
00599   // The begin catch must occur in a landing pad block or all paths
00600   // to it must have come from a landing pad.
00601   Assert(allPredsCameFromLandingPad(CatchBB, VisitedBlocks),
00602          "llvm.eh.begincatch may be reachable without passing a landingpad",
00603          II);
00604 
00605   // Reset the visited block list.
00606   VisitedBlocks.clear();
00607 
00608   IntrinsicInst *SecondBeginCatch = nullptr;
00609 
00610   // This has to be called before it is asserted.  Otherwise, the first assert
00611   // below can never be hit.
00612   bool EndCatchFound = allSuccessorsReachEndCatch(
00613       CatchBB, std::next(static_cast<BasicBlock::iterator>(II)),
00614       &SecondBeginCatch, VisitedBlocks);
00615   Assert(
00616       SecondBeginCatch == nullptr,
00617       "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
00618       II, SecondBeginCatch);
00619   Assert(EndCatchFound,
00620          "Some paths from llvm.eh.begincatch may not reach llvm.eh.endcatch",
00621          II);
00622 }
00623 
00624 static bool allPredCameFromBeginCatch(
00625     BasicBlock *BB, BasicBlock::reverse_iterator InstRbegin,
00626     IntrinsicInst **SecondEndCatch, SmallSet<BasicBlock *, 4> &VisitedBlocks) {
00627   VisitedBlocks.insert(BB);
00628   // Look for a begincatch in this block.
00629   for (BasicBlock::reverse_iterator RI = InstRbegin, RE = BB->rend(); RI != RE;
00630        ++RI) {
00631     IntrinsicInst *IC = dyn_cast<IntrinsicInst>(&*RI);
00632     if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch)
00633       return true;
00634     // If we find another end catch before we find a begin catch, that's
00635     // an error.
00636     if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch) {
00637       *SecondEndCatch = IC;
00638       return false;
00639     }
00640     // If we encounter a landingpad instruction, the search failed.
00641     if (isa<LandingPadInst>(*RI))
00642       return false;
00643   }
00644   // If while searching we find a block with no predeccesors,
00645   // the search failed.
00646   if (pred_empty(BB))
00647     return false;
00648   // Search any predecessors we haven't seen before.
00649   for (BasicBlock *Pred : predecessors(BB)) {
00650     if (VisitedBlocks.count(Pred))
00651       continue;
00652     if (!allPredCameFromBeginCatch(Pred, Pred->rbegin(), SecondEndCatch,
00653                                    VisitedBlocks))
00654       return false;
00655   }
00656   return true;
00657 }
00658 
00659 void Lint::visitEHEndCatch(IntrinsicInst *II) {
00660   // The check in this function makes a potentially dubious assumption about
00661   // the CFG, namely that any block involved in a catch is only used for the
00662   // catch.  This will very likely be true of IR generated by a front end,
00663   // but it may cease to be true, for example, if the IR is run through a
00664   // pass which combines similar blocks.
00665   //
00666   // In general, if we encounter a block the isn't post-dominated by the
00667   // end catch block while we are searching the end catch block's predecessors
00668   // for a call to the begin catch intrinsic, then it is possible that it will
00669   // be legal for a path to reach the end catch block without ever having
00670   // called llvm.eh.begincatch.
00671   //
00672   // What is actually required is that no path is possible at runtime that
00673   // reaches a call to llvm.eh.endcatch without having previously visited
00674   // a call to llvm.eh.begincatch (mentally adjusting for the fact that in
00675   // reality these calls will be removed before code generation).
00676   //
00677   // Because this is a lint check, we take a pessimistic approach and warn if
00678   // the control flow is potentially incorrect.
00679 
00680   BasicBlock *EndCatchBB = II->getParent();
00681 
00682   // Alls paths to the end catch call must pass through a begin catch call.
00683 
00684   // If llvm.eh.begincatch wasn't called in the current block, we'll use this
00685   // lambda to recursively look for it in predecessors.
00686   SmallSet<BasicBlock *, 4> VisitedBlocks;
00687   IntrinsicInst *SecondEndCatch = nullptr;
00688 
00689   // This has to be called before it is asserted.  Otherwise, the first assert
00690   // below can never be hit.
00691   bool BeginCatchFound =
00692       allPredCameFromBeginCatch(EndCatchBB, BasicBlock::reverse_iterator(II),
00693                                 &SecondEndCatch, VisitedBlocks);
00694   Assert(
00695       SecondEndCatch == nullptr,
00696       "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
00697       II, SecondEndCatch);
00698   Assert(BeginCatchFound,
00699          "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
00700          II);
00701 }
00702 
00703 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
00704                    AssumptionCache *AC) {
00705   // Assume undef could be zero.
00706   if (isa<UndefValue>(V))
00707     return true;
00708 
00709   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
00710   if (!VecTy) {
00711     unsigned BitWidth = V->getType()->getIntegerBitWidth();
00712     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00713     computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
00714                      dyn_cast<Instruction>(V), DT);
00715     return KnownZero.isAllOnesValue();
00716   }
00717 
00718   // Per-component check doesn't work with zeroinitializer
00719   Constant *C = dyn_cast<Constant>(V);
00720   if (!C)
00721     return false;
00722 
00723   if (C->isZeroValue())
00724     return true;
00725 
00726   // For a vector, KnownZero will only be true if all values are zero, so check
00727   // this per component
00728   unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
00729   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
00730     Constant *Elem = C->getAggregateElement(I);
00731     if (isa<UndefValue>(Elem))
00732       return true;
00733 
00734     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00735     computeKnownBits(Elem, KnownZero, KnownOne, DL);
00736     if (KnownZero.isAllOnesValue())
00737       return true;
00738   }
00739 
00740   return false;
00741 }
00742 
00743 void Lint::visitSDiv(BinaryOperator &I) {
00744   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00745          "Undefined behavior: Division by zero", &I);
00746 }
00747 
00748 void Lint::visitUDiv(BinaryOperator &I) {
00749   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00750          "Undefined behavior: Division by zero", &I);
00751 }
00752 
00753 void Lint::visitSRem(BinaryOperator &I) {
00754   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00755          "Undefined behavior: Division by zero", &I);
00756 }
00757 
00758 void Lint::visitURem(BinaryOperator &I) {
00759   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00760          "Undefined behavior: Division by zero", &I);
00761 }
00762 
00763 void Lint::visitAllocaInst(AllocaInst &I) {
00764   if (isa<ConstantInt>(I.getArraySize()))
00765     // This isn't undefined behavior, it's just an obvious pessimization.
00766     Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
00767            "Pessimization: Static alloca outside of entry block", &I);
00768 
00769   // TODO: Check for an unusual size (MSB set?)
00770 }
00771 
00772 void Lint::visitVAArgInst(VAArgInst &I) {
00773   visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0,
00774                        nullptr, MemRef::Read | MemRef::Write);
00775 }
00776 
00777 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
00778   visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0,
00779                        nullptr, MemRef::Branchee);
00780 
00781   Assert(I.getNumDestinations() != 0,
00782          "Undefined behavior: indirectbr with no destinations", &I);
00783 }
00784 
00785 void Lint::visitExtractElementInst(ExtractElementInst &I) {
00786   if (ConstantInt *CI = dyn_cast<ConstantInt>(
00787           findValue(I.getIndexOperand(), I.getModule()->getDataLayout(),
00788                     /*OffsetOk=*/false)))
00789     Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
00790            "Undefined result: extractelement index out of range", &I);
00791 }
00792 
00793 void Lint::visitInsertElementInst(InsertElementInst &I) {
00794   if (ConstantInt *CI = dyn_cast<ConstantInt>(
00795           findValue(I.getOperand(2), I.getModule()->getDataLayout(),
00796                     /*OffsetOk=*/false)))
00797     Assert(CI->getValue().ult(I.getType()->getNumElements()),
00798            "Undefined result: insertelement index out of range", &I);
00799 }
00800 
00801 void Lint::visitUnreachableInst(UnreachableInst &I) {
00802   // This isn't undefined behavior, it's merely suspicious.
00803   Assert(&I == I.getParent()->begin() ||
00804              std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
00805          "Unusual: unreachable immediately preceded by instruction without "
00806          "side effects",
00807          &I);
00808 }
00809 
00810 /// findValue - Look through bitcasts and simple memory reference patterns
00811 /// to identify an equivalent, but more informative, value.  If OffsetOk
00812 /// is true, look through getelementptrs with non-zero offsets too.
00813 ///
00814 /// Most analysis passes don't require this logic, because instcombine
00815 /// will simplify most of these kinds of things away. But it's a goal of
00816 /// this Lint pass to be useful even on non-optimized IR.
00817 Value *Lint::findValue(Value *V, const DataLayout &DL, bool OffsetOk) const {
00818   SmallPtrSet<Value *, 4> Visited;
00819   return findValueImpl(V, DL, OffsetOk, Visited);
00820 }
00821 
00822 /// findValueImpl - Implementation helper for findValue.
00823 Value *Lint::findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
00824                            SmallPtrSetImpl<Value *> &Visited) const {
00825   // Detect self-referential values.
00826   if (!Visited.insert(V).second)
00827     return UndefValue::get(V->getType());
00828 
00829   // TODO: Look through sext or zext cast, when the result is known to
00830   // be interpreted as signed or unsigned, respectively.
00831   // TODO: Look through eliminable cast pairs.
00832   // TODO: Look through calls with unique return values.
00833   // TODO: Look through vector insert/extract/shuffle.
00834   V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
00835   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
00836     BasicBlock::iterator BBI = L;
00837     BasicBlock *BB = L->getParent();
00838     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
00839     for (;;) {
00840       if (!VisitedBlocks.insert(BB).second)
00841         break;
00842       if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
00843                                               BB, BBI, 6, AA))
00844         return findValueImpl(U, DL, OffsetOk, Visited);
00845       if (BBI != BB->begin()) break;
00846       BB = BB->getUniquePredecessor();
00847       if (!BB) break;
00848       BBI = BB->end();
00849     }
00850   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
00851     if (Value *W = PN->hasConstantValue())
00852       if (W != V)
00853         return findValueImpl(W, DL, OffsetOk, Visited);
00854   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
00855     if (CI->isNoopCast(DL))
00856       return findValueImpl(CI->getOperand(0), DL, OffsetOk, Visited);
00857   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
00858     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
00859                                      Ex->getIndices()))
00860       if (W != V)
00861         return findValueImpl(W, DL, OffsetOk, Visited);
00862   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00863     // Same as above, but for ConstantExpr instead of Instruction.
00864     if (Instruction::isCast(CE->getOpcode())) {
00865       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
00866                                CE->getOperand(0)->getType(), CE->getType(),
00867                                DL.getIntPtrType(V->getType())))
00868         return findValueImpl(CE->getOperand(0), DL, OffsetOk, Visited);
00869     } else if (CE->getOpcode() == Instruction::ExtractValue) {
00870       ArrayRef<unsigned> Indices = CE->getIndices();
00871       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
00872         if (W != V)
00873           return findValueImpl(W, DL, OffsetOk, Visited);
00874     }
00875   }
00876 
00877   // As a last resort, try SimplifyInstruction or constant folding.
00878   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
00879     if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
00880       return findValueImpl(W, DL, OffsetOk, Visited);
00881   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00882     if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
00883       if (W != V)
00884         return findValueImpl(W, DL, OffsetOk, Visited);
00885   }
00886 
00887   return V;
00888 }
00889 
00890 //===----------------------------------------------------------------------===//
00891 //  Implement the public interfaces to this file...
00892 //===----------------------------------------------------------------------===//
00893 
00894 FunctionPass *llvm::createLintPass() {
00895   return new Lint();
00896 }
00897 
00898 /// lintFunction - Check a function for errors, printing messages on stderr.
00899 ///
00900 void llvm::lintFunction(const Function &f) {
00901   Function &F = const_cast<Function&>(f);
00902   assert(!F.isDeclaration() && "Cannot lint external functions");
00903 
00904   legacy::FunctionPassManager FPM(F.getParent());
00905   Lint *V = new Lint();
00906   FPM.add(V);
00907   FPM.run(F);
00908 }
00909 
00910 /// lintModule - Check a module for errors, printing messages on stderr.
00911 ///
00912 void llvm::lintModule(const Module &M) {
00913   legacy::PassManager PM;
00914   Lint *V = new Lint();
00915   PM.add(V);
00916   PM.run(const_cast<Module&>(M));
00917 }