LLVM API Documentation

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 unsigned Read     = 1;
00063     static unsigned Write    = 2;
00064     static unsigned Callee   = 4;
00065     static 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, bool OffsetOk) const;
00102     Value *findValueImpl(Value *V, bool OffsetOk,
00103                          SmallPtrSetImpl<Value *> &Visited) const;
00104 
00105   public:
00106     Module *Mod;
00107     AliasAnalysis *AA;
00108     AssumptionCache *AC;
00109     DominatorTree *DT;
00110     const DataLayout *DL;
00111     TargetLibraryInfo *TLI;
00112 
00113     std::string Messages;
00114     raw_string_ostream MessagesStr;
00115 
00116     static char ID; // Pass identification, replacement for typeid
00117     Lint() : FunctionPass(ID), MessagesStr(Messages) {
00118       initializeLintPass(*PassRegistry::getPassRegistry());
00119     }
00120 
00121     bool runOnFunction(Function &F) override;
00122 
00123     void getAnalysisUsage(AnalysisUsage &AU) const override {
00124       AU.setPreservesAll();
00125       AU.addRequired<AliasAnalysis>();
00126       AU.addRequired<AssumptionCacheTracker>();
00127       AU.addRequired<TargetLibraryInfoWrapperPass>();
00128       AU.addRequired<DominatorTreeWrapperPass>();
00129     }
00130     void print(raw_ostream &O, const Module *M) const override {}
00131 
00132     void WriteValue(const Value *V) {
00133       if (!V) return;
00134       if (isa<Instruction>(V)) {
00135         MessagesStr << *V << '\n';
00136       } else {
00137         V->printAsOperand(MessagesStr, true, Mod);
00138         MessagesStr << '\n';
00139       }
00140     }
00141 
00142     // CheckFailed - A check failed, so print out the condition and the message
00143     // that failed.  This provides a nice place to put a breakpoint if you want
00144     // to see why something is not correct.
00145     void CheckFailed(const Twine &Message,
00146                      const Value *V1 = nullptr, const Value *V2 = nullptr,
00147                      const Value *V3 = nullptr, const Value *V4 = nullptr) {
00148       MessagesStr << Message.str() << "\n";
00149       WriteValue(V1);
00150       WriteValue(V2);
00151       WriteValue(V3);
00152       WriteValue(V4);
00153     }
00154   };
00155 }
00156 
00157 char Lint::ID = 0;
00158 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
00159                       false, true)
00160 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00161 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00162 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00163 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00164 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
00165                     false, true)
00166 
00167 // Assert - We know that cond should be true, if not print an error message.
00168 #define Assert(C, M) \
00169     do { if (!(C)) { CheckFailed(M); return; } } while (0)
00170 #define Assert1(C, M, V1) \
00171     do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
00172 #define Assert2(C, M, V1, V2) \
00173     do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
00174 #define Assert3(C, M, V1, V2, V3) \
00175     do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
00176 #define Assert4(C, M, V1, V2, V3, V4) \
00177     do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
00178 
00179 // Lint::run - This is the main Analysis entry point for a
00180 // function.
00181 //
00182 bool Lint::runOnFunction(Function &F) {
00183   Mod = F.getParent();
00184   AA = &getAnalysis<AliasAnalysis>();
00185   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00186   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00187   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00188   DL = DLP ? &DLP->getDataLayout() : nullptr;
00189   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00190   visit(F);
00191   dbgs() << MessagesStr.str();
00192   Messages.clear();
00193   return false;
00194 }
00195 
00196 void Lint::visitFunction(Function &F) {
00197   // This isn't undefined behavior, it's just a little unusual, and it's a
00198   // fairly common mistake to neglect to name a function.
00199   Assert1(F.hasName() || F.hasLocalLinkage(),
00200           "Unusual: Unnamed function with non-local linkage", &F);
00201 
00202   // TODO: Check for irreducible control flow.
00203 }
00204 
00205 void Lint::visitCallSite(CallSite CS) {
00206   Instruction &I = *CS.getInstruction();
00207   Value *Callee = CS.getCalledValue();
00208 
00209   visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
00210                        0, nullptr, MemRef::Callee);
00211 
00212   if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
00213     Assert1(CS.getCallingConv() == F->getCallingConv(),
00214             "Undefined behavior: Caller and callee calling convention differ",
00215             &I);
00216 
00217     FunctionType *FT = F->getFunctionType();
00218     unsigned NumActualArgs = CS.arg_size();
00219 
00220     Assert1(FT->isVarArg() ?
00221               FT->getNumParams() <= NumActualArgs :
00222               FT->getNumParams() == NumActualArgs,
00223             "Undefined behavior: Call argument count mismatches callee "
00224             "argument count", &I);
00225 
00226     Assert1(FT->getReturnType() == I.getType(),
00227             "Undefined behavior: Call return type mismatches "
00228             "callee return type", &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         Assert1(Formal->getType() == Actual->getType(),
00239                 "Undefined behavior: Call argument type mismatches "
00240                 "callee parameter type", &I);
00241 
00242         // Check that noalias arguments don't alias other arguments. This is
00243         // not fully precise because we don't know the sizes of the dereferenced
00244         // memory regions.
00245         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
00246           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
00247             if (AI != BI && (*BI)->getType()->isPointerTy()) {
00248               AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
00249               Assert1(Result != AliasAnalysis::MustAlias &&
00250                       Result != AliasAnalysis::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, AA->getTypeStoreSize(Ty),
00259                                DL ? DL->getABITypeAlignment(Ty) : 0,
00260                                Ty, 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       Assert1(!isa<AllocaInst>(Obj),
00271               "Undefined behavior: Call with \"tail\" keyword references "
00272               "alloca", &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(),
00298                                             /*OffsetOk=*/false)))
00299         if (Len->getValue().isIntN(32))
00300           Size = Len->getValue().getZExtValue();
00301       Assert1(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       Assert1(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   Assert1(!F->doesNotReturn(),
00373           "Unusual: Return statement in function with noreturn attribute",
00374           &I);
00375 
00376   if (Value *V = I.getReturnValue()) {
00377     Value *Obj = findValue(V, /*OffsetOk=*/true);
00378     Assert1(!isa<AllocaInst>(Obj),
00379             "Unusual: Returning alloca value", &I);
00380   }
00381 }
00382 
00383 // TODO: Check that the reference is in bounds.
00384 // TODO: Check readnone/readonly function attributes.
00385 void Lint::visitMemoryReference(Instruction &I,
00386                                 Value *Ptr, uint64_t Size, unsigned Align,
00387                                 Type *Ty, unsigned Flags) {
00388   // If no memory is being referenced, it doesn't matter if the pointer
00389   // is valid.
00390   if (Size == 0)
00391     return;
00392 
00393   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
00394   Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
00395           "Undefined behavior: Null pointer dereference", &I);
00396   Assert1(!isa<UndefValue>(UnderlyingObject),
00397           "Undefined behavior: Undef pointer dereference", &I);
00398   Assert1(!isa<ConstantInt>(UnderlyingObject) ||
00399           !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
00400           "Unusual: All-ones pointer dereference", &I);
00401   Assert1(!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       Assert1(!GV->isConstant(),
00408               "Undefined behavior: Write to read-only memory", &I);
00409     Assert1(!isa<Function>(UnderlyingObject) &&
00410             !isa<BlockAddress>(UnderlyingObject),
00411             "Undefined behavior: Write to text section", &I);
00412   }
00413   if (Flags & MemRef::Read) {
00414     Assert1(!isa<Function>(UnderlyingObject),
00415             "Unusual: Load from function body", &I);
00416     Assert1(!isa<BlockAddress>(UnderlyingObject),
00417             "Undefined behavior: Load from block address", &I);
00418   }
00419   if (Flags & MemRef::Callee) {
00420     Assert1(!isa<BlockAddress>(UnderlyingObject),
00421             "Undefined behavior: Call to block address", &I);
00422   }
00423   if (Flags & MemRef::Branchee) {
00424     Assert1(!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   int64_t Offset = 0;
00433   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
00434     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
00435     // something we can handle and if so extract the size of this base object
00436     // along with its alignment.
00437     uint64_t BaseSize = AliasAnalysis::UnknownSize;
00438     unsigned BaseAlign = 0;
00439 
00440     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
00441       Type *ATy = AI->getAllocatedType();
00442       if (DL && !AI->isArrayAllocation() && ATy->isSized())
00443         BaseSize = DL->getTypeAllocSize(ATy);
00444       BaseAlign = AI->getAlignment();
00445       if (DL && BaseAlign == 0 && ATy->isSized())
00446         BaseAlign = DL->getABITypeAlignment(ATy);
00447     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
00448       // If the global may be defined differently in another compilation unit
00449       // then don't warn about funky memory accesses.
00450       if (GV->hasDefinitiveInitializer()) {
00451         Type *GTy = GV->getType()->getElementType();
00452         if (DL && GTy->isSized())
00453           BaseSize = DL->getTypeAllocSize(GTy);
00454         BaseAlign = GV->getAlignment();
00455         if (DL && BaseAlign == 0 && GTy->isSized())
00456           BaseAlign = DL->getABITypeAlignment(GTy);
00457       }
00458     }
00459 
00460     // Accesses from before the start or after the end of the object are not
00461     // defined.
00462     Assert1(Size == AliasAnalysis::UnknownSize ||
00463             BaseSize == AliasAnalysis::UnknownSize ||
00464             (Offset >= 0 && Offset + Size <= BaseSize),
00465             "Undefined behavior: Buffer overflow", &I);
00466 
00467     // Accesses that say that the memory is more aligned than it is are not
00468     // defined.
00469     if (DL && Align == 0 && Ty && Ty->isSized())
00470       Align = DL->getABITypeAlignment(Ty);
00471     Assert1(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
00472             "Undefined behavior: Memory reference address is misaligned", &I);
00473   }
00474 }
00475 
00476 void Lint::visitLoadInst(LoadInst &I) {
00477   visitMemoryReference(I, I.getPointerOperand(),
00478                        AA->getTypeStoreSize(I.getType()), I.getAlignment(),
00479                        I.getType(), MemRef::Read);
00480 }
00481 
00482 void Lint::visitStoreInst(StoreInst &I) {
00483   visitMemoryReference(I, I.getPointerOperand(),
00484                        AA->getTypeStoreSize(I.getOperand(0)->getType()),
00485                        I.getAlignment(),
00486                        I.getOperand(0)->getType(), MemRef::Write);
00487 }
00488 
00489 void Lint::visitXor(BinaryOperator &I) {
00490   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
00491           !isa<UndefValue>(I.getOperand(1)),
00492           "Undefined result: xor(undef, undef)", &I);
00493 }
00494 
00495 void Lint::visitSub(BinaryOperator &I) {
00496   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
00497           !isa<UndefValue>(I.getOperand(1)),
00498           "Undefined result: sub(undef, undef)", &I);
00499 }
00500 
00501 void Lint::visitLShr(BinaryOperator &I) {
00502   if (ConstantInt *CI =
00503         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
00504     Assert1(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 =
00510         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
00511     Assert1(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 =
00517         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
00518     Assert1(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   Assert1(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   Assert2(
00616       SecondBeginCatch == nullptr,
00617       "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
00618       II, SecondBeginCatch);
00619   Assert1(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   Assert2(
00695       SecondEndCatch == nullptr,
00696       "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
00697       II, SecondEndCatch);
00698   Assert1(
00699       BeginCatchFound,
00700       "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
00701       II);
00702 }
00703 
00704 static bool isZero(Value *V, const DataLayout *DL, DominatorTree *DT,
00705                    AssumptionCache *AC) {
00706   // Assume undef could be zero.
00707   if (isa<UndefValue>(V))
00708     return true;
00709 
00710   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
00711   if (!VecTy) {
00712     unsigned BitWidth = V->getType()->getIntegerBitWidth();
00713     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00714     computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
00715                      dyn_cast<Instruction>(V), DT);
00716     return KnownZero.isAllOnesValue();
00717   }
00718 
00719   // Per-component check doesn't work with zeroinitializer
00720   Constant *C = dyn_cast<Constant>(V);
00721   if (!C)
00722     return false;
00723 
00724   if (C->isZeroValue())
00725     return true;
00726 
00727   // For a vector, KnownZero will only be true if all values are zero, so check
00728   // this per component
00729   unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
00730   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
00731     Constant *Elem = C->getAggregateElement(I);
00732     if (isa<UndefValue>(Elem))
00733       return true;
00734 
00735     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00736     computeKnownBits(Elem, KnownZero, KnownOne, DL);
00737     if (KnownZero.isAllOnesValue())
00738       return true;
00739   }
00740 
00741   return false;
00742 }
00743 
00744 void Lint::visitSDiv(BinaryOperator &I) {
00745   Assert1(!isZero(I.getOperand(1), DL, DT, AC),
00746           "Undefined behavior: Division by zero", &I);
00747 }
00748 
00749 void Lint::visitUDiv(BinaryOperator &I) {
00750   Assert1(!isZero(I.getOperand(1), DL, DT, AC),
00751           "Undefined behavior: Division by zero", &I);
00752 }
00753 
00754 void Lint::visitSRem(BinaryOperator &I) {
00755   Assert1(!isZero(I.getOperand(1), DL, DT, AC),
00756           "Undefined behavior: Division by zero", &I);
00757 }
00758 
00759 void Lint::visitURem(BinaryOperator &I) {
00760   Assert1(!isZero(I.getOperand(1), DL, DT, AC),
00761           "Undefined behavior: Division by zero", &I);
00762 }
00763 
00764 void Lint::visitAllocaInst(AllocaInst &I) {
00765   if (isa<ConstantInt>(I.getArraySize()))
00766     // This isn't undefined behavior, it's just an obvious pessimization.
00767     Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
00768             "Pessimization: Static alloca outside of entry block", &I);
00769 
00770   // TODO: Check for an unusual size (MSB set?)
00771 }
00772 
00773 void Lint::visitVAArgInst(VAArgInst &I) {
00774   visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0,
00775                        nullptr, MemRef::Read | MemRef::Write);
00776 }
00777 
00778 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
00779   visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0,
00780                        nullptr, MemRef::Branchee);
00781 
00782   Assert1(I.getNumDestinations() != 0,
00783           "Undefined behavior: indirectbr with no destinations", &I);
00784 }
00785 
00786 void Lint::visitExtractElementInst(ExtractElementInst &I) {
00787   if (ConstantInt *CI =
00788         dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
00789                                         /*OffsetOk=*/false)))
00790     Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
00791             "Undefined result: extractelement index out of range", &I);
00792 }
00793 
00794 void Lint::visitInsertElementInst(InsertElementInst &I) {
00795   if (ConstantInt *CI =
00796         dyn_cast<ConstantInt>(findValue(I.getOperand(2),
00797                                         /*OffsetOk=*/false)))
00798     Assert1(CI->getValue().ult(I.getType()->getNumElements()),
00799             "Undefined result: insertelement index out of range", &I);
00800 }
00801 
00802 void Lint::visitUnreachableInst(UnreachableInst &I) {
00803   // This isn't undefined behavior, it's merely suspicious.
00804   Assert1(&I == I.getParent()->begin() ||
00805           std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
00806           "Unusual: unreachable immediately preceded by instruction without "
00807           "side effects", &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, bool OffsetOk) const {
00818   SmallPtrSet<Value *, 4> Visited;
00819   return findValueImpl(V, OffsetOk, Visited);
00820 }
00821 
00822 /// findValueImpl - Implementation helper for findValue.
00823 Value *Lint::findValueImpl(Value *V, 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, 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, OffsetOk, Visited);
00854   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
00855     if (CI->isNoopCast(DL))
00856       return findValueImpl(CI->getOperand(0), 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, 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(),
00867                                CE->getType(),
00868                                DL ? DL->getIntPtrType(V->getType()) :
00869                                     Type::getInt64Ty(V->getContext())))
00870         return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
00871     } else if (CE->getOpcode() == Instruction::ExtractValue) {
00872       ArrayRef<unsigned> Indices = CE->getIndices();
00873       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
00874         if (W != V)
00875           return findValueImpl(W, OffsetOk, Visited);
00876     }
00877   }
00878 
00879   // As a last resort, try SimplifyInstruction or constant folding.
00880   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
00881     if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
00882       return findValueImpl(W, OffsetOk, Visited);
00883   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00884     if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
00885       if (W != V)
00886         return findValueImpl(W, OffsetOk, Visited);
00887   }
00888 
00889   return V;
00890 }
00891 
00892 //===----------------------------------------------------------------------===//
00893 //  Implement the public interfaces to this file...
00894 //===----------------------------------------------------------------------===//
00895 
00896 FunctionPass *llvm::createLintPass() {
00897   return new Lint();
00898 }
00899 
00900 /// lintFunction - Check a function for errors, printing messages on stderr.
00901 ///
00902 void llvm::lintFunction(const Function &f) {
00903   Function &F = const_cast<Function&>(f);
00904   assert(!F.isDeclaration() && "Cannot lint external functions");
00905 
00906   legacy::FunctionPassManager FPM(F.getParent());
00907   Lint *V = new Lint();
00908   FPM.add(V);
00909   FPM.run(F);
00910 }
00911 
00912 /// lintModule - Check a module for errors, printing messages on stderr.
00913 ///
00914 void llvm::lintModule(const Module &M) {
00915   legacy::PassManager PM;
00916   Lint *V = new Lint();
00917   PM.add(V);
00918   PM.run(const_cast<Module&>(M));
00919 }