85 static const unsigned Read = 1;
86 static const unsigned Write = 2;
87 static const unsigned Callee = 4;
88 static const unsigned Branchee = 8;
99 Type *Ty,
unsigned Flags);
124 Value *findValue(
Value *V,
bool OffsetOk)
const;
136 std::string Messages;
156 for (
const Value *V : Vs) {
159 if (isa<Instruction>(V)) {
160 MessagesStr << *V <<
'\n';
172 void CheckFailed(
const Twine &Message) { MessagesStr << Message <<
'\n'; }
178 template <
typename T1,
typename... Ts>
179 void CheckFailed(
const Twine &Message,
const T1 &V1,
const Ts &...Vs) {
180 CheckFailed(Message);
181 WriteValues({V1, Vs...});
197 #define Assert(C, ...) \ 198 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false) 206 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
207 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
208 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
209 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
211 dbgs() << MessagesStr.str();
220 "Unusual: Unnamed function with non-local linkage", &
F);
225 void Lint::visitCallSite(
CallSite CS) {
232 if (
Function *F = dyn_cast<Function>(findValue(Callee,
235 "Undefined behavior: Caller and callee calling convention differ",
239 unsigned NumActualArgs = CS.
arg_size();
241 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
242 : FT->getNumParams() == NumActualArgs,
243 "Undefined behavior: Call argument count mismatches callee " 248 "Undefined behavior: Call return type mismatches " 249 "callee return type",
256 for (; AI != AE; ++AI) {
261 "Undefined behavior: Call argument type mismatches " 262 "callee parameter type",
280 if (AI != BI && (*BI)->getType()->isPointerTy()) {
283 "Unusual: noalias argument aliases another argument", &I);
291 cast<PointerType>(Formal->
getType())->getElementType();
292 visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
293 DL->getABITypeAlignment(Ty), Ty,
294 MemRef::Read | MemRef::Write);
311 Assert(!isa<AllocaInst>(Obj),
312 "Undefined behavior: Call with \"tail\" keyword references " 321 switch (II->getIntrinsicID()) {
326 case Intrinsic::memcpy: {
339 dyn_cast<ConstantInt>(findValue(MCI->
getLength(),
341 if (Len->getValue().isIntN(32))
345 "Undefined behavior: memcpy source and destination overlap", &I);
348 case Intrinsic::memmove: {
357 case Intrinsic::memset: {
365 case Intrinsic::vastart:
367 "Undefined behavior: va_start called in a non-varargs function",
371 nullptr, MemRef::Read | MemRef::Write);
373 case Intrinsic::vacopy:
375 nullptr, MemRef::Write);
377 nullptr, MemRef::Read);
379 case Intrinsic::vaend:
381 nullptr, MemRef::Read | MemRef::Write);
384 case Intrinsic::stackrestore:
389 nullptr, MemRef::Read | MemRef::Write);
395 return visitCallSite(&I);
399 return visitCallSite(&I);
405 "Unusual: Return statement in function with noreturn attribute", &
I);
408 Value *Obj = findValue(V,
true);
409 Assert(!isa<AllocaInst>(Obj),
"Unusual: Returning alloca value", &I);
417 Type *Ty,
unsigned Flags) {
424 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
425 "Undefined behavior: Null pointer dereference", &I);
426 Assert(!isa<UndefValue>(UnderlyingObject),
427 "Undefined behavior: Undef pointer dereference", &I);
428 Assert(!isa<ConstantInt>(UnderlyingObject) ||
429 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
430 "Unusual: All-ones pointer dereference", &I);
431 Assert(!isa<ConstantInt>(UnderlyingObject) ||
432 !cast<ConstantInt>(UnderlyingObject)->isOne(),
433 "Unusual: Address one pointer dereference", &I);
435 if (Flags & MemRef::Write) {
436 if (
const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
437 Assert(!GV->isConstant(),
"Undefined behavior: Write to read-only memory",
439 Assert(!isa<Function>(UnderlyingObject) &&
440 !isa<BlockAddress>(UnderlyingObject),
441 "Undefined behavior: Write to text section", &I);
443 if (Flags & MemRef::Read) {
444 Assert(!isa<Function>(UnderlyingObject),
"Unusual: Load from function body",
446 Assert(!isa<BlockAddress>(UnderlyingObject),
447 "Undefined behavior: Load from block address", &I);
449 if (Flags & MemRef::Callee) {
450 Assert(!isa<BlockAddress>(UnderlyingObject),
451 "Undefined behavior: Call to block address", &I);
453 if (Flags & MemRef::Branchee) {
454 Assert(!isa<Constant>(UnderlyingObject) ||
455 isa<BlockAddress>(UnderlyingObject),
456 "Undefined behavior: Branch to non-blockaddress", &I);
468 unsigned BaseAlign = 0;
471 Type *ATy = AI->getAllocatedType();
472 if (!AI->isArrayAllocation() && ATy->
isSized())
473 BaseSize = DL->getTypeAllocSize(ATy);
474 BaseAlign = AI->getAlignment();
475 if (BaseAlign == 0 && ATy->
isSized())
476 BaseAlign = DL->getABITypeAlignment(ATy);
480 if (GV->hasDefinitiveInitializer()) {
481 Type *GTy = GV->getValueType();
483 BaseSize = DL->getTypeAllocSize(GTy);
484 BaseAlign = GV->getAlignment();
485 if (BaseAlign == 0 && GTy->
isSized())
486 BaseAlign = DL->getABITypeAlignment(GTy);
494 (Offset >= 0 && Offset +
Size <= BaseSize),
495 "Undefined behavior: Buffer overflow", &I);
499 if (Align == 0 && Ty && Ty->
isSized())
500 Align = DL->getABITypeAlignment(Ty);
502 "Undefined behavior: Memory reference address is misaligned", &I);
506 void Lint::visitLoadInst(
LoadInst &I) {
512 void Lint::visitStoreInst(
StoreInst &I) {
521 "Undefined result: xor(undef, undef)", &I);
526 "Undefined result: sub(undef, undef)", &I);
533 "Undefined result: Shift count out of range", &I);
538 dyn_cast<ConstantInt>(findValue(I.
getOperand(1),
false)))
540 "Undefined result: Shift count out of range", &I);
545 dyn_cast<ConstantInt>(findValue(I.
getOperand(1),
false)))
547 "Undefined result: Shift count out of range", &I);
553 if (isa<UndefValue>(V))
574 if (isa<UndefValue>(Elem))
587 "Undefined behavior: Division by zero", &I);
592 "Undefined behavior: Division by zero", &I);
597 "Undefined behavior: Division by zero", &I);
602 "Undefined behavior: Division by zero", &I);
609 "Pessimization: Static alloca outside of entry block", &
I);
614 void Lint::visitVAArgInst(
VAArgInst &I) {
616 nullptr, MemRef::Read | MemRef::Write);
621 nullptr, MemRef::Branchee);
624 "Undefined behavior: indirectbr with no destinations", &
I);
631 "Undefined result: extractelement index out of range", &I);
638 "Undefined result: insertelement index out of range", &I);
645 "Unusual: unreachable immediately preceded by instruction without " 657 Value *Lint::findValue(
Value *V,
bool OffsetOk)
const {
659 return findValueImpl(V, OffsetOk, Visited);
663 Value *Lint::findValueImpl(
Value *V,
bool OffsetOk,
666 if (!Visited.
insert(V).second)
675 if (
LoadInst *L = dyn_cast<LoadInst>(V)) {
680 if (!VisitedBlocks.
insert(BB).second)
684 return findValueImpl(U, OffsetOk, Visited);
685 if (BBI != BB->
begin())
break;
690 }
else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
691 if (
Value *
W = PN->hasConstantValue())
693 return findValueImpl(
W, OffsetOk, Visited);
694 }
else if (
CastInst *CI = dyn_cast<CastInst>(V)) {
695 if (CI->isNoopCast(*DL))
696 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
701 return findValueImpl(
W, OffsetOk, Visited);
702 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
706 CE->getOperand(0)->getType(), CE->getType(),
708 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
709 }
else if (CE->getOpcode() == Instruction::ExtractValue) {
713 return findValueImpl(
W, OffsetOk, Visited);
718 if (
Instruction *Inst = dyn_cast<Instruction>(V)) {
720 return findValueImpl(
W, OffsetOk, Visited);
721 }
else if (
auto *
C = dyn_cast<Constant>(V)) {
724 return findValueImpl(
W, OffsetOk, Visited);
745 Lint *V =
new Lint();
754 Lint *V =
new Lint();
756 PM.
run(const_cast<Module&>(M));
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Return a value (possibly void), from a function.
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...
A parsed version of the target data layout string in and methods for querying it. ...
void lintModule(const Module &M)
Check a module.
bool hasLocalLinkage() const
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...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static constexpr LocationSize unknown()
This class represents a function call, abstracting a target machine's calling convention.
cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
void lintFunction(const Function &F)
lintFunction - Check a function for errors, printing messages on stderr.
An immutable pass that tracks lazily created AssumptionCache objects.
unsigned getSourceAlignment() const
FIXME: Remove this function once transition to Align is over.
A cache of @llvm.assume calls within a function.
static LocationSize precise(uint64_t Value)
This class wraps the llvm.memset intrinsic.
block Block Frequency true
An instruction for reading from memory.
Value * getLength() const
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void add(Pass *P) override
Add a pass to the queue of passes to run.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
This class wraps the llvm.memmove intrinsic.
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, AliasAnalysis *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 ...
ValTy * getCalledValue() const
Return the pointer to function that is being called.
unsigned getDestAlignment() const
FIXME: Remove this function once transition to Align is over.
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
This file implements a class to represent arbitrary precision integral constant values and operations...
InstrTy * getInstruction() const
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
A constant value that is initialized with an expression using other constant values.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
An instruction for storing to memory.
VectorType * getType() const
Overload to return most specific vector type.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
Value * getOperand(unsigned i) const
bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
AliasResult
The possible results of an alias query.
bool isZeroValue() const
Return true if the value is negative zero or null value.
PassManager manages ModulePassManagers.
const BasicBlock & getEntryBlock() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
static bool runOnFunction(Function &F, bool PostInlining)
This instruction inserts a single (scalar) element into a VectorType value.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
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.
This function has undefined behavior.
This is an important base class in LLVM.
bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
Indirect Branch Instruction.
AttributeList getAttributes() const
Get the parameter attributes of the call.
ValTy * getArgument(unsigned ArgNo) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool doesNotReturn() const
Determine if the function cannot return.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Value * getPointerOperand()
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
self_iterator getIterator()
bool isZero() const
Returns true if value is all zero.
FunctionPassManager manages FunctionPasses.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
const Value * getArraySize() const
Get the number of elements allocated.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
iterator_range< IterTy > args() const
INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR", false, true) INITIALIZE_PASS_END(Lint
This struct is a compact representation of a valid (non-zero power of two) alignment.
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...
FunctionPass * createLintPass()
Create a lint pass.
The two locations precisely alias each other.
Iterator for intrusive lists based on ilist_node.
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
unsigned arg_size() const
void initializeLintPass(PassRegistry &)
This class wraps the llvm.memcpy intrinsic.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
AttributeList getAttributes() const
Return the parameter attributes for this call.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
amdgpu Simplify well known AMD library false FunctionCallee Callee
void setPreservesAll()
Set by analyses that do not transform their input at all.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This file provides utility analysis objects describing memory locations.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool isCall() const
Return true if a CallInst is enclosed.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream...
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it...
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
The two locations alias, but only due to a partial overlap.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Value * getPointerOperand()
Statically lint checks LLVM IR
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack