LLVM  13.0.0git
Lint.cpp
Go to the documentation of this file.
1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass statically checks for common and easily-identified constructs
10 // which produce undefined or likely unintended behavior in LLVM IR.
11 //
12 // It is not a guarantee of correctness, in two ways. First, it isn't
13 // comprehensive. There are checks which could be done statically which are
14 // not yet implemented. Some of these are indicated by TODO comments, but
15 // those aren't comprehensive either. Second, many conditions cannot be
16 // checked statically. This pass does no dynamic instrumentation, so it
17 // can't check for all possible problems.
18 //
19 // Another limitation is that it assumes all code will be executed. A store
20 // through a null pointer in a basic block which is never reached is harmless,
21 // but this pass will warn about it anyway. This is the main reason why most
22 // of these checks live here instead of in the Verifier pass.
23 //
24 // Optimization passes may make conditions that this pass checks for more or
25 // less obvious. If an optimization pass appears to be introducing a warning,
26 // it may be that the optimization pass is merely exposing an existing
27 // condition in the code.
28 //
29 // This code may be run before instcombine. In many cases, instcombine checks
30 // for the same kinds of things and turns instructions with undefined behavior
31 // into unreachable (or equivalent). Because of this, this pass makes some
32 // effort to look through bitcasts and so on.
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "llvm/Analysis/Lint.h"
37 #include "llvm/ADT/APInt.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Twine.h"
45 #include "llvm/Analysis/Loads.h"
47 #include "llvm/Analysis/Passes.h"
50 #include "llvm/IR/Argument.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/Constant.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/GlobalVariable.h"
59 #include "llvm/IR/InstVisitor.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/PassManager.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/InitializePasses.h"
70 #include "llvm/Pass.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/KnownBits.h"
76 #include <cassert>
77 #include <cstdint>
78 #include <iterator>
79 #include <string>
80 
81 using namespace llvm;
82 
83 namespace {
84 namespace MemRef {
85 static const unsigned Read = 1;
86 static const unsigned Write = 2;
87 static const unsigned Callee = 4;
88 static const unsigned Branchee = 8;
89 } // end namespace MemRef
90 
91 class Lint : public InstVisitor<Lint> {
92  friend class InstVisitor<Lint>;
93 
94  void visitFunction(Function &F);
95 
96  void visitCallBase(CallBase &CB);
97  void visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
98  MaybeAlign Alignment, Type *Ty, unsigned Flags);
99  void visitEHBeginCatch(IntrinsicInst *II);
100  void visitEHEndCatch(IntrinsicInst *II);
101 
102  void visitReturnInst(ReturnInst &I);
103  void visitLoadInst(LoadInst &I);
104  void visitStoreInst(StoreInst &I);
105  void visitXor(BinaryOperator &I);
106  void visitSub(BinaryOperator &I);
107  void visitLShr(BinaryOperator &I);
108  void visitAShr(BinaryOperator &I);
109  void visitShl(BinaryOperator &I);
110  void visitSDiv(BinaryOperator &I);
111  void visitUDiv(BinaryOperator &I);
112  void visitSRem(BinaryOperator &I);
113  void visitURem(BinaryOperator &I);
114  void visitAllocaInst(AllocaInst &I);
115  void visitVAArgInst(VAArgInst &I);
116  void visitIndirectBrInst(IndirectBrInst &I);
117  void visitExtractElementInst(ExtractElementInst &I);
118  void visitInsertElementInst(InsertElementInst &I);
119  void visitUnreachableInst(UnreachableInst &I);
120 
121  Value *findValue(Value *V, bool OffsetOk) const;
122  Value *findValueImpl(Value *V, bool OffsetOk,
123  SmallPtrSetImpl<Value *> &Visited) const;
124 
125 public:
126  Module *Mod;
127  const DataLayout *DL;
128  AliasAnalysis *AA;
129  AssumptionCache *AC;
130  DominatorTree *DT;
131  TargetLibraryInfo *TLI;
132 
133  std::string Messages;
134  raw_string_ostream MessagesStr;
135 
136  Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
138  : Mod(Mod), DL(DL), AA(AA), AC(AC), DT(DT), TLI(TLI),
139  MessagesStr(Messages) {}
140 
141  void WriteValues(ArrayRef<const Value *> Vs) {
142  for (const Value *V : Vs) {
143  if (!V)
144  continue;
145  if (isa<Instruction>(V)) {
146  MessagesStr << *V << '\n';
147  } else {
148  V->printAsOperand(MessagesStr, true, Mod);
149  MessagesStr << '\n';
150  }
151  }
152  }
153 
154  /// A check failed, so printout out the condition and the message.
155  ///
156  /// This provides a nice place to put a breakpoint if you want to see why
157  /// something is not correct.
158  void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
159 
160  /// A check failed (with values to print).
161  ///
162  /// This calls the Message-only version so that the above is easier to set
163  /// a breakpoint on.
164  template <typename T1, typename... Ts>
165  void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
166  CheckFailed(Message);
167  WriteValues({V1, Vs...});
168  }
169 };
170 } // end anonymous namespace
171 
172 // Assert - We know that cond should be true, if not print an error message.
173 #define Assert(C, ...) \
174  do { \
175  if (!(C)) { \
176  CheckFailed(__VA_ARGS__); \
177  return; \
178  } \
179  } while (false)
180 
181 void Lint::visitFunction(Function &F) {
182  // This isn't undefined behavior, it's just a little unusual, and it's a
183  // fairly common mistake to neglect to name a function.
184  Assert(F.hasName() || F.hasLocalLinkage(),
185  "Unusual: Unnamed function with non-local linkage", &F);
186 
187  // TODO: Check for irreducible control flow.
188 }
189 
190 void Lint::visitCallBase(CallBase &I) {
191  Value *Callee = I.getCalledOperand();
192 
193  visitMemoryReference(I, MemoryLocation::getAfter(Callee), None, nullptr,
194  MemRef::Callee);
195 
196  if (Function *F = dyn_cast<Function>(findValue(Callee,
197  /*OffsetOk=*/false))) {
198  Assert(I.getCallingConv() == F->getCallingConv(),
199  "Undefined behavior: Caller and callee calling convention differ",
200  &I);
201 
202  FunctionType *FT = F->getFunctionType();
203  unsigned NumActualArgs = I.arg_size();
204 
205  Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
206  : FT->getNumParams() == NumActualArgs,
207  "Undefined behavior: Call argument count mismatches callee "
208  "argument count",
209  &I);
210 
211  Assert(FT->getReturnType() == I.getType(),
212  "Undefined behavior: Call return type mismatches "
213  "callee return type",
214  &I);
215 
216  // Check argument types (in case the callee was casted) and attributes.
217  // TODO: Verify that caller and callee attributes are compatible.
218  Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
219  auto AI = I.arg_begin(), AE = I.arg_end();
220  for (; AI != AE; ++AI) {
221  Value *Actual = *AI;
222  if (PI != PE) {
223  Argument *Formal = &*PI++;
224  Assert(Formal->getType() == Actual->getType(),
225  "Undefined behavior: Call argument type mismatches "
226  "callee parameter type",
227  &I);
228 
229  // Check that noalias arguments don't alias other arguments. This is
230  // not fully precise because we don't know the sizes of the dereferenced
231  // memory regions.
232  if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) {
233  AttributeList PAL = I.getAttributes();
234  unsigned ArgNo = 0;
235  for (auto BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
236  // Skip ByVal arguments since they will be memcpy'd to the callee's
237  // stack so we're not really passing the pointer anyway.
238  if (PAL.hasParamAttribute(ArgNo, Attribute::ByVal))
239  continue;
240  // If both arguments are readonly, they have no dependence.
241  if (Formal->onlyReadsMemory() && I.onlyReadsMemory(ArgNo))
242  continue;
243  if (AI != BI && (*BI)->getType()->isPointerTy()) {
244  AliasResult Result = AA->alias(*AI, *BI);
245  Assert(Result != AliasResult::MustAlias &&
246  Result != AliasResult::PartialAlias,
247  "Unusual: noalias argument aliases another argument", &I);
248  }
249  }
250  }
251 
252  // Check that an sret argument points to valid memory.
253  if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
254  Type *Ty = Formal->getParamStructRetType();
255  MemoryLocation Loc(
256  Actual, LocationSize::precise(DL->getTypeStoreSize(Ty)));
257  visitMemoryReference(I, Loc, DL->getABITypeAlign(Ty), Ty,
258  MemRef::Read | MemRef::Write);
259  }
260  }
261  }
262  }
263 
264  if (const auto *CI = dyn_cast<CallInst>(&I)) {
265  if (CI->isTailCall()) {
266  const AttributeList &PAL = CI->getAttributes();
267  unsigned ArgNo = 0;
268  for (Value *Arg : I.args()) {
269  // Skip ByVal arguments since they will be memcpy'd to the callee's
270  // stack anyway.
271  if (PAL.hasParamAttribute(ArgNo++, Attribute::ByVal))
272  continue;
273  Value *Obj = findValue(Arg, /*OffsetOk=*/true);
274  Assert(!isa<AllocaInst>(Obj),
275  "Undefined behavior: Call with \"tail\" keyword references "
276  "alloca",
277  &I);
278  }
279  }
280  }
281 
282  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
283  switch (II->getIntrinsicID()) {
284  default:
285  break;
286 
287  // TODO: Check more intrinsics
288 
289  case Intrinsic::memcpy: {
290  MemCpyInst *MCI = cast<MemCpyInst>(&I);
291  visitMemoryReference(I, MemoryLocation::getForDest(MCI),
292  MCI->getDestAlign(), nullptr, MemRef::Write);
293  visitMemoryReference(I, MemoryLocation::getForSource(MCI),
294  MCI->getSourceAlign(), nullptr, MemRef::Read);
295 
296  // Check that the memcpy arguments don't overlap. The AliasAnalysis API
297  // isn't expressive enough for what we really want to do. Known partial
298  // overlap is not distinguished from the case where nothing is known.
300  if (const ConstantInt *Len =
301  dyn_cast<ConstantInt>(findValue(MCI->getLength(),
302  /*OffsetOk=*/false)))
303  if (Len->getValue().isIntN(32))
304  Size = LocationSize::precise(Len->getValue().getZExtValue());
305  Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
307  "Undefined behavior: memcpy source and destination overlap", &I);
308  break;
309  }
310  case Intrinsic::memcpy_inline: {
311  MemCpyInlineInst *MCII = cast<MemCpyInlineInst>(&I);
312  const uint64_t Size = MCII->getLength()->getValue().getLimitedValue();
313  visitMemoryReference(I, MemoryLocation::getForDest(MCII),
314  MCII->getDestAlign(), nullptr, MemRef::Write);
315  visitMemoryReference(I, MemoryLocation::getForSource(MCII),
316  MCII->getSourceAlign(), nullptr, MemRef::Read);
317 
318  // Check that the memcpy arguments don't overlap. The AliasAnalysis API
319  // isn't expressive enough for what we really want to do. Known partial
320  // overlap is not distinguished from the case where nothing is known.
322  Assert(AA->alias(MCII->getSource(), LS, MCII->getDest(), LS) !=
324  "Undefined behavior: memcpy source and destination overlap", &I);
325  break;
326  }
327  case Intrinsic::memmove: {
328  MemMoveInst *MMI = cast<MemMoveInst>(&I);
329  visitMemoryReference(I, MemoryLocation::getForDest(MMI),
330  MMI->getDestAlign(), nullptr, MemRef::Write);
331  visitMemoryReference(I, MemoryLocation::getForSource(MMI),
332  MMI->getSourceAlign(), nullptr, MemRef::Read);
333  break;
334  }
335  case Intrinsic::memset: {
336  MemSetInst *MSI = cast<MemSetInst>(&I);
337  visitMemoryReference(I, MemoryLocation::getForDest(MSI),
338  MSI->getDestAlign(), nullptr, MemRef::Write);
339  break;
340  }
341 
342  case Intrinsic::vastart:
343  Assert(I.getParent()->getParent()->isVarArg(),
344  "Undefined behavior: va_start called in a non-varargs function",
345  &I);
346 
347  visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None,
348  nullptr, MemRef::Read | MemRef::Write);
349  break;
350  case Intrinsic::vacopy:
351  visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None,
352  nullptr, MemRef::Write);
353  visitMemoryReference(I, MemoryLocation::getForArgument(&I, 1, TLI), None,
354  nullptr, MemRef::Read);
355  break;
356  case Intrinsic::vaend:
357  visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None,
358  nullptr, MemRef::Read | MemRef::Write);
359  break;
360 
361  case Intrinsic::stackrestore:
362  // Stackrestore doesn't read or write memory, but it sets the
363  // stack pointer, which the compiler may read from or write to
364  // at any time, so check it for both readability and writeability.
365  visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None,
366  nullptr, MemRef::Read | MemRef::Write);
367  break;
368  case Intrinsic::get_active_lane_mask:
369  if (auto *TripCount = dyn_cast<ConstantInt>(I.getArgOperand(1)))
370  Assert(!TripCount->isZero(), "get_active_lane_mask: operand #2 "
371  "must be greater than 0", &I);
372  break;
373  }
374 }
375 
376 void Lint::visitReturnInst(ReturnInst &I) {
377  Function *F = I.getParent()->getParent();
378  Assert(!F->doesNotReturn(),
379  "Unusual: Return statement in function with noreturn attribute", &I);
380 
381  if (Value *V = I.getReturnValue()) {
382  Value *Obj = findValue(V, /*OffsetOk=*/true);
383  Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
384  }
385 }
386 
387 // TODO: Check that the reference is in bounds.
388 // TODO: Check readnone/readonly function attributes.
389 void Lint::visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
390  MaybeAlign Align, Type *Ty, unsigned Flags) {
391  // If no memory is being referenced, it doesn't matter if the pointer
392  // is valid.
393  if (Loc.Size.isZero())
394  return;
395 
396  Value *Ptr = const_cast<Value *>(Loc.Ptr);
397  Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
398  Assert(!isa<ConstantPointerNull>(UnderlyingObject),
399  "Undefined behavior: Null pointer dereference", &I);
400  Assert(!isa<UndefValue>(UnderlyingObject),
401  "Undefined behavior: Undef pointer dereference", &I);
402  Assert(!isa<ConstantInt>(UnderlyingObject) ||
403  !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
404  "Unusual: All-ones pointer dereference", &I);
405  Assert(!isa<ConstantInt>(UnderlyingObject) ||
406  !cast<ConstantInt>(UnderlyingObject)->isOne(),
407  "Unusual: Address one pointer dereference", &I);
408 
409  if (Flags & MemRef::Write) {
410  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
411  Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
412  &I);
413  Assert(!isa<Function>(UnderlyingObject) &&
414  !isa<BlockAddress>(UnderlyingObject),
415  "Undefined behavior: Write to text section", &I);
416  }
417  if (Flags & MemRef::Read) {
418  Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
419  &I);
420  Assert(!isa<BlockAddress>(UnderlyingObject),
421  "Undefined behavior: Load from block address", &I);
422  }
423  if (Flags & MemRef::Callee) {
424  Assert(!isa<BlockAddress>(UnderlyingObject),
425  "Undefined behavior: Call to block address", &I);
426  }
427  if (Flags & MemRef::Branchee) {
428  Assert(!isa<Constant>(UnderlyingObject) ||
429  isa<BlockAddress>(UnderlyingObject),
430  "Undefined behavior: Branch to non-blockaddress", &I);
431  }
432 
433  // Check for buffer overflows and misalignment.
434  // Only handles memory references that read/write something simple like an
435  // alloca instruction or a global variable.
436  int64_t Offset = 0;
437  if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
438  // OK, so the access is to a constant offset from Ptr. Check that Ptr is
439  // something we can handle and if so extract the size of this base object
440  // along with its alignment.
441  uint64_t BaseSize = MemoryLocation::UnknownSize;
442  MaybeAlign BaseAlign;
443 
444  if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
445  Type *ATy = AI->getAllocatedType();
446  if (!AI->isArrayAllocation() && ATy->isSized())
447  BaseSize = DL->getTypeAllocSize(ATy);
448  BaseAlign = AI->getAlign();
449  } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
450  // If the global may be defined differently in another compilation unit
451  // then don't warn about funky memory accesses.
452  if (GV->hasDefinitiveInitializer()) {
453  Type *GTy = GV->getValueType();
454  if (GTy->isSized())
455  BaseSize = DL->getTypeAllocSize(GTy);
456  BaseAlign = GV->getAlign();
457  if (!BaseAlign && GTy->isSized())
458  BaseAlign = DL->getABITypeAlign(GTy);
459  }
460  }
461 
462  // Accesses from before the start or after the end of the object are not
463  // defined.
464  Assert(!Loc.Size.hasValue() || BaseSize == MemoryLocation::UnknownSize ||
465  (Offset >= 0 && Offset + Loc.Size.getValue() <= BaseSize),
466  "Undefined behavior: Buffer overflow", &I);
467 
468  // Accesses that say that the memory is more aligned than it is are not
469  // defined.
470  if (!Align && Ty && Ty->isSized())
471  Align = DL->getABITypeAlign(Ty);
472  if (BaseAlign && Align)
473  Assert(*Align <= commonAlignment(*BaseAlign, Offset),
474  "Undefined behavior: Memory reference address is misaligned", &I);
475  }
476 }
477 
478 void Lint::visitLoadInst(LoadInst &I) {
479  visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), I.getType(),
480  MemRef::Read);
481 }
482 
483 void Lint::visitStoreInst(StoreInst &I) {
484  visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(),
485  I.getOperand(0)->getType(), MemRef::Write);
486 }
487 
488 void Lint::visitXor(BinaryOperator &I) {
489  Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
490  "Undefined result: xor(undef, undef)", &I);
491 }
492 
493 void Lint::visitSub(BinaryOperator &I) {
494  Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
495  "Undefined result: sub(undef, undef)", &I);
496 }
497 
498 void Lint::visitLShr(BinaryOperator &I) {
499  if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
500  /*OffsetOk=*/false)))
501  Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
502  "Undefined result: Shift count out of range", &I);
503 }
504 
505 void Lint::visitAShr(BinaryOperator &I) {
506  if (ConstantInt *CI =
507  dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
508  Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
509  "Undefined result: Shift count out of range", &I);
510 }
511 
512 void Lint::visitShl(BinaryOperator &I) {
513  if (ConstantInt *CI =
514  dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
515  Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
516  "Undefined result: Shift count out of range", &I);
517 }
518 
519 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
520  AssumptionCache *AC) {
521  // Assume undef could be zero.
522  if (isa<UndefValue>(V))
523  return true;
524 
525  VectorType *VecTy = dyn_cast<VectorType>(V->getType());
526  if (!VecTy) {
527  KnownBits Known =
528  computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT);
529  return Known.isZero();
530  }
531 
532  // Per-component check doesn't work with zeroinitializer
533  Constant *C = dyn_cast<Constant>(V);
534  if (!C)
535  return false;
536 
537  if (C->isZeroValue())
538  return true;
539 
540  // For a vector, KnownZero will only be true if all values are zero, so check
541  // this per component
542  for (unsigned I = 0, N = cast<FixedVectorType>(VecTy)->getNumElements();
543  I != N; ++I) {
544  Constant *Elem = C->getAggregateElement(I);
545  if (isa<UndefValue>(Elem))
546  return true;
547 
548  KnownBits Known = computeKnownBits(Elem, DL);
549  if (Known.isZero())
550  return true;
551  }
552 
553  return false;
554 }
555 
556 void Lint::visitSDiv(BinaryOperator &I) {
557  Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
558  "Undefined behavior: Division by zero", &I);
559 }
560 
561 void Lint::visitUDiv(BinaryOperator &I) {
562  Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
563  "Undefined behavior: Division by zero", &I);
564 }
565 
566 void Lint::visitSRem(BinaryOperator &I) {
567  Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
568  "Undefined behavior: Division by zero", &I);
569 }
570 
571 void Lint::visitURem(BinaryOperator &I) {
572  Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
573  "Undefined behavior: Division by zero", &I);
574 }
575 
576 void Lint::visitAllocaInst(AllocaInst &I) {
577  if (isa<ConstantInt>(I.getArraySize()))
578  // This isn't undefined behavior, it's just an obvious pessimization.
579  Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
580  "Pessimization: Static alloca outside of entry block", &I);
581 
582  // TODO: Check for an unusual size (MSB set?)
583 }
584 
585 void Lint::visitVAArgInst(VAArgInst &I) {
586  visitMemoryReference(I, MemoryLocation::get(&I), None, nullptr,
587  MemRef::Read | MemRef::Write);
588 }
589 
590 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
591  visitMemoryReference(I, MemoryLocation::getAfter(I.getAddress()), None,
592  nullptr, MemRef::Branchee);
593 
594  Assert(I.getNumDestinations() != 0,
595  "Undefined behavior: indirectbr with no destinations", &I);
596 }
597 
598 void Lint::visitExtractElementInst(ExtractElementInst &I) {
599  if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
600  /*OffsetOk=*/false)))
601  Assert(
602  CI->getValue().ult(
603  cast<FixedVectorType>(I.getVectorOperandType())->getNumElements()),
604  "Undefined result: extractelement index out of range", &I);
605 }
606 
607 void Lint::visitInsertElementInst(InsertElementInst &I) {
608  if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
609  /*OffsetOk=*/false)))
610  Assert(CI->getValue().ult(
611  cast<FixedVectorType>(I.getType())->getNumElements()),
612  "Undefined result: insertelement index out of range", &I);
613 }
614 
615 void Lint::visitUnreachableInst(UnreachableInst &I) {
616  // This isn't undefined behavior, it's merely suspicious.
617  Assert(&I == &I.getParent()->front() ||
618  std::prev(I.getIterator())->mayHaveSideEffects(),
619  "Unusual: unreachable immediately preceded by instruction without "
620  "side effects",
621  &I);
622 }
623 
624 /// findValue - Look through bitcasts and simple memory reference patterns
625 /// to identify an equivalent, but more informative, value. If OffsetOk
626 /// is true, look through getelementptrs with non-zero offsets too.
627 ///
628 /// Most analysis passes don't require this logic, because instcombine
629 /// will simplify most of these kinds of things away. But it's a goal of
630 /// this Lint pass to be useful even on non-optimized IR.
631 Value *Lint::findValue(Value *V, bool OffsetOk) const {
632  SmallPtrSet<Value *, 4> Visited;
633  return findValueImpl(V, OffsetOk, Visited);
634 }
635 
636 /// findValueImpl - Implementation helper for findValue.
637 Value *Lint::findValueImpl(Value *V, bool OffsetOk,
638  SmallPtrSetImpl<Value *> &Visited) const {
639  // Detect self-referential values.
640  if (!Visited.insert(V).second)
641  return UndefValue::get(V->getType());
642 
643  // TODO: Look through sext or zext cast, when the result is known to
644  // be interpreted as signed or unsigned, respectively.
645  // TODO: Look through eliminable cast pairs.
646  // TODO: Look through calls with unique return values.
647  // TODO: Look through vector insert/extract/shuffle.
648  V = OffsetOk ? getUnderlyingObject(V) : V->stripPointerCasts();
649  if (LoadInst *L = dyn_cast<LoadInst>(V)) {
650  BasicBlock::iterator BBI = L->getIterator();
651  BasicBlock *BB = L->getParent();
652  SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
653  for (;;) {
654  if (!VisitedBlocks.insert(BB).second)
655  break;
656  if (Value *U =
658  return findValueImpl(U, OffsetOk, Visited);
659  if (BBI != BB->begin())
660  break;
661  BB = BB->getUniquePredecessor();
662  if (!BB)
663  break;
664  BBI = BB->end();
665  }
666  } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
667  if (Value *W = PN->hasConstantValue())
668  return findValueImpl(W, OffsetOk, Visited);
669  } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
670  if (CI->isNoopCast(*DL))
671  return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
672  } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
673  if (Value *W =
674  FindInsertedValue(Ex->getAggregateOperand(), Ex->getIndices()))
675  if (W != V)
676  return findValueImpl(W, OffsetOk, Visited);
677  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
678  // Same as above, but for ConstantExpr instead of Instruction.
679  if (Instruction::isCast(CE->getOpcode())) {
680  if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
681  CE->getOperand(0)->getType(), CE->getType(),
682  *DL))
683  return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
684  } else if (CE->getOpcode() == Instruction::ExtractValue) {
685  ArrayRef<unsigned> Indices = CE->getIndices();
686  if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
687  if (W != V)
688  return findValueImpl(W, OffsetOk, Visited);
689  }
690  }
691 
692  // As a last resort, try SimplifyInstruction or constant folding.
693  if (Instruction *Inst = dyn_cast<Instruction>(V)) {
694  if (Value *W = SimplifyInstruction(Inst, {*DL, TLI, DT, AC}))
695  return findValueImpl(W, OffsetOk, Visited);
696  } else if (auto *C = dyn_cast<Constant>(V)) {
697  Value *W = ConstantFoldConstant(C, *DL, TLI);
698  if (W != V)
699  return findValueImpl(W, OffsetOk, Visited);
700  }
701 
702  return V;
703 }
704 
706  auto *Mod = F.getParent();
707  auto *DL = &F.getParent()->getDataLayout();
708  auto *AA = &AM.getResult<AAManager>(F);
709  auto *AC = &AM.getResult<AssumptionAnalysis>(F);
710  auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
711  auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
712  Lint L(Mod, DL, AA, AC, DT, TLI);
713  L.visit(F);
714  dbgs() << L.MessagesStr.str();
715  return PreservedAnalyses::all();
716 }
717 
718 class LintLegacyPass : public FunctionPass {
719 public:
720  static char ID; // Pass identification, replacement for typeid
723  }
724 
725  bool runOnFunction(Function &F) override;
726 
727  void getAnalysisUsage(AnalysisUsage &AU) const override {
728  AU.setPreservesAll();
733  }
734  void print(raw_ostream &O, const Module *M) const override {}
735 };
736 
737 char LintLegacyPass::ID = 0;
738 INITIALIZE_PASS_BEGIN(LintLegacyPass, "lint", "Statically lint-checks LLVM IR",
739  false, true)
746 
748  auto *Mod = F.getParent();
749  auto *DL = &F.getParent()->getDataLayout();
750  auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
751  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
752  auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
753  auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
754  Lint L(Mod, DL, AA, AC, DT, TLI);
755  L.visit(F);
756  dbgs() << L.MessagesStr.str();
757  return false;
758 }
759 
760 //===----------------------------------------------------------------------===//
761 // Implement the public interfaces to this file...
762 //===----------------------------------------------------------------------===//
763 
765 
766 /// lintFunction - Check a function for errors, printing messages on stderr.
767 ///
769  Function &F = const_cast<Function &>(f);
770  assert(!F.isDeclaration() && "Cannot lint external functions");
771 
772  legacy::FunctionPassManager FPM(F.getParent());
773  auto *V = new LintLegacyPass();
774  FPM.add(V);
775  FPM.run(F);
776 }
777 
778 /// lintModule - Check a module for errors, printing messages on stderr.
779 ///
780 void llvm::lintModule(const Module &M) {
782  auto *V = new LintLegacyPass();
783  PM.add(V);
784  PM.run(const_cast<Module &>(M));
785 }
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
AssumptionCache.h
llvm::AAManager
A manager for alias analyses.
Definition: AliasAnalysis.h:1233
llvm::Argument::hasStructRetAttr
bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition: Function.cpp:259
llvm::Type::isSized
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:272
Lint.h
llvm::MemCpyInlineInst::getLength
ConstantInt * getLength() const
Definition: IntrinsicInst.h:916
llvm::AliasResult::PartialAlias
@ PartialAlias
The two locations alias, but only due to a partial overlap.
Definition: AliasAnalysis.h:104
MathExtras.h
llvm::MemoryLocation::get
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Definition: MemoryLocation.cpp:37
llvm
Definition: AllocatorList.h:23
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::ReturnInst
Return a value (possibly void), from a function.
Definition: Instructions.h:2925
llvm::VAArgInst
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Definition: Instructions.h:1810
llvm::CastInst::isNoopCast
static bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, const DataLayout &DL)
A no-op cast is one that can be effected without changing any bits.
Definition: Instructions.cpp:2683
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:112
llvm::LocationSize::afterPointer
constexpr static LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
Definition: MemoryLocation.h:123
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:90
IntrinsicInst.h
llvm::Type::isPointerTy
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:229
llvm::MemIntrinsicBase::getDestAlign
MaybeAlign getDestAlign() const
Definition: IntrinsicInst.h:619
llvm::AnalysisManager::getResult
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:769
llvm::MemoryLocation::Ptr
const Value * Ptr
The address of the start of the location.
Definition: MemoryLocation.h:217
Loads.h
llvm::ExtractElementInst
This instruction extracts a single (scalar) element from a VectorType value.
Definition: Instructions.h:1850
llvm::Function
Definition: Function.h:61
llvm::Instruction::isCast
bool isCast() const
Definition: Instruction.h:168
Pass.h
llvm::UnderlyingObject
Definition: ScheduleDAGInstrs.h:108
llvm::MemMoveInst
This class wraps the llvm.memmove intrinsic.
Definition: IntrinsicInst.h:902
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:614
llvm::ConstantInt::getValue
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:131
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:181
llvm::GlobalVariable
Definition: GlobalVariable.h:40
ValueTracking.h
llvm::createLintLegacyPassPass
FunctionPass * createLintLegacyPassPass()
Definition: Lint.cpp:764
llvm::DominatorTree
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:151
APInt.h
llvm::lintModule
void lintModule(const Module &M)
Lint a module.
Definition: Lint.cpp:780
llvm::MemoryLocation::Size
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
Definition: MemoryLocation.h:226
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:46
Module.h
llvm::AttributeList
Definition: Attributes.h:385
T1
#define T1
Definition: Mips16ISelLowering.cpp:340
llvm::KnownBits::isZero
bool isZero() const
Returns true if value is all zero.
Definition: KnownBits.h:72
llvm::AliasResult
The possible results of an alias query.
Definition: AliasAnalysis.h:81
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::SmallPtrSet< Value *, 4 >
llvm::FunctionType::getNumParams
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:138
llvm::initializeLintLegacyPassPass
void initializeLintLegacyPassPass(PassRegistry &)
LegacyPassManager.h
ConstantFolding.h
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::FunctionType::isVarArg
bool isVarArg() const
Definition: DerivedTypes.h:122
KnownBits.h
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
AliasAnalysis.h
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
checks
Implicit null checks
Definition: ImplicitNullChecks.cpp:822
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:205
Instruction.h
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:77
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
Constants.h
isZero
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:519
llvm::AAResults
Definition: AliasAnalysis.h:456
f
Itanium Name Demangler i e convert the string _Z1fv into f()". You can also use the CRTP base ManglingParser to perform some simple analysis on the mangled name
llvm::LocationSize
Definition: MemoryLocation.h:65
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
Twine.h
InstrTypes.h
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::MemoryLocation::getForSource
static MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
Definition: MemoryLocation.cpp:105
llvm::LocationSize::getValue
uint64_t getValue() const
Definition: MemoryLocation.h:158
llvm::ms_demangle::QualifierMangleMode::Result
@ Result
llvm::MemCpyInlineInst
This class wraps the llvm.memcpy.inline intrinsic.
Definition: IntrinsicInst.h:914
llvm::APInt::getLimitedValue
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:487
TargetLibraryInfo.h
llvm::InsertElementInst
This instruction inserts a single (scalar) element into a VectorType value.
Definition: Instructions.h:1914
false
Definition: StackSlotColoring.cpp:142
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:109
llvm::Instruction::CastOps
CastOps
Definition: Instruction.h:782
llvm::Instruction
Definition: Instruction.h:45
llvm::SimplifyInstruction
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Definition: InstructionSimplify.cpp:5816
llvm::DominatorTreeWrapperPass
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:281
llvm::AttributeList::getAttributes
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
Definition: Attributes.cpp:1666
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:50
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1784
llvm::LocationSize::precise
static LocationSize precise(uint64_t Value)
Definition: MemoryLocation.h:100
llvm::getUnderlyingObject
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
Definition: ValueTracking.cpp:4314
IR
Statically lint checks LLVM IR
Definition: Lint.cpp:744
SmallPtrSet.h
llvm::AttributeList::hasParamAttribute
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
Definition: Attributes.cpp:1589
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
llvm::MemTransferBase::getSourceAlign
MaybeAlign getSourceAlign() const
Definition: IntrinsicInst.h:685
llvm::None
const NoneType None
Definition: None.h:23
Type.h
llvm::MemSetInst
This class wraps the llvm.memset intrinsic.
Definition: IntrinsicInst.h:859
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
LintLegacyPass
Definition: Lint.cpp:718
llvm::Argument::getParamStructRetType
Type * getParamStructRetType() const
If this is an sret argument, return its type.
Definition: Function.cpp:212
llvm::VectorType
Base class of all SIMD vector types.
Definition: DerivedTypes.h:391
BasicBlock.h
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:179
llvm::StoreInst
An instruction for storing to memory.
Definition: Instructions.h:303
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::TargetLibraryInfoWrapperPass
Definition: TargetLibraryInfo.h:447
llvm::LocationSize::hasValue
bool hasValue() const
Definition: MemoryLocation.h:155
llvm::LocationSize::isZero
bool isZero() const
Definition: MemoryLocation.h:170
llvm::AssumptionAnalysis
A function analysis which provides an AssumptionCache.
Definition: AssumptionCache.h:169
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
MemoryLocation.h
I
#define I(x, y, z)
Definition: MD5.cpp:59
LintLegacyPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Lint.cpp:727
ArrayRef.h
llvm::computeKnownBits
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Definition: ValueTracking.cpp:212
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LintLegacyPass::print
void print(raw_ostream &O, const Module *M) const override
print - Print out the internal state of the pass.
Definition: Lint.cpp:734
llvm::MemoryLocation::getForArgument
static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
Definition: MemoryLocation.cpp:147
memcpy
<%struct.s * > cast struct s *S to sbyte *< sbyte * > sbyte uint cast struct s *agg result to sbyte *< sbyte * > sbyte uint cast struct s *memtmp to sbyte *< sbyte * > sbyte uint ret void llc ends up issuing two memcpy or custom lower memcpy(of small size) to be ldmia/stmia. I think option 2 is better but the current register allocator cannot allocate a chunk of registers at a time. A feasible temporary solution is to use specific physical registers at the lowering time for small(<
llvm::WinEH::EncodingType::CE
@ CE
Windows NT (Windows on ARM)
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::legacy::FunctionPassManager::add
void add(Pass *P) override
Add a pass to the queue of passes to run.
Definition: LegacyPassManager.cpp:1344
llvm::MemIntrinsicBase::getDest
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
Definition: IntrinsicInst.h:606
llvm::AssumptionCacheTracker
An immutable pass that tracks lazily created AssumptionCache objects.
Definition: AssumptionCache.h:200
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:32
llvm::BinaryOperator
Definition: InstrTypes.h:190
DataLayout.h
InstVisitor.h
LintLegacyPass::LintLegacyPass
LintLegacyPass()
Definition: Lint.cpp:721
llvm::AssumptionCache
A cache of @llvm.assume calls within a function.
Definition: AssumptionCache.h:41
llvm::Constant::getAggregateElement
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:421
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
llvm::AliasResult::MustAlias
@ MustAlias
The two locations precisely alias each other.
Definition: AliasAnalysis.h:106
llvm::InstVisitor
Base class for instruction visitors.
Definition: InstVisitor.h:79
llvm::CastInst
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:432
llvm::lintFunction
void lintFunction(const Function &F)
lintFunction - Check a function for errors, printing messages on stderr.
Definition: Lint.cpp:768
LintLegacyPass::ID
static char ID
Definition: Lint.cpp:720
llvm::LoadInst
An instruction for reading from memory.
Definition: Instructions.h:174
Argument.h
Callee
amdgpu Simplify well known AMD library false FunctionCallee Callee
Definition: AMDGPULibCalls.cpp:205
runOnFunction
static bool runOnFunction(Function &F, bool PostInlining)
Definition: EntryExitInstrumenter.cpp:69
Constant.h
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
Assert
#define Assert(C,...)
Definition: Lint.cpp:173
llvm::FindInsertedValue
Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, Instruction *InsertBefore=nullptr)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
Definition: ValueTracking.cpp:3964
llvm::commonAlignment
Align commonAlignment(Align A, Align B)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:211
llvm::ConstantExpr
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:931
llvm::KnownBits
Definition: KnownBits.h:23
llvm::legacy::FunctionPassManager::run
bool run(Function &F)
run - Execute all of the passes scheduled for execution.
Definition: LegacyPassManager.cpp:1352
llvm::AnalysisUsage::setPreservesAll
void setPreservesAll()
Set by analyses that do not transform their input at all.
Definition: PassAnalysisSupport.h:130
llvm::MemIntrinsicBase::getLength
Value * getLength() const
Definition: IntrinsicInst.h:597
llvm::PreservedAnalyses::all
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
llvm::legacy::PassManager
PassManager manages ModulePassManagers.
Definition: LegacyPassManager.h:52
GlobalVariable.h
llvm::ExtractValueInst
This instruction extracts a struct member or array element value from an aggregate value.
Definition: Instructions.h:2318
llvm::AArch64CC::LS
@ LS
Definition: AArch64BaseInfo.h:245
Casting.h
Function.h
llvm::FindAvailableLoadedValue
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, AAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition: Loads.cpp:431
PassManager.h
llvm::TargetLibraryInfo
Provides information about what library functions are available for the current target.
Definition: TargetLibraryInfo.h:208
llvm::AAResults::alias
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
Definition: AliasAnalysis.cpp:120
llvm::GetPointerBaseWithConstantOffset
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
Definition: ValueTracking.h:279
llvm::MemoryLocation::UnknownSize
@ UnknownSize
Definition: MemoryLocation.h:214
llvm::legacy::PassManager::add
void add(Pass *P) override
Add a pass to the queue of passes to run.
Definition: LegacyPassManager.cpp:1674
MemRef
Definition: Lint.cpp:84
llvm::IndirectBrInst
Indirect Branch Instruction.
Definition: Instructions.h:3553
llvm::IntrinsicInst
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:45
llvm::DominatorTreeAnalysis
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:252
Instructions.h
llvm::MemCpyInst
This class wraps the llvm.memcpy intrinsic.
Definition: IntrinsicInst.h:890
Dominators.h
llvm::MemoryLocation::getAfter
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
Definition: MemoryLocation.h:267
N
#define N
llvm::AAResultsWrapperPass
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Definition: AliasAnalysis.h:1281
InstructionSimplify.h
llvm::legacy::FunctionPassManager
FunctionPassManager manages FunctionPasses.
Definition: LegacyPassManager.h:71
llvm::Argument::hasNoAliasAttr
bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Definition: Function.cpp:244
llvm::PHINode
Definition: Instructions.h:2572
llvm::ConstantFoldConstant
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
Definition: ConstantFolding.cpp:1215
llvm::legacy::PassManager::run
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Definition: LegacyPassManager.cpp:1680
llvm::CallBase
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1164
DerivedTypes.h
llvm::SmallPtrSetImpl< Value * >
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition: InstructionSimplify.h:44
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
lint
lint
Definition: Lint.cpp:744
llvm::UnreachableInst
This function has undefined behavior.
Definition: Instructions.h:4652
llvm::MemoryLocation::getForDest
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
Definition: MemoryLocation.cpp:126
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
llvm::AllocaInst
an instruction to allocate memory on the stack
Definition: Instructions.h:61
Mod
Module * Mod
Definition: PassBuilderBindings.cpp:54
raw_ostream.h
llvm::Argument::onlyReadsMemory
bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Definition: Function.cpp:280
true
basic Basic Alias true
Definition: BasicAliasAnalysis.cpp:1797
Value.h
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(LintLegacyPass, "lint", "Statically lint-checks LLVM IR", false, true) INITIALIZE_PASS_END(LintLegacyPass
InitializePasses.h
llvm::FunctionType::getReturnType
Type * getReturnType() const
Definition: DerivedTypes.h:123
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
Debug.h
llvm::TargetLibraryAnalysis
Analysis pass providing the TargetLibraryInfo.
Definition: TargetLibraryInfo.h:422
llvm::MemoryLocation
Representation for a specific memory location.
Definition: MemoryLocation.h:209
llvm::DefMaxInstsToScan
cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
llvm::FunctionType
Class to represent function types.
Definition: DerivedTypes.h:102
llvm::MemTransferBase::getSource
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
Definition: IntrinsicInst.h:671
Passes.h
llvm::SmallPtrSetImpl::insert
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:364
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:38
llvm::LintPass::run
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Lint.cpp:705