LLVM 18.0.0git
Verifier.cpp
Go to the documentation of this file.
1//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
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 file defines the function verifier interface, that can be used for some
10// basic correctness checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * All basic blocks should only end with terminator insts, not contain them
27// * The entry node to a function must not have predecessors
28// * All Instructions must be embedded into a basic block
29// * Functions cannot take a void-typed parameter
30// * Verify that a function's argument list agrees with it's declared type.
31// * It is illegal to specify a name for a void value.
32// * It is illegal to have a internal global value with no initializer
33// * It is illegal to have a ret instruction that returns a value that does not
34// agree with the function return value type.
35// * Function call argument types match the function prototype
36// * A landing pad is defined by a landingpad instruction, and can be jumped to
37// only by the unwind edge of an invoke instruction.
38// * A landingpad instruction must be the first non-PHI instruction in the
39// block.
40// * Landingpad instructions must be in a function with a personality function.
41// * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42// The applied restrictions are too numerous to list here.
43// * The convergence entry intrinsic and the loop heart must be the first
44// non-PHI instruction in their respective block. This does not conflict with
45// the landing pads, since these two kinds cannot occur in the same block.
46// * All other things that are tested by asserts spread about the code...
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/IR/Verifier.h"
51#include "llvm/ADT/APFloat.h"
52#include "llvm/ADT/APInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/MapVector.h"
57#include "llvm/ADT/STLExtras.h"
59#include "llvm/ADT/SmallSet.h"
62#include "llvm/ADT/StringMap.h"
63#include "llvm/ADT/StringRef.h"
64#include "llvm/ADT/Twine.h"
66#include "llvm/IR/Argument.h"
68#include "llvm/IR/Attributes.h"
69#include "llvm/IR/BasicBlock.h"
70#include "llvm/IR/CFG.h"
71#include "llvm/IR/CallingConv.h"
72#include "llvm/IR/Comdat.h"
73#include "llvm/IR/Constant.h"
75#include "llvm/IR/Constants.h"
77#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/DebugInfo.h"
80#include "llvm/IR/DebugLoc.h"
82#include "llvm/IR/Dominators.h"
84#include "llvm/IR/Function.h"
85#include "llvm/IR/GCStrategy.h"
86#include "llvm/IR/GlobalAlias.h"
87#include "llvm/IR/GlobalValue.h"
89#include "llvm/IR/InlineAsm.h"
90#include "llvm/IR/InstVisitor.h"
91#include "llvm/IR/InstrTypes.h"
92#include "llvm/IR/Instruction.h"
95#include "llvm/IR/Intrinsics.h"
96#include "llvm/IR/IntrinsicsAArch64.h"
97#include "llvm/IR/IntrinsicsAMDGPU.h"
98#include "llvm/IR/IntrinsicsARM.h"
99#include "llvm/IR/IntrinsicsWebAssembly.h"
100#include "llvm/IR/LLVMContext.h"
101#include "llvm/IR/Metadata.h"
102#include "llvm/IR/Module.h"
104#include "llvm/IR/PassManager.h"
105#include "llvm/IR/Statepoint.h"
106#include "llvm/IR/Type.h"
107#include "llvm/IR/Use.h"
108#include "llvm/IR/User.h"
109#include "llvm/IR/Value.h"
111#include "llvm/Pass.h"
113#include "llvm/Support/Casting.h"
118#include <algorithm>
119#include <cassert>
120#include <cstdint>
121#include <memory>
122#include <optional>
123#include <string>
124#include <utility>
125
126using namespace llvm;
127
129 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
130 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
131 "scopes are not dominating"));
132
133namespace llvm {
134
137 const Module &M;
142
143 /// Track the brokenness of the module while recursively visiting.
144 bool Broken = false;
145 /// Broken debug info can be "recovered" from by stripping the debug info.
146 bool BrokenDebugInfo = false;
147 /// Whether to treat broken debug info as an error.
149
151 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
152 Context(M.getContext()) {}
153
154private:
155 void Write(const Module *M) {
156 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
157 }
158
159 void Write(const Value *V) {
160 if (V)
161 Write(*V);
162 }
163
164 void Write(const Value &V) {
165 if (isa<Instruction>(V)) {
166 V.print(*OS, MST);
167 *OS << '\n';
168 } else {
169 V.printAsOperand(*OS, true, MST);
170 *OS << '\n';
171 }
172 }
173
174 void Write(const Metadata *MD) {
175 if (!MD)
176 return;
177 MD->print(*OS, MST, &M);
178 *OS << '\n';
179 }
180
181 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
182 Write(MD.get());
183 }
184
185 void Write(const NamedMDNode *NMD) {
186 if (!NMD)
187 return;
188 NMD->print(*OS, MST);
189 *OS << '\n';
190 }
191
192 void Write(Type *T) {
193 if (!T)
194 return;
195 *OS << ' ' << *T;
196 }
197
198 void Write(const Comdat *C) {
199 if (!C)
200 return;
201 *OS << *C;
202 }
203
204 void Write(const APInt *AI) {
205 if (!AI)
206 return;
207 *OS << *AI << '\n';
208 }
209
210 void Write(const unsigned i) { *OS << i << '\n'; }
211
212 // NOLINTNEXTLINE(readability-identifier-naming)
213 void Write(const Attribute *A) {
214 if (!A)
215 return;
216 *OS << A->getAsString() << '\n';
217 }
218
219 // NOLINTNEXTLINE(readability-identifier-naming)
220 void Write(const AttributeSet *AS) {
221 if (!AS)
222 return;
223 *OS << AS->getAsString() << '\n';
224 }
225
226 // NOLINTNEXTLINE(readability-identifier-naming)
227 void Write(const AttributeList *AL) {
228 if (!AL)
229 return;
230 AL->print(*OS);
231 }
232
233 void Write(Printable P) { *OS << P << '\n'; }
234
235 template <typename T> void Write(ArrayRef<T> Vs) {
236 for (const T &V : Vs)
237 Write(V);
238 }
239
240 template <typename T1, typename... Ts>
241 void WriteTs(const T1 &V1, const Ts &... Vs) {
242 Write(V1);
243 WriteTs(Vs...);
244 }
245
246 template <typename... Ts> void WriteTs() {}
247
248public:
249 /// A check failed, so printout out the condition and the message.
250 ///
251 /// This provides a nice place to put a breakpoint if you want to see why
252 /// something is not correct.
253 void CheckFailed(const Twine &Message) {
254 if (OS)
255 *OS << Message << '\n';
256 Broken = true;
257 }
258
259 /// A check failed (with values to print).
260 ///
261 /// This calls the Message-only version so that the above is easier to set a
262 /// breakpoint on.
263 template <typename T1, typename... Ts>
264 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
265 CheckFailed(Message);
266 if (OS)
267 WriteTs(V1, Vs...);
268 }
269
270 /// A debug info check failed.
271 void DebugInfoCheckFailed(const Twine &Message) {
272 if (OS)
273 *OS << Message << '\n';
275 BrokenDebugInfo = true;
276 }
277
278 /// A debug info check failed (with values to print).
279 template <typename T1, typename... Ts>
280 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
281 const Ts &... Vs) {
282 DebugInfoCheckFailed(Message);
283 if (OS)
284 WriteTs(V1, Vs...);
285 }
286};
287
288} // namespace llvm
289
290namespace {
291
292class Verifier : public InstVisitor<Verifier>, VerifierSupport {
293 friend class InstVisitor<Verifier>;
294
295 // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
296 // the alignment size should not exceed 2^15. Since encode(Align)
297 // would plus the shift value by 1, the alignment size should
298 // not exceed 2^14, otherwise it can NOT be properly lowered
299 // in backend.
300 static constexpr unsigned ParamMaxAlignment = 1 << 14;
301 DominatorTree DT;
302
303 /// When verifying a basic block, keep track of all of the
304 /// instructions we have seen so far.
305 ///
306 /// This allows us to do efficient dominance checks for the case when an
307 /// instruction has an operand that is an instruction in the same block.
308 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
309
310 /// Keep track of the metadata nodes that have been checked already.
312
313 /// Keep track which DISubprogram is attached to which function.
315
316 /// Track all DICompileUnits visited.
318
319 /// The result type for a landingpad.
320 Type *LandingPadResultTy;
321
322 /// Whether we've seen a call to @llvm.localescape in this function
323 /// already.
324 bool SawFrameEscape;
325
326 /// Whether the current function has a DISubprogram attached to it.
327 bool HasDebugInfo = false;
328
329 /// The current source language.
331
332 /// Whether source was present on the first DIFile encountered in each CU.
333 DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
334
335 /// Stores the count of how many objects were passed to llvm.localescape for a
336 /// given function and the largest index passed to llvm.localrecover.
338
339 // Maps catchswitches and cleanuppads that unwind to siblings to the
340 // terminators that indicate the unwind, used to detect cycles therein.
342
343 /// Cache which blocks are in which funclet, if an EH funclet personality is
344 /// in use. Otherwise empty.
345 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
346
347 /// Cache of constants visited in search of ConstantExprs.
348 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
349
350 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
351 SmallVector<const Function *, 4> DeoptimizeDeclarations;
352
353 /// Cache of attribute lists verified.
354 SmallPtrSet<const void *, 32> AttributeListsVisited;
355
356 // Verify that this GlobalValue is only used in this module.
357 // This map is used to avoid visiting uses twice. We can arrive at a user
358 // twice, if they have multiple operands. In particular for very large
359 // constant expressions, we can arrive at a particular user many times.
360 SmallPtrSet<const Value *, 32> GlobalValueVisited;
361
362 // Keeps track of duplicate function argument debug info.
364
365 TBAAVerifier TBAAVerifyHelper;
366 ConvergenceVerifier ConvergenceVerifyHelper;
367
368 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
369
370 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
371
372public:
373 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
374 const Module &M)
375 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
376 SawFrameEscape(false), TBAAVerifyHelper(this) {
377 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
378 }
379
380 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
381
382 bool verify(const Function &F) {
383 assert(F.getParent() == &M &&
384 "An instance of this class only works with a specific module!");
385
386 // First ensure the function is well-enough formed to compute dominance
387 // information, and directly compute a dominance tree. We don't rely on the
388 // pass manager to provide this as it isolates us from a potentially
389 // out-of-date dominator tree and makes it significantly more complex to run
390 // this code outside of a pass manager.
391 // FIXME: It's really gross that we have to cast away constness here.
392 if (!F.empty())
393 DT.recalculate(const_cast<Function &>(F));
394
395 for (const BasicBlock &BB : F) {
396 if (!BB.empty() && BB.back().isTerminator())
397 continue;
398
399 if (OS) {
400 *OS << "Basic Block in function '" << F.getName()
401 << "' does not have terminator!\n";
402 BB.printAsOperand(*OS, true, MST);
403 *OS << "\n";
404 }
405 return false;
406 }
407
408 auto FailureCB = [this](const Twine &Message) {
409 this->CheckFailed(Message);
410 };
411 ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
412
413 Broken = false;
414 // FIXME: We strip const here because the inst visitor strips const.
415 visit(const_cast<Function &>(F));
416 verifySiblingFuncletUnwinds();
417
418 if (ConvergenceVerifyHelper.sawTokens())
419 ConvergenceVerifyHelper.verify(DT);
420
421 InstsInThisBlock.clear();
422 DebugFnArgs.clear();
423 LandingPadResultTy = nullptr;
424 SawFrameEscape = false;
425 SiblingFuncletInfo.clear();
426 verifyNoAliasScopeDecl();
427 NoAliasScopeDecls.clear();
428
429 return !Broken;
430 }
431
432 /// Verify the module that this instance of \c Verifier was initialized with.
433 bool verify() {
434 Broken = false;
435
436 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
437 for (const Function &F : M)
438 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
439 DeoptimizeDeclarations.push_back(&F);
440
441 // Now that we've visited every function, verify that we never asked to
442 // recover a frame index that wasn't escaped.
443 verifyFrameRecoverIndices();
444 for (const GlobalVariable &GV : M.globals())
445 visitGlobalVariable(GV);
446
447 for (const GlobalAlias &GA : M.aliases())
448 visitGlobalAlias(GA);
449
450 for (const GlobalIFunc &GI : M.ifuncs())
451 visitGlobalIFunc(GI);
452
453 for (const NamedMDNode &NMD : M.named_metadata())
454 visitNamedMDNode(NMD);
455
456 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
457 visitComdat(SMEC.getValue());
458
459 visitModuleFlags();
460 visitModuleIdents();
461 visitModuleCommandLines();
462
463 verifyCompileUnits();
464
465 verifyDeoptimizeCallingConvs();
466 DISubprogramAttachments.clear();
467 return !Broken;
468 }
469
470private:
471 /// Whether a metadata node is allowed to be, or contain, a DILocation.
472 enum class AreDebugLocsAllowed { No, Yes };
473
474 // Verification methods...
475 void visitGlobalValue(const GlobalValue &GV);
476 void visitGlobalVariable(const GlobalVariable &GV);
477 void visitGlobalAlias(const GlobalAlias &GA);
478 void visitGlobalIFunc(const GlobalIFunc &GI);
479 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
480 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
481 const GlobalAlias &A, const Constant &C);
482 void visitNamedMDNode(const NamedMDNode &NMD);
483 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
484 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
485 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
486 void visitComdat(const Comdat &C);
487 void visitModuleIdents();
488 void visitModuleCommandLines();
489 void visitModuleFlags();
490 void visitModuleFlag(const MDNode *Op,
492 SmallVectorImpl<const MDNode *> &Requirements);
493 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
494 void visitFunction(const Function &F);
495 void visitBasicBlock(BasicBlock &BB);
496 void verifyRangeMetadata(const Value &V, const MDNode *Range, Type *Ty,
497 bool IsAbsoluteSymbol);
498 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
499 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
500 void visitProfMetadata(Instruction &I, MDNode *MD);
501 void visitCallStackMetadata(MDNode *MD);
502 void visitMemProfMetadata(Instruction &I, MDNode *MD);
503 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
504 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
505 void visitAnnotationMetadata(MDNode *Annotation);
506 void visitAliasScopeMetadata(const MDNode *MD);
507 void visitAliasScopeListMetadata(const MDNode *MD);
508 void visitAccessGroupMetadata(const MDNode *MD);
509
510 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
511#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
512#include "llvm/IR/Metadata.def"
513 void visitDIScope(const DIScope &N);
514 void visitDIVariable(const DIVariable &N);
515 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
516 void visitDITemplateParameter(const DITemplateParameter &N);
517
518 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
519
520 // InstVisitor overrides...
522 void visit(Instruction &I);
523
524 void visitTruncInst(TruncInst &I);
525 void visitZExtInst(ZExtInst &I);
526 void visitSExtInst(SExtInst &I);
527 void visitFPTruncInst(FPTruncInst &I);
528 void visitFPExtInst(FPExtInst &I);
529 void visitFPToUIInst(FPToUIInst &I);
530 void visitFPToSIInst(FPToSIInst &I);
531 void visitUIToFPInst(UIToFPInst &I);
532 void visitSIToFPInst(SIToFPInst &I);
533 void visitIntToPtrInst(IntToPtrInst &I);
534 void visitPtrToIntInst(PtrToIntInst &I);
535 void visitBitCastInst(BitCastInst &I);
536 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
537 void visitPHINode(PHINode &PN);
538 void visitCallBase(CallBase &Call);
539 void visitUnaryOperator(UnaryOperator &U);
540 void visitBinaryOperator(BinaryOperator &B);
541 void visitICmpInst(ICmpInst &IC);
542 void visitFCmpInst(FCmpInst &FC);
543 void visitExtractElementInst(ExtractElementInst &EI);
544 void visitInsertElementInst(InsertElementInst &EI);
545 void visitShuffleVectorInst(ShuffleVectorInst &EI);
546 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
547 void visitCallInst(CallInst &CI);
548 void visitInvokeInst(InvokeInst &II);
549 void visitGetElementPtrInst(GetElementPtrInst &GEP);
550 void visitLoadInst(LoadInst &LI);
551 void visitStoreInst(StoreInst &SI);
552 void verifyDominatesUse(Instruction &I, unsigned i);
553 void visitInstruction(Instruction &I);
554 void visitTerminator(Instruction &I);
555 void visitBranchInst(BranchInst &BI);
556 void visitReturnInst(ReturnInst &RI);
557 void visitSwitchInst(SwitchInst &SI);
558 void visitIndirectBrInst(IndirectBrInst &BI);
559 void visitCallBrInst(CallBrInst &CBI);
560 void visitSelectInst(SelectInst &SI);
561 void visitUserOp1(Instruction &I);
562 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
563 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
564 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
565 void visitVPIntrinsic(VPIntrinsic &VPI);
566 void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
567 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
568 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
569 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
570 void visitFenceInst(FenceInst &FI);
571 void visitAllocaInst(AllocaInst &AI);
572 void visitExtractValueInst(ExtractValueInst &EVI);
573 void visitInsertValueInst(InsertValueInst &IVI);
574 void visitEHPadPredecessors(Instruction &I);
575 void visitLandingPadInst(LandingPadInst &LPI);
576 void visitResumeInst(ResumeInst &RI);
577 void visitCatchPadInst(CatchPadInst &CPI);
578 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
579 void visitCleanupPadInst(CleanupPadInst &CPI);
580 void visitFuncletPadInst(FuncletPadInst &FPI);
581 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
582 void visitCleanupReturnInst(CleanupReturnInst &CRI);
583
584 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
585 void verifySwiftErrorValue(const Value *SwiftErrorVal);
586 void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
587 void verifyMustTailCall(CallInst &CI);
588 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
589 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
590 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
591 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
592 const Value *V);
593 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
594 const Value *V, bool IsIntrinsic, bool IsInlineAsm);
595 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
596
597 void visitConstantExprsRecursively(const Constant *EntryC);
598 void visitConstantExpr(const ConstantExpr *CE);
599 void verifyInlineAsmCall(const CallBase &Call);
600 void verifyStatepoint(const CallBase &Call);
601 void verifyFrameRecoverIndices();
602 void verifySiblingFuncletUnwinds();
603
604 void verifyFragmentExpression(const DbgVariableIntrinsic &I);
605 template <typename ValueOrMetadata>
606 void verifyFragmentExpression(const DIVariable &V,
608 ValueOrMetadata *Desc);
609 void verifyFnArgs(const DbgVariableIntrinsic &I);
610 void verifyNotEntryValue(const DbgVariableIntrinsic &I);
611
612 /// Module-level debug info verification...
613 void verifyCompileUnits();
614
615 /// Module-level verification that all @llvm.experimental.deoptimize
616 /// declarations share the same calling convention.
617 void verifyDeoptimizeCallingConvs();
618
619 void verifyAttachedCallBundle(const CallBase &Call,
620 const OperandBundleUse &BU);
621
622 /// Verify all-or-nothing property of DIFile source attribute within a CU.
623 void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
624
625 /// Verify the llvm.experimental.noalias.scope.decl declarations
626 void verifyNoAliasScopeDecl();
627};
628
629} // end anonymous namespace
630
631/// We know that cond should be true, if not print an error message.
632#define Check(C, ...) \
633 do { \
634 if (!(C)) { \
635 CheckFailed(__VA_ARGS__); \
636 return; \
637 } \
638 } while (false)
639
640/// We know that a debug info condition should be true, if not print
641/// an error message.
642#define CheckDI(C, ...) \
643 do { \
644 if (!(C)) { \
645 DebugInfoCheckFailed(__VA_ARGS__); \
646 return; \
647 } \
648 } while (false)
649
650void Verifier::visit(Instruction &I) {
651 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
652 Check(I.getOperand(i) != nullptr, "Operand is null", &I);
654}
655
656// Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
657static void forEachUser(const Value *User,
659 llvm::function_ref<bool(const Value *)> Callback) {
660 if (!Visited.insert(User).second)
661 return;
662
665 while (!WorkList.empty()) {
666 const Value *Cur = WorkList.pop_back_val();
667 if (!Visited.insert(Cur).second)
668 continue;
669 if (Callback(Cur))
670 append_range(WorkList, Cur->materialized_users());
671 }
672}
673
674void Verifier::visitGlobalValue(const GlobalValue &GV) {
676 "Global is external, but doesn't have external or weak linkage!", &GV);
677
678 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
679
680 if (MaybeAlign A = GO->getAlign()) {
681 Check(A->value() <= Value::MaximumAlignment,
682 "huge alignment values are unsupported", GO);
683 }
684
685 if (const MDNode *Associated =
686 GO->getMetadata(LLVMContext::MD_associated)) {
687 Check(Associated->getNumOperands() == 1,
688 "associated metadata must have one operand", &GV, Associated);
689 const Metadata *Op = Associated->getOperand(0).get();
690 Check(Op, "associated metadata must have a global value", GO, Associated);
691
692 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
693 Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
694 if (VM) {
695 Check(isa<PointerType>(VM->getValue()->getType()),
696 "associated value must be pointer typed", GV, Associated);
697
698 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
699 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
700 "associated metadata must point to a GlobalObject", GO, Stripped);
701 Check(Stripped != GO,
702 "global values should not associate to themselves", GO,
703 Associated);
704 }
705 }
706
707 // FIXME: Why is getMetadata on GlobalValue protected?
708 if (const MDNode *AbsoluteSymbol =
709 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
710 verifyRangeMetadata(*GO, AbsoluteSymbol, DL.getIntPtrType(GO->getType()),
711 true);
712 }
713 }
714
715 Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
716 "Only global variables can have appending linkage!", &GV);
717
718 if (GV.hasAppendingLinkage()) {
719 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
720 Check(GVar && GVar->getValueType()->isArrayTy(),
721 "Only global arrays can have appending linkage!", GVar);
722 }
723
724 if (GV.isDeclarationForLinker())
725 Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
726
727 if (GV.hasDLLExportStorageClass()) {
729 "dllexport GlobalValue must have default or protected visibility",
730 &GV);
731 }
732 if (GV.hasDLLImportStorageClass()) {
734 "dllimport GlobalValue must have default visibility", &GV);
735 Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
736 &GV);
737
738 Check((GV.isDeclaration() &&
741 "Global is marked as dllimport, but not external", &GV);
742 }
743
744 if (GV.isImplicitDSOLocal())
745 Check(GV.isDSOLocal(),
746 "GlobalValue with local linkage or non-default "
747 "visibility must be dso_local!",
748 &GV);
749
750 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
751 if (const Instruction *I = dyn_cast<Instruction>(V)) {
752 if (!I->getParent() || !I->getParent()->getParent())
753 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
754 I);
755 else if (I->getParent()->getParent()->getParent() != &M)
756 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
757 I->getParent()->getParent(),
758 I->getParent()->getParent()->getParent());
759 return false;
760 } else if (const Function *F = dyn_cast<Function>(V)) {
761 if (F->getParent() != &M)
762 CheckFailed("Global is used by function in a different module", &GV, &M,
763 F, F->getParent());
764 return false;
765 }
766 return true;
767 });
768}
769
770void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
771 if (GV.hasInitializer()) {
773 "Global variable initializer type does not match global "
774 "variable type!",
775 &GV);
776 // If the global has common linkage, it must have a zero initializer and
777 // cannot be constant.
778 if (GV.hasCommonLinkage()) {
780 "'common' global must have a zero initializer!", &GV);
781 Check(!GV.isConstant(), "'common' global may not be marked constant!",
782 &GV);
783 Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
784 }
785 }
786
787 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
788 GV.getName() == "llvm.global_dtors")) {
790 "invalid linkage for intrinsic global variable", &GV);
792 "invalid uses of intrinsic global variable", &GV);
793
794 // Don't worry about emitting an error for it not being an array,
795 // visitGlobalValue will complain on appending non-array.
796 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
797 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
798 PointerType *FuncPtrTy =
799 PointerType::get(Context, DL.getProgramAddressSpace());
800 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
801 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
802 STy->getTypeAtIndex(1) == FuncPtrTy,
803 "wrong type for intrinsic global variable", &GV);
804 Check(STy->getNumElements() == 3,
805 "the third field of the element type is mandatory, "
806 "specify ptr null to migrate from the obsoleted 2-field form");
807 Type *ETy = STy->getTypeAtIndex(2);
808 Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
809 &GV);
810 }
811 }
812
813 if (GV.hasName() && (GV.getName() == "llvm.used" ||
814 GV.getName() == "llvm.compiler.used")) {
816 "invalid linkage for intrinsic global variable", &GV);
818 "invalid uses of intrinsic global variable", &GV);
819
820 Type *GVType = GV.getValueType();
821 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
822 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
823 Check(PTy, "wrong type for intrinsic global variable", &GV);
824 if (GV.hasInitializer()) {
825 const Constant *Init = GV.getInitializer();
826 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
827 Check(InitArray, "wrong initalizer for intrinsic global variable",
828 Init);
829 for (Value *Op : InitArray->operands()) {
830 Value *V = Op->stripPointerCasts();
831 Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
832 isa<GlobalAlias>(V),
833 Twine("invalid ") + GV.getName() + " member", V);
834 Check(V->hasName(),
835 Twine("members of ") + GV.getName() + " must be named", V);
836 }
837 }
838 }
839 }
840
841 // Visit any debug info attachments.
843 GV.getMetadata(LLVMContext::MD_dbg, MDs);
844 for (auto *MD : MDs) {
845 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
846 visitDIGlobalVariableExpression(*GVE);
847 else
848 CheckDI(false, "!dbg attachment of global variable must be a "
849 "DIGlobalVariableExpression");
850 }
851
852 // Scalable vectors cannot be global variables, since we don't know
853 // the runtime size.
855 "Globals cannot contain scalable types", &GV);
856
857 // Check if it's a target extension type that disallows being used as a
858 // global.
859 if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
860 Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
861 "Global @" + GV.getName() + " has illegal target extension type",
862 TTy);
863
864 if (!GV.hasInitializer()) {
865 visitGlobalValue(GV);
866 return;
867 }
868
869 // Walk any aggregate initializers looking for bitcasts between address spaces
870 visitConstantExprsRecursively(GV.getInitializer());
871
872 visitGlobalValue(GV);
873}
874
875void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
877 Visited.insert(&GA);
878 visitAliaseeSubExpr(Visited, GA, C);
879}
880
881void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
882 const GlobalAlias &GA, const Constant &C) {
884 Check(isa<GlobalValue>(C) &&
885 cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
886 "available_externally alias must point to available_externally "
887 "global value",
888 &GA);
889 }
890 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
892 Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
893 &GA);
894 }
895
896 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
897 Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
898
899 Check(!GA2->isInterposable(),
900 "Alias cannot point to an interposable alias", &GA);
901 } else {
902 // Only continue verifying subexpressions of GlobalAliases.
903 // Do not recurse into global initializers.
904 return;
905 }
906 }
907
908 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
909 visitConstantExprsRecursively(CE);
910
911 for (const Use &U : C.operands()) {
912 Value *V = &*U;
913 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
914 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
915 else if (const auto *C2 = dyn_cast<Constant>(V))
916 visitAliaseeSubExpr(Visited, GA, *C2);
917 }
918}
919
920void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
922 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
923 "weak_odr, external, or available_externally linkage!",
924 &GA);
925 const Constant *Aliasee = GA.getAliasee();
926 Check(Aliasee, "Aliasee cannot be NULL!", &GA);
927 Check(GA.getType() == Aliasee->getType(),
928 "Alias and aliasee types should match!", &GA);
929
930 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
931 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
932
933 visitAliaseeSubExpr(GA, *Aliasee);
934
935 visitGlobalValue(GA);
936}
937
938void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
940 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
941 "weak_odr, or external linkage!",
942 &GI);
943 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
944 // is a Function definition.
946 Check(Resolver, "IFunc must have a Function resolver", &GI);
947 Check(!Resolver->isDeclarationForLinker(),
948 "IFunc resolver must be a definition", &GI);
949
950 // Check that the immediate resolver operand (prior to any bitcasts) has the
951 // correct type.
952 const Type *ResolverTy = GI.getResolver()->getType();
953
954 Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
955 "IFunc resolver must return a pointer", &GI);
956
957 const Type *ResolverFuncTy =
959 Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
960 "IFunc resolver has incorrect type", &GI);
961}
962
963void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
964 // There used to be various other llvm.dbg.* nodes, but we don't support
965 // upgrading them and we want to reserve the namespace for future uses.
966 if (NMD.getName().startswith("llvm.dbg."))
967 CheckDI(NMD.getName() == "llvm.dbg.cu",
968 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
969 for (const MDNode *MD : NMD.operands()) {
970 if (NMD.getName() == "llvm.dbg.cu")
971 CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
972
973 if (!MD)
974 continue;
975
976 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
977 }
978}
979
980void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
981 // Only visit each node once. Metadata can be mutually recursive, so this
982 // avoids infinite recursion here, as well as being an optimization.
983 if (!MDNodes.insert(&MD).second)
984 return;
985
986 Check(&MD.getContext() == &Context,
987 "MDNode context does not match Module context!", &MD);
988
989 switch (MD.getMetadataID()) {
990 default:
991 llvm_unreachable("Invalid MDNode subclass");
992 case Metadata::MDTupleKind:
993 break;
994#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
995 case Metadata::CLASS##Kind: \
996 visit##CLASS(cast<CLASS>(MD)); \
997 break;
998#include "llvm/IR/Metadata.def"
999 }
1000
1001 for (const Metadata *Op : MD.operands()) {
1002 if (!Op)
1003 continue;
1004 Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
1005 &MD, Op);
1006 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1007 "DILocation not allowed within this metadata node", &MD, Op);
1008 if (auto *N = dyn_cast<MDNode>(Op)) {
1009 visitMDNode(*N, AllowLocs);
1010 continue;
1011 }
1012 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
1013 visitValueAsMetadata(*V, nullptr);
1014 continue;
1015 }
1016 }
1017
1018 // Check these last, so we diagnose problems in operands first.
1019 Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
1020 Check(MD.isResolved(), "All nodes should be resolved!", &MD);
1021}
1022
1023void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
1024 Check(MD.getValue(), "Expected valid value", &MD);
1025 Check(!MD.getValue()->getType()->isMetadataTy(),
1026 "Unexpected metadata round-trip through values", &MD, MD.getValue());
1027
1028 auto *L = dyn_cast<LocalAsMetadata>(&MD);
1029 if (!L)
1030 return;
1031
1032 Check(F, "function-local metadata used outside a function", L);
1033
1034 // If this was an instruction, bb, or argument, verify that it is in the
1035 // function that we expect.
1036 Function *ActualF = nullptr;
1037 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
1038 Check(I->getParent(), "function-local metadata not in basic block", L, I);
1039 ActualF = I->getParent()->getParent();
1040 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
1041 ActualF = BB->getParent();
1042 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
1043 ActualF = A->getParent();
1044 assert(ActualF && "Unimplemented function local metadata case!");
1045
1046 Check(ActualF == F, "function-local metadata used in wrong function", L);
1047}
1048
1049void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
1050 Metadata *MD = MDV.getMetadata();
1051 if (auto *N = dyn_cast<MDNode>(MD)) {
1052 visitMDNode(*N, AreDebugLocsAllowed::No);
1053 return;
1054 }
1055
1056 // Only visit each node once. Metadata can be mutually recursive, so this
1057 // avoids infinite recursion here, as well as being an optimization.
1058 if (!MDNodes.insert(MD).second)
1059 return;
1060
1061 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
1062 visitValueAsMetadata(*V, F);
1063}
1064
1065static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
1066static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
1067static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
1068
1069void Verifier::visitDILocation(const DILocation &N) {
1070 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1071 "location requires a valid scope", &N, N.getRawScope());
1072 if (auto *IA = N.getRawInlinedAt())
1073 CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
1074 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1075 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1076}
1077
1078void Verifier::visitGenericDINode(const GenericDINode &N) {
1079 CheckDI(N.getTag(), "invalid tag", &N);
1080}
1081
1082void Verifier::visitDIScope(const DIScope &N) {
1083 if (auto *F = N.getRawFile())
1084 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1085}
1086
1087void Verifier::visitDISubrange(const DISubrange &N) {
1088 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1089 bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
1090 CheckDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
1091 N.getRawUpperBound(),
1092 "Subrange must contain count or upperBound", &N);
1093 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1094 "Subrange can have any one of count or upperBound", &N);
1095 auto *CBound = N.getRawCountNode();
1096 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1097 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1098 "Count must be signed constant or DIVariable or DIExpression", &N);
1099 auto Count = N.getCount();
1100 CheckDI(!Count || !isa<ConstantInt *>(Count) ||
1101 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1102 "invalid subrange count", &N);
1103 auto *LBound = N.getRawLowerBound();
1104 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1105 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1106 "LowerBound must be signed constant or DIVariable or DIExpression",
1107 &N);
1108 auto *UBound = N.getRawUpperBound();
1109 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1110 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1111 "UpperBound must be signed constant or DIVariable or DIExpression",
1112 &N);
1113 auto *Stride = N.getRawStride();
1114 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1115 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1116 "Stride must be signed constant or DIVariable or DIExpression", &N);
1117}
1118
1119void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1120 CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1121 CheckDI(N.getRawCountNode() || N.getRawUpperBound(),
1122 "GenericSubrange must contain count or upperBound", &N);
1123 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1124 "GenericSubrange can have any one of count or upperBound", &N);
1125 auto *CBound = N.getRawCountNode();
1126 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1127 "Count must be signed constant or DIVariable or DIExpression", &N);
1128 auto *LBound = N.getRawLowerBound();
1129 CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
1130 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1131 "LowerBound must be signed constant or DIVariable or DIExpression",
1132 &N);
1133 auto *UBound = N.getRawUpperBound();
1134 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1135 "UpperBound must be signed constant or DIVariable or DIExpression",
1136 &N);
1137 auto *Stride = N.getRawStride();
1138 CheckDI(Stride, "GenericSubrange must contain stride", &N);
1139 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1140 "Stride must be signed constant or DIVariable or DIExpression", &N);
1141}
1142
1143void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1144 CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1145}
1146
1147void Verifier::visitDIBasicType(const DIBasicType &N) {
1148 CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1149 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1150 N.getTag() == dwarf::DW_TAG_string_type,
1151 "invalid tag", &N);
1152}
1153
1154void Verifier::visitDIStringType(const DIStringType &N) {
1155 CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1156 CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
1157 &N);
1158}
1159
1160void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1161 // Common scope checks.
1162 visitDIScope(N);
1163
1164 CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
1165 N.getTag() == dwarf::DW_TAG_pointer_type ||
1166 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1167 N.getTag() == dwarf::DW_TAG_reference_type ||
1168 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1169 N.getTag() == dwarf::DW_TAG_const_type ||
1170 N.getTag() == dwarf::DW_TAG_immutable_type ||
1171 N.getTag() == dwarf::DW_TAG_volatile_type ||
1172 N.getTag() == dwarf::DW_TAG_restrict_type ||
1173 N.getTag() == dwarf::DW_TAG_atomic_type ||
1174 N.getTag() == dwarf::DW_TAG_member ||
1175 N.getTag() == dwarf::DW_TAG_inheritance ||
1176 N.getTag() == dwarf::DW_TAG_friend ||
1177 N.getTag() == dwarf::DW_TAG_set_type,
1178 "invalid tag", &N);
1179 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1180 CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1181 N.getRawExtraData());
1182 }
1183
1184 if (N.getTag() == dwarf::DW_TAG_set_type) {
1185 if (auto *T = N.getRawBaseType()) {
1186 auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1187 auto *Basic = dyn_cast_or_null<DIBasicType>(T);
1188 CheckDI(
1189 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1190 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1191 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1192 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1193 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1194 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1195 "invalid set base type", &N, T);
1196 }
1197 }
1198
1199 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1200 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1201 N.getRawBaseType());
1202
1203 if (N.getDWARFAddressSpace()) {
1204 CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1205 N.getTag() == dwarf::DW_TAG_reference_type ||
1206 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1207 "DWARF address space only applies to pointer or reference types",
1208 &N);
1209 }
1210}
1211
1212/// Detect mutually exclusive flags.
1213static bool hasConflictingReferenceFlags(unsigned Flags) {
1214 return ((Flags & DINode::FlagLValueReference) &&
1215 (Flags & DINode::FlagRValueReference)) ||
1216 ((Flags & DINode::FlagTypePassByValue) &&
1217 (Flags & DINode::FlagTypePassByReference));
1218}
1219
1220void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1221 auto *Params = dyn_cast<MDTuple>(&RawParams);
1222 CheckDI(Params, "invalid template params", &N, &RawParams);
1223 for (Metadata *Op : Params->operands()) {
1224 CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1225 &N, Params, Op);
1226 }
1227}
1228
1229void Verifier::visitDICompositeType(const DICompositeType &N) {
1230 // Common scope checks.
1231 visitDIScope(N);
1232
1233 CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
1234 N.getTag() == dwarf::DW_TAG_structure_type ||
1235 N.getTag() == dwarf::DW_TAG_union_type ||
1236 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1237 N.getTag() == dwarf::DW_TAG_class_type ||
1238 N.getTag() == dwarf::DW_TAG_variant_part ||
1239 N.getTag() == dwarf::DW_TAG_namelist,
1240 "invalid tag", &N);
1241
1242 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1243 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1244 N.getRawBaseType());
1245
1246 CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1247 "invalid composite elements", &N, N.getRawElements());
1248 CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1249 N.getRawVTableHolder());
1251 "invalid reference flags", &N);
1252 unsigned DIBlockByRefStruct = 1 << 4;
1253 CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
1254 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1255
1256 if (N.isVector()) {
1257 const DINodeArray Elements = N.getElements();
1258 CheckDI(Elements.size() == 1 &&
1259 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1260 "invalid vector, expected one element of type subrange", &N);
1261 }
1262
1263 if (auto *Params = N.getRawTemplateParams())
1264 visitTemplateParams(N, *Params);
1265
1266 if (auto *D = N.getRawDiscriminator()) {
1267 CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1268 "discriminator can only appear on variant part");
1269 }
1270
1271 if (N.getRawDataLocation()) {
1272 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1273 "dataLocation can only appear in array type");
1274 }
1275
1276 if (N.getRawAssociated()) {
1277 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1278 "associated can only appear in array type");
1279 }
1280
1281 if (N.getRawAllocated()) {
1282 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1283 "allocated can only appear in array type");
1284 }
1285
1286 if (N.getRawRank()) {
1287 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1288 "rank can only appear in array type");
1289 }
1290}
1291
1292void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1293 CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1294 if (auto *Types = N.getRawTypeArray()) {
1295 CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1296 for (Metadata *Ty : N.getTypeArray()->operands()) {
1297 CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1298 }
1299 }
1301 "invalid reference flags", &N);
1302}
1303
1304void Verifier::visitDIFile(const DIFile &N) {
1305 CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1306 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1307 if (Checksum) {
1308 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1309 "invalid checksum kind", &N);
1310 size_t Size;
1311 switch (Checksum->Kind) {
1312 case DIFile::CSK_MD5:
1313 Size = 32;
1314 break;
1315 case DIFile::CSK_SHA1:
1316 Size = 40;
1317 break;
1318 case DIFile::CSK_SHA256:
1319 Size = 64;
1320 break;
1321 }
1322 CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1323 CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1324 "invalid checksum", &N);
1325 }
1326}
1327
1328void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1329 CheckDI(N.isDistinct(), "compile units must be distinct", &N);
1330 CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1331
1332 // Don't bother verifying the compilation directory or producer string
1333 // as those could be empty.
1334 CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1335 N.getRawFile());
1336 CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1337 N.getFile());
1338
1339 CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1340
1341 verifySourceDebugInfo(N, *N.getFile());
1342
1343 CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1344 "invalid emission kind", &N);
1345
1346 if (auto *Array = N.getRawEnumTypes()) {
1347 CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1348 for (Metadata *Op : N.getEnumTypes()->operands()) {
1349 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
1350 CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1351 "invalid enum type", &N, N.getEnumTypes(), Op);
1352 }
1353 }
1354 if (auto *Array = N.getRawRetainedTypes()) {
1355 CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1356 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1357 CheckDI(
1358 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1359 !cast<DISubprogram>(Op)->isDefinition())),
1360 "invalid retained type", &N, Op);
1361 }
1362 }
1363 if (auto *Array = N.getRawGlobalVariables()) {
1364 CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1365 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1366 CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
1367 "invalid global variable ref", &N, Op);
1368 }
1369 }
1370 if (auto *Array = N.getRawImportedEntities()) {
1371 CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1372 for (Metadata *Op : N.getImportedEntities()->operands()) {
1373 CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1374 &N, Op);
1375 }
1376 }
1377 if (auto *Array = N.getRawMacros()) {
1378 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1379 for (Metadata *Op : N.getMacros()->operands()) {
1380 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1381 }
1382 }
1383 CUVisited.insert(&N);
1384}
1385
1386void Verifier::visitDISubprogram(const DISubprogram &N) {
1387 CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1388 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1389 if (auto *F = N.getRawFile())
1390 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1391 else
1392 CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1393 if (auto *T = N.getRawType())
1394 CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1395 CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1396 N.getRawContainingType());
1397 if (auto *Params = N.getRawTemplateParams())
1398 visitTemplateParams(N, *Params);
1399 if (auto *S = N.getRawDeclaration())
1400 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1401 "invalid subprogram declaration", &N, S);
1402 if (auto *RawNode = N.getRawRetainedNodes()) {
1403 auto *Node = dyn_cast<MDTuple>(RawNode);
1404 CheckDI(Node, "invalid retained nodes list", &N, RawNode);
1405 for (Metadata *Op : Node->operands()) {
1406 CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op) ||
1407 isa<DIImportedEntity>(Op)),
1408 "invalid retained nodes, expected DILocalVariable, DILabel or "
1409 "DIImportedEntity",
1410 &N, Node, Op);
1411 }
1412 }
1414 "invalid reference flags", &N);
1415
1416 auto *Unit = N.getRawUnit();
1417 if (N.isDefinition()) {
1418 // Subprogram definitions (not part of the type hierarchy).
1419 CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1420 CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
1421 CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1422 // There's no good way to cross the CU boundary to insert a nested
1423 // DISubprogram definition in one CU into a type defined in another CU.
1424 auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
1425 if (CT && CT->getRawIdentifier() &&
1426 M.getContext().isODRUniquingDebugTypes())
1427 CheckDI(N.getDeclaration(),
1428 "definition subprograms cannot be nested within DICompositeType "
1429 "when enabling ODR",
1430 &N);
1431 if (N.getFile())
1432 verifySourceDebugInfo(*N.getUnit(), *N.getFile());
1433 } else {
1434 // Subprogram declarations (part of the type hierarchy).
1435 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1436 CheckDI(!N.getRawDeclaration(),
1437 "subprogram declaration must not have a declaration field");
1438 }
1439
1440 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1441 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1442 CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1443 for (Metadata *Op : ThrownTypes->operands())
1444 CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1445 Op);
1446 }
1447
1448 if (N.areAllCallsDescribed())
1449 CheckDI(N.isDefinition(),
1450 "DIFlagAllCallsDescribed must be attached to a definition");
1451}
1452
1453void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1454 CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1455 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1456 "invalid local scope", &N, N.getRawScope());
1457 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1458 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1459}
1460
1461void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1462 visitDILexicalBlockBase(N);
1463
1464 CheckDI(N.getLine() || !N.getColumn(),
1465 "cannot have column info without line info", &N);
1466}
1467
1468void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1469 visitDILexicalBlockBase(N);
1470}
1471
1472void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1473 CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1474 if (auto *S = N.getRawScope())
1475 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1476 if (auto *S = N.getRawDecl())
1477 CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1478}
1479
1480void Verifier::visitDINamespace(const DINamespace &N) {
1481 CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1482 if (auto *S = N.getRawScope())
1483 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1484}
1485
1486void Verifier::visitDIMacro(const DIMacro &N) {
1487 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1488 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1489 "invalid macinfo type", &N);
1490 CheckDI(!N.getName().empty(), "anonymous macro", &N);
1491 if (!N.getValue().empty()) {
1492 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1493 }
1494}
1495
1496void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1497 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1498 "invalid macinfo type", &N);
1499 if (auto *F = N.getRawFile())
1500 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1501
1502 if (auto *Array = N.getRawElements()) {
1503 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1504 for (Metadata *Op : N.getElements()->operands()) {
1505 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1506 }
1507 }
1508}
1509
1510void Verifier::visitDIArgList(const DIArgList &N) {
1511 CheckDI(!N.getNumOperands(),
1512 "DIArgList should have no operands other than a list of "
1513 "ValueAsMetadata",
1514 &N);
1515}
1516
1517void Verifier::visitDIModule(const DIModule &N) {
1518 CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1519 CheckDI(!N.getName().empty(), "anonymous module", &N);
1520}
1521
1522void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1523 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1524}
1525
1526void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1527 visitDITemplateParameter(N);
1528
1529 CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1530 &N);
1531}
1532
1533void Verifier::visitDITemplateValueParameter(
1534 const DITemplateValueParameter &N) {
1535 visitDITemplateParameter(N);
1536
1537 CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1538 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1539 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1540 "invalid tag", &N);
1541}
1542
1543void Verifier::visitDIVariable(const DIVariable &N) {
1544 if (auto *S = N.getRawScope())
1545 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1546 if (auto *F = N.getRawFile())
1547 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1548}
1549
1550void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1551 // Checks common to all variables.
1552 visitDIVariable(N);
1553
1554 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1555 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1556 // Check only if the global variable is not an extern
1557 if (N.isDefinition())
1558 CheckDI(N.getType(), "missing global variable type", &N);
1559 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1560 CheckDI(isa<DIDerivedType>(Member),
1561 "invalid static data member declaration", &N, Member);
1562 }
1563}
1564
1565void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1566 // Checks common to all variables.
1567 visitDIVariable(N);
1568
1569 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1570 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1571 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1572 "local variable requires a valid scope", &N, N.getRawScope());
1573 if (auto Ty = N.getType())
1574 CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1575}
1576
1577void Verifier::visitDIAssignID(const DIAssignID &N) {
1578 CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1579 CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1580}
1581
1582void Verifier::visitDILabel(const DILabel &N) {
1583 if (auto *S = N.getRawScope())
1584 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1585 if (auto *F = N.getRawFile())
1586 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1587
1588 CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1589 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1590 "label requires a valid scope", &N, N.getRawScope());
1591}
1592
1593void Verifier::visitDIExpression(const DIExpression &N) {
1594 CheckDI(N.isValid(), "invalid expression", &N);
1595}
1596
1597void Verifier::visitDIGlobalVariableExpression(
1598 const DIGlobalVariableExpression &GVE) {
1599 CheckDI(GVE.getVariable(), "missing variable");
1600 if (auto *Var = GVE.getVariable())
1601 visitDIGlobalVariable(*Var);
1602 if (auto *Expr = GVE.getExpression()) {
1603 visitDIExpression(*Expr);
1604 if (auto Fragment = Expr->getFragmentInfo())
1605 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1606 }
1607}
1608
1609void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1610 CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1611 if (auto *T = N.getRawType())
1612 CheckDI(isType(T), "invalid type ref", &N, T);
1613 if (auto *F = N.getRawFile())
1614 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1615}
1616
1617void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1618 CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1619 N.getTag() == dwarf::DW_TAG_imported_declaration,
1620 "invalid tag", &N);
1621 if (auto *S = N.getRawScope())
1622 CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1623 CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1624 N.getRawEntity());
1625}
1626
1627void Verifier::visitComdat(const Comdat &C) {
1628 // In COFF the Module is invalid if the GlobalValue has private linkage.
1629 // Entities with private linkage don't have entries in the symbol table.
1630 if (TT.isOSBinFormatCOFF())
1631 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1632 Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1633 GV);
1634}
1635
1636void Verifier::visitModuleIdents() {
1637 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1638 if (!Idents)
1639 return;
1640
1641 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1642 // Scan each llvm.ident entry and make sure that this requirement is met.
1643 for (const MDNode *N : Idents->operands()) {
1644 Check(N->getNumOperands() == 1,
1645 "incorrect number of operands in llvm.ident metadata", N);
1646 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1647 ("invalid value for llvm.ident metadata entry operand"
1648 "(the operand should be a string)"),
1649 N->getOperand(0));
1650 }
1651}
1652
1653void Verifier::visitModuleCommandLines() {
1654 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1655 if (!CommandLines)
1656 return;
1657
1658 // llvm.commandline takes a list of metadata entry. Each entry has only one
1659 // string. Scan each llvm.commandline entry and make sure that this
1660 // requirement is met.
1661 for (const MDNode *N : CommandLines->operands()) {
1662 Check(N->getNumOperands() == 1,
1663 "incorrect number of operands in llvm.commandline metadata", N);
1664 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1665 ("invalid value for llvm.commandline metadata entry operand"
1666 "(the operand should be a string)"),
1667 N->getOperand(0));
1668 }
1669}
1670
1671void Verifier::visitModuleFlags() {
1672 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1673 if (!Flags) return;
1674
1675 // Scan each flag, and track the flags and requirements.
1677 SmallVector<const MDNode*, 16> Requirements;
1678 for (const MDNode *MDN : Flags->operands())
1679 visitModuleFlag(MDN, SeenIDs, Requirements);
1680
1681 // Validate that the requirements in the module are valid.
1682 for (const MDNode *Requirement : Requirements) {
1683 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1684 const Metadata *ReqValue = Requirement->getOperand(1);
1685
1686 const MDNode *Op = SeenIDs.lookup(Flag);
1687 if (!Op) {
1688 CheckFailed("invalid requirement on flag, flag is not present in module",
1689 Flag);
1690 continue;
1691 }
1692
1693 if (Op->getOperand(2) != ReqValue) {
1694 CheckFailed(("invalid requirement on flag, "
1695 "flag does not have the required value"),
1696 Flag);
1697 continue;
1698 }
1699 }
1700}
1701
1702void
1703Verifier::visitModuleFlag(const MDNode *Op,
1705 SmallVectorImpl<const MDNode *> &Requirements) {
1706 // Each module flag should have three arguments, the merge behavior (a
1707 // constant int), the flag ID (an MDString), and the value.
1708 Check(Op->getNumOperands() == 3,
1709 "incorrect number of operands in module flag", Op);
1711 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1712 Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1713 "invalid behavior operand in module flag (expected constant integer)",
1714 Op->getOperand(0));
1715 Check(false,
1716 "invalid behavior operand in module flag (unexpected constant)",
1717 Op->getOperand(0));
1718 }
1719 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1720 Check(ID, "invalid ID operand in module flag (expected metadata string)",
1721 Op->getOperand(1));
1722
1723 // Check the values for behaviors with additional requirements.
1724 switch (MFB) {
1725 case Module::Error:
1726 case Module::Warning:
1727 case Module::Override:
1728 // These behavior types accept any value.
1729 break;
1730
1731 case Module::Min: {
1732 auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1733 Check(V && V->getValue().isNonNegative(),
1734 "invalid value for 'min' module flag (expected constant non-negative "
1735 "integer)",
1736 Op->getOperand(2));
1737 break;
1738 }
1739
1740 case Module::Max: {
1741 Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
1742 "invalid value for 'max' module flag (expected constant integer)",
1743 Op->getOperand(2));
1744 break;
1745 }
1746
1747 case Module::Require: {
1748 // The value should itself be an MDNode with two operands, a flag ID (an
1749 // MDString), and a value.
1750 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1751 Check(Value && Value->getNumOperands() == 2,
1752 "invalid value for 'require' module flag (expected metadata pair)",
1753 Op->getOperand(2));
1754 Check(isa<MDString>(Value->getOperand(0)),
1755 ("invalid value for 'require' module flag "
1756 "(first value operand should be a string)"),
1757 Value->getOperand(0));
1758
1759 // Append it to the list of requirements, to check once all module flags are
1760 // scanned.
1761 Requirements.push_back(Value);
1762 break;
1763 }
1764
1765 case Module::Append:
1766 case Module::AppendUnique: {
1767 // These behavior types require the operand be an MDNode.
1768 Check(isa<MDNode>(Op->getOperand(2)),
1769 "invalid value for 'append'-type module flag "
1770 "(expected a metadata node)",
1771 Op->getOperand(2));
1772 break;
1773 }
1774 }
1775
1776 // Unless this is a "requires" flag, check the ID is unique.
1777 if (MFB != Module::Require) {
1778 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1779 Check(Inserted,
1780 "module flag identifiers must be unique (or of 'require' type)", ID);
1781 }
1782
1783 if (ID->getString() == "wchar_size") {
1785 = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1786 Check(Value, "wchar_size metadata requires constant integer argument");
1787 }
1788
1789 if (ID->getString() == "Linker Options") {
1790 // If the llvm.linker.options named metadata exists, we assume that the
1791 // bitcode reader has upgraded the module flag. Otherwise the flag might
1792 // have been created by a client directly.
1793 Check(M.getNamedMetadata("llvm.linker.options"),
1794 "'Linker Options' named metadata no longer supported");
1795 }
1796
1797 if (ID->getString() == "SemanticInterposition") {
1799 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1800 Check(Value,
1801 "SemanticInterposition metadata requires constant integer argument");
1802 }
1803
1804 if (ID->getString() == "CG Profile") {
1805 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
1806 visitModuleFlagCGProfileEntry(MDO);
1807 }
1808}
1809
1810void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
1811 auto CheckFunction = [&](const MDOperand &FuncMDO) {
1812 if (!FuncMDO)
1813 return;
1814 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1815 Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
1816 "expected a Function or null", FuncMDO);
1817 };
1818 auto Node = dyn_cast_or_null<MDNode>(MDO);
1819 Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
1820 CheckFunction(Node->getOperand(0));
1821 CheckFunction(Node->getOperand(1));
1822 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1823 Check(Count && Count->getType()->isIntegerTy(),
1824 "expected an integer constant", Node->getOperand(2));
1825}
1826
1827void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
1828 for (Attribute A : Attrs) {
1829
1830 if (A.isStringAttribute()) {
1831#define GET_ATTR_NAMES
1832#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1833#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1834 if (A.getKindAsString() == #DISPLAY_NAME) { \
1835 auto V = A.getValueAsString(); \
1836 if (!(V.empty() || V == "true" || V == "false")) \
1837 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1838 ""); \
1839 }
1840
1841#include "llvm/IR/Attributes.inc"
1842 continue;
1843 }
1844
1845 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
1846 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
1847 V);
1848 return;
1849 }
1850 }
1851}
1852
1853// VerifyParameterAttrs - Check the given attributes for an argument or return
1854// value of the specified type. The value V is printed in error messages.
1855void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1856 const Value *V) {
1857 if (!Attrs.hasAttributes())
1858 return;
1859
1860 verifyAttributeTypes(Attrs, V);
1861
1862 for (Attribute Attr : Attrs)
1863 Check(Attr.isStringAttribute() ||
1864 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
1865 "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
1866 V);
1867
1868 if (Attrs.hasAttribute(Attribute::ImmArg)) {
1869 Check(Attrs.getNumAttributes() == 1,
1870 "Attribute 'immarg' is incompatible with other attributes", V);
1871 }
1872
1873 // Check for mutually incompatible attributes. Only inreg is compatible with
1874 // sret.
1875 unsigned AttrCount = 0;
1876 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1877 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1878 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
1879 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1880 Attrs.hasAttribute(Attribute::InReg);
1881 AttrCount += Attrs.hasAttribute(Attribute::Nest);
1882 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
1883 Check(AttrCount <= 1,
1884 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1885 "'byref', and 'sret' are incompatible!",
1886 V);
1887
1888 Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
1889 Attrs.hasAttribute(Attribute::ReadOnly)),
1890 "Attributes "
1891 "'inalloca and readonly' are incompatible!",
1892 V);
1893
1894 Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
1895 Attrs.hasAttribute(Attribute::Returned)),
1896 "Attributes "
1897 "'sret and returned' are incompatible!",
1898 V);
1899
1900 Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
1901 Attrs.hasAttribute(Attribute::SExt)),
1902 "Attributes "
1903 "'zeroext and signext' are incompatible!",
1904 V);
1905
1906 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1907 Attrs.hasAttribute(Attribute::ReadOnly)),
1908 "Attributes "
1909 "'readnone and readonly' are incompatible!",
1910 V);
1911
1912 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1913 Attrs.hasAttribute(Attribute::WriteOnly)),
1914 "Attributes "
1915 "'readnone and writeonly' are incompatible!",
1916 V);
1917
1918 Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
1919 Attrs.hasAttribute(Attribute::WriteOnly)),
1920 "Attributes "
1921 "'readonly and writeonly' are incompatible!",
1922 V);
1923
1924 Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
1925 Attrs.hasAttribute(Attribute::AlwaysInline)),
1926 "Attributes "
1927 "'noinline and alwaysinline' are incompatible!",
1928 V);
1929
1930 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1931 for (Attribute Attr : Attrs) {
1932 if (!Attr.isStringAttribute() &&
1933 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1934 CheckFailed("Attribute '" + Attr.getAsString() +
1935 "' applied to incompatible type!", V);
1936 return;
1937 }
1938 }
1939
1940 if (isa<PointerType>(Ty)) {
1941 if (Attrs.hasAttribute(Attribute::ByVal)) {
1942 if (Attrs.hasAttribute(Attribute::Alignment)) {
1943 Align AttrAlign = Attrs.getAlignment().valueOrOne();
1944 Align MaxAlign(ParamMaxAlignment);
1945 Check(AttrAlign <= MaxAlign,
1946 "Attribute 'align' exceed the max size 2^14", V);
1947 }
1948 SmallPtrSet<Type *, 4> Visited;
1949 Check(Attrs.getByValType()->isSized(&Visited),
1950 "Attribute 'byval' does not support unsized types!", V);
1951 }
1952 if (Attrs.hasAttribute(Attribute::ByRef)) {
1953 SmallPtrSet<Type *, 4> Visited;
1954 Check(Attrs.getByRefType()->isSized(&Visited),
1955 "Attribute 'byref' does not support unsized types!", V);
1956 }
1957 if (Attrs.hasAttribute(Attribute::InAlloca)) {
1958 SmallPtrSet<Type *, 4> Visited;
1959 Check(Attrs.getInAllocaType()->isSized(&Visited),
1960 "Attribute 'inalloca' does not support unsized types!", V);
1961 }
1962 if (Attrs.hasAttribute(Attribute::Preallocated)) {
1963 SmallPtrSet<Type *, 4> Visited;
1964 Check(Attrs.getPreallocatedType()->isSized(&Visited),
1965 "Attribute 'preallocated' does not support unsized types!", V);
1966 }
1967 }
1968
1969 if (Attrs.hasAttribute(Attribute::NoFPClass)) {
1970 uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
1971 Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
1972 V);
1973 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
1974 "Invalid value for 'nofpclass' test mask", V);
1975 }
1976}
1977
1978void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1979 const Value *V) {
1980 if (Attrs.hasFnAttr(Attr)) {
1981 StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1982 unsigned N;
1983 if (S.getAsInteger(10, N))
1984 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
1985 }
1986}
1987
1988// Check parameter attributes against a function type.
1989// The value V is printed in error messages.
1990void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
1991 const Value *V, bool IsIntrinsic,
1992 bool IsInlineAsm) {
1993 if (Attrs.isEmpty())
1994 return;
1995
1996 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
1997 Check(Attrs.hasParentContext(Context),
1998 "Attribute list does not match Module context!", &Attrs, V);
1999 for (const auto &AttrSet : Attrs) {
2000 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2001 "Attribute set does not match Module context!", &AttrSet, V);
2002 for (const auto &A : AttrSet) {
2003 Check(A.hasParentContext(Context),
2004 "Attribute does not match Module context!", &A, V);
2005 }
2006 }
2007 }
2008
2009 bool SawNest = false;
2010 bool SawReturned = false;
2011 bool SawSRet = false;
2012 bool SawSwiftSelf = false;
2013 bool SawSwiftAsync = false;
2014 bool SawSwiftError = false;
2015
2016 // Verify return value attributes.
2017 AttributeSet RetAttrs = Attrs.getRetAttrs();
2018 for (Attribute RetAttr : RetAttrs)
2019 Check(RetAttr.isStringAttribute() ||
2020 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2021 "Attribute '" + RetAttr.getAsString() +
2022 "' does not apply to function return values",
2023 V);
2024
2025 unsigned MaxParameterWidth = 0;
2026 auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
2027 if (Ty->isVectorTy()) {
2028 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2029 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2030 if (Size > MaxParameterWidth)
2031 MaxParameterWidth = Size;
2032 }
2033 }
2034 };
2035 GetMaxParameterWidth(FT->getReturnType());
2036 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2037
2038 // Verify parameter attributes.
2039 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2040 Type *Ty = FT->getParamType(i);
2041 AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
2042
2043 if (!IsIntrinsic) {
2044 Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
2045 "immarg attribute only applies to intrinsics", V);
2046 if (!IsInlineAsm)
2047 Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
2048 "Attribute 'elementtype' can only be applied to intrinsics"
2049 " and inline asm.",
2050 V);
2051 }
2052
2053 verifyParameterAttrs(ArgAttrs, Ty, V);
2054 GetMaxParameterWidth(Ty);
2055
2056 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2057 Check(!SawNest, "More than one parameter has attribute nest!", V);
2058 SawNest = true;
2059 }
2060
2061 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2062 Check(!SawReturned, "More than one parameter has attribute returned!", V);
2063 Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
2064 "Incompatible argument and return types for 'returned' attribute",
2065 V);
2066 SawReturned = true;
2067 }
2068
2069 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
2070 Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
2071 Check(i == 0 || i == 1,
2072 "Attribute 'sret' is not on first or second parameter!", V);
2073 SawSRet = true;
2074 }
2075
2076 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
2077 Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
2078 SawSwiftSelf = true;
2079 }
2080
2081 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
2082 Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2083 SawSwiftAsync = true;
2084 }
2085
2086 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
2087 Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
2088 SawSwiftError = true;
2089 }
2090
2091 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
2092 Check(i == FT->getNumParams() - 1,
2093 "inalloca isn't on the last parameter!", V);
2094 }
2095 }
2096
2097 if (!Attrs.hasFnAttrs())
2098 return;
2099
2100 verifyAttributeTypes(Attrs.getFnAttrs(), V);
2101 for (Attribute FnAttr : Attrs.getFnAttrs())
2102 Check(FnAttr.isStringAttribute() ||
2103 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2104 "Attribute '" + FnAttr.getAsString() +
2105 "' does not apply to functions!",
2106 V);
2107
2108 Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2109 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2110 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2111
2112 if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2113 Check(Attrs.hasFnAttr(Attribute::NoInline),
2114 "Attribute 'optnone' requires 'noinline'!", V);
2115
2116 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2117 "Attributes 'optsize and optnone' are incompatible!", V);
2118
2119 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2120 "Attributes 'minsize and optnone' are incompatible!", V);
2121 }
2122
2123 if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2124 Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2125 "Attributes 'aarch64_pstate_sm_enabled and "
2126 "aarch64_pstate_sm_compatible' are incompatible!",
2127 V);
2128 }
2129
2130 if (Attrs.hasFnAttr("aarch64_pstate_za_new")) {
2131 Check(!Attrs.hasFnAttr("aarch64_pstate_za_preserved"),
2132 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2133 "are incompatible!",
2134 V);
2135
2136 Check(!Attrs.hasFnAttr("aarch64_pstate_za_shared"),
2137 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2138 "are incompatible!",
2139 V);
2140 }
2141
2142 if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2143 const GlobalValue *GV = cast<GlobalValue>(V);
2145 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2146 }
2147
2148 if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
2149 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2150 if (ParamNo >= FT->getNumParams()) {
2151 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2152 return false;
2153 }
2154
2155 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2156 CheckFailed("'allocsize' " + Name +
2157 " argument must refer to an integer parameter",
2158 V);
2159 return false;
2160 }
2161
2162 return true;
2163 };
2164
2165 if (!CheckParam("element size", Args->first))
2166 return;
2167
2168 if (Args->second && !CheckParam("number of elements", *Args->second))
2169 return;
2170 }
2171
2172 if (Attrs.hasFnAttr(Attribute::AllocKind)) {
2173 AllocFnKind K = Attrs.getAllocKind();
2176 if (!is_contained(
2178 Type))
2179 CheckFailed(
2180 "'allockind()' requires exactly one of alloc, realloc, and free");
2181 if ((Type == AllocFnKind::Free) &&
2184 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2185 "or aligned modifiers.");
2187 if ((K & ZeroedUninit) == ZeroedUninit)
2188 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2189 }
2190
2191 if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2192 unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2193 if (VScaleMin == 0)
2194 CheckFailed("'vscale_range' minimum must be greater than 0", V);
2195 else if (!isPowerOf2_32(VScaleMin))
2196 CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2197 std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2198 if (VScaleMax && VScaleMin > VScaleMax)
2199 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2200 else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
2201 CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2202 }
2203
2204 if (Attrs.hasFnAttr("frame-pointer")) {
2205 StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2206 if (FP != "all" && FP != "non-leaf" && FP != "none")
2207 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2208 }
2209
2210 // Check EVEX512 feature.
2211 if (MaxParameterWidth >= 512 && Attrs.hasFnAttr("target-features")) {
2212 Triple T(M.getTargetTriple());
2213 if (T.isX86()) {
2214 StringRef TF = Attrs.getFnAttr("target-features").getValueAsString();
2215 Check(!TF.contains("+avx512f") || !TF.contains("-evex512"),
2216 "512-bit vector arguments require 'evex512' for AVX512", V);
2217 }
2218 }
2219
2220 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2221 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2222 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2223}
2224
2225void Verifier::verifyFunctionMetadata(
2226 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2227 for (const auto &Pair : MDs) {
2228 if (Pair.first == LLVMContext::MD_prof) {
2229 MDNode *MD = Pair.second;
2230 Check(MD->getNumOperands() >= 2,
2231 "!prof annotations should have no less than 2 operands", MD);
2232
2233 // Check first operand.
2234 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
2235 MD);
2236 Check(isa<MDString>(MD->getOperand(0)),
2237 "expected string with name of the !prof annotation", MD);
2238 MDString *MDS = cast<MDString>(MD->getOperand(0));
2239 StringRef ProfName = MDS->getString();
2240 Check(ProfName.equals("function_entry_count") ||
2241 ProfName.equals("synthetic_function_entry_count"),
2242 "first operand should be 'function_entry_count'"
2243 " or 'synthetic_function_entry_count'",
2244 MD);
2245
2246 // Check second operand.
2247 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
2248 MD);
2249 Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
2250 "expected integer argument to function_entry_count", MD);
2251 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2252 MDNode *MD = Pair.second;
2253 Check(MD->getNumOperands() == 1,
2254 "!kcfi_type must have exactly one operand", MD);
2255 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2256 MD);
2257 Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
2258 "expected a constant operand for !kcfi_type", MD);
2259 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2260 Check(isa<ConstantInt>(C),
2261 "expected a constant integer operand for !kcfi_type", MD);
2262 IntegerType *Type = cast<ConstantInt>(C)->getType();
2263 Check(Type->getBitWidth() == 32,
2264 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2265 }
2266 }
2267}
2268
2269void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2270 if (!ConstantExprVisited.insert(EntryC).second)
2271 return;
2272
2274 Stack.push_back(EntryC);
2275
2276 while (!Stack.empty()) {
2277 const Constant *C = Stack.pop_back_val();
2278
2279 // Check this constant expression.
2280 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2281 visitConstantExpr(CE);
2282
2283 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2284 // Global Values get visited separately, but we do need to make sure
2285 // that the global value is in the correct module
2286 Check(GV->getParent() == &M, "Referencing global in another module!",
2287 EntryC, &M, GV, GV->getParent());
2288 continue;
2289 }
2290
2291 // Visit all sub-expressions.
2292 for (const Use &U : C->operands()) {
2293 const auto *OpC = dyn_cast<Constant>(U);
2294 if (!OpC)
2295 continue;
2296 if (!ConstantExprVisited.insert(OpC).second)
2297 continue;
2298 Stack.push_back(OpC);
2299 }
2300 }
2301}
2302
2303void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2304 if (CE->getOpcode() == Instruction::BitCast)
2305 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2306 CE->getType()),
2307 "Invalid bitcast", CE);
2308}
2309
2310bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2311 // There shouldn't be more attribute sets than there are parameters plus the
2312 // function and return value.
2313 return Attrs.getNumAttrSets() <= Params + 2;
2314}
2315
2316void Verifier::verifyInlineAsmCall(const CallBase &Call) {
2317 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
2318 unsigned ArgNo = 0;
2319 unsigned LabelNo = 0;
2320 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2321 if (CI.Type == InlineAsm::isLabel) {
2322 ++LabelNo;
2323 continue;
2324 }
2325
2326 // Only deal with constraints that correspond to call arguments.
2327 if (!CI.hasArg())
2328 continue;
2329
2330 if (CI.isIndirect) {
2331 const Value *Arg = Call.getArgOperand(ArgNo);
2332 Check(Arg->getType()->isPointerTy(),
2333 "Operand for indirect constraint must have pointer type", &Call);
2334
2335 Check(Call.getParamElementType(ArgNo),
2336 "Operand for indirect constraint must have elementtype attribute",
2337 &Call);
2338 } else {
2339 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
2340 "Elementtype attribute can only be applied for indirect "
2341 "constraints",
2342 &Call);
2343 }
2344
2345 ArgNo++;
2346 }
2347
2348 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2349 Check(LabelNo == CallBr->getNumIndirectDests(),
2350 "Number of label constraints does not match number of callbr dests",
2351 &Call);
2352 } else {
2353 Check(LabelNo == 0, "Label constraints can only be used with callbr",
2354 &Call);
2355 }
2356}
2357
2358/// Verify that statepoint intrinsic is well formed.
2359void Verifier::verifyStatepoint(const CallBase &Call) {
2360 assert(Call.getCalledFunction() &&
2361 Call.getCalledFunction()->getIntrinsicID() ==
2362 Intrinsic::experimental_gc_statepoint);
2363
2364 Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
2365 !Call.onlyAccessesArgMemory(),
2366 "gc.statepoint must read and write all memory to preserve "
2367 "reordering restrictions required by safepoint semantics",
2368 Call);
2369
2370 const int64_t NumPatchBytes =
2371 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2372 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2373 Check(NumPatchBytes >= 0,
2374 "gc.statepoint number of patchable bytes must be "
2375 "positive",
2376 Call);
2377
2378 Type *TargetElemType = Call.getParamElementType(2);
2379 Check(TargetElemType,
2380 "gc.statepoint callee argument must have elementtype attribute", Call);
2381 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2382 Check(TargetFuncType,
2383 "gc.statepoint callee elementtype must be function type", Call);
2384
2385 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2386 Check(NumCallArgs >= 0,
2387 "gc.statepoint number of arguments to underlying call "
2388 "must be positive",
2389 Call);
2390 const int NumParams = (int)TargetFuncType->getNumParams();
2391 if (TargetFuncType->isVarArg()) {
2392 Check(NumCallArgs >= NumParams,
2393 "gc.statepoint mismatch in number of vararg call args", Call);
2394
2395 // TODO: Remove this limitation
2396 Check(TargetFuncType->getReturnType()->isVoidTy(),
2397 "gc.statepoint doesn't support wrapping non-void "
2398 "vararg functions yet",
2399 Call);
2400 } else
2401 Check(NumCallArgs == NumParams,
2402 "gc.statepoint mismatch in number of call args", Call);
2403
2404 const uint64_t Flags
2405 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2406 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2407 "unknown flag used in gc.statepoint flags argument", Call);
2408
2409 // Verify that the types of the call parameter arguments match
2410 // the type of the wrapped callee.
2411 AttributeList Attrs = Call.getAttributes();
2412 for (int i = 0; i < NumParams; i++) {
2413 Type *ParamType = TargetFuncType->getParamType(i);
2414 Type *ArgType = Call.getArgOperand(5 + i)->getType();
2415 Check(ArgType == ParamType,
2416 "gc.statepoint call argument does not match wrapped "
2417 "function type",
2418 Call);
2419
2420 if (TargetFuncType->isVarArg()) {
2421 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
2422 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
2423 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2424 }
2425 }
2426
2427 const int EndCallArgsInx = 4 + NumCallArgs;
2428
2429 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2430 Check(isa<ConstantInt>(NumTransitionArgsV),
2431 "gc.statepoint number of transition arguments "
2432 "must be constant integer",
2433 Call);
2434 const int NumTransitionArgs =
2435 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2436 Check(NumTransitionArgs == 0,
2437 "gc.statepoint w/inline transition bundle is deprecated", Call);
2438 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2439
2440 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2441 Check(isa<ConstantInt>(NumDeoptArgsV),
2442 "gc.statepoint number of deoptimization arguments "
2443 "must be constant integer",
2444 Call);
2445 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2446 Check(NumDeoptArgs == 0,
2447 "gc.statepoint w/inline deopt operands is deprecated", Call);
2448
2449 const int ExpectedNumArgs = 7 + NumCallArgs;
2450 Check(ExpectedNumArgs == (int)Call.arg_size(),
2451 "gc.statepoint too many arguments", Call);
2452
2453 // Check that the only uses of this gc.statepoint are gc.result or
2454 // gc.relocate calls which are tied to this statepoint and thus part
2455 // of the same statepoint sequence
2456 for (const User *U : Call.users()) {
2457 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2458 Check(UserCall, "illegal use of statepoint token", Call, U);
2459 if (!UserCall)
2460 continue;
2461 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2462 "gc.result or gc.relocate are the only value uses "
2463 "of a gc.statepoint",
2464 Call, U);
2465 if (isa<GCResultInst>(UserCall)) {
2466 Check(UserCall->getArgOperand(0) == &Call,
2467 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2468 } else if (isa<GCRelocateInst>(Call)) {
2469 Check(UserCall->getArgOperand(0) == &Call,
2470 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2471 }
2472 }
2473
2474 // Note: It is legal for a single derived pointer to be listed multiple
2475 // times. It's non-optimal, but it is legal. It can also happen after
2476 // insertion if we strip a bitcast away.
2477 // Note: It is really tempting to check that each base is relocated and
2478 // that a derived pointer is never reused as a base pointer. This turns
2479 // out to be problematic since optimizations run after safepoint insertion
2480 // can recognize equality properties that the insertion logic doesn't know
2481 // about. See example statepoint.ll in the verifier subdirectory
2482}
2483
2484void Verifier::verifyFrameRecoverIndices() {
2485 for (auto &Counts : FrameEscapeInfo) {
2486 Function *F = Counts.first;
2487 unsigned EscapedObjectCount = Counts.second.first;
2488 unsigned MaxRecoveredIndex = Counts.second.second;
2489 Check(MaxRecoveredIndex <= EscapedObjectCount,
2490 "all indices passed to llvm.localrecover must be less than the "
2491 "number of arguments passed to llvm.localescape in the parent "
2492 "function",
2493 F);
2494 }
2495}
2496
2497static Instruction *getSuccPad(Instruction *Terminator) {
2498 BasicBlock *UnwindDest;
2499 if (auto *II = dyn_cast<InvokeInst>(Terminator))
2500 UnwindDest = II->getUnwindDest();
2501 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2502 UnwindDest = CSI->getUnwindDest();
2503 else
2504 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2505 return UnwindDest->getFirstNonPHI();
2506}
2507
2508void Verifier::verifySiblingFuncletUnwinds() {
2511 for (const auto &Pair : SiblingFuncletInfo) {
2512 Instruction *PredPad = Pair.first;
2513 if (Visited.count(PredPad))
2514 continue;
2515 Active.insert(PredPad);
2516 Instruction *Terminator = Pair.second;
2517 do {
2518 Instruction *SuccPad = getSuccPad(Terminator);
2519 if (Active.count(SuccPad)) {
2520 // Found a cycle; report error
2521 Instruction *CyclePad = SuccPad;
2523 do {
2524 CycleNodes.push_back(CyclePad);
2525 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2526 if (CycleTerminator != CyclePad)
2527 CycleNodes.push_back(CycleTerminator);
2528 CyclePad = getSuccPad(CycleTerminator);
2529 } while (CyclePad != SuccPad);
2530 Check(false, "EH pads can't handle each other's exceptions",
2531 ArrayRef<Instruction *>(CycleNodes));
2532 }
2533 // Don't re-walk a node we've already checked
2534 if (!Visited.insert(SuccPad).second)
2535 break;
2536 // Walk to this successor if it has a map entry.
2537 PredPad = SuccPad;
2538 auto TermI = SiblingFuncletInfo.find(PredPad);
2539 if (TermI == SiblingFuncletInfo.end())
2540 break;
2541 Terminator = TermI->second;
2542 Active.insert(PredPad);
2543 } while (true);
2544 // Each node only has one successor, so we've walked all the active
2545 // nodes' successors.
2546 Active.clear();
2547 }
2548}
2549
2550// visitFunction - Verify that a function is ok.
2551//
2552void Verifier::visitFunction(const Function &F) {
2553 visitGlobalValue(F);
2554
2555 // Check function arguments.
2556 FunctionType *FT = F.getFunctionType();
2557 unsigned NumArgs = F.arg_size();
2558
2559 Check(&Context == &F.getContext(),
2560 "Function context does not match Module context!", &F);
2561
2562 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
2563 Check(FT->getNumParams() == NumArgs,
2564 "# formal arguments must match # of arguments for function type!", &F,
2565 FT);
2566 Check(F.getReturnType()->isFirstClassType() ||
2567 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2568 "Functions cannot return aggregate values!", &F);
2569
2570 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2571 "Invalid struct return type!", &F);
2572
2573 AttributeList Attrs = F.getAttributes();
2574
2575 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
2576 "Attribute after last parameter!", &F);
2577
2578 bool IsIntrinsic = F.isIntrinsic();
2579
2580 // Check function attributes.
2581 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
2582
2583 // On function declarations/definitions, we do not support the builtin
2584 // attribute. We do not check this in VerifyFunctionAttrs since that is
2585 // checking for Attributes that can/can not ever be on functions.
2586 Check(!Attrs.hasFnAttr(Attribute::Builtin),
2587 "Attribute 'builtin' can only be applied to a callsite.", &F);
2588
2589 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2590 "Attribute 'elementtype' can only be applied to a callsite.", &F);
2591
2592 // Check that this function meets the restrictions on this calling convention.
2593 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2594 // restrictions can be lifted.
2595 switch (F.getCallingConv()) {
2596 default:
2597 case CallingConv::C:
2598 break;
2599 case CallingConv::X86_INTR: {
2600 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2601 "Calling convention parameter requires byval", &F);
2602 break;
2603 }
2608 Check(F.getReturnType()->isVoidTy(),
2609 "Calling convention requires void return type", &F);
2610 [[fallthrough]];
2616 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
2617 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2618 const unsigned StackAS = DL.getAllocaAddrSpace();
2619 unsigned i = 0;
2620 for (const Argument &Arg : F.args()) {
2621 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
2622 "Calling convention disallows byval", &F);
2623 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2624 "Calling convention disallows preallocated", &F);
2625 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2626 "Calling convention disallows inalloca", &F);
2627
2628 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2629 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2630 // value here.
2631 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2632 "Calling convention disallows stack byref", &F);
2633 }
2634
2635 ++i;
2636 }
2637 }
2638
2639 [[fallthrough]];
2640 case CallingConv::Fast:
2641 case CallingConv::Cold:
2645 Check(!F.isVarArg(),
2646 "Calling convention does not support varargs or "
2647 "perfect forwarding!",
2648 &F);
2649 break;
2650 }
2651
2652 // Check that the argument values match the function type for this function...
2653 unsigned i = 0;
2654 for (const Argument &Arg : F.args()) {
2655 Check(Arg.getType() == FT->getParamType(i),
2656 "Argument value does not match function argument type!", &Arg,
2657 FT->getParamType(i));
2658 Check(Arg.getType()->isFirstClassType(),
2659 "Function arguments must have first-class types!", &Arg);
2660 if (!IsIntrinsic) {
2661 Check(!Arg.getType()->isMetadataTy(),
2662 "Function takes metadata but isn't an intrinsic", &Arg, &F);
2663 Check(!Arg.getType()->isTokenTy(),
2664 "Function takes token but isn't an intrinsic", &Arg, &F);
2665 Check(!Arg.getType()->isX86_AMXTy(),
2666 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
2667 }
2668
2669 // Check that swifterror argument is only used by loads and stores.
2670 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2671 verifySwiftErrorValue(&Arg);
2672 }
2673 ++i;
2674 }
2675
2676 if (!IsIntrinsic) {
2677 Check(!F.getReturnType()->isTokenTy(),
2678 "Function returns a token but isn't an intrinsic", &F);
2679 Check(!F.getReturnType()->isX86_AMXTy(),
2680 "Function returns a x86_amx but isn't an intrinsic", &F);
2681 }
2682
2683 // Get the function metadata attachments.
2685 F.getAllMetadata(MDs);
2686 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
2687 verifyFunctionMetadata(MDs);
2688
2689 // Check validity of the personality function
2690 if (F.hasPersonalityFn()) {
2691 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2692 if (Per)
2693 Check(Per->getParent() == F.getParent(),
2694 "Referencing personality function in another module!", &F,
2695 F.getParent(), Per, Per->getParent());
2696 }
2697
2698 // EH funclet coloring can be expensive, recompute on-demand
2699 BlockEHFuncletColors.clear();
2700
2701 if (F.isMaterializable()) {
2702 // Function has a body somewhere we can't see.
2703 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2704 MDs.empty() ? nullptr : MDs.front().second);
2705 } else if (F.isDeclaration()) {
2706 for (const auto &I : MDs) {
2707 // This is used for call site debug information.
2708 CheckDI(I.first != LLVMContext::MD_dbg ||
2709 !cast<DISubprogram>(I.second)->isDistinct(),
2710 "function declaration may only have a unique !dbg attachment",
2711 &F);
2712 Check(I.first != LLVMContext::MD_prof,
2713 "function declaration may not have a !prof attachment", &F);
2714
2715 // Verify the metadata itself.
2716 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
2717 }
2718 Check(!F.hasPersonalityFn(),
2719 "Function declaration shouldn't have a personality routine", &F);
2720 } else {
2721 // Verify that this function (which has a body) is not named "llvm.*". It
2722 // is not legal to define intrinsics.
2723 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
2724
2725 // Check the entry node
2726 const BasicBlock *Entry = &F.getEntryBlock();
2727 Check(pred_empty(Entry),
2728 "Entry block to function must not have predecessors!", Entry);
2729
2730 // The address of the entry block cannot be taken, unless it is dead.
2731 if (Entry->hasAddressTaken()) {
2732 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
2733 "blockaddress may not be used with the entry block!", Entry);
2734 }
2735
2736 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2737 NumKCFIAttachments = 0;
2738 // Visit metadata attachments.
2739 for (const auto &I : MDs) {
2740 // Verify that the attachment is legal.
2741 auto AllowLocs = AreDebugLocsAllowed::No;
2742 switch (I.first) {
2743 default:
2744 break;
2745 case LLVMContext::MD_dbg: {
2746 ++NumDebugAttachments;
2747 CheckDI(NumDebugAttachments == 1,
2748 "function must have a single !dbg attachment", &F, I.second);
2749 CheckDI(isa<DISubprogram>(I.second),
2750 "function !dbg attachment must be a subprogram", &F, I.second);
2751 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
2752 "function definition may only have a distinct !dbg attachment",
2753 &F);
2754
2755 auto *SP = cast<DISubprogram>(I.second);
2756 const Function *&AttachedTo = DISubprogramAttachments[SP];
2757 CheckDI(!AttachedTo || AttachedTo == &F,
2758 "DISubprogram attached to more than one function", SP, &F);
2759 AttachedTo = &F;
2760 AllowLocs = AreDebugLocsAllowed::Yes;
2761 break;
2762 }
2763 case LLVMContext::MD_prof:
2764 ++NumProfAttachments;
2765 Check(NumProfAttachments == 1,
2766 "function must have a single !prof attachment", &F, I.second);
2767 break;
2768 case LLVMContext::MD_kcfi_type:
2769 ++NumKCFIAttachments;
2770 Check(NumKCFIAttachments == 1,
2771 "function must have a single !kcfi_type attachment", &F,
2772 I.second);
2773 break;
2774 }
2775
2776 // Verify the metadata itself.
2777 visitMDNode(*I.second, AllowLocs);
2778 }
2779 }
2780
2781 // If this function is actually an intrinsic, verify that it is only used in
2782 // direct call/invokes, never having its "address taken".
2783 // Only do this if the module is materialized, otherwise we don't have all the
2784 // uses.
2785 if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
2786 const User *U;
2787 if (F.hasAddressTaken(&U, false, true, false,
2788 /*IgnoreARCAttachedCall=*/true))
2789 Check(false, "Invalid user of intrinsic instruction!", U);
2790 }
2791
2792 // Check intrinsics' signatures.
2793 switch (F.getIntrinsicID()) {
2794 case Intrinsic::experimental_gc_get_pointer_base: {
2795 FunctionType *FT = F.getFunctionType();
2796 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
2797 Check(isa<PointerType>(F.getReturnType()),
2798 "gc.get.pointer.base must return a pointer", F);
2799 Check(FT->getParamType(0) == F.getReturnType(),
2800 "gc.get.pointer.base operand and result must be of the same type", F);
2801 break;
2802 }
2803 case Intrinsic::experimental_gc_get_pointer_offset: {
2804 FunctionType *FT = F.getFunctionType();
2805 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
2806 Check(isa<PointerType>(FT->getParamType(0)),
2807 "gc.get.pointer.offset operand must be a pointer", F);
2808 Check(F.getReturnType()->isIntegerTy(),
2809 "gc.get.pointer.offset must return integer", F);
2810 break;
2811 }
2812 }
2813
2814 auto *N = F.getSubprogram();
2815 HasDebugInfo = (N != nullptr);
2816 if (!HasDebugInfo)
2817 return;
2818
2819 // Check that all !dbg attachments lead to back to N.
2820 //
2821 // FIXME: Check this incrementally while visiting !dbg attachments.
2822 // FIXME: Only check when N is the canonical subprogram for F.
2824 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
2825 // Be careful about using DILocation here since we might be dealing with
2826 // broken code (this is the Verifier after all).
2827 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
2828 if (!DL)
2829 return;
2830 if (!Seen.insert(DL).second)
2831 return;
2832
2833 Metadata *Parent = DL->getRawScope();
2834 CheckDI(Parent && isa<DILocalScope>(Parent),
2835 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
2836
2837 DILocalScope *Scope = DL->getInlinedAtScope();
2838 Check(Scope, "Failed to find DILocalScope", DL);
2839
2840 if (!Seen.insert(Scope).second)
2841 return;
2842
2843 DISubprogram *SP = Scope->getSubprogram();
2844
2845 // Scope and SP could be the same MDNode and we don't want to skip
2846 // validation in that case
2847 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2848 return;
2849
2850 CheckDI(SP->describes(&F),
2851 "!dbg attachment points at wrong subprogram for function", N, &F,
2852 &I, DL, Scope, SP);
2853 };
2854 for (auto &BB : F)
2855 for (auto &I : BB) {
2856 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
2857 // The llvm.loop annotations also contain two DILocations.
2858 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
2859 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
2860 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2861 if (BrokenDebugInfo)
2862 return;
2863 }
2864}
2865
2866// verifyBasicBlock - Verify that a basic block is well formed...
2867//
2868void Verifier::visitBasicBlock(BasicBlock &BB) {
2869 InstsInThisBlock.clear();
2870 ConvergenceVerifyHelper.visit(BB);
2871
2872 // Ensure that basic blocks have terminators!
2873 Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
2874
2875 // Check constraints that this basic block imposes on all of the PHI nodes in
2876 // it.
2877 if (isa<PHINode>(BB.front())) {
2880 llvm::sort(Preds);
2881 for (const PHINode &PN : BB.phis()) {
2882 Check(PN.getNumIncomingValues() == Preds.size(),
2883 "PHINode should have one entry for each predecessor of its "
2884 "parent basic block!",
2885 &PN);
2886
2887 // Get and sort all incoming values in the PHI node...
2888 Values.clear();
2889 Values.reserve(PN.getNumIncomingValues());
2890 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2891 Values.push_back(
2892 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2893 llvm::sort(Values);
2894
2895 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2896 // Check to make sure that if there is more than one entry for a
2897 // particular basic block in this PHI node, that the incoming values are
2898 // all identical.
2899 //
2900 Check(i == 0 || Values[i].first != Values[i - 1].first ||
2901 Values[i].second == Values[i - 1].second,
2902 "PHI node has multiple entries for the same basic block with "
2903 "different incoming values!",
2904 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2905
2906 // Check to make sure that the predecessors and PHI node entries are
2907 // matched up.
2908 Check(Values[i].first == Preds[i],
2909 "PHI node entries do not match predecessors!", &PN,
2910 Values[i].first, Preds[i]);
2911 }
2912 }
2913 }
2914
2915 // Check that all instructions have their parent pointers set up correctly.
2916 for (auto &I : BB)
2917 {
2918 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2919 }
2920}
2921
2922void Verifier::visitTerminator(Instruction &I) {
2923 // Ensure that terminators only exist at the end of the basic block.
2924 Check(&I == I.getParent()->getTerminator(),
2925 "Terminator found in the middle of a basic block!", I.getParent());
2927}
2928
2929void Verifier::visitBranchInst(BranchInst &BI) {
2930 if (BI.isConditional()) {
2932 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2933 }
2934 visitTerminator(BI);
2935}
2936
2937void Verifier::visitReturnInst(ReturnInst &RI) {
2938 Function *F = RI.getParent()->getParent();
2939 unsigned N = RI.getNumOperands();
2940 if (F->getReturnType()->isVoidTy())
2941 Check(N == 0,
2942 "Found return instr that returns non-void in Function of void "
2943 "return type!",
2944 &RI, F->getReturnType());
2945 else
2946 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2947 "Function return type does not match operand "
2948 "type of return inst!",
2949 &RI, F->getReturnType());
2950
2951 // Check to make sure that the return value has necessary properties for
2952 // terminators...
2953 visitTerminator(RI);
2954}
2955
2956void Verifier::visitSwitchInst(SwitchInst &SI) {
2957 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
2958 // Check to make sure that all of the constants in the switch instruction
2959 // have the same type as the switched-on value.
2960 Type *SwitchTy = SI.getCondition()->getType();
2962 for (auto &Case : SI.cases()) {
2963 Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
2964 "Case value is not a constant integer.", &SI);
2965 Check(Case.getCaseValue()->getType() == SwitchTy,
2966 "Switch constants must all be same type as switch value!", &SI);
2967 Check(Constants.insert(Case.getCaseValue()).second,
2968 "Duplicate integer as switch case", &SI, Case.getCaseValue());
2969 }
2970
2971 visitTerminator(SI);
2972}
2973
2974void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2976 "Indirectbr operand must have pointer type!", &BI);
2977 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2979 "Indirectbr destinations must all have pointer type!", &BI);
2980
2981 visitTerminator(BI);
2982}
2983
2984void Verifier::visitCallBrInst(CallBrInst &CBI) {
2985 Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
2986 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2987 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
2988
2989 verifyInlineAsmCall(CBI);
2990 visitTerminator(CBI);
2991}
2992
2993void Verifier::visitSelectInst(SelectInst &SI) {
2994 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2995 SI.getOperand(2)),
2996 "Invalid operands for select instruction!", &SI);
2997
2998 Check(SI.getTrueValue()->getType() == SI.getType(),
2999 "Select values must have same type as select instruction!", &SI);
3000 visitInstruction(SI);
3001}
3002
3003/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3004/// a pass, if any exist, it's an error.
3005///
3006void Verifier::visitUserOp1(Instruction &I) {
3007 Check(false, "User-defined operators should not live outside of a pass!", &I);
3008}
3009
3010void Verifier::visitTruncInst(TruncInst &I) {
3011 // Get the source and destination types
3012 Type *SrcTy = I.getOperand(0)->getType();
3013 Type *DestTy = I.getType();
3014
3015 // Get the size of the types in bits, we'll need this later
3016 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3017 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3018
3019 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
3020 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
3021 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3022 "trunc source and destination must both be a vector or neither", &I);
3023 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
3024
3026}
3027
3028void Verifier::visitZExtInst(ZExtInst &I) {
3029 // Get the source and destination types
3030 Type *SrcTy = I.getOperand(0)->getType();
3031 Type *DestTy = I.getType();
3032
3033 // Get the size of the types in bits, we'll need this later
3034 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
3035 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
3036 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3037 "zext source and destination must both be a vector or neither", &I);
3038 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3039 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3040
3041 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
3042
3044}
3045
3046void Verifier::visitSExtInst(SExtInst &I) {
3047 // Get the source and destination types
3048 Type *SrcTy = I.getOperand(0)->getType();
3049 Type *DestTy = I.getType();
3050
3051 // Get the size of the types in bits, we'll need this later
3052 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3053 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3054
3055 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
3056 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
3057 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3058 "sext source and destination must both be a vector or neither", &I);
3059 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
3060
3062}
3063
3064void Verifier::visitFPTruncInst(FPTruncInst &I) {
3065 // Get the source and destination types
3066 Type *SrcTy = I.getOperand(0)->getType();
3067 Type *DestTy = I.getType();
3068 // Get the size of the types in bits, we'll need this later
3069 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3070 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3071
3072 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
3073 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
3074 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3075 "fptrunc source and destination must both be a vector or neither", &I);
3076 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
3077
3079}
3080
3081void Verifier::visitFPExtInst(FPExtInst &I) {
3082 // Get the source and destination types
3083 Type *SrcTy = I.getOperand(0)->getType();
3084 Type *DestTy = I.getType();
3085
3086 // Get the size of the types in bits, we'll need this later
3087 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3088 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3089
3090 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
3091 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
3092 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3093 "fpext source and destination must both be a vector or neither", &I);
3094 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
3095
3097}
3098
3099void Verifier::visitUIToFPInst(UIToFPInst &I) {
3100 // Get the source and destination types
3101 Type *SrcTy = I.getOperand(0)->getType();
3102 Type *DestTy = I.getType();
3103
3104 bool SrcVec = SrcTy->isVectorTy();
3105 bool DstVec = DestTy->isVectorTy();
3106
3107 Check(SrcVec == DstVec,
3108 "UIToFP source and dest must both be vector or scalar", &I);
3109 Check(SrcTy->isIntOrIntVectorTy(),
3110 "UIToFP source must be integer or integer vector", &I);
3111 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3112 &I);
3113
3114 if (SrcVec && DstVec)
3115 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3116 cast<VectorType>(DestTy)->getElementCount(),
3117 "UIToFP source and dest vector length mismatch", &I);
3118
3120}
3121
3122void Verifier::visitSIToFPInst(SIToFPInst &I) {
3123 // Get the source and destination types
3124 Type *SrcTy = I.getOperand(0)->getType();
3125 Type *DestTy = I.getType();
3126
3127 bool SrcVec = SrcTy->isVectorTy();
3128 bool DstVec = DestTy->isVectorTy();
3129
3130 Check(SrcVec == DstVec,
3131 "SIToFP source and dest must both be vector or scalar", &I);
3132 Check(SrcTy->isIntOrIntVectorTy(),
3133 "SIToFP source must be integer or integer vector", &I);
3134 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3135 &I);
3136
3137 if (SrcVec && DstVec)
3138 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3139 cast<VectorType>(DestTy)->getElementCount(),
3140 "SIToFP source and dest vector length mismatch", &I);
3141
3143}
3144
3145void Verifier::visitFPToUIInst(FPToUIInst &I) {
3146 // Get the source and destination types
3147 Type *SrcTy = I.getOperand(0)->getType();
3148 Type *DestTy = I.getType();
3149
3150 bool SrcVec = SrcTy->isVectorTy();
3151 bool DstVec = DestTy->isVectorTy();
3152
3153 Check(SrcVec == DstVec,
3154 "FPToUI source and dest must both be vector or scalar", &I);
3155 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
3156 Check(DestTy->isIntOrIntVectorTy(),
3157 "FPToUI result must be integer or integer vector", &I);
3158
3159 if (SrcVec && DstVec)
3160 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3161 cast<VectorType>(DestTy)->getElementCount(),
3162 "FPToUI source and dest vector length mismatch", &I);
3163
3165}
3166
3167void Verifier::visitFPToSIInst(FPToSIInst &I) {
3168 // Get the source and destination types
3169 Type *SrcTy = I.getOperand(0)->getType();
3170 Type *DestTy = I.getType();
3171
3172 bool SrcVec = SrcTy->isVectorTy();
3173 bool DstVec = DestTy->isVectorTy();
3174
3175 Check(SrcVec == DstVec,
3176 "FPToSI source and dest must both be vector or scalar", &I);
3177 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
3178 Check(DestTy->isIntOrIntVectorTy(),
3179 "FPToSI result must be integer or integer vector", &I);
3180
3181 if (SrcVec && DstVec)
3182 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3183 cast<VectorType>(DestTy)->getElementCount(),
3184 "FPToSI source and dest vector length mismatch", &I);
3185
3187}
3188
3189void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
3190 // Get the source and destination types
3191 Type *SrcTy = I.getOperand(0)->getType();
3192 Type *DestTy = I.getType();
3193
3194 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3195
3196 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3197 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3198 &I);
3199
3200 if (SrcTy->isVectorTy()) {
3201 auto *VSrc = cast<VectorType>(SrcTy);
3202 auto *VDest = cast<VectorType>(DestTy);
3203 Check(VSrc->getElementCount() == VDest->getElementCount(),
3204 "PtrToInt Vector width mismatch", &I);
3205 }
3206
3208}
3209
3210void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3211 // Get the source and destination types
3212 Type *SrcTy = I.getOperand(0)->getType();
3213 Type *DestTy = I.getType();
3214
3215 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
3216 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3217
3218 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3219 &I);
3220 if (SrcTy->isVectorTy()) {
3221 auto *VSrc = cast<VectorType>(SrcTy);
3222 auto *VDest = cast<VectorType>(DestTy);
3223 Check(VSrc->getElementCount() == VDest->getElementCount(),
3224 "IntToPtr Vector width mismatch", &I);
3225 }
3227}
3228
3229void Verifier::visitBitCastInst(BitCastInst &I) {
3230 Check(
3231 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3232 "Invalid bitcast", &I);
3234}
3235
3236void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3237 Type *SrcTy = I.getOperand(0)->getType();
3238 Type *DestTy = I.getType();
3239
3240 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3241 &I);
3242 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3243 &I);
3245 "AddrSpaceCast must be between different address spaces", &I);
3246 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3247 Check(SrcVTy->getElementCount() ==
3248 cast<VectorType>(DestTy)->getElementCount(),
3249 "AddrSpaceCast vector pointer number of elements mismatch", &I);
3251}
3252
3253/// visitPHINode - Ensure that a PHI node is well formed.
3254///
3255void Verifier::visitPHINode(PHINode &PN) {
3256 // Ensure that the PHI nodes are all grouped together at the top of the block.
3257 // This can be tested by checking whether the instruction before this is
3258 // either nonexistent (because this is begin()) or is a PHI node. If not,
3259 // then there is some other instruction before a PHI.
3260 Check(&PN == &PN.getParent()->front() ||
3261 isa<PHINode>(--BasicBlock::iterator(&PN)),
3262 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3263
3264 // Check that a PHI doesn't yield a Token.
3265 Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3266
3267 // Check that all of the values of the PHI node have the same type as the
3268 // result, and that the incoming blocks are really basic blocks.
3269 for (Value *IncValue : PN.incoming_values()) {
3270 Check(PN.getType() == IncValue->getType(),
3271 "PHI node operands are not the same type as the result!", &PN);
3272 }
3273
3274 // All other PHI node constraints are checked in the visitBasicBlock method.
3275
3276 visitInstruction(PN);
3277}
3278
3279void Verifier::visitCallBase(CallBase &Call) {
3280 Check(Call.getCalledOperand()->getType()->isPointerTy(),
3281 "Called function must be a pointer!", Call);
3282 FunctionType *FTy = Call.getFunctionType();
3283
3284 // Verify that the correct number of arguments are being passed
3285 if (FTy->isVarArg())
3286 Check(Call.arg_size() >= FTy->getNumParams(),
3287 "Called function requires more parameters than were provided!", Call);
3288 else
3289 Check(Call.arg_size() == FTy->getNumParams(),
3290 "Incorrect number of arguments passed to called function!", Call);
3291
3292 // Verify that all arguments to the call match the function type.
3293 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3294 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3295 "Call parameter type does not match function signature!",
3296 Call.getArgOperand(i), FTy->getParamType(i), Call);
3297
3298 AttributeList Attrs = Call.getAttributes();
3299
3300 Check(verifyAttributeCount(Attrs, Call.arg_size()),
3301 "Attribute after last parameter!", Call);
3302
3303 Function *Callee =
3304 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3305 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3306 if (IsIntrinsic)
3307 Check(Callee->getValueType() == FTy,
3308 "Intrinsic called with incompatible signature", Call);
3309
3310 // Disallow calls to functions with the amdgpu_cs_chain[_preserve] calling
3311 // convention.
3312 auto CC = Call.getCallingConv();
3315 "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
3316 "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
3317 Call);
3318
3319 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
3320 if (!Ty->isSized())
3321 return;
3322 Align ABIAlign = DL.getABITypeAlign(Ty);
3323 Align MaxAlign(ParamMaxAlignment);
3324 Check(ABIAlign <= MaxAlign,
3325 "Incorrect alignment of " + Message + " to called function!", Call);
3326 };
3327
3328 if (!IsIntrinsic) {
3329 VerifyTypeAlign(FTy->getReturnType(), "return type");
3330 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3331 Type *Ty = FTy->getParamType(i);
3332 VerifyTypeAlign(Ty, "argument passed");
3333 }
3334 }
3335
3336 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3337 // Don't allow speculatable on call sites, unless the underlying function
3338 // declaration is also speculatable.
3339 Check(Callee && Callee->isSpeculatable(),
3340 "speculatable attribute may not apply to call sites", Call);
3341 }
3342
3343 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3344 Check(Call.getCalledFunction()->getIntrinsicID() ==
3345 Intrinsic::call_preallocated_arg,
3346 "preallocated as a call site attribute can only be on "
3347 "llvm.call.preallocated.arg");
3348 }
3349
3350 // Verify call attributes.
3351 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
3352
3353 // Conservatively check the inalloca argument.
3354 // We have a bug if we can find that there is an underlying alloca without
3355 // inalloca.
3356 if (Call.hasInAllocaArgument()) {
3357 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3358 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3359 Check(AI->isUsedWithInAlloca(),
3360 "inalloca argument for call has mismatched alloca", AI, Call);
3361 }
3362
3363 // For each argument of the callsite, if it has the swifterror argument,
3364 // make sure the underlying alloca/parameter it comes from has a swifterror as
3365 // well.
3366 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3367 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3368 Value *SwiftErrorArg = Call.getArgOperand(i);
3369 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3370 Check(AI->isSwiftError(),
3371 "swifterror argument for call has mismatched alloca", AI, Call);
3372 continue;
3373 }
3374 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3375 Check(ArgI, "swifterror argument should come from an alloca or parameter",
3376 SwiftErrorArg, Call);
3377 Check(ArgI->hasSwiftErrorAttr(),
3378 "swifterror argument for call has mismatched parameter", ArgI,
3379 Call);
3380 }
3381
3382 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3383 // Don't allow immarg on call sites, unless the underlying declaration
3384 // also has the matching immarg.
3385 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
3386 "immarg may not apply only to call sites", Call.getArgOperand(i),
3387 Call);
3388 }
3389
3390 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3391 Value *ArgVal = Call.getArgOperand(i);
3392 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3393 "immarg operand has non-immediate parameter", ArgVal, Call);
3394 }
3395
3396 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3397 Value *ArgVal = Call.getArgOperand(i);
3398 bool hasOB =
3399 Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3400 bool isMustTail = Call.isMustTailCall();
3401 Check(hasOB != isMustTail,
3402 "preallocated operand either requires a preallocated bundle or "
3403 "the call to be musttail (but not both)",
3404 ArgVal, Call);
3405 }
3406 }
3407
3408 if (FTy->isVarArg()) {
3409 // FIXME? is 'nest' even legal here?
3410 bool SawNest = false;
3411 bool SawReturned = false;
3412
3413 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3414 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
3415 SawNest = true;
3416 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
3417 SawReturned = true;
3418 }
3419
3420 // Check attributes on the varargs part.
3421 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3422 Type *Ty = Call.getArgOperand(Idx)->getType();
3423 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
3424 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3425
3426 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
3427 Check(!SawNest, "More than one parameter has attribute nest!", Call);
3428 SawNest = true;
3429 }
3430
3431 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
3432 Check(!SawReturned, "More than one parameter has attribute returned!",
3433 Call);
3434 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
3435 "Incompatible argument and return types for 'returned' "
3436 "attribute",
3437 Call);
3438 SawReturned = true;
3439 }
3440
3441 // Statepoint intrinsic is vararg but the wrapped function may be not.
3442 // Allow sret here and check the wrapped function in verifyStatepoint.
3443 if (!Call.getCalledFunction() ||
3444 Call.getCalledFunction()->getIntrinsicID() !=
3445 Intrinsic::experimental_gc_statepoint)
3446 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
3447 "Attribute 'sret' cannot be used for vararg call arguments!",
3448 Call);
3449
3450 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
3451 Check(Idx == Call.arg_size() - 1,
3452 "inalloca isn't on the last argument!", Call);
3453 }
3454 }
3455
3456 // Verify that there's no metadata unless it's a direct call to an intrinsic.
3457 if (!IsIntrinsic) {
3458 for (Type *ParamTy : FTy->params()) {
3459 Check(!ParamTy->isMetadataTy(),
3460 "Function has metadata parameter but isn't an intrinsic", Call);
3461 Check(!ParamTy->isTokenTy(),
3462 "Function has token parameter but isn't an intrinsic", Call);
3463 }
3464 }
3465
3466 // Verify that indirect calls don't return tokens.
3467 if (!Call.getCalledFunction()) {
3468 Check(!FTy->getReturnType()->isTokenTy(),
3469 "Return type cannot be token for indirect call!");
3470 Check(!FTy->getReturnType()->isX86_AMXTy(),
3471 "Return type cannot be x86_amx for indirect call!");
3472 }
3473
3474 if (Function *F = Call.getCalledFunction())
3475 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3476 visitIntrinsicCall(ID, Call);
3477
3478 // Verify that a callsite has at most one "deopt", at most one "funclet", at
3479 // most one "gc-transition", at most one "cfguardtarget", at most one
3480 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
3481 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3482 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3483 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3484 FoundPtrauthBundle = false, FoundKCFIBundle = false,
3485 FoundAttachedCallBundle = false;
3486 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
3487 OperandBundleUse BU = Call.getOperandBundleAt(i);
3488 uint32_t Tag = BU.getTagID();
3489 if (Tag == LLVMContext::OB_deopt) {
3490 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
3491 FoundDeoptBundle = true;
3492 } else if (Tag == LLVMContext::OB_gc_transition) {
3493 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
3494 Call);
3495 FoundGCTransitionBundle = true;
3496 } else if (Tag == LLVMContext::OB_funclet) {
3497 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
3498 FoundFuncletBundle = true;
3499 Check(BU.Inputs.size() == 1,
3500 "Expected exactly one funclet bundle operand", Call);
3501 Check(isa<FuncletPadInst>(BU.Inputs.front()),
3502 "Funclet bundle operands should correspond to a FuncletPadInst",
3503 Call);
3504 } else if (Tag == LLVMContext::OB_cfguardtarget) {
3505 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
3506 Call);
3507 FoundCFGuardTargetBundle = true;
3508 Check(BU.Inputs.size() == 1,
3509 "Expected exactly one cfguardtarget bundle operand", Call);
3510 } else if (Tag == LLVMContext::OB_ptrauth) {
3511 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
3512 FoundPtrauthBundle = true;
3513 Check(BU.Inputs.size() == 2,
3514 "Expected exactly two ptrauth bundle operands", Call);
3515 Check(isa<ConstantInt>(BU.Inputs[0]) &&
3516 BU.Inputs[0]->getType()->isIntegerTy(32),
3517 "Ptrauth bundle key operand must be an i32 constant", Call);
3518 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
3519 "Ptrauth bundle discriminator operand must be an i64", Call);
3520 } else if (Tag == LLVMContext::OB_kcfi) {
3521 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
3522 FoundKCFIBundle = true;
3523 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
3524 Call);
3525 Check(isa<ConstantInt>(BU.Inputs[0]) &&
3526 BU.Inputs[0]->getType()->isIntegerTy(32),
3527 "Kcfi bundle operand must be an i32 constant", Call);
3528 } else if (Tag == LLVMContext::OB_preallocated) {
3529 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
3530 Call);
3531 FoundPreallocatedBundle = true;
3532 Check(BU.Inputs.size() == 1,
3533 "Expected exactly one preallocated bundle operand", Call);
3534 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3535 Check(Input &&
3536 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3537 "\"preallocated\" argument must be a token from "
3538 "llvm.call.preallocated.setup",
3539 Call);
3540 } else if (Tag == LLVMContext::OB_gc_live) {
3541 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
3542 FoundGCLiveBundle = true;
3544 Check(!FoundAttachedCallBundle,
3545 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3546 FoundAttachedCallBundle = true;
3547 verifyAttachedCallBundle(Call, BU);
3548 }
3549 }
3550
3551 // Verify that callee and callsite agree on whether to use pointer auth.
3552 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
3553 "Direct call cannot have a ptrauth bundle", Call);
3554
3555 // Verify that each inlinable callsite of a debug-info-bearing function in a
3556 // debug-info-bearing function has a debug location attached to it. Failure to
3557 // do so causes assertion failures when the inliner sets up inline scope info
3558 // (Interposable functions are not inlinable, neither are functions without
3559 // definitions.)
3560 if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3561 !Call.getCalledFunction()->isInterposable() &&
3562 !Call.getCalledFunction()->isDeclaration() &&
3563 Call.getCalledFunction()->getSubprogram())
3564 CheckDI(Call.getDebugLoc(),
3565 "inlinable function call in a function with "
3566 "debug info must have a !dbg location",
3567 Call);
3568
3569 if (Call.isInlineAsm())
3570 verifyInlineAsmCall(Call);
3571
3572 ConvergenceVerifyHelper.visit(Call);
3573
3574 visitInstruction(Call);
3575}
3576
3577void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3578 StringRef Context) {
3579 Check(!Attrs.contains(Attribute::InAlloca),
3580 Twine("inalloca attribute not allowed in ") + Context);
3581 Check(!Attrs.contains(Attribute::InReg),
3582 Twine("inreg attribute not allowed in ") + Context);
3583 Check(!Attrs.contains(Attribute::SwiftError),
3584 Twine("swifterror attribute not allowed in ") + Context);
3585 Check(!Attrs.contains(Attribute::Preallocated),
3586 Twine("preallocated attribute not allowed in ") + Context);
3587 Check(!Attrs.contains(Attribute::ByRef),
3588 Twine("byref attribute not allowed in ") + Context);
3589}
3590
3591/// Two types are "congruent" if they are identical, or if they are both pointer
3592/// types with different pointee types and the same address space.
3593static bool isTypeCongruent(Type *L, Type *R) {
3594 if (L == R)
3595 return true;
3596 PointerType *PL = dyn_cast<PointerType>(L);
3597 PointerType *PR = dyn_cast<PointerType>(R);
3598 if (!PL || !PR)
3599 return false;
3600 return PL->getAddressSpace() == PR->getAddressSpace();
3601}
3602
3604 static const Attribute::AttrKind ABIAttrs[] = {
3605 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3606 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3607 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3608 Attribute::ByRef};
3609 AttrBuilder Copy(C);
3610 for (auto AK : ABIAttrs) {
3611 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3612 if (Attr.isValid())
3613 Copy.addAttribute(Attr);
3614 }
3615
3616 // `align` is ABI-affecting only in combination with `byval` or `byref`.
3617 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3618 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3619 Attrs.hasParamAttr(I, Attribute::ByRef)))
3620 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
3621 return Copy;
3622}
3623
3624void Verifier::verifyMustTailCall(CallInst &CI) {
3625 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
3626
3627 Function *F = CI.getParent()->getParent();
3628 FunctionType *CallerTy = F->getFunctionType();
3629 FunctionType *CalleeTy = CI.getFunctionType();
3630 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3631 "cannot guarantee tail call due to mismatched varargs", &CI);
3632 Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
3633 "cannot guarantee tail call due to mismatched return types", &CI);
3634
3635 // - The calling conventions of the caller and callee must match.
3636 Check(F->getCallingConv() == CI.getCallingConv(),
3637 "cannot guarantee tail call due to mismatched calling conv", &CI);
3638
3639 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3640 // or a pointer bitcast followed by a ret instruction.
3641 // - The ret instruction must return the (possibly bitcasted) value
3642 // produced by the call or void.
3643 Value *RetVal = &CI;
3644 Instruction *Next = CI.getNextNode();
3645
3646 // Handle the optional bitcast.
3647 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3648 Check(BI->getOperand(0) == RetVal,
3649 "bitcast following musttail call must use the call", BI);
3650 RetVal = BI;
3651 Next = BI->getNextNode();
3652 }
3653
3654 // Check the return.
3655 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
3656 Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
3657 Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3658 isa<UndefValue>(Ret->getReturnValue()),
3659 "musttail call result must be returned", Ret);
3660
3661 AttributeList CallerAttrs = F->getAttributes();
3662 AttributeList CalleeAttrs = CI.getAttributes();
3665 StringRef CCName =
3666 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3667
3668 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3669 // are allowed in swifttailcc call
3670 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3671 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3672 SmallString<32> Context{CCName, StringRef(" musttail caller")};
3673 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3674 }
3675 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
3676 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3677 SmallString<32> Context{CCName, StringRef(" musttail callee")};
3678 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3679 }
3680 // - Varargs functions are not allowed
3681 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3682 " tail call for varargs function");
3683 return;
3684 }
3685
3686 // - The caller and callee prototypes must match. Pointer types of
3687 // parameters or return types may differ in pointee type, but not
3688 // address space.
3689 if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3690 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3691 "cannot guarantee tail call due to mismatched parameter counts", &CI);
3692 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3693 Check(
3694 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3695 "cannot guarantee tail call due to mismatched parameter types", &CI);
3696 }
3697 }
3698
3699 // - All ABI-impacting function attributes, such as sret, byval, inreg,
3700 // returned, preallocated, and inalloca, must match.
3701 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3702 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3703 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3704 Check(CallerABIAttrs == CalleeABIAttrs,
3705 "cannot guarantee tail call due to mismatched ABI impacting "
3706 "function attributes",
3707 &CI, CI.getOperand(I));
3708 }
3709}
3710
3711void Verifier::visitCallInst(CallInst &CI) {
3712 visitCallBase(CI);
3713
3714 if (CI.isMustTailCall())
3715 verifyMustTailCall(CI);
3716}
3717
3718void Verifier::visitInvokeInst(InvokeInst &II) {
3719 visitCallBase(II);
3720
3721 // Verify that the first non-PHI instruction of the unwind destination is an
3722 // exception handling instruction.
3723 Check(
3724 II.getUnwindDest()->isEHPad(),
3725 "The unwind destination does not have an exception handling instruction!",
3726 &II);
3727
3728 visitTerminator(II);
3729}
3730
3731/// visitUnaryOperator - Check the argument to the unary operator.
3732///
3733void Verifier::visitUnaryOperator(UnaryOperator &U) {
3734 Check(U.getType() == U.getOperand(0)->getType(),
3735 "Unary operators must have same type for"
3736 "operands and result!",
3737 &U);
3738
3739 switch (U.getOpcode()) {
3740 // Check that floating-point arithmetic operators are only used with
3741 // floating-point operands.
3742 case Instruction::FNeg:
3743 Check(U.getType()->isFPOrFPVectorTy(),
3744 "FNeg operator only works with float types!", &U);
3745 break;
3746 default:
3747 llvm_unreachable("Unknown UnaryOperator opcode!");
3748 }
3749
3751}
3752
3753/// visitBinaryOperator - Check that both arguments to the binary operator are
3754/// of the same type!
3755///
3756void Verifier::visitBinaryOperator(BinaryOperator &B) {
3757 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
3758 "Both operands to a binary operator are not of the same type!", &B);
3759
3760 switch (B.getOpcode()) {
3761 // Check that integer arithmetic operators are only used with
3762 // integral operands.
3763 case Instruction::Add:
3764 case Instruction::Sub:
3765 case Instruction::Mul:
3766 case Instruction::SDiv:
3767 case Instruction::UDiv:
3768 case Instruction::SRem:
3769 case Instruction::URem:
3770 Check(B.getType()->isIntOrIntVectorTy(),
3771 "Integer arithmetic operators only work with integral types!", &B);
3772 Check(B.getType() == B.getOperand(0)->getType(),
3773 "Integer arithmetic operators must have same type "
3774 "for operands and result!",
3775 &B);
3776 break;
3777 // Check that floating-point arithmetic operators are only used with
3778 // floating-point operands.
3779 case Instruction::FAdd:
3780 case Instruction::FSub:
3781 case Instruction::FMul:
3782 case Instruction::FDiv:
3783 case Instruction::FRem:
3784 Check(B.getType()->isFPOrFPVectorTy(),
3785 "Floating-point arithmetic operators only work with "
3786 "floating-point types!",
3787 &B);
3788 Check(B.getType() == B.getOperand(0)->getType(),
3789 "Floating-point arithmetic operators must have same type "
3790 "for operands and result!",
3791 &B);
3792 break;
3793 // Check that logical operators are only used with integral operands.
3794 case Instruction::And:
3795 case Instruction::Or:
3796 case Instruction::Xor:
3797 Check(B.getType()->isIntOrIntVectorTy(),
3798 "Logical operators only work with integral types!", &B);
3799 Check(B.getType() == B.getOperand(0)->getType(),
3800 "Logical operators must have same type for operands and result!", &B);
3801 break;
3802 case Instruction::Shl:
3803 case Instruction::LShr:
3804 case Instruction::AShr:
3805 Check(B.getType()->isIntOrIntVectorTy(),
3806 "Shifts only work with integral types!", &B);
3807 Check(B.getType() == B.getOperand(0)->getType(),
3808 "Shift return type must be same as operands!", &B);
3809 break;
3810 default:
3811 llvm_unreachable("Unknown BinaryOperator opcode!");
3812 }
3813
3815}
3816
3817void Verifier::visitICmpInst(ICmpInst &IC) {
3818 // Check that the operands are the same type
3819 Type *Op0Ty = IC.getOperand(0)->getType();
3820 Type *Op1Ty = IC.getOperand(1)->getType();
3821 Check(Op0Ty == Op1Ty,
3822 "Both operands to ICmp instruction are not of the same type!", &IC);
3823 // Check that the operands are the right type
3824 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
3825 "Invalid operand types for ICmp instruction", &IC);
3826 // Check that the predicate is valid.
3827 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
3828
3829 visitInstruction(IC);
3830}
3831
3832void Verifier::visitFCmpInst(FCmpInst &FC) {
3833 // Check that the operands are the same type
3834 Type *Op0Ty = FC.getOperand(0)->getType();
3835 Type *Op1Ty = FC.getOperand(1)->getType();
3836 Check(Op0Ty == Op1Ty,
3837 "Both operands to FCmp instruction are not of the same type!", &FC);
3838 // Check that the operands are the right type
3839 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
3840 &FC);
3841 // Check that the predicate is valid.
3842 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
3843
3844 visitInstruction(FC);
3845}
3846
3847void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3849 "Invalid extractelement operands!", &EI);
3850 visitInstruction(EI);
3851}
3852
3853void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3854 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
3855 IE.getOperand(2)),
3856 "Invalid insertelement operands!", &IE);
3857 visitInstruction(IE);
3858}
3859
3860void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3862 SV.getShuffleMask()),
3863 "Invalid shufflevector operands!", &SV);
3864 visitInstruction(SV);
3865}
3866
3867void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3868 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3869
3870 Check(isa<PointerType>(TargetTy),
3871 "GEP base pointer is not a vector or a vector of pointers", &GEP);
3872 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
3873
3874 if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
3875 SmallPtrSet<Type *, 4> Visited;
3876 Check(!STy->containsScalableVectorType(&Visited),
3877 "getelementptr cannot target structure that contains scalable vector"
3878 "type",
3879 &GEP);
3880 }
3881
3882 SmallVector<Value *, 16> Idxs(GEP.indices());
3883 Check(
3884 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
3885 "GEP indexes must be integers", &GEP);
3886 Type *ElTy =
3887 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
3888 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
3889
3890 Check(GEP.getType()->isPtrOrPtrVectorTy() &&
3891 GEP.getResultElementType() == ElTy,
3892 "GEP is not of right type for indices!", &GEP, ElTy);
3893
3894 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
3895 // Additional checks for vector GEPs.
3896 ElementCount GEPWidth = GEPVTy->getElementCount();
3897 if (GEP.getPointerOperandType()->isVectorTy())
3898 Check(
3899 GEPWidth ==
3900 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
3901 "Vector GEP result width doesn't match operand's", &GEP);
3902 for (Value *Idx : Idxs) {
3903 Type *IndexTy = Idx->getType();
3904 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3905 ElementCount IndexWidth = IndexVTy->getElementCount();
3906 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
3907 }
3908 Check(IndexTy->isIntOrIntVectorTy(),
3909 "All GEP indices should be of integer type");
3910 }
3911 }
3912
3913 if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3914 Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
3915 "GEP address space doesn't match type", &GEP);
3916 }
3917
3919}
3920
3921static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3922 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3923}
3924
3925/// Verify !range and !absolute_symbol metadata. These have the same
3926/// restrictions, except !absolute_symbol allows the full set.
3927void Verifier::verifyRangeMetadata(const Value &I, const MDNode *Range,
3928 Type *Ty, bool IsAbsoluteSymbol) {
3929 unsigned NumOperands = Range->getNumOperands();
3930 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
3931 unsigned NumRanges = NumOperands / 2;
3932 Check(NumRanges >= 1, "It should have at least one range!", Range);
3933
3934 ConstantRange LastRange(1, true); // Dummy initial value
3935 for (unsigned i = 0; i < NumRanges; ++i) {
3936 ConstantInt *Low =
3937 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3938 Check(Low, "The lower limit must be an integer!", Low);
3939 ConstantInt *High =
3940 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3941 Check(High, "The upper limit must be an integer!", High);
3942 Check(High->getType() == Low->getType() &&
3943 High->getType() == Ty->getScalarType(),
3944 "Range types must match instruction type!", &I);
3945
3946 APInt HighV = High->getValue();
3947 APInt LowV = Low->getValue();
3948
3949 // ConstantRange asserts if the ranges are the same except for the min/max
3950 // value. Leave the cases it tolerates for the empty range error below.
3951 Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
3952 "The upper and lower limits cannot be the same value", &I);
3953
3954 ConstantRange CurRange(LowV, HighV);
3955 Check(!CurRange.isEmptySet() && (IsAbsoluteSymbol || !CurRange.isFullSet()),
3956 "Range must not be empty!", Range);
3957 if (i != 0) {
3958 Check(CurRange.intersectWith(LastRange).isEmptySet(),
3959 "Intervals are overlapping", Range);
3960 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3961 Range);
3962 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3963 Range);
3964 }
3965 LastRange = ConstantRange(LowV, HighV);
3966 }
3967 if (NumRanges > 2) {
3968 APInt FirstLow =
3969 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3970 APInt FirstHigh =
3971 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3972 ConstantRange FirstRange(FirstLow, FirstHigh);
3973 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
3974 "Intervals are overlapping", Range);
3975 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3976 Range);
3977 }
3978}
3979
3980void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3981 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
3982 "precondition violation");
3983 verifyRangeMetadata(I, Range, Ty, false);
3984}
3985
3986void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3987 unsigned Size = DL.getTypeSizeInBits(Ty);
3988 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3989 Check(!(Size & (Size - 1)),
3990 "atomic memory access' operand must have a power-of-two size", Ty, I);
3991}
3992
3993void Verifier::visitLoadInst(LoadInst &LI) {
3994 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
3995 Check(PTy, "Load operand must be a pointer.", &LI);
3996 Type *ElTy = LI.getType();
3997 if (MaybeAlign A = LI.getAlign()) {
3998 Check(A->value() <= Value::MaximumAlignment,
3999 "huge alignment values are unsupported", &LI);
4000 }
4001 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
4002 if (LI.isAtomic()) {
4005 "Load cannot have Release ordering", &LI);
4006 Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
4007 "atomic load operand must have integer, pointer, or floating point "
4008 "type!",
4009 ElTy, &LI);
4010 checkAtomicMemAccessSize(ElTy, &LI);
4011 } else {
4013 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4014 }
4015
4016 visitInstruction(LI);
4017}
4018
4019void Verifier::visitStoreInst(StoreInst &SI) {
4020 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
4021 Check(PTy, "Store operand must be a pointer.", &SI);
4022 Type *ElTy = SI.getOperand(0)->getType();
4023 if (MaybeAlign A = SI.getAlign()) {
4024 Check(A->value() <= Value::MaximumAlignment,
4025 "huge alignment values are unsupported", &SI);
4026 }
4027 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
4028 if (SI.isAtomic()) {
4029 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
4030 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4031 "Store cannot have Acquire ordering", &SI);
4032 Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
4033 "atomic store operand must have integer, pointer, or floating point "
4034 "type!",
4035 ElTy, &SI);
4036 checkAtomicMemAccessSize(ElTy, &SI);
4037 } else {
4038 Check(SI.getSyncScopeID() == SyncScope::System,
4039 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4040 }
4041 visitInstruction(SI);
4042}
4043
4044/// Check that SwiftErrorVal is used as a swifterror argument in CS.
4045void Verifier::verifySwiftErrorCall(CallBase &Call,
4046 const Value *SwiftErrorVal) {
4047 for (const auto &I : llvm::enumerate(Call.args())) {
4048 if (I.value() == SwiftErrorVal) {
4049 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
4050 "swifterror value when used in a callsite should be marked "
4051 "with swifterror attribute",
4052 SwiftErrorVal, Call);
4053 }
4054 }
4055}
4056
4057void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
4058 // Check that swifterror value is only used by loads, stores, or as
4059 // a swifterror argument.
4060 for (const User *U : SwiftErrorVal->users()) {
4061 Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
4062 isa<InvokeInst>(U),
4063 "swifterror value can only be loaded and stored from, or "
4064 "as a swifterror argument!",
4065 SwiftErrorVal, U);
4066 // If it is used by a store, check it is the second operand.
4067 if (auto StoreI = dyn_cast<StoreInst>(U))
4068 Check(StoreI->getOperand(1) == SwiftErrorVal,
4069 "swifterror value should be the second operand when used "
4070 "by stores",
4071 SwiftErrorVal, U);
4072 if (auto *Call = dyn_cast<CallBase>(U))
4073 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
4074 }
4075}
4076
4077void Verifier::visitAllocaInst(AllocaInst &AI) {
4078 SmallPtrSet<Type*, 4> Visited;
4079 Check(AI.getAllocatedType()->isSized(&Visited),
4080 "Cannot allocate unsized type", &AI);
4082 "Alloca array size must have integer type", &AI);
4083 if (MaybeAlign A = AI.getAlign()) {
4084 Check(A->value() <= Value::MaximumAlignment,
4085 "huge alignment values are unsupported", &AI);
4086 }
4087
4088 if (AI.isSwiftError()) {
4090 "swifterror alloca must have pointer type", &AI);
4092 "swifterror alloca must not be array allocation", &AI);
4093 verifySwiftErrorValue(&AI);
4094 }
4095
4096 visitInstruction(AI);
4097}
4098
4099void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4100 Type *ElTy = CXI.getOperand(1)->getType();
4101 Check(ElTy->isIntOrPtrTy(),
4102 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4103 checkAtomicMemAccessSize(ElTy, &CXI);
4104 visitInstruction(CXI);
4105}
4106
4107void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4109 "atomicrmw instructions cannot be unordered.", &RMWI);
4110 auto Op = RMWI.getOperation();
4111 Type *ElTy = RMWI.getOperand(1)->getType();
4112 if (Op == AtomicRMWInst::Xchg) {
4113 Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
4114 ElTy->isPointerTy(),
4115 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4116 " operand must have integer or floating point type!",
4117 &RMWI, ElTy);
4118 } else if (AtomicRMWInst::isFPOperation(Op)) {
4119 Check(ElTy->isFloatingPointTy(),
4120 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4121 " operand must have floating point type!",
4122 &RMWI, ElTy);
4123 } else {
4124 Check(ElTy->isIntegerTy(),
4125 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4126 " operand must have integer type!",
4127 &RMWI, ElTy);
4128 }
4129 checkAtomicMemAccessSize(ElTy, &RMWI);
4131 "Invalid binary operation!", &RMWI);
4132 visitInstruction(RMWI);
4133}
4134
4135void Verifier::visitFenceInst(FenceInst &FI) {
4136 const AtomicOrdering Ordering = FI.getOrdering();
4137 Check(Ordering == AtomicOrdering::Acquire ||
4138 Ordering == AtomicOrdering::Release ||
4139 Ordering == AtomicOrdering::AcquireRelease ||
4141 "fence instructions may only have acquire, release, acq_rel, or "
4142 "seq_cst ordering.",
4143 &FI);
4144 visitInstruction(FI);
4145}
4146
4147void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4149 EVI.getIndices()) == EVI.getType(),
4150 "Invalid ExtractValueInst operands!", &EVI);
4151
4152 visitInstruction(EVI);
4153}
4154
4155void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4157 IVI.getIndices()) ==
4158 IVI.getOperand(1)->getType(),
4159 "Invalid InsertValueInst operands!", &IVI);
4160
4161 visitInstruction(IVI);
4162}
4163
4164static Value *getParentPad(Value *EHPad) {
4165 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4166 return FPI->getParentPad();
4167
4168 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4169}
4170
4171void Verifier::visitEHPadPredecessors(Instruction &I) {
4172 assert(I.isEHPad());
4173
4174 BasicBlock *BB = I.getParent();
4175 Function *F = BB->getParent();
4176
4177 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
4178
4179 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
4180 // The landingpad instruction defines its parent as a landing pad block. The
4181 // landing pad block may be branched to only by the unwind edge of an
4182 // invoke.
4183 for (BasicBlock *PredBB : predecessors(BB)) {
4184 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4185 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4186 "Block containing LandingPadInst must be jumped to "
4187 "only by the unwind edge of an invoke.",
4188 LPI);
4189 }
4190 return;
4191 }
4192 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
4193 if (!pred_empty(BB))
4194 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4195 "Block containg CatchPadInst must be jumped to "
4196 "only by its catchswitch.",
4197 CPI);
4198 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4199 "Catchswitch cannot unwind to one of its catchpads",
4200 CPI->getCatchSwitch(), CPI);
4201 return;
4202 }
4203
4204 // Verify that each pred has a legal terminator with a legal to/from EH
4205 // pad relationship.
4206 Instruction *ToPad = &I;
4207 Value *ToPadParent = getParentPad(ToPad);
4208 for (BasicBlock *PredBB : predecessors(BB)) {
4209 Instruction *TI = PredBB->getTerminator();
4210 Value *FromPad;
4211 if (auto *II = dyn_cast<InvokeInst>(TI)) {
4212 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4213 "EH pad must be jumped to via an unwind edge", ToPad, II);
4214 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
4215 FromPad = Bundle->Inputs[0];
4216 else
4217 FromPad = ConstantTokenNone::get(II->getContext());
4218 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4219 FromPad = CRI->getOperand(0);
4220 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
4221 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4222 FromPad = CSI;
4223 } else {
4224 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
4225 }
4226
4227 // The edge may exit from zero or more nested pads.
4229 for (;; FromPad = getParentPad(FromPad)) {
4230 Check(FromPad != ToPad,
4231 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4232 if (FromPad == ToPadParent) {
4233 // This is a legal unwind edge.
4234 break;
4235 }
4236 Check(!isa<ConstantTokenNone>(FromPad),
4237 "A single unwind edge may only enter one EH pad", TI);
4238 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
4239 FromPad);
4240
4241 // This will be diagnosed on the corresponding instruction already. We
4242 // need the extra check here to make sure getParentPad() works.
4243 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4244 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4245 }
4246 }
4247}
4248
4249void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4250 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4251 // isn't a cleanup.
4252 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
4253 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4254
4255 visitEHPadPredecessors(LPI);
4256
4257 if (!LandingPadResultTy)
4258 LandingPadResultTy = LPI.getType();
4259 else
4260 Check(LandingPadResultTy == LPI.getType(),
4261 "The landingpad instruction should have a consistent result type "
4262 "inside a function.",
4263 &LPI);
4264
4265 Function *F = LPI.getParent()->getParent();
4266 Check(F->hasPersonalityFn(),
4267 "LandingPadInst needs to be in a function with a personality.", &LPI);
4268
4269 // The landingpad instruction must be the first non-PHI instruction in the
4270 // block.
4271 Check(LPI.getParent()->getLandingPadInst() == &LPI,
4272 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4273
4274 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
4275 Constant *Clause = LPI.getClause(i);
4276 if (LPI.isCatch(i)) {
4277 Check(isa<PointerType>(Clause->getType()),
4278 "Catch operand does not have pointer type!", &LPI);
4279 } else {
4280 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
4281 Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
4282 "Filter operand is not an array of constants!", &LPI);
4283 }
4284 }
4285
4286 visitInstruction(LPI);
4287}
4288
4289void Verifier::visitResumeInst(ResumeInst &RI) {
4291 "ResumeInst needs to be in a function with a personality.", &RI);
4292
4293 if (!LandingPadResultTy)
4294 LandingPadResultTy = RI.getValue()->getType();
4295 else
4296 Check(LandingPadResultTy == RI.getValue()->getType(),
4297 "The resume instruction should have a consistent result type "
4298 "inside a function.",
4299 &RI);
4300
4301 visitTerminator(RI);
4302}
4303
4304void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4305 BasicBlock *BB = CPI.getParent();
4306
4307 Function *F = BB->getParent();
4308 Check(F->hasPersonalityFn(),
4309 "CatchPadInst needs to be in a function with a personality.", &CPI);
4310
4311 Check(isa<CatchSwitchInst>(CPI.getParentPad()),
4312 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4313 CPI.getParentPad());
4314
4315 // The catchpad instruction must be the first non-PHI instruction in the
4316 // block.
4317 Check(BB->getFirstNonPHI() == &CPI,
4318 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4319
4320 visitEHPadPredecessors(CPI);
4322}
4323
4324void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4325 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
4326 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4327 CatchReturn.getOperand(0));
4328
4329 visitTerminator(CatchReturn);
4330}
4331
4332void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4333 BasicBlock *BB = CPI.getParent();
4334
4335 Function *F = BB->getParent();
4336 Check(F->hasPersonalityFn(),
4337 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4338
4339 // The cleanuppad instruction must be the first non-PHI instruction in the
4340 // block.
4341 Check(BB->getFirstNonPHI() == &CPI,
4342 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4343
4344 auto *ParentPad = CPI.getParentPad();
4345 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4346 "CleanupPadInst has an invalid parent.", &CPI);
4347
4348 visitEHPadPredecessors(CPI);
4350}
4351
4352void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4353 User *FirstUser = nullptr;
4354 Value *FirstUnwindPad = nullptr;
4355 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4357
4358 while (!Worklist.empty()) {
4359 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4360 Check(Seen.insert(CurrentPad).second,
4361 "FuncletPadInst must not be nested within itself", CurrentPad);
4362 Value *UnresolvedAncestorPad = nullptr;
4363 for (User *U : CurrentPad->users()) {
4364 BasicBlock *UnwindDest;
4365 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4366 UnwindDest = CRI->getUnwindDest();
4367 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4368 // We allow catchswitch unwind to caller to nest
4369 // within an outer pad that unwinds somewhere else,
4370 // because catchswitch doesn't have a nounwind variant.
4371 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4372 if (CSI->unwindsToCaller())
4373 continue;
4374 UnwindDest = CSI->getUnwindDest();
4375 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
4376 UnwindDest = II->getUnwindDest();
4377 } else if (isa<CallInst>(U)) {
4378 // Calls which don't unwind may be found inside funclet
4379 // pads that unwind somewhere else. We don't *require*
4380 // such calls to be annotated nounwind.
4381 continue;
4382 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4383 // The unwind dest for a cleanup can only be found by
4384 // recursive search. Add it to the worklist, and we'll
4385 // search for its first use that determines where it unwinds.
4386 Worklist.push_back(CPI);
4387 continue;
4388 } else {
4389 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
4390 continue;
4391 }
4392
4393 Value *UnwindPad;
4394 bool ExitsFPI;
4395 if (UnwindDest) {
4396 UnwindPad = UnwindDest->getFirstNonPHI();
4397 if (!cast<Instruction>(UnwindPad)->isEHPad())
4398 continue;
4399 Value *UnwindParent = getParentPad(UnwindPad);
4400 // Ignore unwind edges that don't exit CurrentPad.
4401 if (UnwindParent == CurrentPad)
4402 continue;
4403 // Determine whether the original funclet pad is exited,
4404 // and if we are scanning nested pads determine how many
4405 // of them are exited so we can stop searching their
4406 // children.
4407 Value *ExitedPad = CurrentPad;
4408 ExitsFPI = false;
4409 do {
4410 if (ExitedPad == &FPI) {
4411 ExitsFPI = true;
4412 // Now we can resolve any ancestors of CurrentPad up to
4413 // FPI, but not including FPI since we need to make sure
4414 // to check all direct users of FPI for consistency.
4415 UnresolvedAncestorPad = &FPI;
4416 break;
4417 }
4418 Value *ExitedParent = getParentPad(ExitedPad);
4419 if (ExitedParent == UnwindParent) {
4420 // ExitedPad is the ancestor-most pad which this unwind
4421 // edge exits, so we can resolve up to it, meaning that
4422 // ExitedParent is the first ancestor still unresolved.
4423 UnresolvedAncestorPad = ExitedParent;
4424 break;
4425 }
4426 ExitedPad = ExitedParent;
4427 } while (!isa<ConstantTokenNone>(ExitedPad));
4428 } else {
4429 // Unwinding to caller exits all pads.
4430 UnwindPad = ConstantTokenNone::get(FPI.getContext());
4431 ExitsFPI = true;
4432 UnresolvedAncestorPad = &FPI;
4433 }
4434
4435 if (ExitsFPI) {
4436 // This unwind edge exits FPI. Make sure it agrees with other
4437 // such edges.
4438 if (FirstUser) {
4439 Check(UnwindPad == FirstUnwindPad,
4440 "Unwind edges out of a funclet "
4441 "pad must have the same unwind "
4442 "dest",
4443 &FPI, U, FirstUser);
4444 } else {
4445 FirstUser = U;
4446 FirstUnwindPad = UnwindPad;
4447 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4448 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4449 getParentPad(UnwindPad) == getParentPad(&FPI))
4450 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4451 }
4452 }
4453 // Make sure we visit all uses of FPI, but for nested pads stop as
4454 // soon as we know where they unwind to.
4455 if (CurrentPad != &FPI)
4456 break;
4457 }
4458 if (UnresolvedAncestorPad) {
4459 if (CurrentPad == UnresolvedAncestorPad) {
4460 // When CurrentPad is FPI itself, we don't mark it as resolved even if
4461 // we've found an unwind edge that exits it, because we need to verify
4462 // all direct uses of FPI.
4463 assert(CurrentPad == &FPI);
4464 continue;
4465 }
4466 // Pop off the worklist any nested pads that we've found an unwind
4467 // destination for. The pads on the worklist are the uncles,
4468 // great-uncles, etc. of CurrentPad. We've found an unwind destination
4469 // for all ancestors of CurrentPad up to but not including
4470 // UnresolvedAncestorPad.
4471 Value *ResolvedPad = CurrentPad;
4472 while (!Worklist.empty()) {
4473 Value *UnclePad = Worklist.back();
4474 Value *AncestorPad = getParentPad(UnclePad);
4475 // Walk ResolvedPad up the ancestor list until we either find the
4476 // uncle's parent or the last resolved ancestor.
4477 while (ResolvedPad != AncestorPad) {
4478 Value *ResolvedParent = getParentPad(ResolvedPad);
4479 if (ResolvedParent == UnresolvedAncestorPad) {
4480 break;
4481 }
4482 ResolvedPad = ResolvedParent;
4483 }
4484 // If the resolved ancestor search didn't find the uncle's parent,
4485 // then the uncle is not yet resolved.
4486 if (ResolvedPad != AncestorPad)
4487 break;
4488 // This uncle is resolved, so pop it from the worklist.
4489 Worklist.pop_back();
4490 }
4491 }
4492 }
4493
4494 if (FirstUnwindPad) {
4495 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
4496 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4497 Value *SwitchUnwindPad;
4498 if (SwitchUnwindDest)
4499 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
4500 else
4501 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
4502 Check(SwitchUnwindPad == FirstUnwindPad,
4503 "Unwind edges out of a catch must have the same unwind dest as "
4504 "the parent catchswitch",
4505 &FPI, FirstUser, CatchSwitch);
4506 }
4507 }
4508
4509 visitInstruction(FPI);
4510}
4511
4512void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
4513 BasicBlock *BB = CatchSwitch.getParent();
4514
4515 Function *F = BB->getParent();
4516 Check(F->hasPersonalityFn(),
4517 "CatchSwitchInst needs to be in a function with a personality.",
4518 &CatchSwitch);
4519
4520 // The catchswitch instruction must be the first non-PHI instruction in the
4521 // block.
4522 Check(BB->getFirstNonPHI() == &CatchSwitch,
4523 "CatchSwitchInst not the first non-PHI instruction in the block.",
4524 &CatchSwitch);
4525
4526 auto *ParentPad = CatchSwitch.getParentPad();
4527 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4528 "CatchSwitchInst has an invalid parent.", ParentPad);
4529
4530 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
4531 Instruction *I = UnwindDest->getFirstNonPHI();
4532 Check(I->isEHPad() && !isa<LandingPadInst>(I),
4533 "CatchSwitchInst must unwind to an EH block which is not a "
4534 "landingpad.",
4535 &CatchSwitch);
4536
4537 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4538 if (getParentPad(I) == ParentPad)
4539 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4540 }
4541
4542 Check(CatchSwitch.getNumHandlers() != 0,
4543 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4544
4545 for (BasicBlock *Handler : CatchSwitch.handlers()) {
4546 Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4547 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4548 }
4549
4550 visitEHPadPredecessors(CatchSwitch);
4551 visitTerminator(CatchSwitch);
4552}
4553
4554void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
4555 Check(isa<CleanupPadInst>(CRI.getOperand(0)),
4556 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4557 CRI.getOperand(0));
4558
4559 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
4560 Instruction *I = UnwindDest->getFirstNonPHI();
4561 Check(I->isEHPad() && !isa<LandingPadInst>(I),
4562 "CleanupReturnInst must unwind to an EH block which is not a "
4563 "landingpad.",
4564 &CRI);
4565 }
4566
4567 visitTerminator(CRI);
4568}
4569
4570void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
4571 Instruction *Op = cast<Instruction>(I.getOperand(i));
4572 // If the we have an invalid invoke, don't try to compute the dominance.
4573 // We already reject it in the invoke specific checks and the dominance
4574 // computation doesn't handle multiple edges.
4575 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4576 if (II->getNormalDest() == II->getUnwindDest())
4577 return;
4578 }
4579
4580 // Quick check whether the def has already been encountered in the same block.
4581 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4582 // uses are defined to happen on the incoming edge, not at the instruction.
4583 //
4584 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4585 // wrapping an SSA value, assert that we've already encountered it. See
4586 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4587 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4588 return;
4589
4590 const Use &U = I.getOperandUse(i);
4591 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
4592}
4593
4594void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
4595 Check(I.getType()->isPointerTy(),
4596 "dereferenceable, dereferenceable_or_null "
4597 "apply only to pointer types",
4598 &I);
4599 Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
4600 "dereferenceable, dereferenceable_or_null apply only to load"
4601 " and inttoptr instructions, use attributes for calls or invokes",
4602 &I);
4603 Check(MD->getNumOperands() == 1,
4604 "dereferenceable, dereferenceable_or_null "
4605 "take one operand!",
4606 &I);
4607 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
4608 Check(CI && CI->getType()->isIntegerTy(64),
4609 "dereferenceable, "
4610 "dereferenceable_or_null metadata value must be an i64!",
4611 &I);
4612}
4613
4614void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4615 Check(MD->getNumOperands() >= 2,
4616 "!prof annotations should have no less than 2 operands", MD);
4617
4618 // Check first operand.
4619 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
4620 Check(isa<MDString>(MD->getOperand(0)),
4621 "expected string with name of the !prof annotation", MD);
4622 MDString *MDS = cast<MDString>(MD->getOperand(0));
4623 StringRef ProfName = MDS->getString();
4624
4625 // Check consistency of !prof branch_weights metadata.
4626 if (ProfName.equals("branch_weights")) {
4627 if (isa<InvokeInst>(&I)) {
4628 Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
4629 "Wrong number of InvokeInst branch_weights operands", MD);
4630 } else {
4631 unsigned ExpectedNumOperands = 0;
4632 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4633 ExpectedNumOperands = BI->getNumSuccessors();
4634 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4635 ExpectedNumOperands = SI->getNumSuccessors();
4636 else if (isa<CallInst>(&I))
4637 ExpectedNumOperands = 1;
4638 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4639 ExpectedNumOperands = IBI->getNumDestinations();
4640 else if (isa<SelectInst>(&I))
4641 ExpectedNumOperands = 2;
4642 else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
4643 ExpectedNumOperands = CI->getNumSuccessors();
4644 else
4645 CheckFailed("!prof branch_weights are not allowed for this instruction",
4646 MD);
4647
4648 Check(MD->getNumOperands() == 1 + ExpectedNumOperands,
4649 "Wrong number of operands", MD);
4650 }
4651 for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4652 auto &MDO = MD->getOperand(i);
4653 Check(MDO, "second operand should not be null", MD);
4654 Check(mdconst::dyn_extract<ConstantInt>(MDO),
4655 "!prof brunch_weights operand is not a const int");
4656 }
4657 }
4658}
4659
4660void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
4661 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
4662 bool ExpectedInstTy =
4663 isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
4664 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
4665 I, MD);
4666 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4667 // only be found as DbgAssignIntrinsic operands.
4668 if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
4669 for (auto *User : AsValue->users()) {
4670 CheckDI(isa<DbgAssignIntrinsic>(User),
4671 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4672 MD, User);
4673 // All of the dbg.assign intrinsics should be in the same function as I.
4674 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
4675 CheckDI(DAI->getFunction() == I.getFunction(),
4676 "dbg.assign not in same function as inst", DAI, &I);
4677 }
4678 }
4679}