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