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