LLVM 24.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"
40#include "llvm/ADT/Twine.h"
46#include "llvm/Analysis/Loads.h"
52#include "llvm/IR/Argument.h"
53#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/Constant.h"
55#include "llvm/IR/Constants.h"
56#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
61#include "llvm/IR/InstVisitor.h"
62#include "llvm/IR/InstrTypes.h"
63#include "llvm/IR/Instruction.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/PassManager.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/Value.h"
74#include <cassert>
75#include <cstdint>
76#include <iterator>
77#include <string>
78
79using namespace llvm;
80
81namespace {
82namespace MemRef {
83static const unsigned Read = 1;
84static const unsigned Write = 2;
85static const unsigned Callee = 4;
86static const unsigned Branchee = 8;
87} // end namespace MemRef
88
89class Lint : public InstVisitor<Lint> {
90 friend class InstVisitor<Lint>;
91
92 void visitFunction(Function &F);
93
94 void visitCallBase(CallBase &CB);
95 void visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
96 MaybeAlign Alignment, Type *Ty, unsigned Flags);
97
98 void visitReturnInst(ReturnInst &I);
99 void visitLoadInst(LoadInst &I);
100 void visitStoreInst(StoreInst &I);
101 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
102 void visitAtomicRMWInst(AtomicRMWInst &I);
103 void visitXor(BinaryOperator &I);
104 void visitSub(BinaryOperator &I);
105 void visitLShr(BinaryOperator &I);
106 void visitAShr(BinaryOperator &I);
107 void visitShl(BinaryOperator &I);
108 void visitSDiv(BinaryOperator &I);
109 void visitUDiv(BinaryOperator &I);
110 void visitSRem(BinaryOperator &I);
111 void visitURem(BinaryOperator &I);
112 void visitAllocaInst(AllocaInst &I);
113 void visitVAArgInst(VAArgInst &I);
114 void visitIndirectBrInst(IndirectBrInst &I);
115 void visitExtractElementInst(ExtractElementInst &I);
116 void visitInsertElementInst(InsertElementInst &I);
117 void visitUnreachableInst(UnreachableInst &I);
118
119 Value *findValue(Value *V, bool OffsetOk) const;
120 Value *findValueImpl(Value *V, bool OffsetOk,
121 SmallPtrSetImpl<Value *> &Visited) const;
122
123public:
124 Module *Mod;
125 const Triple &TT;
126 const DataLayout *DL;
128 AssumptionCache *AC;
129 DominatorTree *DT;
131
132 std::string Messages;
133 raw_string_ostream MessagesStr;
134
135 Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
137 : Mod(Mod), TT(Mod->getTargetTriple()), DL(DL), AA(AA), AC(AC), DT(DT),
138 TLI(TLI), MessagesStr(Messages) {}
139
140 void WriteValues(ArrayRef<const Value *> Vs) {
141 for (const Value *V : Vs) {
142 if (!V)
143 continue;
144 if (isa<Instruction>(V)) {
145 MessagesStr << *V << '\n';
146 } else {
147 V->printAsOperand(MessagesStr, true, Mod);
148 MessagesStr << '\n';
149 }
150 }
151 }
152
153 /// A check failed, so printout out the condition and the message.
154 ///
155 /// This provides a nice place to put a breakpoint if you want to see why
156 /// something is not correct.
157 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
158
159 /// A check failed (with values to print).
160 ///
161 /// This calls the Message-only version so that the above is easier to set
162 /// a breakpoint on.
163 template <typename T1, typename... Ts>
164 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
165 CheckFailed(Message);
166 WriteValues({V1, Vs...});
167 }
168};
169} // end anonymous namespace
170
171// Check - We know that cond should be true, if not print an error message.
172#define Check(C, ...) \
173 do { \
174 if (!(C)) { \
175 CheckFailed(__VA_ARGS__); \
176 return; \
177 } \
178 } while (false)
179
180void Lint::visitFunction(Function &F) {
181 // This isn't undefined behavior, it's just a little unusual, and it's a
182 // fairly common mistake to neglect to name a function.
183 Check(F.hasName() || F.hasLocalLinkage(),
184 "Unusual: Unnamed function with non-local linkage", &F);
185
186 // TODO: Check for irreducible control flow.
187}
188
189void Lint::visitCallBase(CallBase &I) {
190 Value *Callee = I.getCalledOperand();
191
192 visitMemoryReference(I, MemoryLocation::getAfter(Callee), std::nullopt,
193 nullptr, MemRef::Callee);
194
195 if (Function *F = dyn_cast<Function>(findValue(Callee,
196 /*OffsetOk=*/false))) {
197 Check(I.getCallingConv() == F->getCallingConv(),
198 "Undefined behavior: Caller and callee calling convention differ",
199 &I);
200
201 FunctionType *FT = F->getFunctionType();
202 unsigned NumActualArgs = I.arg_size();
203
204 Check(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
205 : FT->getNumParams() == NumActualArgs,
206 "Undefined behavior: Call argument count mismatches callee "
207 "argument count",
208 &I);
209
210 Check(FT->getReturnType() == I.getType(),
211 "Undefined behavior: Call return type mismatches "
212 "callee return type",
213 &I);
214
215 // Check argument types (in case the callee was casted) and attributes.
216 // TODO: Verify that caller and callee attributes are compatible.
217 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
218 auto AI = I.arg_begin(), AE = I.arg_end();
219 for (; AI != AE; ++AI) {
220 Value *Actual = *AI;
221 if (PI != PE) {
222 Argument *Formal = &*PI++;
223 Check(Formal->getType() == Actual->getType(),
224 "Undefined behavior: Call argument type mismatches "
225 "callee parameter type",
226 &I);
227
228 // Check that noalias arguments don't alias other arguments. This is
229 // not fully precise because we don't know the sizes of the dereferenced
230 // memory regions.
231 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) {
232 AttributeList PAL = I.getAttributes();
233 unsigned ArgNo = 0;
234 for (auto *BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
235 // Skip ByVal arguments since they will be memcpy'd to the callee's
236 // stack so we're not really passing the pointer anyway.
237 if (PAL.hasParamAttr(ArgNo, Attribute::ByVal))
238 continue;
239 // If both arguments are readonly, they have no dependence.
240 if (Formal->onlyReadsMemory() && I.onlyReadsMemory(ArgNo))
241 continue;
242 // Skip readnone arguments since those are guaranteed not to be
243 // dereferenced anyway.
244 if (I.doesNotAccessMemory(ArgNo))
245 continue;
246 if (AI != BI && (*BI)->getType()->isPointerTy() &&
248 AliasResult Result = AA->alias(*AI, *BI);
249 Check(Result != AliasResult::MustAlias &&
251 "Unusual: noalias argument aliases another argument", &I);
252 }
253 }
254 }
255
256 // Check that an sret argument points to valid memory.
257 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
258 Type *Ty = Formal->getParamStructRetType();
259 MemoryLocation Loc(
260 Actual, LocationSize::precise(DL->getTypeStoreSize(Ty)));
261 visitMemoryReference(I, Loc, DL->getABITypeAlign(Ty), Ty,
262 MemRef::Read | MemRef::Write);
263 }
264
265 // Check that ABI attributes for the function and call-site match.
266 unsigned ArgNo = AI->getOperandNo();
267 AttributeList CallAttrs = I.getAttributes();
268 for (Attribute::AttrKind Attr :
269 drop_begin(enum_seq(Attribute::None, Attribute::EndAttrKinds,
271 if (!Attribute::isABIAttr(Attr))
272 continue;
273
274 Attribute CallAttr = CallAttrs.getParamAttr(ArgNo, Attr);
275 Attribute FnAttr = F->getParamAttribute(ArgNo, Attr);
276
277 if ((Attr == Attribute::ZExt || Attr == Attribute::SExt) &&
278 CallAttr.isValid() && !FnAttr.isValid()) {
279 // As an exception, allow zeroext/signext at the call-site, while
280 // missing on the function. This means that the caller extends,
281 // while the callee does not assume extension. The call-site
282 // extension is redundant in that case, but perfectly well-defined.
283 continue;
284 }
285
286 Check(CallAttr.isValid() == FnAttr.isValid(),
287 Twine("Undefined behavior: ABI attribute ") +
288 Attribute::getNameFromAttrKind(Attr) +
289 " not present on both function and call-site",
290 &I);
291 if (CallAttr.isValid() && FnAttr.isValid()) {
292 Check(CallAttr == FnAttr,
293 Twine("Undefined behavior: ABI attribute ") +
294 Attribute::getNameFromAttrKind(Attr) +
295 " does not have same argument for function and call-site",
296 &I);
297 }
298 }
299 }
300 }
301 }
302
303 if (const auto *CI = dyn_cast<CallInst>(&I)) {
304 if (CI->isTailCall()) {
305 const AttributeList &PAL = CI->getAttributes();
306 unsigned ArgNo = 0;
307 for (Value *Arg : I.args()) {
308 // Skip ByVal arguments since they will be memcpy'd to the callee's
309 // stack anyway.
310 if (PAL.hasParamAttr(ArgNo++, Attribute::ByVal))
311 continue;
312 Value *Obj = findValue(Arg, /*OffsetOk=*/true);
314 "Undefined behavior: Call with \"tail\" keyword references "
315 "alloca",
316 &I);
317 }
318 }
319 }
320
321 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
322 switch (II->getIntrinsicID()) {
323 default:
324 break;
325
326 // TODO: Check more intrinsics
327
328 case Intrinsic::memcpy:
329 case Intrinsic::memcpy_inline: {
330 MemCpyInst *MCI = cast<MemCpyInst>(&I);
331 visitMemoryReference(I, MemoryLocation::getForDest(MCI),
332 MCI->getDestAlign(), nullptr, MemRef::Write);
333 visitMemoryReference(I, MemoryLocation::getForSource(MCI),
334 MCI->getSourceAlign(), nullptr, MemRef::Read);
335
336 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
337 // isn't expressive enough for what we really want to do. Known partial
338 // overlap is not distinguished from the case where nothing is known.
340 if (const ConstantInt *Len =
341 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
342 /*OffsetOk=*/false)))
343 if (Len->getValue().isIntN(32))
344 Size = LocationSize::precise(Len->getValue().getZExtValue());
345 Check(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
347 "Undefined behavior: memcpy source and destination overlap", &I);
348 break;
349 }
350 case Intrinsic::memmove: {
351 MemMoveInst *MMI = cast<MemMoveInst>(&I);
352 visitMemoryReference(I, MemoryLocation::getForDest(MMI),
353 MMI->getDestAlign(), nullptr, MemRef::Write);
354 visitMemoryReference(I, MemoryLocation::getForSource(MMI),
355 MMI->getSourceAlign(), nullptr, MemRef::Read);
356 break;
357 }
358 case Intrinsic::memset:
359 case Intrinsic::memset_inline: {
360 MemSetInst *MSI = cast<MemSetInst>(&I);
361 visitMemoryReference(I, MemoryLocation::getForDest(MSI),
362 MSI->getDestAlign(), nullptr, MemRef::Write);
363 break;
364 }
365 case Intrinsic::vastart:
366 // vastart in non-varargs function is rejected by the verifier
367 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
368 std::nullopt, nullptr, MemRef::Read | MemRef::Write);
369 break;
370 case Intrinsic::vacopy:
371 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
372 std::nullopt, nullptr, MemRef::Write);
373 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 1, TLI),
374 std::nullopt, nullptr, MemRef::Read);
375 break;
376 case Intrinsic::vaend:
377 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
378 std::nullopt, nullptr, MemRef::Read | MemRef::Write);
379 break;
380
381 case Intrinsic::stackrestore:
382 // Stackrestore doesn't read or write memory, but it sets the
383 // stack pointer, which the compiler may read from or write to
384 // at any time, so check it for both readability and writeability.
385 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI),
386 std::nullopt, nullptr, MemRef::Read | MemRef::Write);
387 break;
388 }
389}
390
391void Lint::visitReturnInst(ReturnInst &I) {
392 Function *F = I.getParent()->getParent();
393 Check(!F->doesNotReturn(),
394 "Unusual: Return statement in function with noreturn attribute", &I);
395
396 if (Value *V = I.getReturnValue()) {
397 Value *Obj = findValue(V, /*OffsetOk=*/true);
398 Check(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
399 }
400}
401
402// TODO: Check that the reference is in bounds.
403// TODO: Check readnone/readonly function attributes.
404void Lint::visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
405 MaybeAlign Align, Type *Ty, unsigned Flags) {
406 // If no memory is being referenced, it doesn't matter if the pointer
407 // is valid.
408 if (Loc.Size.isZero())
409 return;
410
411 Value *Ptr = const_cast<Value *>(Loc.Ptr);
412 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
413 Check(!isa<ConstantPointerNull>(UnderlyingObject),
414 "Undefined behavior: Null pointer dereference", &I);
415 Check(!isa<UndefValue>(UnderlyingObject),
416 "Undefined behavior: Undef pointer dereference", &I);
417 Check(!isa<ConstantInt>(UnderlyingObject) ||
418 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
419 "Unusual: All-ones pointer dereference", &I);
420 Check(!isa<ConstantInt>(UnderlyingObject) ||
421 !cast<ConstantInt>(UnderlyingObject)->isOne(),
422 "Unusual: Address one pointer dereference", &I);
423
424 if (Flags & MemRef::Write) {
425 if (TT.isAMDGPU())
427 UnderlyingObject->getType()->getPointerAddressSpace()),
428 "Undefined behavior: Write to memory in const addrspace", &I);
429
430 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
431 Check(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
432 &I);
433 Check(!isa<Function>(UnderlyingObject) &&
434 !isa<BlockAddress>(UnderlyingObject),
435 "Undefined behavior: Write to text section", &I);
436 }
437 if (Flags & MemRef::Read) {
438 Check(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
439 &I);
440 Check(!isa<BlockAddress>(UnderlyingObject),
441 "Undefined behavior: Load from block address", &I);
442 }
443 if (Flags & MemRef::Callee) {
444 Check(!isa<BlockAddress>(UnderlyingObject),
445 "Undefined behavior: Call to block address", &I);
446 }
447 if (Flags & MemRef::Branchee) {
448 Check(!isa<Constant>(UnderlyingObject) ||
449 isa<BlockAddress>(UnderlyingObject),
450 "Undefined behavior: Branch to non-blockaddress", &I);
451 }
452
453 // Check for buffer overflows and misalignment.
454 // Only handles memory references that read/write something simple like an
455 // alloca instruction or a global variable.
456 int64_t Offset = 0;
458 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
459 // something we can handle and if so extract the size of this base object
460 // along with its alignment.
462 MaybeAlign BaseAlign;
463
464 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
465 std::optional<TypeSize> ATy = AI->getAllocationSize(*DL);
466 if (ATy && !ATy->isScalable())
467 BaseSize = ATy->getFixedValue();
468 BaseAlign = AI->getAlign();
469 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
470 // If the global may be defined differently in another compilation unit
471 // then don't warn about funky memory accesses.
472 if (GV->hasDefinitiveInitializer()) {
473 Type *GTy = GV->getValueType();
474 if (GTy->isSized())
475 BaseSize = DL->getTypeAllocSize(GTy);
476 BaseAlign = GV->getAlign();
477 if (!BaseAlign && GTy->isSized())
478 BaseAlign = DL->getABITypeAlign(GTy);
479 }
480 }
481
482 // Accesses from before the start or after the end of the object are not
483 // defined.
484 Check(!Loc.Size.hasValue() || Loc.Size.isScalable() ||
485 BaseSize == MemoryLocation::UnknownSize ||
486 (Offset >= 0 && Offset + Loc.Size.getValue() <= BaseSize),
487 "Undefined behavior: Buffer overflow", &I);
488
489 // Accesses that say that the memory is more aligned than it is are not
490 // defined.
491 if (!Align && Ty && Ty->isSized())
492 Align = DL->getABITypeAlign(Ty);
493 if (BaseAlign && Align)
494 Check(*Align <= commonAlignment(*BaseAlign, Offset),
495 "Undefined behavior: Memory reference address is misaligned", &I);
496 }
497}
498
499void Lint::visitLoadInst(LoadInst &I) {
500 visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), I.getType(),
501 MemRef::Read);
502}
503
504void Lint::visitStoreInst(StoreInst &I) {
505 visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(),
506 I.getOperand(0)->getType(), MemRef::Write);
507}
508
509void Lint::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
510 visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(),
511 I.getOperand(0)->getType(), MemRef::Write);
512}
513
514void Lint::visitAtomicRMWInst(AtomicRMWInst &I) {
515 visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(),
516 I.getOperand(0)->getType(), MemRef::Write);
517}
518
519void Lint::visitXor(BinaryOperator &I) {
520 Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
521 "Undefined result: xor(undef, undef)", &I);
522}
523
524void Lint::visitSub(BinaryOperator &I) {
525 Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
526 "Undefined result: sub(undef, undef)", &I);
527}
528
529void Lint::visitLShr(BinaryOperator &I) {
530 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
531 /*OffsetOk=*/false)))
532 Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
533 "Undefined result: Shift count out of range", &I);
534}
535
536void Lint::visitAShr(BinaryOperator &I) {
537 if (ConstantInt *CI =
538 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
539 Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
540 "Undefined result: Shift count out of range", &I);
541}
542
543void Lint::visitShl(BinaryOperator &I) {
544 if (ConstantInt *CI =
545 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
546 Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
547 "Undefined result: Shift count out of range", &I);
548}
549
550static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
551 AssumptionCache *AC) {
552 // Assume undef could be zero.
553 if (isa<UndefValue>(V))
554 return true;
555
556 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
557 if (!VecTy) {
559 return Known.isZero();
560 }
561
562 // Per-component check doesn't work with zeroinitializer
564 if (!C)
565 return false;
566
567 if (C->isNullValue())
568 return true;
569
570 // For a vector, KnownZero will only be true if all values are zero, so check
571 // this per component
572 for (unsigned I = 0, N = cast<FixedVectorType>(VecTy)->getNumElements();
573 I != N; ++I) {
574 Constant *Elem = C->getAggregateElement(I);
575 if (isa<UndefValue>(Elem))
576 return true;
577
579 if (Known.isZero())
580 return true;
581 }
582
583 return false;
584}
585
586void Lint::visitSDiv(BinaryOperator &I) {
587 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
588 "Undefined behavior: Division by zero", &I);
589}
590
591void Lint::visitUDiv(BinaryOperator &I) {
592 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
593 "Undefined behavior: Division by zero", &I);
594}
595
596void Lint::visitSRem(BinaryOperator &I) {
597 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
598 "Undefined behavior: Division by zero", &I);
599}
600
601void Lint::visitURem(BinaryOperator &I) {
602 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
603 "Undefined behavior: Division by zero", &I);
604}
605
606void Lint::visitAllocaInst(AllocaInst &I) {
607 if (isa<ConstantInt>(I.getArraySize()))
608 // This isn't undefined behavior, it's just an obvious pessimization.
609 Check(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
610 "Pessimization: Static alloca outside of entry block", &I);
611
612 // TODO: Check for an unusual size (MSB set?)
613}
614
615void Lint::visitVAArgInst(VAArgInst &I) {
616 visitMemoryReference(I, MemoryLocation::get(&I), std::nullopt, nullptr,
617 MemRef::Read | MemRef::Write);
618}
619
620void Lint::visitIndirectBrInst(IndirectBrInst &I) {
621 visitMemoryReference(I, MemoryLocation::getAfter(I.getAddress()),
622 std::nullopt, nullptr, MemRef::Branchee);
623
624 Check(I.getNumDestinations() != 0,
625 "Undefined behavior: indirectbr with no destinations", &I);
626}
627
628void Lint::visitExtractElementInst(ExtractElementInst &I) {
629 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
630 /*OffsetOk=*/false))) {
631 ElementCount EC = I.getVectorOperandType()->getElementCount();
632 Check(EC.isScalable() || CI->getValue().ult(EC.getFixedValue()),
633 "Undefined result: extractelement index out of range", &I);
634 }
635}
636
637void Lint::visitInsertElementInst(InsertElementInst &I) {
638 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
639 /*OffsetOk=*/false))) {
640 ElementCount EC = I.getType()->getElementCount();
641 Check(EC.isScalable() || CI->getValue().ult(EC.getFixedValue()),
642 "Undefined result: insertelement index out of range", &I);
643 }
644}
645
646void Lint::visitUnreachableInst(UnreachableInst &I) {
647 // This isn't undefined behavior, it's merely suspicious.
648 Check(&I == &I.getParent()->front() ||
649 std::prev(I.getIterator())->mayHaveSideEffects(),
650 "Unusual: unreachable immediately preceded by instruction without "
651 "side effects",
652 &I);
653}
654
655/// findValue - Look through bitcasts and simple memory reference patterns
656/// to identify an equivalent, but more informative, value. If OffsetOk
657/// is true, look through getelementptrs with non-zero offsets too.
658///
659/// Most analysis passes don't require this logic, because instcombine
660/// will simplify most of these kinds of things away. But it's a goal of
661/// this Lint pass to be useful even on non-optimized IR.
662Value *Lint::findValue(Value *V, bool OffsetOk) const {
663 SmallPtrSet<Value *, 4> Visited;
664 return findValueImpl(V, OffsetOk, Visited);
665}
666
667/// findValueImpl - Implementation helper for findValue.
668Value *Lint::findValueImpl(Value *V, bool OffsetOk,
669 SmallPtrSetImpl<Value *> &Visited) const {
670 // Detect self-referential values.
671 if (!Visited.insert(V).second)
672 return PoisonValue::get(V->getType());
673
674 // TODO: Look through sext or zext cast, when the result is known to
675 // be interpreted as signed or unsigned, respectively.
676 // TODO: Look through eliminable cast pairs.
677 // TODO: Look through calls with unique return values.
678 // TODO: Look through vector insert/extract/shuffle.
679 V = OffsetOk ? getUnderlyingObject(V) : V->stripPointerCasts();
680 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
681 BasicBlock::iterator BBI = L->getIterator();
682 BasicBlock *BB = L->getParent();
683 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
684 BatchAAResults BatchAA(*AA);
685 for (;;) {
686 if (!VisitedBlocks.insert(BB).second)
687 break;
688 if (Value *U =
689 FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, &BatchAA))
690 return findValueImpl(U, OffsetOk, Visited);
691 if (BBI != BB->begin())
692 break;
693 BB = BB->getUniquePredecessor();
694 if (!BB)
695 break;
696 BBI = BB->end();
697 }
698 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
699 if (Value *W = PN->hasConstantValue())
700 return findValueImpl(W, OffsetOk, Visited);
701 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
702 if (CI->isNoopCast(*DL))
703 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
704 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
705 if (Value *W =
706 FindInsertedValue(Ex->getAggregateOperand(), Ex->getIndices()))
707 if (W != V)
708 return findValueImpl(W, OffsetOk, Visited);
709 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
710 // Same as above, but for ConstantExpr instead of Instruction.
711 if (Instruction::isCast(CE->getOpcode())) {
713 CE->getOperand(0)->getType(), CE->getType(),
714 *DL))
715 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
716 }
717 }
718
719 // As a last resort, try SimplifyInstruction or constant folding.
720 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
721 if (Value *W = simplifyInstruction(Inst, {*DL, TLI, DT, AC}))
722 return findValueImpl(W, OffsetOk, Visited);
723 } else if (auto *C = dyn_cast<Constant>(V)) {
725 if (W != V)
726 return findValueImpl(W, OffsetOk, Visited);
727 }
728
729 return V;
730}
731
733 auto *Mod = F.getParent();
734 auto *DL = &F.getDataLayout();
735 auto *AA = &AM.getResult<AAManager>(F);
736 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
737 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
738 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
739 Lint L(Mod, DL, AA, AC, DT, TLI);
740 L.visit(F);
741 dbgs() << L.MessagesStr.str();
742 if (AbortOnError && !L.MessagesStr.str().empty())
744 "linter found errors, aborting. (enabled by abort-on-error)", false);
745 return PreservedAnalyses::all();
746}
747
749 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
750 PassInfoMixin<LintPass>::printPipeline(OS, MapClassName2PassName);
751 if (AbortOnError)
752 OS << "<abort-on-error>";
753}
754
755//===----------------------------------------------------------------------===//
756// Implement the public interfaces to this file...
757//===----------------------------------------------------------------------===//
758
759/// lintFunction - Check a function for errors, printing messages on stderr.
760///
761void llvm::lintFunction(const Function &f, bool AbortOnError) {
762 Function &F = const_cast<Function &>(f);
763 assert(!F.isDeclaration() && "Cannot lint external functions");
764
766 FAM.registerPass([&] { return TargetLibraryAnalysis(); });
767 FAM.registerPass([&] { return DominatorTreeAnalysis(); });
768 FAM.registerPass([&] { return AssumptionAnalysis(); });
769 FAM.registerPass([&] {
771 AA.registerFunctionAnalysis<BasicAA>();
772 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
773 AA.registerFunctionAnalysis<TypeBasedAA>();
774 return AA;
775 });
776 LintPass(AbortOnError).run(F, FAM);
777}
778
779/// lintModule - Check a module for errors, printing messages on stderr.
780///
781void llvm::lintModule(const Module &M, bool AbortOnError) {
782 for (const Function &F : M) {
783 if (!F.isDeclaration())
784 lintFunction(F, AbortOnError);
785 }
786}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU address space definition.
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
@ FnAttr
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
#define Check(C,...)
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
#define T1
AttributeSet CallAttrs
uint64_t IntrinsicInst * II
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
This is the interface for a metadata-based scoped no-alias analysis.
This file defines the SmallPtrSet class.
This is the interface for a metadata-based TBAA.
A manager for alias analyses.
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Definition Function.cpp:266
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Definition Function.cpp:302
LLVM_ABI Type * getParamStructRetType() const
If this is an sret argument, return its type.
Definition Function.cpp:223
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition Function.cpp:281
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
Analysis pass providing a never-invalidated alias analysis result.
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static LLVM_ABI 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 is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This instruction extracts a single (scalar) element from a VectorType value.
Argument * arg_iterator
Definition Function.h:73
Indirect Branch Instruction.
This instruction inserts a single (scalar) element into a VectorType value.
Base class for instruction visitors.
Definition InstVisitor.h:78
bool isCast() const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition Lint.cpp:732
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition Lint.cpp:748
An instruction for reading from memory.
bool hasValue() const
static LocationSize precise(uint64_t Value)
bool isScalable() const
TypeSize getValue() const
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
MaybeAlign getSourceAlign() const
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
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...
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Return a value (possibly void), from a function.
Analysis pass providing a never-invalidated alias analysis result.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Analysis pass providing a never-invalidated alias analysis result.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
This function has undefined behavior.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool isConstantAddressSpace(unsigned AS)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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.
constexpr force_iteration_on_noniterable_enum_t force_iteration_on_noniterable_enum
Definition Sequence.h:110
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *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:554
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr auto enum_seq(EnumT Begin, EnumT End)
Iterate over an enum type from Begin up to - but not including - End.
Definition Sequence.h:373
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI void lintModule(const Module &M, bool AbortOnError=false)
Lint a module.
Definition Lint.cpp:781
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI void lintFunction(const Function &F, bool AbortOnError=false)
lintFunction - Check a function for errors, printing messages on stderr.
Definition Lint.cpp:761
#define N
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111