887688737b0b26fbdeab872319ee3d872bb366d1
[oota-llvm.git] / lib / Analysis / Lint.cpp
1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass statically checks for common and easily-identified constructs
11 // which produce undefined or likely unintended behavior in LLVM IR.
12 //
13 // It is not a guarantee of correctness, in two ways. First, it isn't
14 // comprehensive. There are checks which could be done statically which are
15 // not yet implemented. Some of these are indicated by TODO comments, but
16 // those aren't comprehensive either. Second, many conditions cannot be
17 // checked statically. This pass does no dynamic instrumentation, so it
18 // can't check for all possible problems.
19 //
20 // Another limitation is that it assumes all code will be executed. A store
21 // through a null pointer in a basic block which is never reached is harmless,
22 // but this pass will warn about it anyway. This is the main reason why most
23 // of these checks live here instead of in the Verifier pass.
24 //
25 // Optimization passes may make conditions that this pass checks for more or
26 // less obvious. If an optimization pass appears to be introducing a warning,
27 // it may be that the optimization pass is merely exposing an existing
28 // condition in the code.
29 //
30 // This code may be run before instcombine. In many cases, instcombine checks
31 // for the same kinds of things and turns instructions with undefined behavior
32 // into unreachable (or equivalent). Because of this, this pass makes some
33 // effort to look through bitcasts and so on.
34 //
35 //===----------------------------------------------------------------------===//
36
37 #include "llvm/Analysis/Lint.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/Analysis/AliasAnalysis.h"
41 #include "llvm/Analysis/AssumptionCache.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/InstructionSimplify.h"
44 #include "llvm/Analysis/Loads.h"
45 #include "llvm/Analysis/Passes.h"
46 #include "llvm/Analysis/TargetLibraryInfo.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/IR/CallSite.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/InstVisitor.h"
53 #include "llvm/IR/IntrinsicInst.h"
54 #include "llvm/IR/LegacyPassManager.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 using namespace llvm;
59
60 namespace {
61   namespace MemRef {
62     static const unsigned Read     = 1;
63     static const unsigned Write    = 2;
64     static const unsigned Callee   = 4;
65     static const unsigned Branchee = 8;
66   }
67
68   class Lint : public FunctionPass, public InstVisitor<Lint> {
69     friend class InstVisitor<Lint>;
70
71     void visitFunction(Function &F);
72
73     void visitCallSite(CallSite CS);
74     void visitMemoryReference(Instruction &I, Value *Ptr,
75                               uint64_t Size, unsigned Align,
76                               Type *Ty, unsigned Flags);
77     void visitEHBeginCatch(IntrinsicInst *II);
78     void visitEHEndCatch(IntrinsicInst *II);
79
80     void visitCallInst(CallInst &I);
81     void visitInvokeInst(InvokeInst &I);
82     void visitReturnInst(ReturnInst &I);
83     void visitLoadInst(LoadInst &I);
84     void visitStoreInst(StoreInst &I);
85     void visitXor(BinaryOperator &I);
86     void visitSub(BinaryOperator &I);
87     void visitLShr(BinaryOperator &I);
88     void visitAShr(BinaryOperator &I);
89     void visitShl(BinaryOperator &I);
90     void visitSDiv(BinaryOperator &I);
91     void visitUDiv(BinaryOperator &I);
92     void visitSRem(BinaryOperator &I);
93     void visitURem(BinaryOperator &I);
94     void visitAllocaInst(AllocaInst &I);
95     void visitVAArgInst(VAArgInst &I);
96     void visitIndirectBrInst(IndirectBrInst &I);
97     void visitExtractElementInst(ExtractElementInst &I);
98     void visitInsertElementInst(InsertElementInst &I);
99     void visitUnreachableInst(UnreachableInst &I);
100
101     Value *findValue(Value *V, const DataLayout &DL, bool OffsetOk) const;
102     Value *findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
103                          SmallPtrSetImpl<Value *> &Visited) const;
104
105   public:
106     Module *Mod;
107     AliasAnalysis *AA;
108     AssumptionCache *AC;
109     DominatorTree *DT;
110     TargetLibraryInfo *TLI;
111
112     std::string Messages;
113     raw_string_ostream MessagesStr;
114
115     static char ID; // Pass identification, replacement for typeid
116     Lint() : FunctionPass(ID), MessagesStr(Messages) {
117       initializeLintPass(*PassRegistry::getPassRegistry());
118     }
119
120     bool runOnFunction(Function &F) override;
121
122     void getAnalysisUsage(AnalysisUsage &AU) const override {
123       AU.setPreservesAll();
124       AU.addRequired<AliasAnalysis>();
125       AU.addRequired<AssumptionCacheTracker>();
126       AU.addRequired<TargetLibraryInfoWrapperPass>();
127       AU.addRequired<DominatorTreeWrapperPass>();
128     }
129     void print(raw_ostream &O, const Module *M) const override {}
130
131     void WriteValues(ArrayRef<const Value *> Vs) {
132       for (const Value *V : Vs) {
133         if (!V)
134           continue;
135         if (isa<Instruction>(V)) {
136           MessagesStr << *V << '\n';
137         } else {
138           V->printAsOperand(MessagesStr, true, Mod);
139           MessagesStr << '\n';
140         }
141       }
142     }
143
144     // CheckFailed - A check failed, so print out the condition and the message
145     // that failed.  This provides a nice place to put a breakpoint if you want
146     // to see why something is not correct.
147     template <typename... Ts>
148     void CheckFailed(const Twine &Message, const Ts &...Vs) {
149       MessagesStr << Message << '\n';
150       WriteValues({Vs...});
151     }
152   };
153 }
154
155 char Lint::ID = 0;
156 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
157                       false, true)
158 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
159 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
160 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
161 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
162 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
163                     false, true)
164
165 // Assert - We know that cond should be true, if not print an error message.
166 #define Assert(C, ...) \
167     do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
168
169 // Lint::run - This is the main Analysis entry point for a
170 // function.
171 //
172 bool Lint::runOnFunction(Function &F) {
173   Mod = F.getParent();
174   AA = &getAnalysis<AliasAnalysis>();
175   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
176   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
177   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
178   visit(F);
179   dbgs() << MessagesStr.str();
180   Messages.clear();
181   return false;
182 }
183
184 void Lint::visitFunction(Function &F) {
185   // This isn't undefined behavior, it's just a little unusual, and it's a
186   // fairly common mistake to neglect to name a function.
187   Assert(F.hasName() || F.hasLocalLinkage(),
188          "Unusual: Unnamed function with non-local linkage", &F);
189
190   // TODO: Check for irreducible control flow.
191 }
192
193 void Lint::visitCallSite(CallSite CS) {
194   Instruction &I = *CS.getInstruction();
195   Value *Callee = CS.getCalledValue();
196   const DataLayout &DL = CS->getModule()->getDataLayout();
197
198   visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
199                        0, nullptr, MemRef::Callee);
200
201   if (Function *F = dyn_cast<Function>(findValue(Callee, DL,
202                                                  /*OffsetOk=*/false))) {
203     Assert(CS.getCallingConv() == F->getCallingConv(),
204            "Undefined behavior: Caller and callee calling convention differ",
205            &I);
206
207     FunctionType *FT = F->getFunctionType();
208     unsigned NumActualArgs = CS.arg_size();
209
210     Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
211                           : FT->getNumParams() == NumActualArgs,
212            "Undefined behavior: Call argument count mismatches callee "
213            "argument count",
214            &I);
215
216     Assert(FT->getReturnType() == I.getType(),
217            "Undefined behavior: Call return type mismatches "
218            "callee return type",
219            &I);
220
221     // Check argument types (in case the callee was casted) and attributes.
222     // TODO: Verify that caller and callee attributes are compatible.
223     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
224     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
225     for (; AI != AE; ++AI) {
226       Value *Actual = *AI;
227       if (PI != PE) {
228         Argument *Formal = PI++;
229         Assert(Formal->getType() == Actual->getType(),
230                "Undefined behavior: Call argument type mismatches "
231                "callee parameter type",
232                &I);
233
234         // Check that noalias arguments don't alias other arguments. This is
235         // not fully precise because we don't know the sizes of the dereferenced
236         // memory regions.
237         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
238           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
239             if (AI != BI && (*BI)->getType()->isPointerTy()) {
240               AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
241               Assert(Result != AliasAnalysis::MustAlias &&
242                          Result != AliasAnalysis::PartialAlias,
243                      "Unusual: noalias argument aliases another argument", &I);
244             }
245
246         // Check that an sret argument points to valid memory.
247         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
248           Type *Ty =
249             cast<PointerType>(Formal->getType())->getElementType();
250           visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
251                                DL.getABITypeAlignment(Ty), Ty,
252                                MemRef::Read | MemRef::Write);
253         }
254       }
255     }
256   }
257
258   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
259     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
260          AI != AE; ++AI) {
261       Value *Obj = findValue(*AI, DL, /*OffsetOk=*/true);
262       Assert(!isa<AllocaInst>(Obj),
263              "Undefined behavior: Call with \"tail\" keyword references "
264              "alloca",
265              &I);
266     }
267
268
269   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
270     switch (II->getIntrinsicID()) {
271     default: break;
272
273     // TODO: Check more intrinsics
274
275     case Intrinsic::memcpy: {
276       MemCpyInst *MCI = cast<MemCpyInst>(&I);
277       // TODO: If the size is known, use it.
278       visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
279                            MCI->getAlignment(), nullptr,
280                            MemRef::Write);
281       visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
282                            MCI->getAlignment(), nullptr,
283                            MemRef::Read);
284
285       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
286       // isn't expressive enough for what we really want to do. Known partial
287       // overlap is not distinguished from the case where nothing is known.
288       uint64_t Size = 0;
289       if (const ConstantInt *Len =
290               dyn_cast<ConstantInt>(findValue(MCI->getLength(), DL,
291                                               /*OffsetOk=*/false)))
292         if (Len->getValue().isIntN(32))
293           Size = Len->getValue().getZExtValue();
294       Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
295                  AliasAnalysis::MustAlias,
296              "Undefined behavior: memcpy source and destination overlap", &I);
297       break;
298     }
299     case Intrinsic::memmove: {
300       MemMoveInst *MMI = cast<MemMoveInst>(&I);
301       // TODO: If the size is known, use it.
302       visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
303                            MMI->getAlignment(), nullptr,
304                            MemRef::Write);
305       visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
306                            MMI->getAlignment(), nullptr,
307                            MemRef::Read);
308       break;
309     }
310     case Intrinsic::memset: {
311       MemSetInst *MSI = cast<MemSetInst>(&I);
312       // TODO: If the size is known, use it.
313       visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
314                            MSI->getAlignment(), nullptr,
315                            MemRef::Write);
316       break;
317     }
318
319     case Intrinsic::vastart:
320       Assert(I.getParent()->getParent()->isVarArg(),
321              "Undefined behavior: va_start called in a non-varargs function",
322              &I);
323
324       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
325                            0, nullptr, MemRef::Read | MemRef::Write);
326       break;
327     case Intrinsic::vacopy:
328       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
329                            0, nullptr, MemRef::Write);
330       visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
331                            0, nullptr, MemRef::Read);
332       break;
333     case Intrinsic::vaend:
334       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
335                            0, nullptr, MemRef::Read | MemRef::Write);
336       break;
337
338     case Intrinsic::stackrestore:
339       // Stackrestore doesn't read or write memory, but it sets the
340       // stack pointer, which the compiler may read from or write to
341       // at any time, so check it for both readability and writeability.
342       visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
343                            0, nullptr, MemRef::Read | MemRef::Write);
344       break;
345
346     case Intrinsic::eh_begincatch:
347       visitEHBeginCatch(II);
348       break;
349     case Intrinsic::eh_endcatch:
350       visitEHEndCatch(II);
351       break;
352     }
353 }
354
355 void Lint::visitCallInst(CallInst &I) {
356   return visitCallSite(&I);
357 }
358
359 void Lint::visitInvokeInst(InvokeInst &I) {
360   return visitCallSite(&I);
361 }
362
363 void Lint::visitReturnInst(ReturnInst &I) {
364   Function *F = I.getParent()->getParent();
365   Assert(!F->doesNotReturn(),
366          "Unusual: Return statement in function with noreturn attribute", &I);
367
368   if (Value *V = I.getReturnValue()) {
369     Value *Obj =
370         findValue(V, F->getParent()->getDataLayout(), /*OffsetOk=*/true);
371     Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
372   }
373 }
374
375 // TODO: Check that the reference is in bounds.
376 // TODO: Check readnone/readonly function attributes.
377 void Lint::visitMemoryReference(Instruction &I,
378                                 Value *Ptr, uint64_t Size, unsigned Align,
379                                 Type *Ty, unsigned Flags) {
380   // If no memory is being referenced, it doesn't matter if the pointer
381   // is valid.
382   if (Size == 0)
383     return;
384
385   Value *UnderlyingObject =
386       findValue(Ptr, I.getModule()->getDataLayout(), /*OffsetOk=*/true);
387   Assert(!isa<ConstantPointerNull>(UnderlyingObject),
388          "Undefined behavior: Null pointer dereference", &I);
389   Assert(!isa<UndefValue>(UnderlyingObject),
390          "Undefined behavior: Undef pointer dereference", &I);
391   Assert(!isa<ConstantInt>(UnderlyingObject) ||
392              !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
393          "Unusual: All-ones pointer dereference", &I);
394   Assert(!isa<ConstantInt>(UnderlyingObject) ||
395              !cast<ConstantInt>(UnderlyingObject)->isOne(),
396          "Unusual: Address one pointer dereference", &I);
397
398   if (Flags & MemRef::Write) {
399     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
400       Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
401              &I);
402     Assert(!isa<Function>(UnderlyingObject) &&
403                !isa<BlockAddress>(UnderlyingObject),
404            "Undefined behavior: Write to text section", &I);
405   }
406   if (Flags & MemRef::Read) {
407     Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
408            &I);
409     Assert(!isa<BlockAddress>(UnderlyingObject),
410            "Undefined behavior: Load from block address", &I);
411   }
412   if (Flags & MemRef::Callee) {
413     Assert(!isa<BlockAddress>(UnderlyingObject),
414            "Undefined behavior: Call to block address", &I);
415   }
416   if (Flags & MemRef::Branchee) {
417     Assert(!isa<Constant>(UnderlyingObject) ||
418                isa<BlockAddress>(UnderlyingObject),
419            "Undefined behavior: Branch to non-blockaddress", &I);
420   }
421
422   // Check for buffer overflows and misalignment.
423   // Only handles memory references that read/write something simple like an
424   // alloca instruction or a global variable.
425   auto &DL = I.getModule()->getDataLayout();
426   int64_t Offset = 0;
427   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
428     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
429     // something we can handle and if so extract the size of this base object
430     // along with its alignment.
431     uint64_t BaseSize = AliasAnalysis::UnknownSize;
432     unsigned BaseAlign = 0;
433
434     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
435       Type *ATy = AI->getAllocatedType();
436       if (!AI->isArrayAllocation() && ATy->isSized())
437         BaseSize = DL.getTypeAllocSize(ATy);
438       BaseAlign = AI->getAlignment();
439       if (BaseAlign == 0 && ATy->isSized())
440         BaseAlign = DL.getABITypeAlignment(ATy);
441     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
442       // If the global may be defined differently in another compilation unit
443       // then don't warn about funky memory accesses.
444       if (GV->hasDefinitiveInitializer()) {
445         Type *GTy = GV->getType()->getElementType();
446         if (GTy->isSized())
447           BaseSize = DL.getTypeAllocSize(GTy);
448         BaseAlign = GV->getAlignment();
449         if (BaseAlign == 0 && GTy->isSized())
450           BaseAlign = DL.getABITypeAlignment(GTy);
451       }
452     }
453
454     // Accesses from before the start or after the end of the object are not
455     // defined.
456     Assert(Size == AliasAnalysis::UnknownSize ||
457                BaseSize == AliasAnalysis::UnknownSize ||
458                (Offset >= 0 && Offset + Size <= BaseSize),
459            "Undefined behavior: Buffer overflow", &I);
460
461     // Accesses that say that the memory is more aligned than it is are not
462     // defined.
463     if (Align == 0 && Ty && Ty->isSized())
464       Align = DL.getABITypeAlignment(Ty);
465     Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
466            "Undefined behavior: Memory reference address is misaligned", &I);
467   }
468 }
469
470 void Lint::visitLoadInst(LoadInst &I) {
471   visitMemoryReference(I, I.getPointerOperand(),
472                        AA->getTypeStoreSize(I.getType()), I.getAlignment(),
473                        I.getType(), MemRef::Read);
474 }
475
476 void Lint::visitStoreInst(StoreInst &I) {
477   visitMemoryReference(I, I.getPointerOperand(),
478                        AA->getTypeStoreSize(I.getOperand(0)->getType()),
479                        I.getAlignment(),
480                        I.getOperand(0)->getType(), MemRef::Write);
481 }
482
483 void Lint::visitXor(BinaryOperator &I) {
484   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
485          "Undefined result: xor(undef, undef)", &I);
486 }
487
488 void Lint::visitSub(BinaryOperator &I) {
489   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
490          "Undefined result: sub(undef, undef)", &I);
491 }
492
493 void Lint::visitLShr(BinaryOperator &I) {
494   if (ConstantInt *CI = dyn_cast<ConstantInt>(
495           findValue(I.getOperand(1), I.getModule()->getDataLayout(),
496                     /*OffsetOk=*/false)))
497     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
498            "Undefined result: Shift count out of range", &I);
499 }
500
501 void Lint::visitAShr(BinaryOperator &I) {
502   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
503           I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
504     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
505            "Undefined result: Shift count out of range", &I);
506 }
507
508 void Lint::visitShl(BinaryOperator &I) {
509   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
510           I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
511     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
512            "Undefined result: Shift count out of range", &I);
513 }
514
515 static bool
516 allPredsCameFromLandingPad(BasicBlock *BB,
517                            SmallSet<BasicBlock *, 4> &VisitedBlocks) {
518   VisitedBlocks.insert(BB);
519   if (BB->isLandingPad())
520     return true;
521   // If we find a block with no predecessors, the search failed.
522   if (pred_empty(BB))
523     return false;
524   for (BasicBlock *Pred : predecessors(BB)) {
525     if (VisitedBlocks.count(Pred))
526       continue;
527     if (!allPredsCameFromLandingPad(Pred, VisitedBlocks))
528       return false;
529   }
530   return true;
531 }
532
533 static bool
534 allSuccessorsReachEndCatch(BasicBlock *BB, BasicBlock::iterator InstBegin,
535                            IntrinsicInst **SecondBeginCatch,
536                            SmallSet<BasicBlock *, 4> &VisitedBlocks) {
537   VisitedBlocks.insert(BB);
538   for (BasicBlock::iterator I = InstBegin, E = BB->end(); I != E; ++I) {
539     IntrinsicInst *IC = dyn_cast<IntrinsicInst>(I);
540     if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch)
541       return true;
542     // If we find another begincatch while looking for an endcatch,
543     // that's also an error.
544     if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch) {
545       *SecondBeginCatch = IC;
546       return false;
547     }
548   }
549
550   // If we reach a block with no successors while searching, the
551   // search has failed.
552   if (succ_empty(BB))
553     return false;
554   // Otherwise, search all of the successors.
555   for (BasicBlock *Succ : successors(BB)) {
556     if (VisitedBlocks.count(Succ))
557       continue;
558     if (!allSuccessorsReachEndCatch(Succ, Succ->begin(), SecondBeginCatch,
559                                     VisitedBlocks))
560       return false;
561   }
562   return true;
563 }
564
565 void Lint::visitEHBeginCatch(IntrinsicInst *II) {
566   // The checks in this function make a potentially dubious assumption about
567   // the CFG, namely that any block involved in a catch is only used for the
568   // catch.  This will very likely be true of IR generated by a front end,
569   // but it may cease to be true, for example, if the IR is run through a
570   // pass which combines similar blocks.
571   //
572   // In general, if we encounter a block the isn't dominated by the catch
573   // block while we are searching the catch block's successors for a call
574   // to end catch intrinsic, then it is possible that it will be legal for
575   // a path through this block to never reach a call to llvm.eh.endcatch.
576   // An analogous statement could be made about our search for a landing
577   // pad among the catch block's predecessors.
578   //
579   // What is actually required is that no path is possible at runtime that
580   // reaches a call to llvm.eh.begincatch without having previously visited
581   // a landingpad instruction and that no path is possible at runtime that
582   // calls llvm.eh.begincatch and does not subsequently call llvm.eh.endcatch
583   // (mentally adjusting for the fact that in reality these calls will be
584   // removed before code generation).
585   //
586   // Because this is a lint check, we take a pessimistic approach and warn if
587   // the control flow is potentially incorrect.
588
589   SmallSet<BasicBlock *, 4> VisitedBlocks;
590   BasicBlock *CatchBB = II->getParent();
591
592   // The begin catch must occur in a landing pad block or all paths
593   // to it must have come from a landing pad.
594   Assert(allPredsCameFromLandingPad(CatchBB, VisitedBlocks),
595          "llvm.eh.begincatch may be reachable without passing a landingpad",
596          II);
597
598   // Reset the visited block list.
599   VisitedBlocks.clear();
600
601   IntrinsicInst *SecondBeginCatch = nullptr;
602
603   // This has to be called before it is asserted.  Otherwise, the first assert
604   // below can never be hit.
605   bool EndCatchFound = allSuccessorsReachEndCatch(
606       CatchBB, std::next(static_cast<BasicBlock::iterator>(II)),
607       &SecondBeginCatch, VisitedBlocks);
608   Assert(
609       SecondBeginCatch == nullptr,
610       "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
611       II, SecondBeginCatch);
612   Assert(EndCatchFound,
613          "Some paths from llvm.eh.begincatch may not reach llvm.eh.endcatch",
614          II);
615 }
616
617 static bool allPredCameFromBeginCatch(
618     BasicBlock *BB, BasicBlock::reverse_iterator InstRbegin,
619     IntrinsicInst **SecondEndCatch, SmallSet<BasicBlock *, 4> &VisitedBlocks) {
620   VisitedBlocks.insert(BB);
621   // Look for a begincatch in this block.
622   for (BasicBlock::reverse_iterator RI = InstRbegin, RE = BB->rend(); RI != RE;
623        ++RI) {
624     IntrinsicInst *IC = dyn_cast<IntrinsicInst>(&*RI);
625     if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch)
626       return true;
627     // If we find another end catch before we find a begin catch, that's
628     // an error.
629     if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch) {
630       *SecondEndCatch = IC;
631       return false;
632     }
633     // If we encounter a landingpad instruction, the search failed.
634     if (isa<LandingPadInst>(*RI))
635       return false;
636   }
637   // If while searching we find a block with no predeccesors,
638   // the search failed.
639   if (pred_empty(BB))
640     return false;
641   // Search any predecessors we haven't seen before.
642   for (BasicBlock *Pred : predecessors(BB)) {
643     if (VisitedBlocks.count(Pred))
644       continue;
645     if (!allPredCameFromBeginCatch(Pred, Pred->rbegin(), SecondEndCatch,
646                                    VisitedBlocks))
647       return false;
648   }
649   return true;
650 }
651
652 void Lint::visitEHEndCatch(IntrinsicInst *II) {
653   // The check in this function makes a potentially dubious assumption about
654   // the CFG, namely that any block involved in a catch is only used for the
655   // catch.  This will very likely be true of IR generated by a front end,
656   // but it may cease to be true, for example, if the IR is run through a
657   // pass which combines similar blocks.
658   //
659   // In general, if we encounter a block the isn't post-dominated by the
660   // end catch block while we are searching the end catch block's predecessors
661   // for a call to the begin catch intrinsic, then it is possible that it will
662   // be legal for a path to reach the end catch block without ever having
663   // called llvm.eh.begincatch.
664   //
665   // What is actually required is that no path is possible at runtime that
666   // reaches a call to llvm.eh.endcatch without having previously visited
667   // a call to llvm.eh.begincatch (mentally adjusting for the fact that in
668   // reality these calls will be removed before code generation).
669   //
670   // Because this is a lint check, we take a pessimistic approach and warn if
671   // the control flow is potentially incorrect.
672
673   BasicBlock *EndCatchBB = II->getParent();
674
675   // Alls paths to the end catch call must pass through a begin catch call.
676
677   // If llvm.eh.begincatch wasn't called in the current block, we'll use this
678   // lambda to recursively look for it in predecessors.
679   SmallSet<BasicBlock *, 4> VisitedBlocks;
680   IntrinsicInst *SecondEndCatch = nullptr;
681
682   // This has to be called before it is asserted.  Otherwise, the first assert
683   // below can never be hit.
684   bool BeginCatchFound =
685       allPredCameFromBeginCatch(EndCatchBB, BasicBlock::reverse_iterator(II),
686                                 &SecondEndCatch, VisitedBlocks);
687   Assert(
688       SecondEndCatch == nullptr,
689       "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
690       II, SecondEndCatch);
691   Assert(BeginCatchFound,
692          "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
693          II);
694 }
695
696 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
697                    AssumptionCache *AC) {
698   // Assume undef could be zero.
699   if (isa<UndefValue>(V))
700     return true;
701
702   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
703   if (!VecTy) {
704     unsigned BitWidth = V->getType()->getIntegerBitWidth();
705     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
706     computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
707                      dyn_cast<Instruction>(V), DT);
708     return KnownZero.isAllOnesValue();
709   }
710
711   // Per-component check doesn't work with zeroinitializer
712   Constant *C = dyn_cast<Constant>(V);
713   if (!C)
714     return false;
715
716   if (C->isZeroValue())
717     return true;
718
719   // For a vector, KnownZero will only be true if all values are zero, so check
720   // this per component
721   unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
722   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
723     Constant *Elem = C->getAggregateElement(I);
724     if (isa<UndefValue>(Elem))
725       return true;
726
727     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
728     computeKnownBits(Elem, KnownZero, KnownOne, DL);
729     if (KnownZero.isAllOnesValue())
730       return true;
731   }
732
733   return false;
734 }
735
736 void Lint::visitSDiv(BinaryOperator &I) {
737   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
738          "Undefined behavior: Division by zero", &I);
739 }
740
741 void Lint::visitUDiv(BinaryOperator &I) {
742   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
743          "Undefined behavior: Division by zero", &I);
744 }
745
746 void Lint::visitSRem(BinaryOperator &I) {
747   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
748          "Undefined behavior: Division by zero", &I);
749 }
750
751 void Lint::visitURem(BinaryOperator &I) {
752   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
753          "Undefined behavior: Division by zero", &I);
754 }
755
756 void Lint::visitAllocaInst(AllocaInst &I) {
757   if (isa<ConstantInt>(I.getArraySize()))
758     // This isn't undefined behavior, it's just an obvious pessimization.
759     Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
760            "Pessimization: Static alloca outside of entry block", &I);
761
762   // TODO: Check for an unusual size (MSB set?)
763 }
764
765 void Lint::visitVAArgInst(VAArgInst &I) {
766   visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0,
767                        nullptr, MemRef::Read | MemRef::Write);
768 }
769
770 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
771   visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0,
772                        nullptr, MemRef::Branchee);
773
774   Assert(I.getNumDestinations() != 0,
775          "Undefined behavior: indirectbr with no destinations", &I);
776 }
777
778 void Lint::visitExtractElementInst(ExtractElementInst &I) {
779   if (ConstantInt *CI = dyn_cast<ConstantInt>(
780           findValue(I.getIndexOperand(), I.getModule()->getDataLayout(),
781                     /*OffsetOk=*/false)))
782     Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
783            "Undefined result: extractelement index out of range", &I);
784 }
785
786 void Lint::visitInsertElementInst(InsertElementInst &I) {
787   if (ConstantInt *CI = dyn_cast<ConstantInt>(
788           findValue(I.getOperand(2), I.getModule()->getDataLayout(),
789                     /*OffsetOk=*/false)))
790     Assert(CI->getValue().ult(I.getType()->getNumElements()),
791            "Undefined result: insertelement index out of range", &I);
792 }
793
794 void Lint::visitUnreachableInst(UnreachableInst &I) {
795   // This isn't undefined behavior, it's merely suspicious.
796   Assert(&I == I.getParent()->begin() ||
797              std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
798          "Unusual: unreachable immediately preceded by instruction without "
799          "side effects",
800          &I);
801 }
802
803 /// findValue - Look through bitcasts and simple memory reference patterns
804 /// to identify an equivalent, but more informative, value.  If OffsetOk
805 /// is true, look through getelementptrs with non-zero offsets too.
806 ///
807 /// Most analysis passes don't require this logic, because instcombine
808 /// will simplify most of these kinds of things away. But it's a goal of
809 /// this Lint pass to be useful even on non-optimized IR.
810 Value *Lint::findValue(Value *V, const DataLayout &DL, bool OffsetOk) const {
811   SmallPtrSet<Value *, 4> Visited;
812   return findValueImpl(V, DL, OffsetOk, Visited);
813 }
814
815 /// findValueImpl - Implementation helper for findValue.
816 Value *Lint::findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
817                            SmallPtrSetImpl<Value *> &Visited) const {
818   // Detect self-referential values.
819   if (!Visited.insert(V).second)
820     return UndefValue::get(V->getType());
821
822   // TODO: Look through sext or zext cast, when the result is known to
823   // be interpreted as signed or unsigned, respectively.
824   // TODO: Look through eliminable cast pairs.
825   // TODO: Look through calls with unique return values.
826   // TODO: Look through vector insert/extract/shuffle.
827   V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
828   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
829     BasicBlock::iterator BBI = L;
830     BasicBlock *BB = L->getParent();
831     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
832     for (;;) {
833       if (!VisitedBlocks.insert(BB).second)
834         break;
835       if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
836                                               BB, BBI, 6, AA))
837         return findValueImpl(U, DL, OffsetOk, Visited);
838       if (BBI != BB->begin()) break;
839       BB = BB->getUniquePredecessor();
840       if (!BB) break;
841       BBI = BB->end();
842     }
843   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
844     if (Value *W = PN->hasConstantValue())
845       if (W != V)
846         return findValueImpl(W, DL, OffsetOk, Visited);
847   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
848     if (CI->isNoopCast(DL))
849       return findValueImpl(CI->getOperand(0), DL, OffsetOk, Visited);
850   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
851     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
852                                      Ex->getIndices()))
853       if (W != V)
854         return findValueImpl(W, DL, OffsetOk, Visited);
855   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
856     // Same as above, but for ConstantExpr instead of Instruction.
857     if (Instruction::isCast(CE->getOpcode())) {
858       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
859                                CE->getOperand(0)->getType(), CE->getType(),
860                                DL.getIntPtrType(V->getType())))
861         return findValueImpl(CE->getOperand(0), DL, OffsetOk, Visited);
862     } else if (CE->getOpcode() == Instruction::ExtractValue) {
863       ArrayRef<unsigned> Indices = CE->getIndices();
864       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
865         if (W != V)
866           return findValueImpl(W, DL, OffsetOk, Visited);
867     }
868   }
869
870   // As a last resort, try SimplifyInstruction or constant folding.
871   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
872     if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
873       return findValueImpl(W, DL, OffsetOk, Visited);
874   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
875     if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
876       if (W != V)
877         return findValueImpl(W, DL, OffsetOk, Visited);
878   }
879
880   return V;
881 }
882
883 //===----------------------------------------------------------------------===//
884 //  Implement the public interfaces to this file...
885 //===----------------------------------------------------------------------===//
886
887 FunctionPass *llvm::createLintPass() {
888   return new Lint();
889 }
890
891 /// lintFunction - Check a function for errors, printing messages on stderr.
892 ///
893 void llvm::lintFunction(const Function &f) {
894   Function &F = const_cast<Function&>(f);
895   assert(!F.isDeclaration() && "Cannot lint external functions");
896
897   legacy::FunctionPassManager FPM(F.getParent());
898   Lint *V = new Lint();
899   FPM.add(V);
900   FPM.run(F);
901 }
902
903 /// lintModule - Check a module for errors, printing messages on stderr.
904 ///
905 void llvm::lintModule(const Module &M) {
906   legacy::PassManager PM;
907   Lint *V = new Lint();
908   PM.add(V);
909   PM.run(const_cast<Module&>(M));
910 }