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/Module.h"
00053 #include "llvm/IR/InstVisitor.h"
00054 #include "llvm/IR/IntrinsicInst.h"
00055 #include "llvm/IR/LegacyPassManager.h"
00056 #include "llvm/Pass.h"
00057 #include "llvm/Support/Debug.h"
00058 #include "llvm/Support/raw_ostream.h"
00059 using namespace llvm;
00060 
00061 namespace {
00062   namespace MemRef {
00063     static const unsigned Read     = 1;
00064     static const unsigned Write    = 2;
00065     static const unsigned Callee   = 4;
00066     static const unsigned Branchee = 8;
00067   }
00068 
00069   class Lint : public FunctionPass, public InstVisitor<Lint> {
00070     friend class InstVisitor<Lint>;
00071 
00072     void visitFunction(Function &F);
00073 
00074     void visitCallSite(CallSite CS);
00075     void visitMemoryReference(Instruction &I, Value *Ptr,
00076                               uint64_t Size, unsigned Align,
00077                               Type *Ty, unsigned Flags);
00078     void visitEHBeginCatch(IntrinsicInst *II);
00079     void visitEHEndCatch(IntrinsicInst *II);
00080 
00081     void visitCallInst(CallInst &I);
00082     void visitInvokeInst(InvokeInst &I);
00083     void visitReturnInst(ReturnInst &I);
00084     void visitLoadInst(LoadInst &I);
00085     void visitStoreInst(StoreInst &I);
00086     void visitXor(BinaryOperator &I);
00087     void visitSub(BinaryOperator &I);
00088     void visitLShr(BinaryOperator &I);
00089     void visitAShr(BinaryOperator &I);
00090     void visitShl(BinaryOperator &I);
00091     void visitSDiv(BinaryOperator &I);
00092     void visitUDiv(BinaryOperator &I);
00093     void visitSRem(BinaryOperator &I);
00094     void visitURem(BinaryOperator &I);
00095     void visitAllocaInst(AllocaInst &I);
00096     void visitVAArgInst(VAArgInst &I);
00097     void visitIndirectBrInst(IndirectBrInst &I);
00098     void visitExtractElementInst(ExtractElementInst &I);
00099     void visitInsertElementInst(InsertElementInst &I);
00100     void visitUnreachableInst(UnreachableInst &I);
00101 
00102     Value *findValue(Value *V, bool OffsetOk) const;
00103     Value *findValueImpl(Value *V, bool OffsetOk,
00104                          SmallPtrSetImpl<Value *> &Visited) const;
00105 
00106   public:
00107     Module *Mod;
00108     const DataLayout *DL;
00109     AliasAnalysis *AA;
00110     AssumptionCache *AC;
00111     DominatorTree *DT;
00112     TargetLibraryInfo *TLI;
00113 
00114     std::string Messages;
00115     raw_string_ostream MessagesStr;
00116 
00117     static char ID; // Pass identification, replacement for typeid
00118     Lint() : FunctionPass(ID), MessagesStr(Messages) {
00119       initializeLintPass(*PassRegistry::getPassRegistry());
00120     }
00121 
00122     bool runOnFunction(Function &F) override;
00123 
00124     void getAnalysisUsage(AnalysisUsage &AU) const override {
00125       AU.setPreservesAll();
00126       AU.addRequired<AAResultsWrapperPass>();
00127       AU.addRequired<AssumptionCacheTracker>();
00128       AU.addRequired<TargetLibraryInfoWrapperPass>();
00129       AU.addRequired<DominatorTreeWrapperPass>();
00130     }
00131     void print(raw_ostream &O, const Module *M) const override {}
00132 
00133     void WriteValues(ArrayRef<const Value *> Vs) {
00134       for (const Value *V : Vs) {
00135         if (!V)
00136           continue;
00137         if (isa<Instruction>(V)) {
00138           MessagesStr << *V << '\n';
00139         } else {
00140           V->printAsOperand(MessagesStr, true, Mod);
00141           MessagesStr << '\n';
00142         }
00143       }
00144     }
00145 
00146     /// \brief A check failed, so printout out the condition and the message.
00147     ///
00148     /// This provides a nice place to put a breakpoint if you want to see why
00149     /// something is not correct.
00150     void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
00151 
00152     /// \brief A check failed (with values to print).
00153     ///
00154     /// This calls the Message-only version so that the above is easier to set
00155     /// a breakpoint on.
00156     template <typename T1, typename... Ts>
00157     void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
00158       CheckFailed(Message);
00159       WriteValues({V1, Vs...});
00160     }
00161   };
00162 }
00163 
00164 char Lint::ID = 0;
00165 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
00166                       false, true)
00167 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00168 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00169 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00170 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
00171 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
00172                     false, true)
00173 
00174 // Assert - We know that cond should be true, if not print an error message.
00175 #define Assert(C, ...) \
00176     do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
00177 
00178 // Lint::run - This is the main Analysis entry point for a
00179 // function.
00180 //
00181 bool Lint::runOnFunction(Function &F) {
00182   Mod = F.getParent();
00183   DL = &F.getParent()->getDataLayout();
00184   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
00185   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00186   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00187   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00188   visit(F);
00189   dbgs() << MessagesStr.str();
00190   Messages.clear();
00191   return false;
00192 }
00193 
00194 void Lint::visitFunction(Function &F) {
00195   // This isn't undefined behavior, it's just a little unusual, and it's a
00196   // fairly common mistake to neglect to name a function.
00197   Assert(F.hasName() || F.hasLocalLinkage(),
00198          "Unusual: Unnamed function with non-local linkage", &F);
00199 
00200   // TODO: Check for irreducible control flow.
00201 }
00202 
00203 void Lint::visitCallSite(CallSite CS) {
00204   Instruction &I = *CS.getInstruction();
00205   Value *Callee = CS.getCalledValue();
00206 
00207   visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
00208                        MemRef::Callee);
00209 
00210   if (Function *F = dyn_cast<Function>(findValue(Callee,
00211                                                  /*OffsetOk=*/false))) {
00212     Assert(CS.getCallingConv() == F->getCallingConv(),
00213            "Undefined behavior: Caller and callee calling convention differ",
00214            &I);
00215 
00216     FunctionType *FT = F->getFunctionType();
00217     unsigned NumActualArgs = CS.arg_size();
00218 
00219     Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
00220                           : FT->getNumParams() == NumActualArgs,
00221            "Undefined behavior: Call argument count mismatches callee "
00222            "argument count",
00223            &I);
00224 
00225     Assert(FT->getReturnType() == I.getType(),
00226            "Undefined behavior: Call return type mismatches "
00227            "callee return type",
00228            &I);
00229 
00230     // Check argument types (in case the callee was casted) and attributes.
00231     // TODO: Verify that caller and callee attributes are compatible.
00232     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
00233     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
00234     for (; AI != AE; ++AI) {
00235       Value *Actual = *AI;
00236       if (PI != PE) {
00237         Argument *Formal = &*PI++;
00238         Assert(Formal->getType() == Actual->getType(),
00239                "Undefined behavior: Call argument type mismatches "
00240                "callee parameter type",
00241                &I);
00242 
00243         // Check that noalias arguments don't alias other arguments. This is
00244         // not fully precise because we don't know the sizes of the dereferenced
00245         // memory regions.
00246         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
00247           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
00248             if (AI != BI && (*BI)->getType()->isPointerTy()) {
00249               AliasResult Result = AA->alias(*AI, *BI);
00250               Assert(Result != MustAlias && Result != PartialAlias,
00251                      "Unusual: noalias argument aliases another argument", &I);
00252             }
00253 
00254         // Check that an sret argument points to valid memory.
00255         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
00256           Type *Ty =
00257             cast<PointerType>(Formal->getType())->getElementType();
00258           visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
00259                                DL->getABITypeAlignment(Ty), Ty,
00260                                MemRef::Read | MemRef::Write);
00261         }
00262       }
00263     }
00264   }
00265 
00266   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
00267     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
00268          AI != AE; ++AI) {
00269       Value *Obj = findValue(*AI, /*OffsetOk=*/true);
00270       Assert(!isa<AllocaInst>(Obj),
00271              "Undefined behavior: Call with \"tail\" keyword references "
00272              "alloca",
00273              &I);
00274     }
00275 
00276 
00277   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
00278     switch (II->getIntrinsicID()) {
00279     default: break;
00280 
00281     // TODO: Check more intrinsics
00282 
00283     case Intrinsic::memcpy: {
00284       MemCpyInst *MCI = cast<MemCpyInst>(&I);
00285       // TODO: If the size is known, use it.
00286       visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
00287                            MCI->getAlignment(), nullptr, MemRef::Write);
00288       visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
00289                            MCI->getAlignment(), nullptr, MemRef::Read);
00290 
00291       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
00292       // isn't expressive enough for what we really want to do. Known partial
00293       // overlap is not distinguished from the case where nothing is known.
00294       uint64_t Size = 0;
00295       if (const ConstantInt *Len =
00296               dyn_cast<ConstantInt>(findValue(MCI->getLength(),
00297                                               /*OffsetOk=*/false)))
00298         if (Len->getValue().isIntN(32))
00299           Size = Len->getValue().getZExtValue();
00300       Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
00301                  MustAlias,
00302              "Undefined behavior: memcpy source and destination overlap", &I);
00303       break;
00304     }
00305     case Intrinsic::memmove: {
00306       MemMoveInst *MMI = cast<MemMoveInst>(&I);
00307       // TODO: If the size is known, use it.
00308       visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
00309                            MMI->getAlignment(), nullptr, MemRef::Write);
00310       visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
00311                            MMI->getAlignment(), nullptr, MemRef::Read);
00312       break;
00313     }
00314     case Intrinsic::memset: {
00315       MemSetInst *MSI = cast<MemSetInst>(&I);
00316       // TODO: If the size is known, use it.
00317       visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
00318                            MSI->getAlignment(), nullptr, MemRef::Write);
00319       break;
00320     }
00321 
00322     case Intrinsic::vastart:
00323       Assert(I.getParent()->getParent()->isVarArg(),
00324              "Undefined behavior: va_start called in a non-varargs function",
00325              &I);
00326 
00327       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00328                            nullptr, MemRef::Read | MemRef::Write);
00329       break;
00330     case Intrinsic::vacopy:
00331       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00332                            nullptr, MemRef::Write);
00333       visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
00334                            nullptr, MemRef::Read);
00335       break;
00336     case Intrinsic::vaend:
00337       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00338                            nullptr, MemRef::Read | MemRef::Write);
00339       break;
00340 
00341     case Intrinsic::stackrestore:
00342       // Stackrestore doesn't read or write memory, but it sets the
00343       // stack pointer, which the compiler may read from or write to
00344       // at any time, so check it for both readability and writeability.
00345       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00346                            nullptr, MemRef::Read | MemRef::Write);
00347       break;
00348     }
00349 }
00350 
00351 void Lint::visitCallInst(CallInst &I) {
00352   return visitCallSite(&I);
00353 }
00354 
00355 void Lint::visitInvokeInst(InvokeInst &I) {
00356   return visitCallSite(&I);
00357 }
00358 
00359 void Lint::visitReturnInst(ReturnInst &I) {
00360   Function *F = I.getParent()->getParent();
00361   Assert(!F->doesNotReturn(),
00362          "Unusual: Return statement in function with noreturn attribute", &I);
00363 
00364   if (Value *V = I.getReturnValue()) {
00365     Value *Obj = findValue(V, /*OffsetOk=*/true);
00366     Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
00367   }
00368 }
00369 
00370 // TODO: Check that the reference is in bounds.
00371 // TODO: Check readnone/readonly function attributes.
00372 void Lint::visitMemoryReference(Instruction &I,
00373                                 Value *Ptr, uint64_t Size, unsigned Align,
00374                                 Type *Ty, unsigned Flags) {
00375   // If no memory is being referenced, it doesn't matter if the pointer
00376   // is valid.
00377   if (Size == 0)
00378     return;
00379 
00380   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
00381   Assert(!isa<ConstantPointerNull>(UnderlyingObject),
00382          "Undefined behavior: Null pointer dereference", &I);
00383   Assert(!isa<UndefValue>(UnderlyingObject),
00384          "Undefined behavior: Undef pointer dereference", &I);
00385   Assert(!isa<ConstantInt>(UnderlyingObject) ||
00386              !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
00387          "Unusual: All-ones pointer dereference", &I);
00388   Assert(!isa<ConstantInt>(UnderlyingObject) ||
00389              !cast<ConstantInt>(UnderlyingObject)->isOne(),
00390          "Unusual: Address one pointer dereference", &I);
00391 
00392   if (Flags & MemRef::Write) {
00393     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
00394       Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
00395              &I);
00396     Assert(!isa<Function>(UnderlyingObject) &&
00397                !isa<BlockAddress>(UnderlyingObject),
00398            "Undefined behavior: Write to text section", &I);
00399   }
00400   if (Flags & MemRef::Read) {
00401     Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
00402            &I);
00403     Assert(!isa<BlockAddress>(UnderlyingObject),
00404            "Undefined behavior: Load from block address", &I);
00405   }
00406   if (Flags & MemRef::Callee) {
00407     Assert(!isa<BlockAddress>(UnderlyingObject),
00408            "Undefined behavior: Call to block address", &I);
00409   }
00410   if (Flags & MemRef::Branchee) {
00411     Assert(!isa<Constant>(UnderlyingObject) ||
00412                isa<BlockAddress>(UnderlyingObject),
00413            "Undefined behavior: Branch to non-blockaddress", &I);
00414   }
00415 
00416   // Check for buffer overflows and misalignment.
00417   // Only handles memory references that read/write something simple like an
00418   // alloca instruction or a global variable.
00419   int64_t Offset = 0;
00420   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
00421     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
00422     // something we can handle and if so extract the size of this base object
00423     // along with its alignment.
00424     uint64_t BaseSize = MemoryLocation::UnknownSize;
00425     unsigned BaseAlign = 0;
00426 
00427     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
00428       Type *ATy = AI->getAllocatedType();
00429       if (!AI->isArrayAllocation() && ATy->isSized())
00430         BaseSize = DL->getTypeAllocSize(ATy);
00431       BaseAlign = AI->getAlignment();
00432       if (BaseAlign == 0 && ATy->isSized())
00433         BaseAlign = DL->getABITypeAlignment(ATy);
00434     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
00435       // If the global may be defined differently in another compilation unit
00436       // then don't warn about funky memory accesses.
00437       if (GV->hasDefinitiveInitializer()) {
00438         Type *GTy = GV->getValueType();
00439         if (GTy->isSized())
00440           BaseSize = DL->getTypeAllocSize(GTy);
00441         BaseAlign = GV->getAlignment();
00442         if (BaseAlign == 0 && GTy->isSized())
00443           BaseAlign = DL->getABITypeAlignment(GTy);
00444       }
00445     }
00446 
00447     // Accesses from before the start or after the end of the object are not
00448     // defined.
00449     Assert(Size == MemoryLocation::UnknownSize ||
00450                BaseSize == MemoryLocation::UnknownSize ||
00451                (Offset >= 0 && Offset + Size <= BaseSize),
00452            "Undefined behavior: Buffer overflow", &I);
00453 
00454     // Accesses that say that the memory is more aligned than it is are not
00455     // defined.
00456     if (Align == 0 && Ty && Ty->isSized())
00457       Align = DL->getABITypeAlignment(Ty);
00458     Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
00459            "Undefined behavior: Memory reference address is misaligned", &I);
00460   }
00461 }
00462 
00463 void Lint::visitLoadInst(LoadInst &I) {
00464   visitMemoryReference(I, I.getPointerOperand(),
00465                        DL->getTypeStoreSize(I.getType()), I.getAlignment(),
00466                        I.getType(), MemRef::Read);
00467 }
00468 
00469 void Lint::visitStoreInst(StoreInst &I) {
00470   visitMemoryReference(I, I.getPointerOperand(),
00471                        DL->getTypeStoreSize(I.getOperand(0)->getType()),
00472                        I.getAlignment(),
00473                        I.getOperand(0)->getType(), MemRef::Write);
00474 }
00475 
00476 void Lint::visitXor(BinaryOperator &I) {
00477   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
00478          "Undefined result: xor(undef, undef)", &I);
00479 }
00480 
00481 void Lint::visitSub(BinaryOperator &I) {
00482   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
00483          "Undefined result: sub(undef, undef)", &I);
00484 }
00485 
00486 void Lint::visitLShr(BinaryOperator &I) {
00487   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
00488                                                         /*OffsetOk=*/false)))
00489     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00490            "Undefined result: Shift count out of range", &I);
00491 }
00492 
00493 void Lint::visitAShr(BinaryOperator &I) {
00494   if (ConstantInt *CI =
00495           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
00496     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00497            "Undefined result: Shift count out of range", &I);
00498 }
00499 
00500 void Lint::visitShl(BinaryOperator &I) {
00501   if (ConstantInt *CI =
00502           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
00503     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00504            "Undefined result: Shift count out of range", &I);
00505 }
00506 
00507 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
00508                    AssumptionCache *AC) {
00509   // Assume undef could be zero.
00510   if (isa<UndefValue>(V))
00511     return true;
00512 
00513   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
00514   if (!VecTy) {
00515     unsigned BitWidth = V->getType()->getIntegerBitWidth();
00516     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00517     computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
00518                      dyn_cast<Instruction>(V), DT);
00519     return KnownZero.isAllOnesValue();
00520   }
00521 
00522   // Per-component check doesn't work with zeroinitializer
00523   Constant *C = dyn_cast<Constant>(V);
00524   if (!C)
00525     return false;
00526 
00527   if (C->isZeroValue())
00528     return true;
00529 
00530   // For a vector, KnownZero will only be true if all values are zero, so check
00531   // this per component
00532   unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
00533   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
00534     Constant *Elem = C->getAggregateElement(I);
00535     if (isa<UndefValue>(Elem))
00536       return true;
00537 
00538     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00539     computeKnownBits(Elem, KnownZero, KnownOne, DL);
00540     if (KnownZero.isAllOnesValue())
00541       return true;
00542   }
00543 
00544   return false;
00545 }
00546 
00547 void Lint::visitSDiv(BinaryOperator &I) {
00548   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00549          "Undefined behavior: Division by zero", &I);
00550 }
00551 
00552 void Lint::visitUDiv(BinaryOperator &I) {
00553   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00554          "Undefined behavior: Division by zero", &I);
00555 }
00556 
00557 void Lint::visitSRem(BinaryOperator &I) {
00558   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00559          "Undefined behavior: Division by zero", &I);
00560 }
00561 
00562 void Lint::visitURem(BinaryOperator &I) {
00563   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00564          "Undefined behavior: Division by zero", &I);
00565 }
00566 
00567 void Lint::visitAllocaInst(AllocaInst &I) {
00568   if (isa<ConstantInt>(I.getArraySize()))
00569     // This isn't undefined behavior, it's just an obvious pessimization.
00570     Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
00571            "Pessimization: Static alloca outside of entry block", &I);
00572 
00573   // TODO: Check for an unusual size (MSB set?)
00574 }
00575 
00576 void Lint::visitVAArgInst(VAArgInst &I) {
00577   visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
00578                        nullptr, MemRef::Read | MemRef::Write);
00579 }
00580 
00581 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
00582   visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
00583                        nullptr, MemRef::Branchee);
00584 
00585   Assert(I.getNumDestinations() != 0,
00586          "Undefined behavior: indirectbr with no destinations", &I);
00587 }
00588 
00589 void Lint::visitExtractElementInst(ExtractElementInst &I) {
00590   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
00591                                                         /*OffsetOk=*/false)))
00592     Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
00593            "Undefined result: extractelement index out of range", &I);
00594 }
00595 
00596 void Lint::visitInsertElementInst(InsertElementInst &I) {
00597   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
00598                                                         /*OffsetOk=*/false)))
00599     Assert(CI->getValue().ult(I.getType()->getNumElements()),
00600            "Undefined result: insertelement index out of range", &I);
00601 }
00602 
00603 void Lint::visitUnreachableInst(UnreachableInst &I) {
00604   // This isn't undefined behavior, it's merely suspicious.
00605   Assert(&I == &I.getParent()->front() ||
00606              std::prev(I.getIterator())->mayHaveSideEffects(),
00607          "Unusual: unreachable immediately preceded by instruction without "
00608          "side effects",
00609          &I);
00610 }
00611 
00612 /// findValue - Look through bitcasts and simple memory reference patterns
00613 /// to identify an equivalent, but more informative, value.  If OffsetOk
00614 /// is true, look through getelementptrs with non-zero offsets too.
00615 ///
00616 /// Most analysis passes don't require this logic, because instcombine
00617 /// will simplify most of these kinds of things away. But it's a goal of
00618 /// this Lint pass to be useful even on non-optimized IR.
00619 Value *Lint::findValue(Value *V, bool OffsetOk) const {
00620   SmallPtrSet<Value *, 4> Visited;
00621   return findValueImpl(V, OffsetOk, Visited);
00622 }
00623 
00624 /// findValueImpl - Implementation helper for findValue.
00625 Value *Lint::findValueImpl(Value *V, bool OffsetOk,
00626                            SmallPtrSetImpl<Value *> &Visited) const {
00627   // Detect self-referential values.
00628   if (!Visited.insert(V).second)
00629     return UndefValue::get(V->getType());
00630 
00631   // TODO: Look through sext or zext cast, when the result is known to
00632   // be interpreted as signed or unsigned, respectively.
00633   // TODO: Look through eliminable cast pairs.
00634   // TODO: Look through calls with unique return values.
00635   // TODO: Look through vector insert/extract/shuffle.
00636   V = OffsetOk ? GetUnderlyingObject(V, *DL) : V->stripPointerCasts();
00637   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
00638     BasicBlock::iterator BBI = L->getIterator();
00639     BasicBlock *BB = L->getParent();
00640     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
00641     for (;;) {
00642       if (!VisitedBlocks.insert(BB).second)
00643         break;
00644       if (Value *U =
00645           FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA))
00646         return findValueImpl(U, OffsetOk, Visited);
00647       if (BBI != BB->begin()) break;
00648       BB = BB->getUniquePredecessor();
00649       if (!BB) break;
00650       BBI = BB->end();
00651     }
00652   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
00653     if (Value *W = PN->hasConstantValue())
00654       if (W != V)
00655         return findValueImpl(W, OffsetOk, Visited);
00656   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
00657     if (CI->isNoopCast(*DL))
00658       return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
00659   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
00660     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
00661                                      Ex->getIndices()))
00662       if (W != V)
00663         return findValueImpl(W, OffsetOk, Visited);
00664   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00665     // Same as above, but for ConstantExpr instead of Instruction.
00666     if (Instruction::isCast(CE->getOpcode())) {
00667       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
00668                                CE->getOperand(0)->getType(), CE->getType(),
00669                                DL->getIntPtrType(V->getType())))
00670         return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
00671     } else if (CE->getOpcode() == Instruction::ExtractValue) {
00672       ArrayRef<unsigned> Indices = CE->getIndices();
00673       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
00674         if (W != V)
00675           return findValueImpl(W, OffsetOk, Visited);
00676     }
00677   }
00678 
00679   // As a last resort, try SimplifyInstruction or constant folding.
00680   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
00681     if (Value *W = SimplifyInstruction(Inst, *DL, TLI, DT, AC))
00682       return findValueImpl(W, OffsetOk, Visited);
00683   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00684     if (Value *W = ConstantFoldConstantExpression(CE, *DL, TLI))
00685       if (W != V)
00686         return findValueImpl(W, OffsetOk, Visited);
00687   }
00688 
00689   return V;
00690 }
00691 
00692 //===----------------------------------------------------------------------===//
00693 //  Implement the public interfaces to this file...
00694 //===----------------------------------------------------------------------===//
00695 
00696 FunctionPass *llvm::createLintPass() {
00697   return new Lint();
00698 }
00699 
00700 /// lintFunction - Check a function for errors, printing messages on stderr.
00701 ///
00702 void llvm::lintFunction(const Function &f) {
00703   Function &F = const_cast<Function&>(f);
00704   assert(!F.isDeclaration() && "Cannot lint external functions");
00705 
00706   legacy::FunctionPassManager FPM(F.getParent());
00707   Lint *V = new Lint();
00708   FPM.add(V);
00709   FPM.run(F);
00710 }
00711 
00712 /// lintModule - Check a module for errors, printing messages on stderr.
00713 ///
00714 void llvm::lintModule(const Module &M) {
00715   legacy::PassManager PM;
00716   Lint *V = new Lint();
00717   PM.add(V);
00718   PM.run(const_cast<Module&>(M));
00719 }