xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision 1fd87a682ad7442327078e1eeb63edc4258f9815)
10b57cec5SDimitry Andric //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the function verifier interface, that can be used for some
104824e7fdSDimitry Andric // basic correctness checking of input to the system.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // Note that this does not provide full `Java style' security and verifications,
130b57cec5SDimitry Andric // instead it just tries to ensure that code is well-formed.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //  * Both of a binary operator's parameters are of the same type
160b57cec5SDimitry Andric //  * Verify that the indices of mem access instructions match other operands
170b57cec5SDimitry Andric //  * Verify that arithmetic and other things are only performed on first-class
180b57cec5SDimitry Andric //    types.  Verify that shifts & logicals only happen on integrals f.e.
190b57cec5SDimitry Andric //  * All of the constants in a switch statement are of the correct type
200b57cec5SDimitry Andric //  * The code is in valid SSA form
210b57cec5SDimitry Andric //  * It should be illegal to put a label into any other type (like a structure)
220b57cec5SDimitry Andric //    or to return one. [except constant arrays!]
230b57cec5SDimitry Andric //  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
240b57cec5SDimitry Andric //  * PHI nodes must have an entry for each predecessor, with no extras.
250b57cec5SDimitry Andric //  * PHI nodes must be the first thing in a basic block, all grouped together
260b57cec5SDimitry Andric //  * PHI nodes must have at least one entry
270b57cec5SDimitry Andric //  * All basic blocks should only end with terminator insts, not contain them
280b57cec5SDimitry Andric //  * The entry node to a function must not have predecessors
290b57cec5SDimitry Andric //  * All Instructions must be embedded into a basic block
300b57cec5SDimitry Andric //  * Functions cannot take a void-typed parameter
310b57cec5SDimitry Andric //  * Verify that a function's argument list agrees with it's declared type.
320b57cec5SDimitry Andric //  * It is illegal to specify a name for a void value.
330b57cec5SDimitry Andric //  * It is illegal to have a internal global value with no initializer
340b57cec5SDimitry Andric //  * It is illegal to have a ret instruction that returns a value that does not
350b57cec5SDimitry Andric //    agree with the function return value type.
360b57cec5SDimitry Andric //  * Function call argument types match the function prototype
370b57cec5SDimitry Andric //  * A landing pad is defined by a landingpad instruction, and can be jumped to
380b57cec5SDimitry Andric //    only by the unwind edge of an invoke instruction.
390b57cec5SDimitry Andric //  * A landingpad instruction must be the first non-PHI instruction in the
400b57cec5SDimitry Andric //    block.
410b57cec5SDimitry Andric //  * Landingpad instructions must be in a function with a personality function.
420b57cec5SDimitry Andric //  * All other things that are tested by asserts spread about the code...
430b57cec5SDimitry Andric //
440b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
470b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
480b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
490b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
500b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
510b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
520b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
530b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
540b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
550b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
560b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
570b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
580b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
590b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
600b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
610b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
620b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
630b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
640b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
650b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
660b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
670b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
680b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
690b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
700b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
710b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
720b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
730b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
740b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
750b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
760b57cec5SDimitry Andric #include "llvm/IR/Function.h"
770b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
780b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
790b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
800b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
810b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
820b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
830b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
840b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
850b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
860b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
87480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
880b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
890b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
900b57cec5SDimitry Andric #include "llvm/IR/Module.h"
910b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
920b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
930b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
940b57cec5SDimitry Andric #include "llvm/IR/Type.h"
950b57cec5SDimitry Andric #include "llvm/IR/Use.h"
960b57cec5SDimitry Andric #include "llvm/IR/User.h"
970b57cec5SDimitry Andric #include "llvm/IR/Value.h"
98480093f4SDimitry Andric #include "llvm/InitializePasses.h"
990b57cec5SDimitry Andric #include "llvm/Pass.h"
1000b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1010b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1020b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1030b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
1040b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1050b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
1060b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1070b57cec5SDimitry Andric #include <algorithm>
1080b57cec5SDimitry Andric #include <cassert>
1090b57cec5SDimitry Andric #include <cstdint>
1100b57cec5SDimitry Andric #include <memory>
1110b57cec5SDimitry Andric #include <string>
1120b57cec5SDimitry Andric #include <utility>
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric using namespace llvm;
1150b57cec5SDimitry Andric 
116e8d8bef9SDimitry Andric static cl::opt<bool> VerifyNoAliasScopeDomination(
117e8d8bef9SDimitry Andric     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
118e8d8bef9SDimitry Andric     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
119e8d8bef9SDimitry Andric              "scopes are not dominating"));
120e8d8bef9SDimitry Andric 
1210b57cec5SDimitry Andric namespace llvm {
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric struct VerifierSupport {
1240b57cec5SDimitry Andric   raw_ostream *OS;
1250b57cec5SDimitry Andric   const Module &M;
1260b57cec5SDimitry Andric   ModuleSlotTracker MST;
1278bcb0991SDimitry Andric   Triple TT;
1280b57cec5SDimitry Andric   const DataLayout &DL;
1290b57cec5SDimitry Andric   LLVMContext &Context;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1320b57cec5SDimitry Andric   bool Broken = false;
1330b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1340b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1350b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1360b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
1398bcb0991SDimitry Andric       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
1408bcb0991SDimitry Andric         Context(M.getContext()) {}
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric private:
1430b57cec5SDimitry Andric   void Write(const Module *M) {
1440b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   void Write(const Value *V) {
1480b57cec5SDimitry Andric     if (V)
1490b57cec5SDimitry Andric       Write(*V);
1500b57cec5SDimitry Andric   }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   void Write(const Value &V) {
1530b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1540b57cec5SDimitry Andric       V.print(*OS, MST);
1550b57cec5SDimitry Andric       *OS << '\n';
1560b57cec5SDimitry Andric     } else {
1570b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1580b57cec5SDimitry Andric       *OS << '\n';
1590b57cec5SDimitry Andric     }
1600b57cec5SDimitry Andric   }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   void Write(const Metadata *MD) {
1630b57cec5SDimitry Andric     if (!MD)
1640b57cec5SDimitry Andric       return;
1650b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
1660b57cec5SDimitry Andric     *OS << '\n';
1670b57cec5SDimitry Andric   }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
1700b57cec5SDimitry Andric     Write(MD.get());
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
1740b57cec5SDimitry Andric     if (!NMD)
1750b57cec5SDimitry Andric       return;
1760b57cec5SDimitry Andric     NMD->print(*OS, MST);
1770b57cec5SDimitry Andric     *OS << '\n';
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   void Write(Type *T) {
1810b57cec5SDimitry Andric     if (!T)
1820b57cec5SDimitry Andric       return;
1830b57cec5SDimitry Andric     *OS << ' ' << *T;
1840b57cec5SDimitry Andric   }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   void Write(const Comdat *C) {
1870b57cec5SDimitry Andric     if (!C)
1880b57cec5SDimitry Andric       return;
1890b57cec5SDimitry Andric     *OS << *C;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   void Write(const APInt *AI) {
1930b57cec5SDimitry Andric     if (!AI)
1940b57cec5SDimitry Andric       return;
1950b57cec5SDimitry Andric     *OS << *AI << '\n';
1960b57cec5SDimitry Andric   }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
1990b57cec5SDimitry Andric 
200fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
201fe6060f1SDimitry Andric   void Write(const Attribute *A) {
202fe6060f1SDimitry Andric     if (!A)
203fe6060f1SDimitry Andric       return;
204fe6060f1SDimitry Andric     *OS << A->getAsString() << '\n';
205fe6060f1SDimitry Andric   }
206fe6060f1SDimitry Andric 
207fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
208fe6060f1SDimitry Andric   void Write(const AttributeSet *AS) {
209fe6060f1SDimitry Andric     if (!AS)
210fe6060f1SDimitry Andric       return;
211fe6060f1SDimitry Andric     *OS << AS->getAsString() << '\n';
212fe6060f1SDimitry Andric   }
213fe6060f1SDimitry Andric 
214fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
215fe6060f1SDimitry Andric   void Write(const AttributeList *AL) {
216fe6060f1SDimitry Andric     if (!AL)
217fe6060f1SDimitry Andric       return;
218fe6060f1SDimitry Andric     AL->print(*OS);
219fe6060f1SDimitry Andric   }
220fe6060f1SDimitry Andric 
2210b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
2220b57cec5SDimitry Andric     for (const T &V : Vs)
2230b57cec5SDimitry Andric       Write(V);
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2270b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2280b57cec5SDimitry Andric     Write(V1);
2290b57cec5SDimitry Andric     WriteTs(Vs...);
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric public:
2350b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2360b57cec5SDimitry Andric   ///
2370b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2380b57cec5SDimitry Andric   /// something is not correct.
2390b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2400b57cec5SDimitry Andric     if (OS)
2410b57cec5SDimitry Andric       *OS << Message << '\n';
2420b57cec5SDimitry Andric     Broken = true;
2430b57cec5SDimitry Andric   }
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   /// A check failed (with values to print).
2460b57cec5SDimitry Andric   ///
2470b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2480b57cec5SDimitry Andric   /// breakpoint on.
2490b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2500b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2510b57cec5SDimitry Andric     CheckFailed(Message);
2520b57cec5SDimitry Andric     if (OS)
2530b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2540b57cec5SDimitry Andric   }
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   /// A debug info check failed.
2570b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
2580b57cec5SDimitry Andric     if (OS)
2590b57cec5SDimitry Andric       *OS << Message << '\n';
2600b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
2610b57cec5SDimitry Andric     BrokenDebugInfo = true;
2620b57cec5SDimitry Andric   }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
2650b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2660b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
2670b57cec5SDimitry Andric                             const Ts &... Vs) {
2680b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
2690b57cec5SDimitry Andric     if (OS)
2700b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2710b57cec5SDimitry Andric   }
2720b57cec5SDimitry Andric };
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric } // namespace llvm
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric namespace {
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
2790b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   DominatorTree DT;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
2840b57cec5SDimitry Andric   /// instructions we have seen so far.
2850b57cec5SDimitry Andric   ///
2860b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
2870b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
2880b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
2910b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
2940b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
2970b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   /// The result type for a landingpad.
3000b57cec5SDimitry Andric   Type *LandingPadResultTy;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
3030b57cec5SDimitry Andric   /// already.
3040b57cec5SDimitry Andric   bool SawFrameEscape;
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
3070b57cec5SDimitry Andric   bool HasDebugInfo = false;
3080b57cec5SDimitry Andric 
309e8d8bef9SDimitry Andric   /// The current source language.
310e8d8bef9SDimitry Andric   dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
311e8d8bef9SDimitry Andric 
3120b57cec5SDimitry Andric   /// Whether source was present on the first DIFile encountered in each CU.
3130b57cec5SDimitry Andric   DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
3160b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
3170b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
3200b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
3210b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
3240b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
3270b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
3280b57cec5SDimitry Andric 
329fe6060f1SDimitry Andric   /// Cache of attribute lists verified.
330fe6060f1SDimitry Andric   SmallPtrSet<const void *, 32> AttributeListsVisited;
331fe6060f1SDimitry Andric 
3320b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3330b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3340b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3350b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3360b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3390b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3420b57cec5SDimitry Andric 
343e8d8bef9SDimitry Andric   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
344e8d8bef9SDimitry Andric 
3450b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric public:
3480b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3490b57cec5SDimitry Andric                     const Module &M)
3500b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3510b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3520b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   bool verify(const Function &F) {
3580b57cec5SDimitry Andric     assert(F.getParent() == &M &&
3590b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
3620b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
3630b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
3640b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
3650b57cec5SDimitry Andric     // this code outside of a pass manager.
3660b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
3670b57cec5SDimitry Andric     if (!F.empty())
3680b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
3710b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
3720b57cec5SDimitry Andric         continue;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric       if (OS) {
3750b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
3760b57cec5SDimitry Andric             << "' does not have terminator!\n";
3770b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
3780b57cec5SDimitry Andric         *OS << "\n";
3790b57cec5SDimitry Andric       }
3800b57cec5SDimitry Andric       return false;
3810b57cec5SDimitry Andric     }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric     Broken = false;
3840b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
3850b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
3860b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
3870b57cec5SDimitry Andric     InstsInThisBlock.clear();
3880b57cec5SDimitry Andric     DebugFnArgs.clear();
3890b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
3900b57cec5SDimitry Andric     SawFrameEscape = false;
3910b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
392e8d8bef9SDimitry Andric     verifyNoAliasScopeDecl();
393e8d8bef9SDimitry Andric     NoAliasScopeDecls.clear();
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric     return !Broken;
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
3990b57cec5SDimitry Andric   bool verify() {
4000b57cec5SDimitry Andric     Broken = false;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
4030b57cec5SDimitry Andric     for (const Function &F : M)
4040b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
4050b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
4080b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
4090b57cec5SDimitry Andric     verifyFrameRecoverIndices();
4100b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
4110b57cec5SDimitry Andric       visitGlobalVariable(GV);
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
4140b57cec5SDimitry Andric       visitGlobalAlias(GA);
4150b57cec5SDimitry Andric 
416349cc55cSDimitry Andric     for (const GlobalIFunc &GI : M.ifuncs())
417349cc55cSDimitry Andric       visitGlobalIFunc(GI);
418349cc55cSDimitry Andric 
4190b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
4200b57cec5SDimitry Andric       visitNamedMDNode(NMD);
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
4230b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
4240b57cec5SDimitry Andric 
425349cc55cSDimitry Andric     visitModuleFlags();
426349cc55cSDimitry Andric     visitModuleIdents();
427349cc55cSDimitry Andric     visitModuleCommandLines();
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric     verifyCompileUnits();
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
4320b57cec5SDimitry Andric     DISubprogramAttachments.clear();
4330b57cec5SDimitry Andric     return !Broken;
4340b57cec5SDimitry Andric   }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric private:
4375ffd83dbSDimitry Andric   /// Whether a metadata node is allowed to be, or contain, a DILocation.
4385ffd83dbSDimitry Andric   enum class AreDebugLocsAllowed { No, Yes };
4395ffd83dbSDimitry Andric 
4400b57cec5SDimitry Andric   // Verification methods...
4410b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4420b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4430b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
444349cc55cSDimitry Andric   void visitGlobalIFunc(const GlobalIFunc &GI);
4450b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
4460b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
4470b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
4480b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
4495ffd83dbSDimitry Andric   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
4500b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
4510b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
4520b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
453349cc55cSDimitry Andric   void visitModuleIdents();
454349cc55cSDimitry Andric   void visitModuleCommandLines();
455349cc55cSDimitry Andric   void visitModuleFlags();
4560b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
4570b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
4580b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
4590b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
4600b57cec5SDimitry Andric   void visitFunction(const Function &F);
4610b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
4620b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
4630b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
4648bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
465e8d8bef9SDimitry Andric   void visitAnnotationMetadata(MDNode *Annotation);
466349cc55cSDimitry Andric   void visitAliasScopeMetadata(const MDNode *MD);
467349cc55cSDimitry Andric   void visitAliasScopeListMetadata(const MDNode *MD);
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
4700b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
4710b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
4720b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
4730b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
4740b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
4750b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   // InstVisitor overrides...
4800b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
4810b57cec5SDimitry Andric   void visit(Instruction &I);
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
4840b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
4850b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
4860b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
4870b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
4880b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
4890b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
4900b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
4910b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
4920b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
4930b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
4940b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
4950b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
4960b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
4970b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
4980b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
4990b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
5000b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
5010b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
5020b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
5030b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
5040b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
5050b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
5060b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
5070b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
5080b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
5090b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
5100b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
5110b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
5120b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
5130b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
5140b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
5150b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
5160b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
5170b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
5180b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
5190b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
5200b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
5210b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
5220b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
5230b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
5240b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
5250b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
5260b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
5270b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
5280b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
5290b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
5300b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
5310b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
5320b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
5330b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
5340b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
5350b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
5360b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
5370b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
5380b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
5390b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
5400b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
5430b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
5440eae32dcSDimitry Andric   void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
5450b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
5460b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
547fe6060f1SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
5480b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
549fe6060f1SDimitry Andric   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
550fe6060f1SDimitry Andric                                     const Value *V);
5510b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
55204eeddc0SDimitry Andric                            const Value *V, bool IsIntrinsic, bool IsInlineAsm);
5530b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
5560b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
55704eeddc0SDimitry Andric   void verifyInlineAsmCall(const CallBase &Call);
5580b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
5590b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
5600b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
5630b57cec5SDimitry Andric   template <typename ValueOrMetadata>
5640b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
5650b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
5660b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
5670b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
5688bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   /// Module-level debug info verification...
5710b57cec5SDimitry Andric   void verifyCompileUnits();
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
5740b57cec5SDimitry Andric   /// declarations share the same calling convention.
5750b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
5760b57cec5SDimitry Andric 
577349cc55cSDimitry Andric   void verifyAttachedCallBundle(const CallBase &Call,
578349cc55cSDimitry Andric                                 const OperandBundleUse &BU);
579349cc55cSDimitry Andric 
5800b57cec5SDimitry Andric   /// Verify all-or-nothing property of DIFile source attribute within a CU.
5810b57cec5SDimitry Andric   void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
582e8d8bef9SDimitry Andric 
583e8d8bef9SDimitry Andric   /// Verify the llvm.experimental.noalias.scope.decl declarations
584e8d8bef9SDimitry Andric   void verifyNoAliasScopeDecl();
5850b57cec5SDimitry Andric };
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric } // end anonymous namespace
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
5900b57cec5SDimitry Andric #define Assert(C, ...) \
5910b57cec5SDimitry Andric   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
5940b57cec5SDimitry Andric /// an error message.
5950b57cec5SDimitry Andric #define AssertDI(C, ...) \
5960b57cec5SDimitry Andric   do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
5990b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
6000b57cec5SDimitry Andric     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
6010b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric 
6040eae32dcSDimitry Andric // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
6050b57cec5SDimitry Andric static void forEachUser(const Value *User,
6060b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
6070b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
6080b57cec5SDimitry Andric   if (!Visited.insert(User).second)
6090b57cec5SDimitry Andric     return;
6100eae32dcSDimitry Andric 
6110eae32dcSDimitry Andric   SmallVector<const Value *> WorkList;
6120eae32dcSDimitry Andric   append_range(WorkList, User->materialized_users());
6130eae32dcSDimitry Andric   while (!WorkList.empty()) {
6140eae32dcSDimitry Andric    const Value *Cur = WorkList.pop_back_val();
6150eae32dcSDimitry Andric     if (!Visited.insert(Cur).second)
6160eae32dcSDimitry Andric       continue;
6170eae32dcSDimitry Andric     if (Callback(Cur))
6180eae32dcSDimitry Andric       append_range(WorkList, Cur->materialized_users());
6190eae32dcSDimitry Andric   }
6200b57cec5SDimitry Andric }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
6230b57cec5SDimitry Andric   Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
6240b57cec5SDimitry Andric          "Global is external, but doesn't have external or weak linkage!", &GV);
6250b57cec5SDimitry Andric 
6260eae32dcSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
6270eae32dcSDimitry Andric 
6280eae32dcSDimitry Andric     if (MaybeAlign A = GO->getAlign()) {
6290eae32dcSDimitry Andric       Assert(A->value() <= Value::MaximumAlignment,
6305ffd83dbSDimitry Andric              "huge alignment values are unsupported", GO);
6310eae32dcSDimitry Andric     }
6320eae32dcSDimitry Andric   }
6330b57cec5SDimitry Andric   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
6340b57cec5SDimitry Andric          "Only global variables can have appending linkage!", &GV);
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
6370b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
6380b57cec5SDimitry Andric     Assert(GVar && GVar->getValueType()->isArrayTy(),
6390b57cec5SDimitry Andric            "Only global arrays can have appending linkage!", GVar);
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
6430b57cec5SDimitry Andric     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
6460b57cec5SDimitry Andric     Assert(!GV.isDSOLocal(),
6470b57cec5SDimitry Andric            "GlobalValue with DLLImport Storage is dso_local!", &GV);
6480b57cec5SDimitry Andric 
649e8d8bef9SDimitry Andric     Assert((GV.isDeclaration() &&
650e8d8bef9SDimitry Andric             (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
6510b57cec5SDimitry Andric                GV.hasAvailableExternallyLinkage(),
6520b57cec5SDimitry Andric            "Global is marked as dllimport, but not external", &GV);
6530b57cec5SDimitry Andric   }
6540b57cec5SDimitry Andric 
6555ffd83dbSDimitry Andric   if (GV.isImplicitDSOLocal())
6560b57cec5SDimitry Andric     Assert(GV.isDSOLocal(),
6575ffd83dbSDimitry Andric            "GlobalValue with local linkage or non-default "
6585ffd83dbSDimitry Andric            "visibility must be dso_local!",
6590b57cec5SDimitry Andric            &GV);
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
6620b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
6630b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
6640b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
6650b57cec5SDimitry Andric                     I);
6660b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
6670b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
6680b57cec5SDimitry Andric                     I->getParent()->getParent(),
6690b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
6700b57cec5SDimitry Andric       return false;
6710b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
6720b57cec5SDimitry Andric       if (F->getParent() != &M)
6730b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
6740b57cec5SDimitry Andric                     F, F->getParent());
6750b57cec5SDimitry Andric       return false;
6760b57cec5SDimitry Andric     }
6770b57cec5SDimitry Andric     return true;
6780b57cec5SDimitry Andric   });
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
6820b57cec5SDimitry Andric   if (GV.hasInitializer()) {
6830b57cec5SDimitry Andric     Assert(GV.getInitializer()->getType() == GV.getValueType(),
6840b57cec5SDimitry Andric            "Global variable initializer type does not match global "
6850b57cec5SDimitry Andric            "variable type!",
6860b57cec5SDimitry Andric            &GV);
6870b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
6880b57cec5SDimitry Andric     // cannot be constant.
6890b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
6900b57cec5SDimitry Andric       Assert(GV.getInitializer()->isNullValue(),
6910b57cec5SDimitry Andric              "'common' global must have a zero initializer!", &GV);
6920b57cec5SDimitry Andric       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
6930b57cec5SDimitry Andric              &GV);
6940b57cec5SDimitry Andric       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
6950b57cec5SDimitry Andric     }
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
6990b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
7000b57cec5SDimitry Andric     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
7010b57cec5SDimitry Andric            "invalid linkage for intrinsic global variable", &GV);
7020b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
7030b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
7040b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
7050b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
7060b57cec5SDimitry Andric       PointerType *FuncPtrTy =
7070b57cec5SDimitry Andric           FunctionType::get(Type::getVoidTy(Context), false)->
7080b57cec5SDimitry Andric           getPointerTo(DL.getProgramAddressSpace());
7090b57cec5SDimitry Andric       Assert(STy &&
7100b57cec5SDimitry Andric                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
7110b57cec5SDimitry Andric                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
7120b57cec5SDimitry Andric                  STy->getTypeAtIndex(1) == FuncPtrTy,
7130b57cec5SDimitry Andric              "wrong type for intrinsic global variable", &GV);
7140b57cec5SDimitry Andric       Assert(STy->getNumElements() == 3,
7150b57cec5SDimitry Andric              "the third field of the element type is mandatory, "
7160b57cec5SDimitry Andric              "specify i8* null to migrate from the obsoleted 2-field form");
7170b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
718fe6060f1SDimitry Andric       Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
7190b57cec5SDimitry Andric       Assert(ETy->isPointerTy() &&
720fe6060f1SDimitry Andric                  cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
7210b57cec5SDimitry Andric              "wrong type for intrinsic global variable", &GV);
7220b57cec5SDimitry Andric     }
7230b57cec5SDimitry Andric   }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
7260b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
7270b57cec5SDimitry Andric     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
7280b57cec5SDimitry Andric            "invalid linkage for intrinsic global variable", &GV);
7290b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
7300b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
7310b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
7320b57cec5SDimitry Andric       Assert(PTy, "wrong type for intrinsic global variable", &GV);
7330b57cec5SDimitry Andric       if (GV.hasInitializer()) {
7340b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
7350b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
7360b57cec5SDimitry Andric         Assert(InitArray, "wrong initalizer for intrinsic global variable",
7370b57cec5SDimitry Andric                Init);
7380b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
7398bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
7400b57cec5SDimitry Andric           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
7410b57cec5SDimitry Andric                      isa<GlobalAlias>(V),
7420eae32dcSDimitry Andric                  Twine("invalid ") + GV.getName() + " member", V);
7430eae32dcSDimitry Andric           Assert(V->hasName(),
7440eae32dcSDimitry Andric                  Twine("members of ") + GV.getName() + " must be named", V);
7450b57cec5SDimitry Andric         }
7460b57cec5SDimitry Andric       }
7470b57cec5SDimitry Andric     }
7480b57cec5SDimitry Andric   }
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   // Visit any debug info attachments.
7510b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
7520b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
7530b57cec5SDimitry Andric   for (auto *MD : MDs) {
7540b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
7550b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
7560b57cec5SDimitry Andric     else
7570b57cec5SDimitry Andric       AssertDI(false, "!dbg attachment of global variable must be a "
7580b57cec5SDimitry Andric                       "DIGlobalVariableExpression");
7590b57cec5SDimitry Andric   }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
762e8d8bef9SDimitry Andric   // the runtime size. If the global is an array containing scalable vectors,
763e8d8bef9SDimitry Andric   // that will be caught by the isValidElementType methods in StructType or
764e8d8bef9SDimitry Andric   // ArrayType instead.
7655ffd83dbSDimitry Andric   Assert(!isa<ScalableVectorType>(GV.getValueType()),
7665ffd83dbSDimitry Andric          "Globals cannot contain scalable vectors", &GV);
7670b57cec5SDimitry Andric 
768e8d8bef9SDimitry Andric   if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
769e8d8bef9SDimitry Andric     Assert(!STy->containsScalableVectorType(),
770e8d8bef9SDimitry Andric            "Globals cannot contain scalable vectors", &GV);
771e8d8bef9SDimitry Andric 
7720b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
7730b57cec5SDimitry Andric     visitGlobalValue(GV);
7740b57cec5SDimitry Andric     return;
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
7780b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   visitGlobalValue(GV);
7810b57cec5SDimitry Andric }
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
7840b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
7850b57cec5SDimitry Andric   Visited.insert(&GA);
7860b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
7900b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
7910b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
7920b57cec5SDimitry Andric     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
7930b57cec5SDimitry Andric            &GA);
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
7960b57cec5SDimitry Andric       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric       Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
7990b57cec5SDimitry Andric              &GA);
8000b57cec5SDimitry Andric     } else {
8010b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
8020b57cec5SDimitry Andric       // Do not recurse into global initializers.
8030b57cec5SDimitry Andric       return;
8040b57cec5SDimitry Andric     }
8050b57cec5SDimitry Andric   }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
8080b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
8110b57cec5SDimitry Andric     Value *V = &*U;
8120b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
8130b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
8140b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
8150b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
8160b57cec5SDimitry Andric   }
8170b57cec5SDimitry Andric }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
8200b57cec5SDimitry Andric   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
8210b57cec5SDimitry Andric          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
8220b57cec5SDimitry Andric          "weak_odr, or external linkage!",
8230b57cec5SDimitry Andric          &GA);
8240b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
8250b57cec5SDimitry Andric   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
8260b57cec5SDimitry Andric   Assert(GA.getType() == Aliasee->getType(),
8270b57cec5SDimitry Andric          "Alias and aliasee types should match!", &GA);
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
8300b57cec5SDimitry Andric          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   visitGlobalValue(GA);
8350b57cec5SDimitry Andric }
8360b57cec5SDimitry Andric 
837349cc55cSDimitry Andric void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
838349cc55cSDimitry Andric   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
839349cc55cSDimitry Andric   // has a Function
840349cc55cSDimitry Andric   const Function *Resolver = GI.getResolverFunction();
841349cc55cSDimitry Andric   Assert(Resolver, "IFunc must have a Function resolver", &GI);
842349cc55cSDimitry Andric 
843349cc55cSDimitry Andric   // Check that the immediate resolver operand (prior to any bitcasts) has the
844349cc55cSDimitry Andric   // correct type
845349cc55cSDimitry Andric   const Type *ResolverTy = GI.getResolver()->getType();
846349cc55cSDimitry Andric   const Type *ResolverFuncTy =
847349cc55cSDimitry Andric       GlobalIFunc::getResolverFunctionType(GI.getValueType());
848349cc55cSDimitry Andric   Assert(ResolverTy == ResolverFuncTy->getPointerTo(),
849349cc55cSDimitry Andric          "IFunc resolver has incorrect type", &GI);
850349cc55cSDimitry Andric }
851349cc55cSDimitry Andric 
8520b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
8530b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
8540b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
8550b57cec5SDimitry Andric   if (NMD.getName().startswith("llvm.dbg."))
8560b57cec5SDimitry Andric     AssertDI(NMD.getName() == "llvm.dbg.cu",
8570b57cec5SDimitry Andric              "unrecognized named metadata node in the llvm.dbg namespace",
8580b57cec5SDimitry Andric              &NMD);
8590b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
8600b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
8610b57cec5SDimitry Andric       AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric     if (!MD)
8640b57cec5SDimitry Andric       continue;
8650b57cec5SDimitry Andric 
8665ffd83dbSDimitry Andric     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
8670b57cec5SDimitry Andric   }
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8705ffd83dbSDimitry Andric void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
8710b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
8720b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
8730b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
8740b57cec5SDimitry Andric     return;
8750b57cec5SDimitry Andric 
876fe6060f1SDimitry Andric   Assert(&MD.getContext() == &Context,
877fe6060f1SDimitry Andric          "MDNode context does not match Module context!", &MD);
878fe6060f1SDimitry Andric 
8790b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
8800b57cec5SDimitry Andric   default:
8810b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
8820b57cec5SDimitry Andric   case Metadata::MDTupleKind:
8830b57cec5SDimitry Andric     break;
8840b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
8850b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
8860b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
8870b57cec5SDimitry Andric     break;
8880b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
8890b57cec5SDimitry Andric   }
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
8920b57cec5SDimitry Andric     if (!Op)
8930b57cec5SDimitry Andric       continue;
8940b57cec5SDimitry Andric     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
8950b57cec5SDimitry Andric            &MD, Op);
8965ffd83dbSDimitry Andric     AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
8975ffd83dbSDimitry Andric              "DILocation not allowed within this metadata node", &MD, Op);
8980b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
8995ffd83dbSDimitry Andric       visitMDNode(*N, AllowLocs);
9000b57cec5SDimitry Andric       continue;
9010b57cec5SDimitry Andric     }
9020b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
9030b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
9040b57cec5SDimitry Andric       continue;
9050b57cec5SDimitry Andric     }
9060b57cec5SDimitry Andric   }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
9090b57cec5SDimitry Andric   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
9100b57cec5SDimitry Andric   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
9140b57cec5SDimitry Andric   Assert(MD.getValue(), "Expected valid value", &MD);
9150b57cec5SDimitry Andric   Assert(!MD.getValue()->getType()->isMetadataTy(),
9160b57cec5SDimitry Andric          "Unexpected metadata round-trip through values", &MD, MD.getValue());
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
9190b57cec5SDimitry Andric   if (!L)
9200b57cec5SDimitry Andric     return;
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   Assert(F, "function-local metadata used outside a function", L);
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
9250b57cec5SDimitry Andric   // function that we expect.
9260b57cec5SDimitry Andric   Function *ActualF = nullptr;
9270b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
9280b57cec5SDimitry Andric     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
9290b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
9300b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
9310b57cec5SDimitry Andric     ActualF = BB->getParent();
9320b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
9330b57cec5SDimitry Andric     ActualF = A->getParent();
9340b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   Assert(ActualF == F, "function-local metadata used in wrong function", L);
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
9400b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
9410b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
9425ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::No);
9430b57cec5SDimitry Andric     return;
9440b57cec5SDimitry Andric   }
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
9470b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
9480b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
9490b57cec5SDimitry Andric     return;
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
9520b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
9560b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
9570b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
9600b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
9610b57cec5SDimitry Andric            "location requires a valid scope", &N, N.getRawScope());
9620b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
9630b57cec5SDimitry Andric     AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
9640b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
9650b57cec5SDimitry Andric     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
9690b57cec5SDimitry Andric   AssertDI(N.getTag(), "invalid tag", &N);
9700b57cec5SDimitry Andric }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
9730b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
9740b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
9780b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
979e8d8bef9SDimitry Andric   bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
980e8d8bef9SDimitry Andric   AssertDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
981e8d8bef9SDimitry Andric                N.getRawUpperBound(),
9825ffd83dbSDimitry Andric            "Subrange must contain count or upperBound", &N);
9835ffd83dbSDimitry Andric   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
9845ffd83dbSDimitry Andric            "Subrange can have any one of count or upperBound", &N);
985fe6060f1SDimitry Andric   auto *CBound = N.getRawCountNode();
986fe6060f1SDimitry Andric   AssertDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
987fe6060f1SDimitry Andric                isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
988fe6060f1SDimitry Andric            "Count must be signed constant or DIVariable or DIExpression", &N);
9890b57cec5SDimitry Andric   auto Count = N.getCount();
9905ffd83dbSDimitry Andric   AssertDI(!Count || !Count.is<ConstantInt *>() ||
9910b57cec5SDimitry Andric                Count.get<ConstantInt *>()->getSExtValue() >= -1,
9920b57cec5SDimitry Andric            "invalid subrange count", &N);
9935ffd83dbSDimitry Andric   auto *LBound = N.getRawLowerBound();
9945ffd83dbSDimitry Andric   AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
9955ffd83dbSDimitry Andric                isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
9965ffd83dbSDimitry Andric            "LowerBound must be signed constant or DIVariable or DIExpression",
9975ffd83dbSDimitry Andric            &N);
9985ffd83dbSDimitry Andric   auto *UBound = N.getRawUpperBound();
9995ffd83dbSDimitry Andric   AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
10005ffd83dbSDimitry Andric                isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
10015ffd83dbSDimitry Andric            "UpperBound must be signed constant or DIVariable or DIExpression",
10025ffd83dbSDimitry Andric            &N);
10035ffd83dbSDimitry Andric   auto *Stride = N.getRawStride();
10045ffd83dbSDimitry Andric   AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
10055ffd83dbSDimitry Andric                isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
10065ffd83dbSDimitry Andric            "Stride must be signed constant or DIVariable or DIExpression", &N);
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric 
1009e8d8bef9SDimitry Andric void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1010e8d8bef9SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1011e8d8bef9SDimitry Andric   AssertDI(N.getRawCountNode() || N.getRawUpperBound(),
1012e8d8bef9SDimitry Andric            "GenericSubrange must contain count or upperBound", &N);
1013e8d8bef9SDimitry Andric   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1014e8d8bef9SDimitry Andric            "GenericSubrange can have any one of count or upperBound", &N);
1015e8d8bef9SDimitry Andric   auto *CBound = N.getRawCountNode();
1016e8d8bef9SDimitry Andric   AssertDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1017e8d8bef9SDimitry Andric            "Count must be signed constant or DIVariable or DIExpression", &N);
1018e8d8bef9SDimitry Andric   auto *LBound = N.getRawLowerBound();
1019e8d8bef9SDimitry Andric   AssertDI(LBound, "GenericSubrange must contain lowerBound", &N);
1020e8d8bef9SDimitry Andric   AssertDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1021e8d8bef9SDimitry Andric            "LowerBound must be signed constant or DIVariable or DIExpression",
1022e8d8bef9SDimitry Andric            &N);
1023e8d8bef9SDimitry Andric   auto *UBound = N.getRawUpperBound();
1024e8d8bef9SDimitry Andric   AssertDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1025e8d8bef9SDimitry Andric            "UpperBound must be signed constant or DIVariable or DIExpression",
1026e8d8bef9SDimitry Andric            &N);
1027e8d8bef9SDimitry Andric   auto *Stride = N.getRawStride();
1028e8d8bef9SDimitry Andric   AssertDI(Stride, "GenericSubrange must contain stride", &N);
1029e8d8bef9SDimitry Andric   AssertDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1030e8d8bef9SDimitry Andric            "Stride must be signed constant or DIVariable or DIExpression", &N);
1031e8d8bef9SDimitry Andric }
1032e8d8bef9SDimitry Andric 
10330b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
10340b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
10350b57cec5SDimitry Andric }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
10380b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
1039e8d8bef9SDimitry Andric                N.getTag() == dwarf::DW_TAG_unspecified_type ||
1040e8d8bef9SDimitry Andric                N.getTag() == dwarf::DW_TAG_string_type,
10410b57cec5SDimitry Andric            "invalid tag", &N);
1042e8d8bef9SDimitry Andric }
1043e8d8bef9SDimitry Andric 
1044e8d8bef9SDimitry Andric void Verifier::visitDIStringType(const DIStringType &N) {
1045e8d8bef9SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
10460b57cec5SDimitry Andric   AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
10470b57cec5SDimitry Andric             "has conflicting flags", &N);
10480b57cec5SDimitry Andric }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
10510b57cec5SDimitry Andric   // Common scope checks.
10520b57cec5SDimitry Andric   visitDIScope(N);
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
10550b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_pointer_type ||
10560b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
10570b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_reference_type ||
10580b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
10590b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_const_type ||
106004eeddc0SDimitry Andric                N.getTag() == dwarf::DW_TAG_immutable_type ||
10610b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_volatile_type ||
10620b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_restrict_type ||
10630b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_atomic_type ||
10640b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_member ||
10650b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_inheritance ||
1066fe6060f1SDimitry Andric                N.getTag() == dwarf::DW_TAG_friend ||
1067fe6060f1SDimitry Andric                N.getTag() == dwarf::DW_TAG_set_type,
10680b57cec5SDimitry Andric            "invalid tag", &N);
10690b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
10700b57cec5SDimitry Andric     AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
10710b57cec5SDimitry Andric              N.getRawExtraData());
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric 
1074fe6060f1SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_set_type) {
1075fe6060f1SDimitry Andric     if (auto *T = N.getRawBaseType()) {
1076fe6060f1SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1077fe6060f1SDimitry Andric       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
1078fe6060f1SDimitry Andric       AssertDI(
1079fe6060f1SDimitry Andric           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1080fe6060f1SDimitry Andric               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1081fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1082fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1083fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1084fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1085fe6060f1SDimitry Andric           "invalid set base type", &N, T);
1086fe6060f1SDimitry Andric     }
1087fe6060f1SDimitry Andric   }
1088fe6060f1SDimitry Andric 
10890b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
10900b57cec5SDimitry Andric   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
10910b57cec5SDimitry Andric            N.getRawBaseType());
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
10940b57cec5SDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
10950b57cec5SDimitry Andric                  N.getTag() == dwarf::DW_TAG_reference_type ||
10960b57cec5SDimitry Andric                  N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
10970b57cec5SDimitry Andric              "DWARF address space only applies to pointer or reference types",
10980b57cec5SDimitry Andric              &N);
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric /// Detect mutually exclusive flags.
11030b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
11040b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
11050b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
11060b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
11070b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
11080b57cec5SDimitry Andric }
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
11110b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
11120b57cec5SDimitry Andric   AssertDI(Params, "invalid template params", &N, &RawParams);
11130b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
11140b57cec5SDimitry Andric     AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
11150b57cec5SDimitry Andric              &N, Params, Op);
11160b57cec5SDimitry Andric   }
11170b57cec5SDimitry Andric }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
11200b57cec5SDimitry Andric   // Common scope checks.
11210b57cec5SDimitry Andric   visitDIScope(N);
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
11240b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_structure_type ||
11250b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_union_type ||
11260b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_enumeration_type ||
11270b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_class_type ||
1128349cc55cSDimitry Andric                N.getTag() == dwarf::DW_TAG_variant_part ||
1129349cc55cSDimitry Andric                N.getTag() == dwarf::DW_TAG_namelist,
11300b57cec5SDimitry Andric            "invalid tag", &N);
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
11330b57cec5SDimitry Andric   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
11340b57cec5SDimitry Andric            N.getRawBaseType());
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric   AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
11370b57cec5SDimitry Andric            "invalid composite elements", &N, N.getRawElements());
11380b57cec5SDimitry Andric   AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
11390b57cec5SDimitry Andric            N.getRawVTableHolder());
11400b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
11410b57cec5SDimitry Andric            "invalid reference flags", &N);
11428bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
11438bcb0991SDimitry Andric   AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,
11448bcb0991SDimitry Andric            "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric   if (N.isVector()) {
11470b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
11480b57cec5SDimitry Andric     AssertDI(Elements.size() == 1 &&
11490b57cec5SDimitry Andric              Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
11500b57cec5SDimitry Andric              "invalid vector, expected one element of type subrange", &N);
11510b57cec5SDimitry Andric   }
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
11540b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
11570b57cec5SDimitry Andric     AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
11580b57cec5SDimitry Andric              "discriminator can only appear on variant part");
11590b57cec5SDimitry Andric   }
11605ffd83dbSDimitry Andric 
11615ffd83dbSDimitry Andric   if (N.getRawDataLocation()) {
11625ffd83dbSDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
11635ffd83dbSDimitry Andric              "dataLocation can only appear in array type");
11645ffd83dbSDimitry Andric   }
1165e8d8bef9SDimitry Andric 
1166e8d8bef9SDimitry Andric   if (N.getRawAssociated()) {
1167e8d8bef9SDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1168e8d8bef9SDimitry Andric              "associated can only appear in array type");
1169e8d8bef9SDimitry Andric   }
1170e8d8bef9SDimitry Andric 
1171e8d8bef9SDimitry Andric   if (N.getRawAllocated()) {
1172e8d8bef9SDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1173e8d8bef9SDimitry Andric              "allocated can only appear in array type");
1174e8d8bef9SDimitry Andric   }
1175e8d8bef9SDimitry Andric 
1176e8d8bef9SDimitry Andric   if (N.getRawRank()) {
1177e8d8bef9SDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1178e8d8bef9SDimitry Andric              "rank can only appear in array type");
1179e8d8bef9SDimitry Andric   }
11800b57cec5SDimitry Andric }
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
11830b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
11840b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
11850b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
11860b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
11870b57cec5SDimitry Andric       AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
11880b57cec5SDimitry Andric     }
11890b57cec5SDimitry Andric   }
11900b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
11910b57cec5SDimitry Andric            "invalid reference flags", &N);
11920b57cec5SDimitry Andric }
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
11950b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
11960b57cec5SDimitry Andric   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
11970b57cec5SDimitry Andric   if (Checksum) {
11980b57cec5SDimitry Andric     AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
11990b57cec5SDimitry Andric              "invalid checksum kind", &N);
12000b57cec5SDimitry Andric     size_t Size;
12010b57cec5SDimitry Andric     switch (Checksum->Kind) {
12020b57cec5SDimitry Andric     case DIFile::CSK_MD5:
12030b57cec5SDimitry Andric       Size = 32;
12040b57cec5SDimitry Andric       break;
12050b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
12060b57cec5SDimitry Andric       Size = 40;
12070b57cec5SDimitry Andric       break;
12085ffd83dbSDimitry Andric     case DIFile::CSK_SHA256:
12095ffd83dbSDimitry Andric       Size = 64;
12105ffd83dbSDimitry Andric       break;
12110b57cec5SDimitry Andric     }
12120b57cec5SDimitry Andric     AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
12130b57cec5SDimitry Andric     AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
12140b57cec5SDimitry Andric              "invalid checksum", &N);
12150b57cec5SDimitry Andric   }
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
12190b57cec5SDimitry Andric   AssertDI(N.isDistinct(), "compile units must be distinct", &N);
12200b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
12230b57cec5SDimitry Andric   // as those could be empty.
12240b57cec5SDimitry Andric   AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
12250b57cec5SDimitry Andric            N.getRawFile());
12260b57cec5SDimitry Andric   AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
12270b57cec5SDimitry Andric            N.getFile());
12280b57cec5SDimitry Andric 
1229e8d8bef9SDimitry Andric   CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1230e8d8bef9SDimitry Andric 
12310b57cec5SDimitry Andric   verifySourceDebugInfo(N, *N.getFile());
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric   AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
12340b57cec5SDimitry Andric            "invalid emission kind", &N);
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
12370b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
12380b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
12390b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
12400b57cec5SDimitry Andric       AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
12410b57cec5SDimitry Andric                "invalid enum type", &N, N.getEnumTypes(), Op);
12420b57cec5SDimitry Andric     }
12430b57cec5SDimitry Andric   }
12440b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
12450b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
12460b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
12470b57cec5SDimitry Andric       AssertDI(Op && (isa<DIType>(Op) ||
12480b57cec5SDimitry Andric                       (isa<DISubprogram>(Op) &&
12490b57cec5SDimitry Andric                        !cast<DISubprogram>(Op)->isDefinition())),
12500b57cec5SDimitry Andric                "invalid retained type", &N, Op);
12510b57cec5SDimitry Andric     }
12520b57cec5SDimitry Andric   }
12530b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
12540b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
12550b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
12560b57cec5SDimitry Andric       AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
12570b57cec5SDimitry Andric                "invalid global variable ref", &N, Op);
12580b57cec5SDimitry Andric     }
12590b57cec5SDimitry Andric   }
12600b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
12610b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
12620b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
12630b57cec5SDimitry Andric       AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
12640b57cec5SDimitry Andric                &N, Op);
12650b57cec5SDimitry Andric     }
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
12680b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
12690b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
12700b57cec5SDimitry Andric       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
12710b57cec5SDimitry Andric     }
12720b57cec5SDimitry Andric   }
12730b57cec5SDimitry Andric   CUVisited.insert(&N);
12740b57cec5SDimitry Andric }
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
12770b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
12780b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
12790b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
12800b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
12810b57cec5SDimitry Andric   else
12820b57cec5SDimitry Andric     AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
12830b57cec5SDimitry Andric   if (auto *T = N.getRawType())
12840b57cec5SDimitry Andric     AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
12850b57cec5SDimitry Andric   AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
12860b57cec5SDimitry Andric            N.getRawContainingType());
12870b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
12880b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
12890b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
12900b57cec5SDimitry Andric     AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
12910b57cec5SDimitry Andric              "invalid subprogram declaration", &N, S);
12920b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
12930b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
12940b57cec5SDimitry Andric     AssertDI(Node, "invalid retained nodes list", &N, RawNode);
12950b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
12960b57cec5SDimitry Andric       AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
12970b57cec5SDimitry Andric                "invalid retained nodes, expected DILocalVariable or DILabel",
12980b57cec5SDimitry Andric                &N, Node, Op);
12990b57cec5SDimitry Andric     }
13000b57cec5SDimitry Andric   }
13010b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
13020b57cec5SDimitry Andric            "invalid reference flags", &N);
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
13050b57cec5SDimitry Andric   if (N.isDefinition()) {
13060b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
13070b57cec5SDimitry Andric     AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
13080b57cec5SDimitry Andric     AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
13090b57cec5SDimitry Andric     AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
13100b57cec5SDimitry Andric     if (N.getFile())
13110b57cec5SDimitry Andric       verifySourceDebugInfo(*N.getUnit(), *N.getFile());
13120b57cec5SDimitry Andric   } else {
13130b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
13140b57cec5SDimitry Andric     AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
13150b57cec5SDimitry Andric   }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
13180b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
13190b57cec5SDimitry Andric     AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
13200b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
13210b57cec5SDimitry Andric       AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
13220b57cec5SDimitry Andric                Op);
13230b57cec5SDimitry Andric   }
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
13260b57cec5SDimitry Andric     AssertDI(N.isDefinition(),
13270b57cec5SDimitry Andric              "DIFlagAllCallsDescribed must be attached to a definition");
13280b57cec5SDimitry Andric }
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
13310b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
13320b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
13330b57cec5SDimitry Andric            "invalid local scope", &N, N.getRawScope());
13340b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
13350b57cec5SDimitry Andric     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
13360b57cec5SDimitry Andric }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
13390b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric   AssertDI(N.getLine() || !N.getColumn(),
13420b57cec5SDimitry Andric            "cannot have column info without line info", &N);
13430b57cec5SDimitry Andric }
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
13460b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
13470b57cec5SDimitry Andric }
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
13500b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
13510b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
13520b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
13530b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
13540b57cec5SDimitry Andric     AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
13580b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
13590b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
13600b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
13610b57cec5SDimitry Andric }
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
13640b57cec5SDimitry Andric   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
13650b57cec5SDimitry Andric                N.getMacinfoType() == dwarf::DW_MACINFO_undef,
13660b57cec5SDimitry Andric            "invalid macinfo type", &N);
13670b57cec5SDimitry Andric   AssertDI(!N.getName().empty(), "anonymous macro", &N);
13680b57cec5SDimitry Andric   if (!N.getValue().empty()) {
13690b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
13700b57cec5SDimitry Andric   }
13710b57cec5SDimitry Andric }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
13740b57cec5SDimitry Andric   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
13750b57cec5SDimitry Andric            "invalid macinfo type", &N);
13760b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
13770b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
13800b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
13810b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
13820b57cec5SDimitry Andric       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
13830b57cec5SDimitry Andric     }
13840b57cec5SDimitry Andric   }
13850b57cec5SDimitry Andric }
13860b57cec5SDimitry Andric 
1387fe6060f1SDimitry Andric void Verifier::visitDIArgList(const DIArgList &N) {
1388fe6060f1SDimitry Andric   AssertDI(!N.getNumOperands(),
1389fe6060f1SDimitry Andric            "DIArgList should have no operands other than a list of "
1390fe6060f1SDimitry Andric            "ValueAsMetadata",
1391fe6060f1SDimitry Andric            &N);
1392fe6060f1SDimitry Andric }
1393fe6060f1SDimitry Andric 
13940b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
13950b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
13960b57cec5SDimitry Andric   AssertDI(!N.getName().empty(), "anonymous module", &N);
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
14000b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
14010b57cec5SDimitry Andric }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
14040b57cec5SDimitry Andric   visitDITemplateParameter(N);
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
14070b57cec5SDimitry Andric            &N);
14080b57cec5SDimitry Andric }
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
14110b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
14120b57cec5SDimitry Andric   visitDITemplateParameter(N);
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
14150b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
14160b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
14170b57cec5SDimitry Andric            "invalid tag", &N);
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
14210b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
14220b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
14230b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
14240b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
14250b57cec5SDimitry Andric }
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
14280b57cec5SDimitry Andric   // Checks common to all variables.
14290b57cec5SDimitry Andric   visitDIVariable(N);
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
14320b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
14335ffd83dbSDimitry Andric   // Assert only if the global variable is not an extern
14345ffd83dbSDimitry Andric   if (N.isDefinition())
14350b57cec5SDimitry Andric     AssertDI(N.getType(), "missing global variable type", &N);
14360b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
14370b57cec5SDimitry Andric     AssertDI(isa<DIDerivedType>(Member),
14380b57cec5SDimitry Andric              "invalid static data member declaration", &N, Member);
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric }
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
14430b57cec5SDimitry Andric   // Checks common to all variables.
14440b57cec5SDimitry Andric   visitDIVariable(N);
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
14470b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
14480b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
14490b57cec5SDimitry Andric            "local variable requires a valid scope", &N, N.getRawScope());
14500b57cec5SDimitry Andric   if (auto Ty = N.getType())
14510b57cec5SDimitry Andric     AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
14520b57cec5SDimitry Andric }
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
14550b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
14560b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
14570b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
14580b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
14610b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
14620b57cec5SDimitry Andric            "label requires a valid scope", &N, N.getRawScope());
14630b57cec5SDimitry Andric }
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
14660b57cec5SDimitry Andric   AssertDI(N.isValid(), "invalid expression", &N);
14670b57cec5SDimitry Andric }
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
14700b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
14710b57cec5SDimitry Andric   AssertDI(GVE.getVariable(), "missing variable");
14720b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
14730b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
14740b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
14750b57cec5SDimitry Andric     visitDIExpression(*Expr);
14760b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
14770b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
14780b57cec5SDimitry Andric   }
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
14820b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
14830b57cec5SDimitry Andric   if (auto *T = N.getRawType())
14840b57cec5SDimitry Andric     AssertDI(isType(T), "invalid type ref", &N, T);
14850b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
14860b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
14870b57cec5SDimitry Andric }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
14900b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
14910b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_imported_declaration,
14920b57cec5SDimitry Andric            "invalid tag", &N);
14930b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
14940b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
14950b57cec5SDimitry Andric   AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
14960b57cec5SDimitry Andric            N.getRawEntity());
14970b57cec5SDimitry Andric }
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
15008bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
15018bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
15028bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
15030b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
15048bcb0991SDimitry Andric       Assert(!GV->hasPrivateLinkage(),
15058bcb0991SDimitry Andric              "comdat global value has private linkage", GV);
15060b57cec5SDimitry Andric }
15070b57cec5SDimitry Andric 
1508349cc55cSDimitry Andric void Verifier::visitModuleIdents() {
15090b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
15100b57cec5SDimitry Andric   if (!Idents)
15110b57cec5SDimitry Andric     return;
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
15140b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
15150b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
15160b57cec5SDimitry Andric     Assert(N->getNumOperands() == 1,
15170b57cec5SDimitry Andric            "incorrect number of operands in llvm.ident metadata", N);
15180b57cec5SDimitry Andric     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
15190b57cec5SDimitry Andric            ("invalid value for llvm.ident metadata entry operand"
15200b57cec5SDimitry Andric             "(the operand should be a string)"),
15210b57cec5SDimitry Andric            N->getOperand(0));
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric }
15240b57cec5SDimitry Andric 
1525349cc55cSDimitry Andric void Verifier::visitModuleCommandLines() {
15260b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
15270b57cec5SDimitry Andric   if (!CommandLines)
15280b57cec5SDimitry Andric     return;
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
15310b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
15320b57cec5SDimitry Andric   // requirement is met.
15330b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
15340b57cec5SDimitry Andric     Assert(N->getNumOperands() == 1,
15350b57cec5SDimitry Andric            "incorrect number of operands in llvm.commandline metadata", N);
15360b57cec5SDimitry Andric     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
15370b57cec5SDimitry Andric            ("invalid value for llvm.commandline metadata entry operand"
15380b57cec5SDimitry Andric             "(the operand should be a string)"),
15390b57cec5SDimitry Andric            N->getOperand(0));
15400b57cec5SDimitry Andric   }
15410b57cec5SDimitry Andric }
15420b57cec5SDimitry Andric 
1543349cc55cSDimitry Andric void Verifier::visitModuleFlags() {
15440b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
15450b57cec5SDimitry Andric   if (!Flags) return;
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
15480b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
15490b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
15500b57cec5SDimitry Andric   for (const MDNode *MDN : Flags->operands())
15510b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
15540b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
15550b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
15560b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
15590b57cec5SDimitry Andric     if (!Op) {
15600b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
15610b57cec5SDimitry Andric                   Flag);
15620b57cec5SDimitry Andric       continue;
15630b57cec5SDimitry Andric     }
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
15660b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
15670b57cec5SDimitry Andric                    "flag does not have the required value"),
15680b57cec5SDimitry Andric                   Flag);
15690b57cec5SDimitry Andric       continue;
15700b57cec5SDimitry Andric     }
15710b57cec5SDimitry Andric   }
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric void
15750b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
15760b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
15770b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
15780b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
15790b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
15800b57cec5SDimitry Andric   Assert(Op->getNumOperands() == 3,
15810b57cec5SDimitry Andric          "incorrect number of operands in module flag", Op);
15820b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
15830b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
15840b57cec5SDimitry Andric     Assert(
15850b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
15860b57cec5SDimitry Andric         "invalid behavior operand in module flag (expected constant integer)",
15870b57cec5SDimitry Andric         Op->getOperand(0));
15880b57cec5SDimitry Andric     Assert(false,
15890b57cec5SDimitry Andric            "invalid behavior operand in module flag (unexpected constant)",
15900b57cec5SDimitry Andric            Op->getOperand(0));
15910b57cec5SDimitry Andric   }
15920b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
15930b57cec5SDimitry Andric   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
15940b57cec5SDimitry Andric          Op->getOperand(1));
15950b57cec5SDimitry Andric 
15964824e7fdSDimitry Andric   // Check the values for behaviors with additional requirements.
15970b57cec5SDimitry Andric   switch (MFB) {
15980b57cec5SDimitry Andric   case Module::Error:
15990b57cec5SDimitry Andric   case Module::Warning:
16000b57cec5SDimitry Andric   case Module::Override:
16010b57cec5SDimitry Andric     // These behavior types accept any value.
16020b57cec5SDimitry Andric     break;
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric   case Module::Max: {
16050b57cec5SDimitry Andric     Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
16060b57cec5SDimitry Andric            "invalid value for 'max' module flag (expected constant integer)",
16070b57cec5SDimitry Andric            Op->getOperand(2));
16080b57cec5SDimitry Andric     break;
16090b57cec5SDimitry Andric   }
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   case Module::Require: {
16120b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
16130b57cec5SDimitry Andric     // MDString), and a value.
16140b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
16150b57cec5SDimitry Andric     Assert(Value && Value->getNumOperands() == 2,
16160b57cec5SDimitry Andric            "invalid value for 'require' module flag (expected metadata pair)",
16170b57cec5SDimitry Andric            Op->getOperand(2));
16180b57cec5SDimitry Andric     Assert(isa<MDString>(Value->getOperand(0)),
16190b57cec5SDimitry Andric            ("invalid value for 'require' module flag "
16200b57cec5SDimitry Andric             "(first value operand should be a string)"),
16210b57cec5SDimitry Andric            Value->getOperand(0));
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
16240b57cec5SDimitry Andric     // scanned.
16250b57cec5SDimitry Andric     Requirements.push_back(Value);
16260b57cec5SDimitry Andric     break;
16270b57cec5SDimitry Andric   }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric   case Module::Append:
16300b57cec5SDimitry Andric   case Module::AppendUnique: {
16310b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
16320b57cec5SDimitry Andric     Assert(isa<MDNode>(Op->getOperand(2)),
16330b57cec5SDimitry Andric            "invalid value for 'append'-type module flag "
16340b57cec5SDimitry Andric            "(expected a metadata node)",
16350b57cec5SDimitry Andric            Op->getOperand(2));
16360b57cec5SDimitry Andric     break;
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric   }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
16410b57cec5SDimitry Andric   if (MFB != Module::Require) {
16420b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
16430b57cec5SDimitry Andric     Assert(Inserted,
16440b57cec5SDimitry Andric            "module flag identifiers must be unique (or of 'require' type)", ID);
16450b57cec5SDimitry Andric   }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
16480b57cec5SDimitry Andric     ConstantInt *Value
16490b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
16500b57cec5SDimitry Andric     Assert(Value, "wchar_size metadata requires constant integer argument");
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
16540b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
16550b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
16560b57cec5SDimitry Andric     // have been created by a client directly.
16570b57cec5SDimitry Andric     Assert(M.getNamedMetadata("llvm.linker.options"),
16580b57cec5SDimitry Andric            "'Linker Options' named metadata no longer supported");
16590b57cec5SDimitry Andric   }
16600b57cec5SDimitry Andric 
16615ffd83dbSDimitry Andric   if (ID->getString() == "SemanticInterposition") {
16625ffd83dbSDimitry Andric     ConstantInt *Value =
16635ffd83dbSDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
16645ffd83dbSDimitry Andric     Assert(Value,
16655ffd83dbSDimitry Andric            "SemanticInterposition metadata requires constant integer argument");
16665ffd83dbSDimitry Andric   }
16675ffd83dbSDimitry Andric 
16680b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
16690b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
16700b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
16710b57cec5SDimitry Andric   }
16720b57cec5SDimitry Andric }
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
16750b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
16760b57cec5SDimitry Andric     if (!FuncMDO)
16770b57cec5SDimitry Andric       return;
16780b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1679e8d8bef9SDimitry Andric     Assert(F && isa<Function>(F->getValue()->stripPointerCasts()),
1680e8d8bef9SDimitry Andric            "expected a Function or null", FuncMDO);
16810b57cec5SDimitry Andric   };
16820b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
16830b57cec5SDimitry Andric   Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
16840b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
16850b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
16860b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
16870b57cec5SDimitry Andric   Assert(Count && Count->getType()->isIntegerTy(),
16880b57cec5SDimitry Andric          "expected an integer constant", Node->getOperand(2));
16890b57cec5SDimitry Andric }
16900b57cec5SDimitry Andric 
1691fe6060f1SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
16920b57cec5SDimitry Andric   for (Attribute A : Attrs) {
1693fe6060f1SDimitry Andric 
1694fe6060f1SDimitry Andric     if (A.isStringAttribute()) {
1695fe6060f1SDimitry Andric #define GET_ATTR_NAMES
1696fe6060f1SDimitry Andric #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1697fe6060f1SDimitry Andric #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1698fe6060f1SDimitry Andric   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1699fe6060f1SDimitry Andric     auto V = A.getValueAsString();                                             \
1700fe6060f1SDimitry Andric     if (!(V.empty() || V == "true" || V == "false"))                           \
1701fe6060f1SDimitry Andric       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1702fe6060f1SDimitry Andric                   "");                                                         \
1703fe6060f1SDimitry Andric   }
1704fe6060f1SDimitry Andric 
1705fe6060f1SDimitry Andric #include "llvm/IR/Attributes.inc"
17060b57cec5SDimitry Andric       continue;
1707fe6060f1SDimitry Andric     }
17080b57cec5SDimitry Andric 
1709fe6060f1SDimitry Andric     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
17105ffd83dbSDimitry Andric       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
17115ffd83dbSDimitry Andric                   V);
17125ffd83dbSDimitry Andric       return;
17135ffd83dbSDimitry Andric     }
17140b57cec5SDimitry Andric   }
17150b57cec5SDimitry Andric }
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
17180b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
17190b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
17200b57cec5SDimitry Andric                                     const Value *V) {
17210b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
17220b57cec5SDimitry Andric     return;
17230b57cec5SDimitry Andric 
1724fe6060f1SDimitry Andric   verifyAttributeTypes(Attrs, V);
1725fe6060f1SDimitry Andric 
1726fe6060f1SDimitry Andric   for (Attribute Attr : Attrs)
1727fe6060f1SDimitry Andric     Assert(Attr.isStringAttribute() ||
1728fe6060f1SDimitry Andric            Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
1729fe6060f1SDimitry Andric            "Attribute '" + Attr.getAsString() +
1730fe6060f1SDimitry Andric                "' does not apply to parameters",
1731fe6060f1SDimitry Andric            V);
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
17340b57cec5SDimitry Andric     Assert(Attrs.getNumAttributes() == 1,
17350b57cec5SDimitry Andric            "Attribute 'immarg' is incompatible with other attributes", V);
17360b57cec5SDimitry Andric   }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
17390b57cec5SDimitry Andric   // sret.
17400b57cec5SDimitry Andric   unsigned AttrCount = 0;
17410b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
17420b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
17435ffd83dbSDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
17440b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
17450b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
17460b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1747e8d8bef9SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
17485ffd83dbSDimitry Andric   Assert(AttrCount <= 1,
17495ffd83dbSDimitry Andric          "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1750e8d8bef9SDimitry Andric          "'byref', and 'sret' are incompatible!",
17510b57cec5SDimitry Andric          V);
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
17540b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::ReadOnly)),
17550b57cec5SDimitry Andric          "Attributes "
17560b57cec5SDimitry Andric          "'inalloca and readonly' are incompatible!",
17570b57cec5SDimitry Andric          V);
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
17600b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::Returned)),
17610b57cec5SDimitry Andric          "Attributes "
17620b57cec5SDimitry Andric          "'sret and returned' are incompatible!",
17630b57cec5SDimitry Andric          V);
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
17660b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::SExt)),
17670b57cec5SDimitry Andric          "Attributes "
17680b57cec5SDimitry Andric          "'zeroext and signext' are incompatible!",
17690b57cec5SDimitry Andric          V);
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
17720b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::ReadOnly)),
17730b57cec5SDimitry Andric          "Attributes "
17740b57cec5SDimitry Andric          "'readnone and readonly' are incompatible!",
17750b57cec5SDimitry Andric          V);
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
17780b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::WriteOnly)),
17790b57cec5SDimitry Andric          "Attributes "
17800b57cec5SDimitry Andric          "'readnone and writeonly' are incompatible!",
17810b57cec5SDimitry Andric          V);
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
17840b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::WriteOnly)),
17850b57cec5SDimitry Andric          "Attributes "
17860b57cec5SDimitry Andric          "'readonly and writeonly' are incompatible!",
17870b57cec5SDimitry Andric          V);
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
17900b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::AlwaysInline)),
17910b57cec5SDimitry Andric          "Attributes "
17920b57cec5SDimitry Andric          "'noinline and alwaysinline' are incompatible!",
17930b57cec5SDimitry Andric          V);
17940b57cec5SDimitry Andric 
179504eeddc0SDimitry Andric   AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1796fe6060f1SDimitry Andric   for (Attribute Attr : Attrs) {
1797fe6060f1SDimitry Andric     if (!Attr.isStringAttribute() &&
1798fe6060f1SDimitry Andric         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1799fe6060f1SDimitry Andric       CheckFailed("Attribute '" + Attr.getAsString() +
1800fe6060f1SDimitry Andric                   "' applied to incompatible type!", V);
1801fe6060f1SDimitry Andric       return;
1802fe6060f1SDimitry Andric     }
1803fe6060f1SDimitry Andric   }
18040b57cec5SDimitry Andric 
18050b57cec5SDimitry Andric   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1806fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByVal)) {
18070b57cec5SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
1808fe6060f1SDimitry Andric       Assert(Attrs.getByValType()->isSized(&Visited),
1809fe6060f1SDimitry Andric              "Attribute 'byval' does not support unsized types!", V);
18100b57cec5SDimitry Andric     }
1811fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByRef)) {
1812fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
1813fe6060f1SDimitry Andric       Assert(Attrs.getByRefType()->isSized(&Visited),
1814fe6060f1SDimitry Andric              "Attribute 'byref' does not support unsized types!", V);
1815fe6060f1SDimitry Andric     }
1816fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::InAlloca)) {
1817fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
1818fe6060f1SDimitry Andric       Assert(Attrs.getInAllocaType()->isSized(&Visited),
1819fe6060f1SDimitry Andric              "Attribute 'inalloca' does not support unsized types!", V);
1820fe6060f1SDimitry Andric     }
1821fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::Preallocated)) {
1822fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
1823fe6060f1SDimitry Andric       Assert(Attrs.getPreallocatedType()->isSized(&Visited),
1824fe6060f1SDimitry Andric              "Attribute 'preallocated' does not support unsized types!", V);
1825fe6060f1SDimitry Andric     }
1826fe6060f1SDimitry Andric     if (!PTy->isOpaque()) {
182704eeddc0SDimitry Andric       if (!isa<PointerType>(PTy->getNonOpaquePointerElementType()))
18280b57cec5SDimitry Andric         Assert(!Attrs.hasAttribute(Attribute::SwiftError),
18290b57cec5SDimitry Andric                "Attribute 'swifterror' only applies to parameters "
18300b57cec5SDimitry Andric                "with pointer to pointer type!",
18310b57cec5SDimitry Andric                V);
1832e8d8bef9SDimitry Andric       if (Attrs.hasAttribute(Attribute::ByRef)) {
183304eeddc0SDimitry Andric         Assert(Attrs.getByRefType() == PTy->getNonOpaquePointerElementType(),
1834e8d8bef9SDimitry Andric                "Attribute 'byref' type does not match parameter!", V);
1835e8d8bef9SDimitry Andric       }
1836e8d8bef9SDimitry Andric 
1837e8d8bef9SDimitry Andric       if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
183804eeddc0SDimitry Andric         Assert(Attrs.getByValType() == PTy->getNonOpaquePointerElementType(),
1839e8d8bef9SDimitry Andric                "Attribute 'byval' type does not match parameter!", V);
1840e8d8bef9SDimitry Andric       }
1841e8d8bef9SDimitry Andric 
1842e8d8bef9SDimitry Andric       if (Attrs.hasAttribute(Attribute::Preallocated)) {
184304eeddc0SDimitry Andric         Assert(Attrs.getPreallocatedType() ==
184404eeddc0SDimitry Andric                    PTy->getNonOpaquePointerElementType(),
1845e8d8bef9SDimitry Andric                "Attribute 'preallocated' type does not match parameter!", V);
1846e8d8bef9SDimitry Andric       }
1847fe6060f1SDimitry Andric 
1848fe6060f1SDimitry Andric       if (Attrs.hasAttribute(Attribute::InAlloca)) {
184904eeddc0SDimitry Andric         Assert(Attrs.getInAllocaType() == PTy->getNonOpaquePointerElementType(),
1850fe6060f1SDimitry Andric                "Attribute 'inalloca' type does not match parameter!", V);
1851fe6060f1SDimitry Andric       }
1852fe6060f1SDimitry Andric 
1853fe6060f1SDimitry Andric       if (Attrs.hasAttribute(Attribute::ElementType)) {
185404eeddc0SDimitry Andric         Assert(Attrs.getElementType() == PTy->getNonOpaquePointerElementType(),
1855fe6060f1SDimitry Andric                "Attribute 'elementtype' type does not match parameter!", V);
1856fe6060f1SDimitry Andric       }
1857fe6060f1SDimitry Andric     }
1858fe6060f1SDimitry Andric   }
1859fe6060f1SDimitry Andric }
1860fe6060f1SDimitry Andric 
1861fe6060f1SDimitry Andric void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1862fe6060f1SDimitry Andric                                             const Value *V) {
1863349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attr)) {
1864349cc55cSDimitry Andric     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1865fe6060f1SDimitry Andric     unsigned N;
1866fe6060f1SDimitry Andric     if (S.getAsInteger(10, N))
1867fe6060f1SDimitry Andric       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
18680b57cec5SDimitry Andric   }
18690b57cec5SDimitry Andric }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric // Check parameter attributes against a function type.
18720b57cec5SDimitry Andric // The value V is printed in error messages.
18730b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
187404eeddc0SDimitry Andric                                    const Value *V, bool IsIntrinsic,
187504eeddc0SDimitry Andric                                    bool IsInlineAsm) {
18760b57cec5SDimitry Andric   if (Attrs.isEmpty())
18770b57cec5SDimitry Andric     return;
18780b57cec5SDimitry Andric 
1879fe6060f1SDimitry Andric   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
1880fe6060f1SDimitry Andric     Assert(Attrs.hasParentContext(Context),
1881fe6060f1SDimitry Andric            "Attribute list does not match Module context!", &Attrs, V);
1882fe6060f1SDimitry Andric     for (const auto &AttrSet : Attrs) {
1883fe6060f1SDimitry Andric       Assert(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
1884fe6060f1SDimitry Andric              "Attribute set does not match Module context!", &AttrSet, V);
1885fe6060f1SDimitry Andric       for (const auto &A : AttrSet) {
1886fe6060f1SDimitry Andric         Assert(A.hasParentContext(Context),
1887fe6060f1SDimitry Andric                "Attribute does not match Module context!", &A, V);
1888fe6060f1SDimitry Andric       }
1889fe6060f1SDimitry Andric     }
1890fe6060f1SDimitry Andric   }
1891fe6060f1SDimitry Andric 
18920b57cec5SDimitry Andric   bool SawNest = false;
18930b57cec5SDimitry Andric   bool SawReturned = false;
18940b57cec5SDimitry Andric   bool SawSRet = false;
18950b57cec5SDimitry Andric   bool SawSwiftSelf = false;
1896fe6060f1SDimitry Andric   bool SawSwiftAsync = false;
18970b57cec5SDimitry Andric   bool SawSwiftError = false;
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric   // Verify return value attributes.
1900349cc55cSDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttrs();
1901fe6060f1SDimitry Andric   for (Attribute RetAttr : RetAttrs)
1902fe6060f1SDimitry Andric     Assert(RetAttr.isStringAttribute() ||
1903fe6060f1SDimitry Andric            Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
1904fe6060f1SDimitry Andric            "Attribute '" + RetAttr.getAsString() +
1905fe6060f1SDimitry Andric                "' does not apply to function return values",
19060b57cec5SDimitry Andric            V);
1907fe6060f1SDimitry Andric 
19080b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric   // Verify parameter attributes.
19110b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
19120b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
1913349cc55cSDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric     if (!IsIntrinsic) {
19160b57cec5SDimitry Andric       Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),
19170b57cec5SDimitry Andric              "immarg attribute only applies to intrinsics",V);
191804eeddc0SDimitry Andric       if (!IsInlineAsm)
1919fe6060f1SDimitry Andric         Assert(!ArgAttrs.hasAttribute(Attribute::ElementType),
192004eeddc0SDimitry Andric                "Attribute 'elementtype' can only be applied to intrinsics"
192104eeddc0SDimitry Andric                " and inline asm.", V);
19220b57cec5SDimitry Andric     }
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
19270b57cec5SDimitry Andric       Assert(!SawNest, "More than one parameter has attribute nest!", V);
19280b57cec5SDimitry Andric       SawNest = true;
19290b57cec5SDimitry Andric     }
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
19320b57cec5SDimitry Andric       Assert(!SawReturned, "More than one parameter has attribute returned!",
19330b57cec5SDimitry Andric              V);
19340b57cec5SDimitry Andric       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
19350b57cec5SDimitry Andric              "Incompatible argument and return types for 'returned' attribute",
19360b57cec5SDimitry Andric              V);
19370b57cec5SDimitry Andric       SawReturned = true;
19380b57cec5SDimitry Andric     }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
19410b57cec5SDimitry Andric       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
19420b57cec5SDimitry Andric       Assert(i == 0 || i == 1,
19430b57cec5SDimitry Andric              "Attribute 'sret' is not on first or second parameter!", V);
19440b57cec5SDimitry Andric       SawSRet = true;
19450b57cec5SDimitry Andric     }
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
19480b57cec5SDimitry Andric       Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
19490b57cec5SDimitry Andric       SawSwiftSelf = true;
19500b57cec5SDimitry Andric     }
19510b57cec5SDimitry Andric 
1952fe6060f1SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
1953fe6060f1SDimitry Andric       Assert(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
1954fe6060f1SDimitry Andric       SawSwiftAsync = true;
1955fe6060f1SDimitry Andric     }
1956fe6060f1SDimitry Andric 
19570b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
19580b57cec5SDimitry Andric       Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
19590b57cec5SDimitry Andric              V);
19600b57cec5SDimitry Andric       SawSwiftError = true;
19610b57cec5SDimitry Andric     }
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
19640b57cec5SDimitry Andric       Assert(i == FT->getNumParams() - 1,
19650b57cec5SDimitry Andric              "inalloca isn't on the last parameter!", V);
19660b57cec5SDimitry Andric     }
19670b57cec5SDimitry Andric   }
19680b57cec5SDimitry Andric 
1969349cc55cSDimitry Andric   if (!Attrs.hasFnAttrs())
19700b57cec5SDimitry Andric     return;
19710b57cec5SDimitry Andric 
1972349cc55cSDimitry Andric   verifyAttributeTypes(Attrs.getFnAttrs(), V);
1973349cc55cSDimitry Andric   for (Attribute FnAttr : Attrs.getFnAttrs())
1974fe6060f1SDimitry Andric     Assert(FnAttr.isStringAttribute() ||
1975fe6060f1SDimitry Andric            Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
1976fe6060f1SDimitry Andric            "Attribute '" + FnAttr.getAsString() +
1977fe6060f1SDimitry Andric                "' does not apply to functions!",
1978fe6060f1SDimitry Andric            V);
19790b57cec5SDimitry Andric 
1980349cc55cSDimitry Andric   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1981349cc55cSDimitry Andric            Attrs.hasFnAttr(Attribute::ReadOnly)),
19820b57cec5SDimitry Andric          "Attributes 'readnone and readonly' are incompatible!", V);
19830b57cec5SDimitry Andric 
1984349cc55cSDimitry Andric   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1985349cc55cSDimitry Andric            Attrs.hasFnAttr(Attribute::WriteOnly)),
19860b57cec5SDimitry Andric          "Attributes 'readnone and writeonly' are incompatible!", V);
19870b57cec5SDimitry Andric 
1988349cc55cSDimitry Andric   Assert(!(Attrs.hasFnAttr(Attribute::ReadOnly) &&
1989349cc55cSDimitry Andric            Attrs.hasFnAttr(Attribute::WriteOnly)),
19900b57cec5SDimitry Andric          "Attributes 'readonly and writeonly' are incompatible!", V);
19910b57cec5SDimitry Andric 
1992349cc55cSDimitry Andric   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1993349cc55cSDimitry Andric            Attrs.hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly)),
19940b57cec5SDimitry Andric          "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
19950b57cec5SDimitry Andric          "incompatible!",
19960b57cec5SDimitry Andric          V);
19970b57cec5SDimitry Andric 
1998349cc55cSDimitry Andric   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1999349cc55cSDimitry Andric            Attrs.hasFnAttr(Attribute::InaccessibleMemOnly)),
20000b57cec5SDimitry Andric          "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
20010b57cec5SDimitry Andric 
2002349cc55cSDimitry Andric   Assert(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2003349cc55cSDimitry Andric            Attrs.hasFnAttr(Attribute::AlwaysInline)),
20040b57cec5SDimitry Andric          "Attributes 'noinline and alwaysinline' are incompatible!", V);
20050b57cec5SDimitry Andric 
2006349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2007349cc55cSDimitry Andric     Assert(Attrs.hasFnAttr(Attribute::NoInline),
20080b57cec5SDimitry Andric            "Attribute 'optnone' requires 'noinline'!", V);
20090b57cec5SDimitry Andric 
2010349cc55cSDimitry Andric     Assert(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
20110b57cec5SDimitry Andric            "Attributes 'optsize and optnone' are incompatible!", V);
20120b57cec5SDimitry Andric 
2013349cc55cSDimitry Andric     Assert(!Attrs.hasFnAttr(Attribute::MinSize),
20140b57cec5SDimitry Andric            "Attributes 'minsize and optnone' are incompatible!", V);
20150b57cec5SDimitry Andric   }
20160b57cec5SDimitry Andric 
2017349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
20180b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
20190b57cec5SDimitry Andric     Assert(GV->hasGlobalUnnamedAddr(),
20200b57cec5SDimitry Andric            "Attribute 'jumptable' requires 'unnamed_addr'", V);
20210b57cec5SDimitry Andric   }
20220b57cec5SDimitry Andric 
2023349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::AllocSize)) {
20240b57cec5SDimitry Andric     std::pair<unsigned, Optional<unsigned>> Args =
2025349cc55cSDimitry Andric         Attrs.getFnAttrs().getAllocSizeArgs();
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
20280b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
20290b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
20300b57cec5SDimitry Andric         return false;
20310b57cec5SDimitry Andric       }
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
20340b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
20350b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
20360b57cec5SDimitry Andric                     V);
20370b57cec5SDimitry Andric         return false;
20380b57cec5SDimitry Andric       }
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric       return true;
20410b57cec5SDimitry Andric     };
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric     if (!CheckParam("element size", Args.first))
20440b57cec5SDimitry Andric       return;
20450b57cec5SDimitry Andric 
20460b57cec5SDimitry Andric     if (Args.second && !CheckParam("number of elements", *Args.second))
20470b57cec5SDimitry Andric       return;
20480b57cec5SDimitry Andric   }
2049480093f4SDimitry Andric 
2050349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
20510eae32dcSDimitry Andric     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
20520eae32dcSDimitry Andric     if (VScaleMin == 0)
20530eae32dcSDimitry Andric       CheckFailed("'vscale_range' minimum must be greater than 0", V);
2054fe6060f1SDimitry Andric 
20550eae32dcSDimitry Andric     Optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
20560eae32dcSDimitry Andric     if (VScaleMax && VScaleMin > VScaleMax)
2057fe6060f1SDimitry Andric       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2058fe6060f1SDimitry Andric   }
2059fe6060f1SDimitry Andric 
2060349cc55cSDimitry Andric   if (Attrs.hasFnAttr("frame-pointer")) {
2061349cc55cSDimitry Andric     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2062480093f4SDimitry Andric     if (FP != "all" && FP != "non-leaf" && FP != "none")
2063480093f4SDimitry Andric       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2064480093f4SDimitry Andric   }
2065480093f4SDimitry Andric 
2066fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2067fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2068fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
20690b57cec5SDimitry Andric }
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
20720b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
20730b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
20740b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
20750b57cec5SDimitry Andric       MDNode *MD = Pair.second;
20760b57cec5SDimitry Andric       Assert(MD->getNumOperands() >= 2,
20770b57cec5SDimitry Andric              "!prof annotations should have no less than 2 operands", MD);
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric       // Check first operand.
20800b57cec5SDimitry Andric       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
20810b57cec5SDimitry Andric              MD);
20820b57cec5SDimitry Andric       Assert(isa<MDString>(MD->getOperand(0)),
20830b57cec5SDimitry Andric              "expected string with name of the !prof annotation", MD);
20840b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
20850b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
20860b57cec5SDimitry Andric       Assert(ProfName.equals("function_entry_count") ||
20870b57cec5SDimitry Andric                  ProfName.equals("synthetic_function_entry_count"),
20880b57cec5SDimitry Andric              "first operand should be 'function_entry_count'"
20890b57cec5SDimitry Andric              " or 'synthetic_function_entry_count'",
20900b57cec5SDimitry Andric              MD);
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric       // Check second operand.
20930b57cec5SDimitry Andric       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
20940b57cec5SDimitry Andric              MD);
20950b57cec5SDimitry Andric       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
20960b57cec5SDimitry Andric              "expected integer argument to function_entry_count", MD);
20970b57cec5SDimitry Andric     }
20980b57cec5SDimitry Andric   }
20990b57cec5SDimitry Andric }
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
21020b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
21030b57cec5SDimitry Andric     return;
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
21060b57cec5SDimitry Andric   Stack.push_back(EntryC);
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric   while (!Stack.empty()) {
21090b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric     // Check this constant expression.
21120b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
21130b57cec5SDimitry Andric       visitConstantExpr(CE);
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
21160b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
21170b57cec5SDimitry Andric       // that the global value is in the correct module
21180b57cec5SDimitry Andric       Assert(GV->getParent() == &M, "Referencing global in another module!",
21190b57cec5SDimitry Andric              EntryC, &M, GV, GV->getParent());
21200b57cec5SDimitry Andric       continue;
21210b57cec5SDimitry Andric     }
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric     // Visit all sub-expressions.
21240b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
21250b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
21260b57cec5SDimitry Andric       if (!OpC)
21270b57cec5SDimitry Andric         continue;
21280b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
21290b57cec5SDimitry Andric         continue;
21300b57cec5SDimitry Andric       Stack.push_back(OpC);
21310b57cec5SDimitry Andric     }
21320b57cec5SDimitry Andric   }
21330b57cec5SDimitry Andric }
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
21360b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
21370b57cec5SDimitry Andric     Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
21380b57cec5SDimitry Andric                                  CE->getType()),
21390b57cec5SDimitry Andric            "Invalid bitcast", CE);
21400b57cec5SDimitry Andric }
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
21430b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
21440b57cec5SDimitry Andric   // function and return value.
21450b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
21460b57cec5SDimitry Andric }
21470b57cec5SDimitry Andric 
214804eeddc0SDimitry Andric void Verifier::verifyInlineAsmCall(const CallBase &Call) {
214904eeddc0SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
215004eeddc0SDimitry Andric   unsigned ArgNo = 0;
215104eeddc0SDimitry Andric   for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
215204eeddc0SDimitry Andric     // Only deal with constraints that correspond to call arguments.
215304eeddc0SDimitry Andric     if (!CI.hasArg())
215404eeddc0SDimitry Andric       continue;
215504eeddc0SDimitry Andric 
215604eeddc0SDimitry Andric     if (CI.isIndirect) {
215704eeddc0SDimitry Andric       const Value *Arg = Call.getArgOperand(ArgNo);
215804eeddc0SDimitry Andric       Assert(Arg->getType()->isPointerTy(),
215904eeddc0SDimitry Andric              "Operand for indirect constraint must have pointer type",
216004eeddc0SDimitry Andric              &Call);
216104eeddc0SDimitry Andric 
216204eeddc0SDimitry Andric       Assert(Call.getAttributes().getParamElementType(ArgNo),
216304eeddc0SDimitry Andric              "Operand for indirect constraint must have elementtype attribute",
216404eeddc0SDimitry Andric              &Call);
216504eeddc0SDimitry Andric     } else {
216604eeddc0SDimitry Andric       Assert(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
216704eeddc0SDimitry Andric              "Elementtype attribute can only be applied for indirect "
216804eeddc0SDimitry Andric              "constraints", &Call);
216904eeddc0SDimitry Andric     }
217004eeddc0SDimitry Andric 
217104eeddc0SDimitry Andric     ArgNo++;
217204eeddc0SDimitry Andric   }
217304eeddc0SDimitry Andric }
217404eeddc0SDimitry Andric 
21750b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
21760b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
21770b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
21780b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
21790b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
21820b57cec5SDimitry Andric              !Call.onlyAccessesArgMemory(),
21830b57cec5SDimitry Andric          "gc.statepoint must read and write all memory to preserve "
21840b57cec5SDimitry Andric          "reordering restrictions required by safepoint semantics",
21850b57cec5SDimitry Andric          Call);
21860b57cec5SDimitry Andric 
21870b57cec5SDimitry Andric   const int64_t NumPatchBytes =
21880b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
21890b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
21900b57cec5SDimitry Andric   Assert(NumPatchBytes >= 0,
21910b57cec5SDimitry Andric          "gc.statepoint number of patchable bytes must be "
21920b57cec5SDimitry Andric          "positive",
21930b57cec5SDimitry Andric          Call);
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric   const Value *Target = Call.getArgOperand(2);
21960b57cec5SDimitry Andric   auto *PT = dyn_cast<PointerType>(Target->getType());
219704eeddc0SDimitry Andric   Assert(PT && PT->getPointerElementType()->isFunctionTy(),
21980b57cec5SDimitry Andric          "gc.statepoint callee must be of function pointer type", Call, Target);
219904eeddc0SDimitry Andric   FunctionType *TargetFuncType =
220004eeddc0SDimitry Andric       cast<FunctionType>(PT->getPointerElementType());
22010b57cec5SDimitry Andric 
22020b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
22030b57cec5SDimitry Andric   Assert(NumCallArgs >= 0,
22040b57cec5SDimitry Andric          "gc.statepoint number of arguments to underlying call "
22050b57cec5SDimitry Andric          "must be positive",
22060b57cec5SDimitry Andric          Call);
22070b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
22080b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
22090b57cec5SDimitry Andric     Assert(NumCallArgs >= NumParams,
22100b57cec5SDimitry Andric            "gc.statepoint mismatch in number of vararg call args", Call);
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric     // TODO: Remove this limitation
22130b57cec5SDimitry Andric     Assert(TargetFuncType->getReturnType()->isVoidTy(),
22140b57cec5SDimitry Andric            "gc.statepoint doesn't support wrapping non-void "
22150b57cec5SDimitry Andric            "vararg functions yet",
22160b57cec5SDimitry Andric            Call);
22170b57cec5SDimitry Andric   } else
22180b57cec5SDimitry Andric     Assert(NumCallArgs == NumParams,
22190b57cec5SDimitry Andric            "gc.statepoint mismatch in number of call args", Call);
22200b57cec5SDimitry Andric 
22210b57cec5SDimitry Andric   const uint64_t Flags
22220b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
22230b57cec5SDimitry Andric   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
22240b57cec5SDimitry Andric          "unknown flag used in gc.statepoint flags argument", Call);
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
22270b57cec5SDimitry Andric   // the type of the wrapped callee.
22280b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
22290b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
22300b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
22310b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
22320b57cec5SDimitry Andric     Assert(ArgType == ParamType,
22330b57cec5SDimitry Andric            "gc.statepoint call argument does not match wrapped "
22340b57cec5SDimitry Andric            "function type",
22350b57cec5SDimitry Andric            Call);
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
2238349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
22390b57cec5SDimitry Andric       Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
22400b57cec5SDimitry Andric              "Attribute 'sret' cannot be used for vararg call arguments!",
22410b57cec5SDimitry Andric              Call);
22420b57cec5SDimitry Andric     }
22430b57cec5SDimitry Andric   }
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
22480b57cec5SDimitry Andric   Assert(isa<ConstantInt>(NumTransitionArgsV),
22490b57cec5SDimitry Andric          "gc.statepoint number of transition arguments "
22500b57cec5SDimitry Andric          "must be constant integer",
22510b57cec5SDimitry Andric          Call);
22520b57cec5SDimitry Andric   const int NumTransitionArgs =
22530b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
22545ffd83dbSDimitry Andric   Assert(NumTransitionArgs == 0,
2255e8d8bef9SDimitry Andric          "gc.statepoint w/inline transition bundle is deprecated", Call);
2256e8d8bef9SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
22575ffd83dbSDimitry Andric 
22580b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
22590b57cec5SDimitry Andric   Assert(isa<ConstantInt>(NumDeoptArgsV),
22600b57cec5SDimitry Andric          "gc.statepoint number of deoptimization arguments "
22610b57cec5SDimitry Andric          "must be constant integer",
22620b57cec5SDimitry Andric          Call);
22630b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
22645ffd83dbSDimitry Andric   Assert(NumDeoptArgs == 0,
2265e8d8bef9SDimitry Andric          "gc.statepoint w/inline deopt operands is deprecated", Call);
22665ffd83dbSDimitry Andric 
2267e8d8bef9SDimitry Andric   const int ExpectedNumArgs = 7 + NumCallArgs;
2268e8d8bef9SDimitry Andric   Assert(ExpectedNumArgs == (int)Call.arg_size(),
2269e8d8bef9SDimitry Andric          "gc.statepoint too many arguments", Call);
22700b57cec5SDimitry Andric 
22710b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
22720b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
22730b57cec5SDimitry Andric   // of the same statepoint sequence
22740b57cec5SDimitry Andric   for (const User *U : Call.users()) {
22750b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
22760b57cec5SDimitry Andric     Assert(UserCall, "illegal use of statepoint token", Call, U);
22770b57cec5SDimitry Andric     if (!UserCall)
22780b57cec5SDimitry Andric       continue;
22790b57cec5SDimitry Andric     Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
22800b57cec5SDimitry Andric            "gc.result or gc.relocate are the only value uses "
22810b57cec5SDimitry Andric            "of a gc.statepoint",
22820b57cec5SDimitry Andric            Call, U);
22830b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
22840b57cec5SDimitry Andric       Assert(UserCall->getArgOperand(0) == &Call,
22850b57cec5SDimitry Andric              "gc.result connected to wrong gc.statepoint", Call, UserCall);
22860b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
22870b57cec5SDimitry Andric       Assert(UserCall->getArgOperand(0) == &Call,
22880b57cec5SDimitry Andric              "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
22890b57cec5SDimitry Andric     }
22900b57cec5SDimitry Andric   }
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
22930b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
22940b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
22950b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
22960b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
22970b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
22980b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
22990b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
23000b57cec5SDimitry Andric }
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
23030b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
23040b57cec5SDimitry Andric     Function *F = Counts.first;
23050b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
23060b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
23070b57cec5SDimitry Andric     Assert(MaxRecoveredIndex <= EscapedObjectCount,
23080b57cec5SDimitry Andric            "all indices passed to llvm.localrecover must be less than the "
23090b57cec5SDimitry Andric            "number of arguments passed to llvm.localescape in the parent "
23100b57cec5SDimitry Andric            "function",
23110b57cec5SDimitry Andric            F);
23120b57cec5SDimitry Andric   }
23130b57cec5SDimitry Andric }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
23160b57cec5SDimitry Andric   BasicBlock *UnwindDest;
23170b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
23180b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
23190b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
23200b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
23210b57cec5SDimitry Andric   else
23220b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
23230b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
23240b57cec5SDimitry Andric }
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
23270b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
23280b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
23290b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
23300b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
23310b57cec5SDimitry Andric     if (Visited.count(PredPad))
23320b57cec5SDimitry Andric       continue;
23330b57cec5SDimitry Andric     Active.insert(PredPad);
23340b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
23350b57cec5SDimitry Andric     do {
23360b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
23370b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
23380b57cec5SDimitry Andric         // Found a cycle; report error
23390b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
23400b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
23410b57cec5SDimitry Andric         do {
23420b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
23430b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
23440b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
23450b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
23460b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
23470b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
23480b57cec5SDimitry Andric         Assert(false, "EH pads can't handle each other's exceptions",
23490b57cec5SDimitry Andric                ArrayRef<Instruction *>(CycleNodes));
23500b57cec5SDimitry Andric       }
23510b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
23520b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
23530b57cec5SDimitry Andric         break;
23540b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
23550b57cec5SDimitry Andric       PredPad = SuccPad;
23560b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
23570b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
23580b57cec5SDimitry Andric         break;
23590b57cec5SDimitry Andric       Terminator = TermI->second;
23600b57cec5SDimitry Andric       Active.insert(PredPad);
23610b57cec5SDimitry Andric     } while (true);
23620b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
23630b57cec5SDimitry Andric     // nodes' successors.
23640b57cec5SDimitry Andric     Active.clear();
23650b57cec5SDimitry Andric   }
23660b57cec5SDimitry Andric }
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
23690b57cec5SDimitry Andric //
23700b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
23710b57cec5SDimitry Andric   visitGlobalValue(F);
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric   // Check function arguments.
23740b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
23750b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric   Assert(&Context == &F.getContext(),
23780b57cec5SDimitry Andric          "Function context does not match Module context!", &F);
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
23810b57cec5SDimitry Andric   Assert(FT->getNumParams() == NumArgs,
23820b57cec5SDimitry Andric          "# formal arguments must match # of arguments for function type!", &F,
23830b57cec5SDimitry Andric          FT);
23840b57cec5SDimitry Andric   Assert(F.getReturnType()->isFirstClassType() ||
23850b57cec5SDimitry Andric              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
23860b57cec5SDimitry Andric          "Functions cannot return aggregate values!", &F);
23870b57cec5SDimitry Andric 
23880b57cec5SDimitry Andric   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
23890b57cec5SDimitry Andric          "Invalid struct return type!", &F);
23900b57cec5SDimitry Andric 
23910b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric   Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
23940b57cec5SDimitry Andric          "Attribute after last parameter!", &F);
23950b57cec5SDimitry Andric 
2396fe6060f1SDimitry Andric   bool IsIntrinsic = F.isIntrinsic();
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric   // Check function attributes.
239904eeddc0SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
24000b57cec5SDimitry Andric 
24010b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
24020b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
24030b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
2404349cc55cSDimitry Andric   Assert(!Attrs.hasFnAttr(Attribute::Builtin),
24050b57cec5SDimitry Andric          "Attribute 'builtin' can only be applied to a callsite.", &F);
24060b57cec5SDimitry Andric 
2407fe6060f1SDimitry Andric   Assert(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2408fe6060f1SDimitry Andric          "Attribute 'elementtype' can only be applied to a callsite.", &F);
2409fe6060f1SDimitry Andric 
24100b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
24110b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
24120b57cec5SDimitry Andric   // restrictions can be lifted.
24130b57cec5SDimitry Andric   switch (F.getCallingConv()) {
24140b57cec5SDimitry Andric   default:
24150b57cec5SDimitry Andric   case CallingConv::C:
24160b57cec5SDimitry Andric     break;
2417e8d8bef9SDimitry Andric   case CallingConv::X86_INTR: {
2418349cc55cSDimitry Andric     Assert(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2419e8d8bef9SDimitry Andric            "Calling convention parameter requires byval", &F);
2420e8d8bef9SDimitry Andric     break;
2421e8d8bef9SDimitry Andric   }
24220b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
24230b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
24240b57cec5SDimitry Andric     Assert(F.getReturnType()->isVoidTy(),
24250b57cec5SDimitry Andric            "Calling convention requires void return type", &F);
24260b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
24270b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
24280b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
24290b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
24300b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
24310b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
24320b57cec5SDimitry Andric     Assert(!F.hasStructRetAttr(),
24330b57cec5SDimitry Andric            "Calling convention does not allow sret", &F);
2434e8d8bef9SDimitry Andric     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2435e8d8bef9SDimitry Andric       const unsigned StackAS = DL.getAllocaAddrSpace();
2436e8d8bef9SDimitry Andric       unsigned i = 0;
2437e8d8bef9SDimitry Andric       for (const Argument &Arg : F.args()) {
2438349cc55cSDimitry Andric         Assert(!Attrs.hasParamAttr(i, Attribute::ByVal),
2439e8d8bef9SDimitry Andric                "Calling convention disallows byval", &F);
2440349cc55cSDimitry Andric         Assert(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2441e8d8bef9SDimitry Andric                "Calling convention disallows preallocated", &F);
2442349cc55cSDimitry Andric         Assert(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2443e8d8bef9SDimitry Andric                "Calling convention disallows inalloca", &F);
2444e8d8bef9SDimitry Andric 
2445349cc55cSDimitry Andric         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2446e8d8bef9SDimitry Andric           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2447e8d8bef9SDimitry Andric           // value here.
2448e8d8bef9SDimitry Andric           Assert(Arg.getType()->getPointerAddressSpace() != StackAS,
2449e8d8bef9SDimitry Andric                  "Calling convention disallows stack byref", &F);
2450e8d8bef9SDimitry Andric         }
2451e8d8bef9SDimitry Andric 
2452e8d8bef9SDimitry Andric         ++i;
2453e8d8bef9SDimitry Andric       }
2454e8d8bef9SDimitry Andric     }
2455e8d8bef9SDimitry Andric 
24560b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
24570b57cec5SDimitry Andric   case CallingConv::Fast:
24580b57cec5SDimitry Andric   case CallingConv::Cold:
24590b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
24600b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
24610b57cec5SDimitry Andric   case CallingConv::PTX_Device:
24620b57cec5SDimitry Andric     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
24630b57cec5SDimitry Andric                           "perfect forwarding!",
24640b57cec5SDimitry Andric            &F);
24650b57cec5SDimitry Andric     break;
24660b57cec5SDimitry Andric   }
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
24690b57cec5SDimitry Andric   unsigned i = 0;
24700b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
24710b57cec5SDimitry Andric     Assert(Arg.getType() == FT->getParamType(i),
24720b57cec5SDimitry Andric            "Argument value does not match function argument type!", &Arg,
24730b57cec5SDimitry Andric            FT->getParamType(i));
24740b57cec5SDimitry Andric     Assert(Arg.getType()->isFirstClassType(),
24750b57cec5SDimitry Andric            "Function arguments must have first-class types!", &Arg);
2476fe6060f1SDimitry Andric     if (!IsIntrinsic) {
24770b57cec5SDimitry Andric       Assert(!Arg.getType()->isMetadataTy(),
24780b57cec5SDimitry Andric              "Function takes metadata but isn't an intrinsic", &Arg, &F);
24790b57cec5SDimitry Andric       Assert(!Arg.getType()->isTokenTy(),
24800b57cec5SDimitry Andric              "Function takes token but isn't an intrinsic", &Arg, &F);
2481fe6060f1SDimitry Andric       Assert(!Arg.getType()->isX86_AMXTy(),
2482fe6060f1SDimitry Andric              "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
24830b57cec5SDimitry Andric     }
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
2486349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
24870b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
24880b57cec5SDimitry Andric     }
24890b57cec5SDimitry Andric     ++i;
24900b57cec5SDimitry Andric   }
24910b57cec5SDimitry Andric 
2492fe6060f1SDimitry Andric   if (!IsIntrinsic) {
24930b57cec5SDimitry Andric     Assert(!F.getReturnType()->isTokenTy(),
2494fe6060f1SDimitry Andric            "Function returns a token but isn't an intrinsic", &F);
2495fe6060f1SDimitry Andric     Assert(!F.getReturnType()->isX86_AMXTy(),
2496fe6060f1SDimitry Andric            "Function returns a x86_amx but isn't an intrinsic", &F);
2497fe6060f1SDimitry Andric   }
24980b57cec5SDimitry Andric 
24990b57cec5SDimitry Andric   // Get the function metadata attachments.
25000b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
25010b57cec5SDimitry Andric   F.getAllMetadata(MDs);
25020b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
25030b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric   // Check validity of the personality function
25060b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
25070b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
25080b57cec5SDimitry Andric     if (Per)
25090b57cec5SDimitry Andric       Assert(Per->getParent() == F.getParent(),
25100b57cec5SDimitry Andric              "Referencing personality function in another module!",
25110b57cec5SDimitry Andric              &F, F.getParent(), Per, Per->getParent());
25120b57cec5SDimitry Andric   }
25130b57cec5SDimitry Andric 
25140b57cec5SDimitry Andric   if (F.isMaterializable()) {
25150b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
25160b57cec5SDimitry Andric     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
25170b57cec5SDimitry Andric            MDs.empty() ? nullptr : MDs.front().second);
25180b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
25190b57cec5SDimitry Andric     for (const auto &I : MDs) {
25200b57cec5SDimitry Andric       // This is used for call site debug information.
25210b57cec5SDimitry Andric       AssertDI(I.first != LLVMContext::MD_dbg ||
25220b57cec5SDimitry Andric                    !cast<DISubprogram>(I.second)->isDistinct(),
25230b57cec5SDimitry Andric                "function declaration may only have a unique !dbg attachment",
25240b57cec5SDimitry Andric                &F);
25250b57cec5SDimitry Andric       Assert(I.first != LLVMContext::MD_prof,
25260b57cec5SDimitry Andric              "function declaration may not have a !prof attachment", &F);
25270b57cec5SDimitry Andric 
25280b57cec5SDimitry Andric       // Verify the metadata itself.
25295ffd83dbSDimitry Andric       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
25300b57cec5SDimitry Andric     }
25310b57cec5SDimitry Andric     Assert(!F.hasPersonalityFn(),
25320b57cec5SDimitry Andric            "Function declaration shouldn't have a personality routine", &F);
25330b57cec5SDimitry Andric   } else {
25340b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
25350b57cec5SDimitry Andric     // is not legal to define intrinsics.
2536fe6060f1SDimitry Andric     Assert(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric     // Check the entry node
25390b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
25400b57cec5SDimitry Andric     Assert(pred_empty(Entry),
25410b57cec5SDimitry Andric            "Entry block to function must not have predecessors!", Entry);
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
25440b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
25450b57cec5SDimitry Andric       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
25460b57cec5SDimitry Andric              "blockaddress may not be used with the entry block!", Entry);
25470b57cec5SDimitry Andric     }
25480b57cec5SDimitry Andric 
25490b57cec5SDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
25500b57cec5SDimitry Andric     // Visit metadata attachments.
25510b57cec5SDimitry Andric     for (const auto &I : MDs) {
25520b57cec5SDimitry Andric       // Verify that the attachment is legal.
25535ffd83dbSDimitry Andric       auto AllowLocs = AreDebugLocsAllowed::No;
25540b57cec5SDimitry Andric       switch (I.first) {
25550b57cec5SDimitry Andric       default:
25560b57cec5SDimitry Andric         break;
25570b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
25580b57cec5SDimitry Andric         ++NumDebugAttachments;
25590b57cec5SDimitry Andric         AssertDI(NumDebugAttachments == 1,
25600b57cec5SDimitry Andric                  "function must have a single !dbg attachment", &F, I.second);
25610b57cec5SDimitry Andric         AssertDI(isa<DISubprogram>(I.second),
25620b57cec5SDimitry Andric                  "function !dbg attachment must be a subprogram", &F, I.second);
2563e8d8bef9SDimitry Andric         AssertDI(cast<DISubprogram>(I.second)->isDistinct(),
2564e8d8bef9SDimitry Andric                  "function definition may only have a distinct !dbg attachment",
2565e8d8bef9SDimitry Andric                  &F);
2566e8d8bef9SDimitry Andric 
25670b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
25680b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
25690b57cec5SDimitry Andric         AssertDI(!AttachedTo || AttachedTo == &F,
25700b57cec5SDimitry Andric                  "DISubprogram attached to more than one function", SP, &F);
25710b57cec5SDimitry Andric         AttachedTo = &F;
25725ffd83dbSDimitry Andric         AllowLocs = AreDebugLocsAllowed::Yes;
25730b57cec5SDimitry Andric         break;
25740b57cec5SDimitry Andric       }
25750b57cec5SDimitry Andric       case LLVMContext::MD_prof:
25760b57cec5SDimitry Andric         ++NumProfAttachments;
25770b57cec5SDimitry Andric         Assert(NumProfAttachments == 1,
25780b57cec5SDimitry Andric                "function must have a single !prof attachment", &F, I.second);
25790b57cec5SDimitry Andric         break;
25800b57cec5SDimitry Andric       }
25810b57cec5SDimitry Andric 
25820b57cec5SDimitry Andric       // Verify the metadata itself.
25835ffd83dbSDimitry Andric       visitMDNode(*I.second, AllowLocs);
25840b57cec5SDimitry Andric     }
25850b57cec5SDimitry Andric   }
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
25880b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
25890b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
25900b57cec5SDimitry Andric   // uses.
2591fe6060f1SDimitry Andric   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
25920b57cec5SDimitry Andric     const User *U;
2593349cc55cSDimitry Andric     if (F.hasAddressTaken(&U, false, true, false,
2594349cc55cSDimitry Andric                           /*IgnoreARCAttachedCall=*/true))
25950b57cec5SDimitry Andric       Assert(false, "Invalid user of intrinsic instruction!", U);
25960b57cec5SDimitry Andric   }
25970b57cec5SDimitry Andric 
2598fe6060f1SDimitry Andric   // Check intrinsics' signatures.
2599fe6060f1SDimitry Andric   switch (F.getIntrinsicID()) {
2600fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_base: {
2601fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
2602fe6060f1SDimitry Andric     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2603fe6060f1SDimitry Andric     Assert(isa<PointerType>(F.getReturnType()),
2604fe6060f1SDimitry Andric            "gc.get.pointer.base must return a pointer", F);
2605fe6060f1SDimitry Andric     Assert(FT->getParamType(0) == F.getReturnType(),
2606fe6060f1SDimitry Andric            "gc.get.pointer.base operand and result must be of the same type",
2607fe6060f1SDimitry Andric            F);
2608fe6060f1SDimitry Andric     break;
2609fe6060f1SDimitry Andric   }
2610fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_offset: {
2611fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
2612fe6060f1SDimitry Andric     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2613fe6060f1SDimitry Andric     Assert(isa<PointerType>(FT->getParamType(0)),
2614fe6060f1SDimitry Andric            "gc.get.pointer.offset operand must be a pointer", F);
2615fe6060f1SDimitry Andric     Assert(F.getReturnType()->isIntegerTy(),
2616fe6060f1SDimitry Andric            "gc.get.pointer.offset must return integer", F);
2617fe6060f1SDimitry Andric     break;
2618fe6060f1SDimitry Andric   }
2619fe6060f1SDimitry Andric   }
2620fe6060f1SDimitry Andric 
26210b57cec5SDimitry Andric   auto *N = F.getSubprogram();
26220b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
26230b57cec5SDimitry Andric   if (!HasDebugInfo)
26240b57cec5SDimitry Andric     return;
26250b57cec5SDimitry Andric 
26265ffd83dbSDimitry Andric   // Check that all !dbg attachments lead to back to N.
26270b57cec5SDimitry Andric   //
26280b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
26290b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
26300b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
26310b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
26320b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
26330b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
26340b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
26350b57cec5SDimitry Andric     if (!DL)
26360b57cec5SDimitry Andric       return;
26370b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
26380b57cec5SDimitry Andric       return;
26390b57cec5SDimitry Andric 
26400b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
26410b57cec5SDimitry Andric     AssertDI(Parent && isa<DILocalScope>(Parent),
26420b57cec5SDimitry Andric              "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
26430b57cec5SDimitry Andric              Parent);
26445ffd83dbSDimitry Andric 
26450b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
26465ffd83dbSDimitry Andric     Assert(Scope, "Failed to find DILocalScope", DL);
26475ffd83dbSDimitry Andric 
26485ffd83dbSDimitry Andric     if (!Seen.insert(Scope).second)
26490b57cec5SDimitry Andric       return;
26500b57cec5SDimitry Andric 
26515ffd83dbSDimitry Andric     DISubprogram *SP = Scope->getSubprogram();
26520b57cec5SDimitry Andric 
26530b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
26540b57cec5SDimitry Andric     // validation in that case
26550b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
26560b57cec5SDimitry Andric       return;
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric     AssertDI(SP->describes(&F),
26590b57cec5SDimitry Andric              "!dbg attachment points at wrong subprogram for function", N, &F,
26600b57cec5SDimitry Andric              &I, DL, Scope, SP);
26610b57cec5SDimitry Andric   };
26620b57cec5SDimitry Andric   for (auto &BB : F)
26630b57cec5SDimitry Andric     for (auto &I : BB) {
26640b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
26650b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
26660b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
26670b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
26680b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
26690b57cec5SDimitry Andric       if (BrokenDebugInfo)
26700b57cec5SDimitry Andric         return;
26710b57cec5SDimitry Andric     }
26720b57cec5SDimitry Andric }
26730b57cec5SDimitry Andric 
26740b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
26750b57cec5SDimitry Andric //
26760b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
26770b57cec5SDimitry Andric   InstsInThisBlock.clear();
26780b57cec5SDimitry Andric 
26790b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
26800b57cec5SDimitry Andric   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
26810b57cec5SDimitry Andric 
26820b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
26830b57cec5SDimitry Andric   // it.
26840b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
2685e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
26860b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
26870b57cec5SDimitry Andric     llvm::sort(Preds);
26880b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
26890b57cec5SDimitry Andric       Assert(PN.getNumIncomingValues() == Preds.size(),
26900b57cec5SDimitry Andric              "PHINode should have one entry for each predecessor of its "
26910b57cec5SDimitry Andric              "parent basic block!",
26920b57cec5SDimitry Andric              &PN);
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
26950b57cec5SDimitry Andric       Values.clear();
26960b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
26970b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
26980b57cec5SDimitry Andric         Values.push_back(
26990b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
27000b57cec5SDimitry Andric       llvm::sort(Values);
27010b57cec5SDimitry Andric 
27020b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
27030b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
27040b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
27050b57cec5SDimitry Andric         // all identical.
27060b57cec5SDimitry Andric         //
27070b57cec5SDimitry Andric         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
27080b57cec5SDimitry Andric                    Values[i].second == Values[i - 1].second,
27090b57cec5SDimitry Andric                "PHI node has multiple entries for the same basic block with "
27100b57cec5SDimitry Andric                "different incoming values!",
27110b57cec5SDimitry Andric                &PN, Values[i].first, Values[i].second, Values[i - 1].second);
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
27140b57cec5SDimitry Andric         // matched up.
27150b57cec5SDimitry Andric         Assert(Values[i].first == Preds[i],
27160b57cec5SDimitry Andric                "PHI node entries do not match predecessors!", &PN,
27170b57cec5SDimitry Andric                Values[i].first, Preds[i]);
27180b57cec5SDimitry Andric       }
27190b57cec5SDimitry Andric     }
27200b57cec5SDimitry Andric   }
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
27230b57cec5SDimitry Andric   for (auto &I : BB)
27240b57cec5SDimitry Andric   {
27250b57cec5SDimitry Andric     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
27260b57cec5SDimitry Andric   }
27270b57cec5SDimitry Andric }
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
27300b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
27310b57cec5SDimitry Andric   Assert(&I == I.getParent()->getTerminator(),
27320b57cec5SDimitry Andric          "Terminator found in the middle of a basic block!", I.getParent());
27330b57cec5SDimitry Andric   visitInstruction(I);
27340b57cec5SDimitry Andric }
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
27370b57cec5SDimitry Andric   if (BI.isConditional()) {
27380b57cec5SDimitry Andric     Assert(BI.getCondition()->getType()->isIntegerTy(1),
27390b57cec5SDimitry Andric            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
27400b57cec5SDimitry Andric   }
27410b57cec5SDimitry Andric   visitTerminator(BI);
27420b57cec5SDimitry Andric }
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
27450b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
27460b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
27470b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
27480b57cec5SDimitry Andric     Assert(N == 0,
27490b57cec5SDimitry Andric            "Found return instr that returns non-void in Function of void "
27500b57cec5SDimitry Andric            "return type!",
27510b57cec5SDimitry Andric            &RI, F->getReturnType());
27520b57cec5SDimitry Andric   else
27530b57cec5SDimitry Andric     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
27540b57cec5SDimitry Andric            "Function return type does not match operand "
27550b57cec5SDimitry Andric            "type of return inst!",
27560b57cec5SDimitry Andric            &RI, F->getReturnType());
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
27590b57cec5SDimitry Andric   // terminators...
27600b57cec5SDimitry Andric   visitTerminator(RI);
27610b57cec5SDimitry Andric }
27620b57cec5SDimitry Andric 
27630b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
2764349cc55cSDimitry Andric   Assert(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
27650b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
27660b57cec5SDimitry Andric   // have the same type as the switched-on value.
27670b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
27680b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
27690b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
27700b57cec5SDimitry Andric     Assert(Case.getCaseValue()->getType() == SwitchTy,
27710b57cec5SDimitry Andric            "Switch constants must all be same type as switch value!", &SI);
27720b57cec5SDimitry Andric     Assert(Constants.insert(Case.getCaseValue()).second,
27730b57cec5SDimitry Andric            "Duplicate integer as switch case", &SI, Case.getCaseValue());
27740b57cec5SDimitry Andric   }
27750b57cec5SDimitry Andric 
27760b57cec5SDimitry Andric   visitTerminator(SI);
27770b57cec5SDimitry Andric }
27780b57cec5SDimitry Andric 
27790b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
27800b57cec5SDimitry Andric   Assert(BI.getAddress()->getType()->isPointerTy(),
27810b57cec5SDimitry Andric          "Indirectbr operand must have pointer type!", &BI);
27820b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
27830b57cec5SDimitry Andric     Assert(BI.getDestination(i)->getType()->isLabelTy(),
27840b57cec5SDimitry Andric            "Indirectbr destinations must all have pointer type!", &BI);
27850b57cec5SDimitry Andric 
27860b57cec5SDimitry Andric   visitTerminator(BI);
27870b57cec5SDimitry Andric }
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
27900b57cec5SDimitry Andric   Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
27910b57cec5SDimitry Andric          &CBI);
2792fe6060f1SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2793fe6060f1SDimitry Andric   Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed");
27940b57cec5SDimitry Andric   for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
27950b57cec5SDimitry Andric     Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
27960b57cec5SDimitry Andric            "Callbr successors must all have pointer type!", &CBI);
27970b57cec5SDimitry Andric   for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
2798349cc55cSDimitry Andric     Assert(i >= CBI.arg_size() || !isa<BasicBlock>(CBI.getOperand(i)),
27990b57cec5SDimitry Andric            "Using an unescaped label as a callbr argument!", &CBI);
28000b57cec5SDimitry Andric     if (isa<BasicBlock>(CBI.getOperand(i)))
28010b57cec5SDimitry Andric       for (unsigned j = i + 1; j != e; ++j)
28020b57cec5SDimitry Andric         Assert(CBI.getOperand(i) != CBI.getOperand(j),
28030b57cec5SDimitry Andric                "Duplicate callbr destination!", &CBI);
28040b57cec5SDimitry Andric   }
28058bcb0991SDimitry Andric   {
28068bcb0991SDimitry Andric     SmallPtrSet<BasicBlock *, 4> ArgBBs;
28078bcb0991SDimitry Andric     for (Value *V : CBI.args())
28088bcb0991SDimitry Andric       if (auto *BA = dyn_cast<BlockAddress>(V))
28098bcb0991SDimitry Andric         ArgBBs.insert(BA->getBasicBlock());
28108bcb0991SDimitry Andric     for (BasicBlock *BB : CBI.getIndirectDests())
28115ffd83dbSDimitry Andric       Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI);
28128bcb0991SDimitry Andric   }
28130b57cec5SDimitry Andric 
281404eeddc0SDimitry Andric   verifyInlineAsmCall(CBI);
28150b57cec5SDimitry Andric   visitTerminator(CBI);
28160b57cec5SDimitry Andric }
28170b57cec5SDimitry Andric 
28180b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
28190b57cec5SDimitry Andric   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
28200b57cec5SDimitry Andric                                          SI.getOperand(2)),
28210b57cec5SDimitry Andric          "Invalid operands for select instruction!", &SI);
28220b57cec5SDimitry Andric 
28230b57cec5SDimitry Andric   Assert(SI.getTrueValue()->getType() == SI.getType(),
28240b57cec5SDimitry Andric          "Select values must have same type as select instruction!", &SI);
28250b57cec5SDimitry Andric   visitInstruction(SI);
28260b57cec5SDimitry Andric }
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
28290b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
28300b57cec5SDimitry Andric ///
28310b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
28320b57cec5SDimitry Andric   Assert(false, "User-defined operators should not live outside of a pass!", &I);
28330b57cec5SDimitry Andric }
28340b57cec5SDimitry Andric 
28350b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
28360b57cec5SDimitry Andric   // Get the source and destination types
28370b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28380b57cec5SDimitry Andric   Type *DestTy = I.getType();
28390b57cec5SDimitry Andric 
28400b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
28410b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
28420b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
28430b57cec5SDimitry Andric 
28440b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
28450b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
28460b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
28470b57cec5SDimitry Andric          "trunc source and destination must both be a vector or neither", &I);
28480b57cec5SDimitry Andric   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
28490b57cec5SDimitry Andric 
28500b57cec5SDimitry Andric   visitInstruction(I);
28510b57cec5SDimitry Andric }
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
28540b57cec5SDimitry Andric   // Get the source and destination types
28550b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28560b57cec5SDimitry Andric   Type *DestTy = I.getType();
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
28590b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
28600b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
28610b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
28620b57cec5SDimitry Andric          "zext source and destination must both be a vector or neither", &I);
28630b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
28640b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
28670b57cec5SDimitry Andric 
28680b57cec5SDimitry Andric   visitInstruction(I);
28690b57cec5SDimitry Andric }
28700b57cec5SDimitry Andric 
28710b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
28720b57cec5SDimitry Andric   // Get the source and destination types
28730b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28740b57cec5SDimitry Andric   Type *DestTy = I.getType();
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
28770b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
28780b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
28790b57cec5SDimitry Andric 
28800b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
28810b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
28820b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
28830b57cec5SDimitry Andric          "sext source and destination must both be a vector or neither", &I);
28840b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
28850b57cec5SDimitry Andric 
28860b57cec5SDimitry Andric   visitInstruction(I);
28870b57cec5SDimitry Andric }
28880b57cec5SDimitry Andric 
28890b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
28900b57cec5SDimitry Andric   // Get the source and destination types
28910b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28920b57cec5SDimitry Andric   Type *DestTy = I.getType();
28930b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
28940b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
28950b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
28980b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
28990b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
29000b57cec5SDimitry Andric          "fptrunc source and destination must both be a vector or neither", &I);
29010b57cec5SDimitry Andric   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric   visitInstruction(I);
29040b57cec5SDimitry Andric }
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
29070b57cec5SDimitry Andric   // Get the source and destination types
29080b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29090b57cec5SDimitry Andric   Type *DestTy = I.getType();
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
29120b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
29130b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
29160b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
29170b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
29180b57cec5SDimitry Andric          "fpext source and destination must both be a vector or neither", &I);
29190b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
29200b57cec5SDimitry Andric 
29210b57cec5SDimitry Andric   visitInstruction(I);
29220b57cec5SDimitry Andric }
29230b57cec5SDimitry Andric 
29240b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
29250b57cec5SDimitry Andric   // Get the source and destination types
29260b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29270b57cec5SDimitry Andric   Type *DestTy = I.getType();
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
29300b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
29330b57cec5SDimitry Andric          "UIToFP source and dest must both be vector or scalar", &I);
29340b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
29350b57cec5SDimitry Andric          "UIToFP source must be integer or integer vector", &I);
29360b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
29370b57cec5SDimitry Andric          &I);
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric   if (SrcVec && DstVec)
29405ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
29415ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
29420b57cec5SDimitry Andric            "UIToFP source and dest vector length mismatch", &I);
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric   visitInstruction(I);
29450b57cec5SDimitry Andric }
29460b57cec5SDimitry Andric 
29470b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
29480b57cec5SDimitry Andric   // Get the source and destination types
29490b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29500b57cec5SDimitry Andric   Type *DestTy = I.getType();
29510b57cec5SDimitry Andric 
29520b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
29530b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
29560b57cec5SDimitry Andric          "SIToFP source and dest must both be vector or scalar", &I);
29570b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
29580b57cec5SDimitry Andric          "SIToFP source must be integer or integer vector", &I);
29590b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
29600b57cec5SDimitry Andric          &I);
29610b57cec5SDimitry Andric 
29620b57cec5SDimitry Andric   if (SrcVec && DstVec)
29635ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
29645ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
29650b57cec5SDimitry Andric            "SIToFP source and dest vector length mismatch", &I);
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric   visitInstruction(I);
29680b57cec5SDimitry Andric }
29690b57cec5SDimitry Andric 
29700b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
29710b57cec5SDimitry Andric   // Get the source and destination types
29720b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29730b57cec5SDimitry Andric   Type *DestTy = I.getType();
29740b57cec5SDimitry Andric 
29750b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
29760b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
29790b57cec5SDimitry Andric          "FPToUI source and dest must both be vector or scalar", &I);
29800b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
29810b57cec5SDimitry Andric          &I);
29820b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(),
29830b57cec5SDimitry Andric          "FPToUI result must be integer or integer vector", &I);
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric   if (SrcVec && DstVec)
29865ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
29875ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
29880b57cec5SDimitry Andric            "FPToUI source and dest vector length mismatch", &I);
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric   visitInstruction(I);
29910b57cec5SDimitry Andric }
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &I) {
29940b57cec5SDimitry Andric   // Get the source and destination types
29950b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29960b57cec5SDimitry Andric   Type *DestTy = I.getType();
29970b57cec5SDimitry Andric 
29980b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
29990b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
30000b57cec5SDimitry Andric 
30010b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
30020b57cec5SDimitry Andric          "FPToSI source and dest must both be vector or scalar", &I);
30030b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
30040b57cec5SDimitry Andric          &I);
30050b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(),
30060b57cec5SDimitry Andric          "FPToSI result must be integer or integer vector", &I);
30070b57cec5SDimitry Andric 
30080b57cec5SDimitry Andric   if (SrcVec && DstVec)
30095ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
30105ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
30110b57cec5SDimitry Andric            "FPToSI source and dest vector length mismatch", &I);
30120b57cec5SDimitry Andric 
30130b57cec5SDimitry Andric   visitInstruction(I);
30140b57cec5SDimitry Andric }
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
30170b57cec5SDimitry Andric   // Get the source and destination types
30180b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30190b57cec5SDimitry Andric   Type *DestTy = I.getType();
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric   Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
30220b57cec5SDimitry Andric 
30230b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
30240b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
30250b57cec5SDimitry Andric          &I);
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
30285ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
30295ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
30305ffd83dbSDimitry Andric     Assert(VSrc->getElementCount() == VDest->getElementCount(),
30310b57cec5SDimitry Andric            "PtrToInt Vector width mismatch", &I);
30320b57cec5SDimitry Andric   }
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric   visitInstruction(I);
30350b57cec5SDimitry Andric }
30360b57cec5SDimitry Andric 
30370b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
30380b57cec5SDimitry Andric   // Get the source and destination types
30390b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30400b57cec5SDimitry Andric   Type *DestTy = I.getType();
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
30430b57cec5SDimitry Andric          "IntToPtr source must be an integral", &I);
30440b57cec5SDimitry Andric   Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
30470b57cec5SDimitry Andric          &I);
30480b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
30495ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
30505ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
30515ffd83dbSDimitry Andric     Assert(VSrc->getElementCount() == VDest->getElementCount(),
30520b57cec5SDimitry Andric            "IntToPtr Vector width mismatch", &I);
30530b57cec5SDimitry Andric   }
30540b57cec5SDimitry Andric   visitInstruction(I);
30550b57cec5SDimitry Andric }
30560b57cec5SDimitry Andric 
30570b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
30580b57cec5SDimitry Andric   Assert(
30590b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
30600b57cec5SDimitry Andric       "Invalid bitcast", &I);
30610b57cec5SDimitry Andric   visitInstruction(I);
30620b57cec5SDimitry Andric }
30630b57cec5SDimitry Andric 
30640b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
30650b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30660b57cec5SDimitry Andric   Type *DestTy = I.getType();
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
30690b57cec5SDimitry Andric          &I);
30700b57cec5SDimitry Andric   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
30710b57cec5SDimitry Andric          &I);
30720b57cec5SDimitry Andric   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
30730b57cec5SDimitry Andric          "AddrSpaceCast must be between different address spaces", &I);
30745ffd83dbSDimitry Andric   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3075e8d8bef9SDimitry Andric     Assert(SrcVTy->getElementCount() ==
3076e8d8bef9SDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
30770b57cec5SDimitry Andric            "AddrSpaceCast vector pointer number of elements mismatch", &I);
30780b57cec5SDimitry Andric   visitInstruction(I);
30790b57cec5SDimitry Andric }
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
30820b57cec5SDimitry Andric ///
30830b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
30840b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
30850b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
30860b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
30870b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
30880b57cec5SDimitry Andric   Assert(&PN == &PN.getParent()->front() ||
30890b57cec5SDimitry Andric              isa<PHINode>(--BasicBlock::iterator(&PN)),
30900b57cec5SDimitry Andric          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
30930b57cec5SDimitry Andric   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
30940b57cec5SDimitry Andric 
30950b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
30960b57cec5SDimitry Andric   // result, and that the incoming blocks are really basic blocks.
30970b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
30980b57cec5SDimitry Andric     Assert(PN.getType() == IncValue->getType(),
30990b57cec5SDimitry Andric            "PHI node operands are not the same type as the result!", &PN);
31000b57cec5SDimitry Andric   }
31010b57cec5SDimitry Andric 
31020b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric   visitInstruction(PN);
31050b57cec5SDimitry Andric }
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
31085ffd83dbSDimitry Andric   Assert(Call.getCalledOperand()->getType()->isPointerTy(),
31090b57cec5SDimitry Andric          "Called function must be a pointer!", Call);
31105ffd83dbSDimitry Andric   PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
31110b57cec5SDimitry Andric 
3112fe6060f1SDimitry Andric   Assert(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
31130b57cec5SDimitry Andric          "Called function is not the same type as the call!", Call);
31140b57cec5SDimitry Andric 
31150b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
31180b57cec5SDimitry Andric   if (FTy->isVarArg())
31190b57cec5SDimitry Andric     Assert(Call.arg_size() >= FTy->getNumParams(),
31200b57cec5SDimitry Andric            "Called function requires more parameters than were provided!",
31210b57cec5SDimitry Andric            Call);
31220b57cec5SDimitry Andric   else
31230b57cec5SDimitry Andric     Assert(Call.arg_size() == FTy->getNumParams(),
31240b57cec5SDimitry Andric            "Incorrect number of arguments passed to called function!", Call);
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
31270b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
31280b57cec5SDimitry Andric     Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
31290b57cec5SDimitry Andric            "Call parameter type does not match function signature!",
31300b57cec5SDimitry Andric            Call.getArgOperand(i), FTy->getParamType(i), Call);
31310b57cec5SDimitry Andric 
31320b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric   Assert(verifyAttributeCount(Attrs, Call.arg_size()),
31350b57cec5SDimitry Andric          "Attribute after last parameter!", Call);
31360b57cec5SDimitry Andric 
31375ffd83dbSDimitry Andric   Function *Callee =
31385ffd83dbSDimitry Andric       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3139fe6060f1SDimitry Andric   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3140fe6060f1SDimitry Andric   if (IsIntrinsic)
3141fe6060f1SDimitry Andric     Assert(Callee->getValueType() == FTy,
3142fe6060f1SDimitry Andric            "Intrinsic called with incompatible signature", Call);
31430b57cec5SDimitry Andric 
3144349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
31450b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
31460b57cec5SDimitry Andric     // declaration is also speculatable.
31470b57cec5SDimitry Andric     Assert(Callee && Callee->isSpeculatable(),
31480b57cec5SDimitry Andric            "speculatable attribute may not apply to call sites", Call);
31490b57cec5SDimitry Andric   }
31500b57cec5SDimitry Andric 
3151349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
31525ffd83dbSDimitry Andric     Assert(Call.getCalledFunction()->getIntrinsicID() ==
31535ffd83dbSDimitry Andric                Intrinsic::call_preallocated_arg,
31545ffd83dbSDimitry Andric            "preallocated as a call site attribute can only be on "
31555ffd83dbSDimitry Andric            "llvm.call.preallocated.arg");
31565ffd83dbSDimitry Andric   }
31575ffd83dbSDimitry Andric 
31580b57cec5SDimitry Andric   // Verify call attributes.
315904eeddc0SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
31600b57cec5SDimitry Andric 
31610b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
31620b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
31630b57cec5SDimitry Andric   // inalloca.
31640b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
31650b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
31660b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
31670b57cec5SDimitry Andric       Assert(AI->isUsedWithInAlloca(),
31680b57cec5SDimitry Andric              "inalloca argument for call has mismatched alloca", AI, Call);
31690b57cec5SDimitry Andric   }
31700b57cec5SDimitry Andric 
31710b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
31720b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
31730b57cec5SDimitry Andric   // well.
31740b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
31750b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
31760b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
31770b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
31780b57cec5SDimitry Andric         Assert(AI->isSwiftError(),
31790b57cec5SDimitry Andric                "swifterror argument for call has mismatched alloca", AI, Call);
31800b57cec5SDimitry Andric         continue;
31810b57cec5SDimitry Andric       }
31820b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
31830b57cec5SDimitry Andric       Assert(ArgI,
31840b57cec5SDimitry Andric              "swifterror argument should come from an alloca or parameter",
31850b57cec5SDimitry Andric              SwiftErrorArg, Call);
31860b57cec5SDimitry Andric       Assert(ArgI->hasSwiftErrorAttr(),
31870b57cec5SDimitry Andric              "swifterror argument for call has mismatched parameter", ArgI,
31880b57cec5SDimitry Andric              Call);
31890b57cec5SDimitry Andric     }
31900b57cec5SDimitry Andric 
3191349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
31920b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
31930b57cec5SDimitry Andric       // also has the matching immarg.
31940b57cec5SDimitry Andric       Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
31950b57cec5SDimitry Andric              "immarg may not apply only to call sites",
31960b57cec5SDimitry Andric              Call.getArgOperand(i), Call);
31970b57cec5SDimitry Andric     }
31980b57cec5SDimitry Andric 
31990b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
32000b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
32010b57cec5SDimitry Andric       Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
32020b57cec5SDimitry Andric              "immarg operand has non-immediate parameter", ArgVal, Call);
32030b57cec5SDimitry Andric     }
32045ffd83dbSDimitry Andric 
32055ffd83dbSDimitry Andric     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
32065ffd83dbSDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
32075ffd83dbSDimitry Andric       bool hasOB =
32085ffd83dbSDimitry Andric           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
32095ffd83dbSDimitry Andric       bool isMustTail = Call.isMustTailCall();
32105ffd83dbSDimitry Andric       Assert(hasOB != isMustTail,
32115ffd83dbSDimitry Andric              "preallocated operand either requires a preallocated bundle or "
32125ffd83dbSDimitry Andric              "the call to be musttail (but not both)",
32135ffd83dbSDimitry Andric              ArgVal, Call);
32145ffd83dbSDimitry Andric     }
32150b57cec5SDimitry Andric   }
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric   if (FTy->isVarArg()) {
32180b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
32190b57cec5SDimitry Andric     bool SawNest = false;
32200b57cec5SDimitry Andric     bool SawReturned = false;
32210b57cec5SDimitry Andric 
32220b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3223349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
32240b57cec5SDimitry Andric         SawNest = true;
3225349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
32260b57cec5SDimitry Andric         SawReturned = true;
32270b57cec5SDimitry Andric     }
32280b57cec5SDimitry Andric 
32290b57cec5SDimitry Andric     // Check attributes on the varargs part.
32300b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
32310b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
3232349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
32330b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
32340b57cec5SDimitry Andric 
32350b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
32360b57cec5SDimitry Andric         Assert(!SawNest, "More than one parameter has attribute nest!", Call);
32370b57cec5SDimitry Andric         SawNest = true;
32380b57cec5SDimitry Andric       }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
32410b57cec5SDimitry Andric         Assert(!SawReturned, "More than one parameter has attribute returned!",
32420b57cec5SDimitry Andric                Call);
32430b57cec5SDimitry Andric         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
32440b57cec5SDimitry Andric                "Incompatible argument and return types for 'returned' "
32450b57cec5SDimitry Andric                "attribute",
32460b57cec5SDimitry Andric                Call);
32470b57cec5SDimitry Andric         SawReturned = true;
32480b57cec5SDimitry Andric       }
32490b57cec5SDimitry Andric 
32500b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
32510b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
32520b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
32530b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
32540b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
32550b57cec5SDimitry Andric         Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
32560b57cec5SDimitry Andric                "Attribute 'sret' cannot be used for vararg call arguments!",
32570b57cec5SDimitry Andric                Call);
32580b57cec5SDimitry Andric 
32590b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
32600b57cec5SDimitry Andric         Assert(Idx == Call.arg_size() - 1,
32610b57cec5SDimitry Andric                "inalloca isn't on the last argument!", Call);
32620b57cec5SDimitry Andric     }
32630b57cec5SDimitry Andric   }
32640b57cec5SDimitry Andric 
32650b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
32660b57cec5SDimitry Andric   if (!IsIntrinsic) {
32670b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
32680b57cec5SDimitry Andric       Assert(!ParamTy->isMetadataTy(),
32690b57cec5SDimitry Andric              "Function has metadata parameter but isn't an intrinsic", Call);
32700b57cec5SDimitry Andric       Assert(!ParamTy->isTokenTy(),
32710b57cec5SDimitry Andric              "Function has token parameter but isn't an intrinsic", Call);
32720b57cec5SDimitry Andric     }
32730b57cec5SDimitry Andric   }
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
3276fe6060f1SDimitry Andric   if (!Call.getCalledFunction()) {
32770b57cec5SDimitry Andric     Assert(!FTy->getReturnType()->isTokenTy(),
32780b57cec5SDimitry Andric            "Return type cannot be token for indirect call!");
3279fe6060f1SDimitry Andric     Assert(!FTy->getReturnType()->isX86_AMXTy(),
3280fe6060f1SDimitry Andric            "Return type cannot be x86_amx for indirect call!");
3281fe6060f1SDimitry Andric   }
32820b57cec5SDimitry Andric 
32830b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
32840b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
32850b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
32860b57cec5SDimitry Andric 
3287480093f4SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet", at
32885ffd83dbSDimitry Andric   // most one "gc-transition", at most one "cfguardtarget",
32895ffd83dbSDimitry Andric   // and at most one "preallocated" operand bundle.
32900b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
32915ffd83dbSDimitry Andric        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3292fe6060f1SDimitry Andric        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3293fe6060f1SDimitry Andric        FoundAttachedCallBundle = false;
32940b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
32950b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
32960b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
32970b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
32980b57cec5SDimitry Andric       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
32990b57cec5SDimitry Andric       FoundDeoptBundle = true;
33000b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
33010b57cec5SDimitry Andric       Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
33020b57cec5SDimitry Andric              Call);
33030b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
33040b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
33050b57cec5SDimitry Andric       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
33060b57cec5SDimitry Andric       FoundFuncletBundle = true;
33070b57cec5SDimitry Andric       Assert(BU.Inputs.size() == 1,
33080b57cec5SDimitry Andric              "Expected exactly one funclet bundle operand", Call);
33090b57cec5SDimitry Andric       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
33100b57cec5SDimitry Andric              "Funclet bundle operands should correspond to a FuncletPadInst",
33110b57cec5SDimitry Andric              Call);
3312480093f4SDimitry Andric     } else if (Tag == LLVMContext::OB_cfguardtarget) {
3313480093f4SDimitry Andric       Assert(!FoundCFGuardTargetBundle,
3314480093f4SDimitry Andric              "Multiple CFGuardTarget operand bundles", Call);
3315480093f4SDimitry Andric       FoundCFGuardTargetBundle = true;
3316480093f4SDimitry Andric       Assert(BU.Inputs.size() == 1,
3317480093f4SDimitry Andric              "Expected exactly one cfguardtarget bundle operand", Call);
33185ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_preallocated) {
33195ffd83dbSDimitry Andric       Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
33205ffd83dbSDimitry Andric              Call);
33215ffd83dbSDimitry Andric       FoundPreallocatedBundle = true;
33225ffd83dbSDimitry Andric       Assert(BU.Inputs.size() == 1,
33235ffd83dbSDimitry Andric              "Expected exactly one preallocated bundle operand", Call);
33245ffd83dbSDimitry Andric       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
33255ffd83dbSDimitry Andric       Assert(Input &&
33265ffd83dbSDimitry Andric                  Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
33275ffd83dbSDimitry Andric              "\"preallocated\" argument must be a token from "
33285ffd83dbSDimitry Andric              "llvm.call.preallocated.setup",
33295ffd83dbSDimitry Andric              Call);
33305ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_gc_live) {
33315ffd83dbSDimitry Andric       Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles",
33325ffd83dbSDimitry Andric              Call);
33335ffd83dbSDimitry Andric       FoundGCLiveBundle = true;
3334fe6060f1SDimitry Andric     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
3335fe6060f1SDimitry Andric       Assert(!FoundAttachedCallBundle,
3336fe6060f1SDimitry Andric              "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3337fe6060f1SDimitry Andric       FoundAttachedCallBundle = true;
3338349cc55cSDimitry Andric       verifyAttachedCallBundle(Call, BU);
33390b57cec5SDimitry Andric     }
33400b57cec5SDimitry Andric   }
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
33430b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
33440b57cec5SDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info.
33450b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
33460b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
33470b57cec5SDimitry Andric     AssertDI(Call.getDebugLoc(),
33480b57cec5SDimitry Andric              "inlinable function call in a function with "
33490b57cec5SDimitry Andric              "debug info must have a !dbg location",
33500b57cec5SDimitry Andric              Call);
33510b57cec5SDimitry Andric 
335204eeddc0SDimitry Andric   if (Call.isInlineAsm())
335304eeddc0SDimitry Andric     verifyInlineAsmCall(Call);
335404eeddc0SDimitry Andric 
33550b57cec5SDimitry Andric   visitInstruction(Call);
33560b57cec5SDimitry Andric }
33570b57cec5SDimitry Andric 
33580eae32dcSDimitry Andric void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3359fe6060f1SDimitry Andric                                          StringRef Context) {
3360fe6060f1SDimitry Andric   Assert(!Attrs.contains(Attribute::InAlloca),
3361fe6060f1SDimitry Andric          Twine("inalloca attribute not allowed in ") + Context);
3362fe6060f1SDimitry Andric   Assert(!Attrs.contains(Attribute::InReg),
3363fe6060f1SDimitry Andric          Twine("inreg attribute not allowed in ") + Context);
3364fe6060f1SDimitry Andric   Assert(!Attrs.contains(Attribute::SwiftError),
3365fe6060f1SDimitry Andric          Twine("swifterror attribute not allowed in ") + Context);
3366fe6060f1SDimitry Andric   Assert(!Attrs.contains(Attribute::Preallocated),
3367fe6060f1SDimitry Andric          Twine("preallocated attribute not allowed in ") + Context);
3368fe6060f1SDimitry Andric   Assert(!Attrs.contains(Attribute::ByRef),
3369fe6060f1SDimitry Andric          Twine("byref attribute not allowed in ") + Context);
3370fe6060f1SDimitry Andric }
3371fe6060f1SDimitry Andric 
33720b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
33730b57cec5SDimitry Andric /// types with different pointee types and the same address space.
33740b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
33750b57cec5SDimitry Andric   if (L == R)
33760b57cec5SDimitry Andric     return true;
33770b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
33780b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
33790b57cec5SDimitry Andric   if (!PL || !PR)
33800b57cec5SDimitry Andric     return false;
33810b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
33820b57cec5SDimitry Andric }
33830b57cec5SDimitry Andric 
338404eeddc0SDimitry Andric static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
33850b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
33860b57cec5SDimitry Andric       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3387fe6060f1SDimitry Andric       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3388fe6060f1SDimitry Andric       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3389fe6060f1SDimitry Andric       Attribute::ByRef};
339004eeddc0SDimitry Andric   AttrBuilder Copy(C);
33910b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
3392349cc55cSDimitry Andric     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3393fe6060f1SDimitry Andric     if (Attr.isValid())
3394fe6060f1SDimitry Andric       Copy.addAttribute(Attr);
33950b57cec5SDimitry Andric   }
3396e8d8bef9SDimitry Andric 
3397e8d8bef9SDimitry Andric   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3398349cc55cSDimitry Andric   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3399349cc55cSDimitry Andric       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3400349cc55cSDimitry Andric        Attrs.hasParamAttr(I, Attribute::ByRef)))
34010b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
34020b57cec5SDimitry Andric   return Copy;
34030b57cec5SDimitry Andric }
34040b57cec5SDimitry Andric 
34050b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
34060b57cec5SDimitry Andric   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
34070b57cec5SDimitry Andric 
34080b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
34090b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
34100b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
34110b57cec5SDimitry Andric   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
34120b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched varargs", &CI);
34130b57cec5SDimitry Andric   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
34140b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched return types", &CI);
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
34170b57cec5SDimitry Andric   Assert(F->getCallingConv() == CI.getCallingConv(),
34180b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched calling conv", &CI);
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
34210b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
34220b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
34230b57cec5SDimitry Andric   //   produced by the call or void.
34240b57cec5SDimitry Andric   Value *RetVal = &CI;
34250b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
34260b57cec5SDimitry Andric 
34270b57cec5SDimitry Andric   // Handle the optional bitcast.
34280b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
34290b57cec5SDimitry Andric     Assert(BI->getOperand(0) == RetVal,
34300b57cec5SDimitry Andric            "bitcast following musttail call must use the call", BI);
34310b57cec5SDimitry Andric     RetVal = BI;
34320b57cec5SDimitry Andric     Next = BI->getNextNode();
34330b57cec5SDimitry Andric   }
34340b57cec5SDimitry Andric 
34350b57cec5SDimitry Andric   // Check the return.
34360b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
34370b57cec5SDimitry Andric   Assert(Ret, "musttail call must precede a ret with an optional bitcast",
34380b57cec5SDimitry Andric          &CI);
3439fe6060f1SDimitry Andric   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3440fe6060f1SDimitry Andric              isa<UndefValue>(Ret->getReturnValue()),
34410b57cec5SDimitry Andric          "musttail call result must be returned", Ret);
3442fe6060f1SDimitry Andric 
3443fe6060f1SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
3444fe6060f1SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
3445fe6060f1SDimitry Andric   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3446fe6060f1SDimitry Andric       CI.getCallingConv() == CallingConv::Tail) {
3447fe6060f1SDimitry Andric     StringRef CCName =
3448fe6060f1SDimitry Andric         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3449fe6060f1SDimitry Andric 
3450fe6060f1SDimitry Andric     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3451fe6060f1SDimitry Andric     //   are allowed in swifttailcc call
3452349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
345304eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3454fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3455fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3456fe6060f1SDimitry Andric     }
3457349cc55cSDimitry Andric     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
345804eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3459fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3460fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3461fe6060f1SDimitry Andric     }
3462fe6060f1SDimitry Andric     // - Varargs functions are not allowed
3463fe6060f1SDimitry Andric     Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3464fe6060f1SDimitry Andric                                       " tail call for varargs function");
3465fe6060f1SDimitry Andric     return;
3466fe6060f1SDimitry Andric   }
3467fe6060f1SDimitry Andric 
3468fe6060f1SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
3469fe6060f1SDimitry Andric   //   parameters or return types may differ in pointee type, but not
3470fe6060f1SDimitry Andric   //   address space.
3471fe6060f1SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3472fe6060f1SDimitry Andric     Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3473fe6060f1SDimitry Andric            "cannot guarantee tail call due to mismatched parameter counts",
3474fe6060f1SDimitry Andric            &CI);
3475349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3476fe6060f1SDimitry Andric       Assert(
3477fe6060f1SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3478fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
3479fe6060f1SDimitry Andric     }
3480fe6060f1SDimitry Andric   }
3481fe6060f1SDimitry Andric 
3482fe6060f1SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3483fe6060f1SDimitry Andric   //   returned, preallocated, and inalloca, must match.
3484349cc55cSDimitry Andric   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
348504eeddc0SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
348604eeddc0SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3487fe6060f1SDimitry Andric     Assert(CallerABIAttrs == CalleeABIAttrs,
3488fe6060f1SDimitry Andric            "cannot guarantee tail call due to mismatched ABI impacting "
3489fe6060f1SDimitry Andric            "function attributes",
3490fe6060f1SDimitry Andric            &CI, CI.getOperand(I));
3491fe6060f1SDimitry Andric   }
34920b57cec5SDimitry Andric }
34930b57cec5SDimitry Andric 
34940b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
34950b57cec5SDimitry Andric   visitCallBase(CI);
34960b57cec5SDimitry Andric 
34970b57cec5SDimitry Andric   if (CI.isMustTailCall())
34980b57cec5SDimitry Andric     verifyMustTailCall(CI);
34990b57cec5SDimitry Andric }
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
35020b57cec5SDimitry Andric   visitCallBase(II);
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
35050b57cec5SDimitry Andric   // exception handling instruction.
35060b57cec5SDimitry Andric   Assert(
35070b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
35080b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
35090b57cec5SDimitry Andric       &II);
35100b57cec5SDimitry Andric 
35110b57cec5SDimitry Andric   visitTerminator(II);
35120b57cec5SDimitry Andric }
35130b57cec5SDimitry Andric 
35140b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
35150b57cec5SDimitry Andric ///
35160b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
35170b57cec5SDimitry Andric   Assert(U.getType() == U.getOperand(0)->getType(),
35180b57cec5SDimitry Andric          "Unary operators must have same type for"
35190b57cec5SDimitry Andric          "operands and result!",
35200b57cec5SDimitry Andric          &U);
35210b57cec5SDimitry Andric 
35220b57cec5SDimitry Andric   switch (U.getOpcode()) {
35230b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
35240b57cec5SDimitry Andric   // floating-point operands.
35250b57cec5SDimitry Andric   case Instruction::FNeg:
35260b57cec5SDimitry Andric     Assert(U.getType()->isFPOrFPVectorTy(),
35270b57cec5SDimitry Andric            "FNeg operator only works with float types!", &U);
35280b57cec5SDimitry Andric     break;
35290b57cec5SDimitry Andric   default:
35300b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
35310b57cec5SDimitry Andric   }
35320b57cec5SDimitry Andric 
35330b57cec5SDimitry Andric   visitInstruction(U);
35340b57cec5SDimitry Andric }
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
35370b57cec5SDimitry Andric /// of the same type!
35380b57cec5SDimitry Andric ///
35390b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
35400b57cec5SDimitry Andric   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
35410b57cec5SDimitry Andric          "Both operands to a binary operator are not of the same type!", &B);
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric   switch (B.getOpcode()) {
35440b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
35450b57cec5SDimitry Andric   // integral operands.
35460b57cec5SDimitry Andric   case Instruction::Add:
35470b57cec5SDimitry Andric   case Instruction::Sub:
35480b57cec5SDimitry Andric   case Instruction::Mul:
35490b57cec5SDimitry Andric   case Instruction::SDiv:
35500b57cec5SDimitry Andric   case Instruction::UDiv:
35510b57cec5SDimitry Andric   case Instruction::SRem:
35520b57cec5SDimitry Andric   case Instruction::URem:
35530b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
35540b57cec5SDimitry Andric            "Integer arithmetic operators only work with integral types!", &B);
35550b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
35560b57cec5SDimitry Andric            "Integer arithmetic operators must have same type "
35570b57cec5SDimitry Andric            "for operands and result!",
35580b57cec5SDimitry Andric            &B);
35590b57cec5SDimitry Andric     break;
35600b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
35610b57cec5SDimitry Andric   // floating-point operands.
35620b57cec5SDimitry Andric   case Instruction::FAdd:
35630b57cec5SDimitry Andric   case Instruction::FSub:
35640b57cec5SDimitry Andric   case Instruction::FMul:
35650b57cec5SDimitry Andric   case Instruction::FDiv:
35660b57cec5SDimitry Andric   case Instruction::FRem:
35670b57cec5SDimitry Andric     Assert(B.getType()->isFPOrFPVectorTy(),
35680b57cec5SDimitry Andric            "Floating-point arithmetic operators only work with "
35690b57cec5SDimitry Andric            "floating-point types!",
35700b57cec5SDimitry Andric            &B);
35710b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
35720b57cec5SDimitry Andric            "Floating-point arithmetic operators must have same type "
35730b57cec5SDimitry Andric            "for operands and result!",
35740b57cec5SDimitry Andric            &B);
35750b57cec5SDimitry Andric     break;
35760b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
35770b57cec5SDimitry Andric   case Instruction::And:
35780b57cec5SDimitry Andric   case Instruction::Or:
35790b57cec5SDimitry Andric   case Instruction::Xor:
35800b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
35810b57cec5SDimitry Andric            "Logical operators only work with integral types!", &B);
35820b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
35830b57cec5SDimitry Andric            "Logical operators must have same type for operands and result!",
35840b57cec5SDimitry Andric            &B);
35850b57cec5SDimitry Andric     break;
35860b57cec5SDimitry Andric   case Instruction::Shl:
35870b57cec5SDimitry Andric   case Instruction::LShr:
35880b57cec5SDimitry Andric   case Instruction::AShr:
35890b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
35900b57cec5SDimitry Andric            "Shifts only work with integral types!", &B);
35910b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
35920b57cec5SDimitry Andric            "Shift return type must be same as operands!", &B);
35930b57cec5SDimitry Andric     break;
35940b57cec5SDimitry Andric   default:
35950b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
35960b57cec5SDimitry Andric   }
35970b57cec5SDimitry Andric 
35980b57cec5SDimitry Andric   visitInstruction(B);
35990b57cec5SDimitry Andric }
36000b57cec5SDimitry Andric 
36010b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
36020b57cec5SDimitry Andric   // Check that the operands are the same type
36030b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
36040b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
36050b57cec5SDimitry Andric   Assert(Op0Ty == Op1Ty,
36060b57cec5SDimitry Andric          "Both operands to ICmp instruction are not of the same type!", &IC);
36070b57cec5SDimitry Andric   // Check that the operands are the right type
36080b57cec5SDimitry Andric   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
36090b57cec5SDimitry Andric          "Invalid operand types for ICmp instruction", &IC);
36100b57cec5SDimitry Andric   // Check that the predicate is valid.
36110b57cec5SDimitry Andric   Assert(IC.isIntPredicate(),
36120b57cec5SDimitry Andric          "Invalid predicate in ICmp instruction!", &IC);
36130b57cec5SDimitry Andric 
36140b57cec5SDimitry Andric   visitInstruction(IC);
36150b57cec5SDimitry Andric }
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
36180b57cec5SDimitry Andric   // Check that the operands are the same type
36190b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
36200b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
36210b57cec5SDimitry Andric   Assert(Op0Ty == Op1Ty,
36220b57cec5SDimitry Andric          "Both operands to FCmp instruction are not of the same type!", &FC);
36230b57cec5SDimitry Andric   // Check that the operands are the right type
36240b57cec5SDimitry Andric   Assert(Op0Ty->isFPOrFPVectorTy(),
36250b57cec5SDimitry Andric          "Invalid operand types for FCmp instruction", &FC);
36260b57cec5SDimitry Andric   // Check that the predicate is valid.
36270b57cec5SDimitry Andric   Assert(FC.isFPPredicate(),
36280b57cec5SDimitry Andric          "Invalid predicate in FCmp instruction!", &FC);
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric   visitInstruction(FC);
36310b57cec5SDimitry Andric }
36320b57cec5SDimitry Andric 
36330b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
36340b57cec5SDimitry Andric   Assert(
36350b57cec5SDimitry Andric       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
36360b57cec5SDimitry Andric       "Invalid extractelement operands!", &EI);
36370b57cec5SDimitry Andric   visitInstruction(EI);
36380b57cec5SDimitry Andric }
36390b57cec5SDimitry Andric 
36400b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
36410b57cec5SDimitry Andric   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
36420b57cec5SDimitry Andric                                             IE.getOperand(2)),
36430b57cec5SDimitry Andric          "Invalid insertelement operands!", &IE);
36440b57cec5SDimitry Andric   visitInstruction(IE);
36450b57cec5SDimitry Andric }
36460b57cec5SDimitry Andric 
36470b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
36480b57cec5SDimitry Andric   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
36495ffd83dbSDimitry Andric                                             SV.getShuffleMask()),
36500b57cec5SDimitry Andric          "Invalid shufflevector operands!", &SV);
36510b57cec5SDimitry Andric   visitInstruction(SV);
36520b57cec5SDimitry Andric }
36530b57cec5SDimitry Andric 
36540b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
36550b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
36560b57cec5SDimitry Andric 
36570b57cec5SDimitry Andric   Assert(isa<PointerType>(TargetTy),
36580b57cec5SDimitry Andric          "GEP base pointer is not a vector or a vector of pointers", &GEP);
36590b57cec5SDimitry Andric   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
36600b57cec5SDimitry Andric 
3661e8d8bef9SDimitry Andric   SmallVector<Value *, 16> Idxs(GEP.indices());
36620b57cec5SDimitry Andric   Assert(all_of(
36630b57cec5SDimitry Andric       Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
36640b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
36650b57cec5SDimitry Andric   Type *ElTy =
36660b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
36670b57cec5SDimitry Andric   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric   Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
36700b57cec5SDimitry Andric              GEP.getResultElementType() == ElTy,
36710b57cec5SDimitry Andric          "GEP is not of right type for indices!", &GEP, ElTy);
36720b57cec5SDimitry Andric 
36735ffd83dbSDimitry Andric   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
36740b57cec5SDimitry Andric     // Additional checks for vector GEPs.
36755ffd83dbSDimitry Andric     ElementCount GEPWidth = GEPVTy->getElementCount();
36760b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
36775ffd83dbSDimitry Andric       Assert(
36785ffd83dbSDimitry Andric           GEPWidth ==
36795ffd83dbSDimitry Andric               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
36800b57cec5SDimitry Andric           "Vector GEP result width doesn't match operand's", &GEP);
36810b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
36820b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
36835ffd83dbSDimitry Andric       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
36845ffd83dbSDimitry Andric         ElementCount IndexWidth = IndexVTy->getElementCount();
36850b57cec5SDimitry Andric         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
36860b57cec5SDimitry Andric       }
36870b57cec5SDimitry Andric       Assert(IndexTy->isIntOrIntVectorTy(),
36880b57cec5SDimitry Andric              "All GEP indices should be of integer type");
36890b57cec5SDimitry Andric     }
36900b57cec5SDimitry Andric   }
36910b57cec5SDimitry Andric 
36920b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
36930b57cec5SDimitry Andric     Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
36940b57cec5SDimitry Andric            "GEP address space doesn't match type", &GEP);
36950b57cec5SDimitry Andric   }
36960b57cec5SDimitry Andric 
36970b57cec5SDimitry Andric   visitInstruction(GEP);
36980b57cec5SDimitry Andric }
36990b57cec5SDimitry Andric 
37000b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
37010b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
37020b57cec5SDimitry Andric }
37030b57cec5SDimitry Andric 
37040b57cec5SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
37050b57cec5SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
37060b57cec5SDimitry Andric          "precondition violation");
37070b57cec5SDimitry Andric 
37080b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
37090b57cec5SDimitry Andric   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
37100b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
37110b57cec5SDimitry Andric   Assert(NumRanges >= 1, "It should have at least one range!", Range);
37120b57cec5SDimitry Andric 
37130b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
37140b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
37150b57cec5SDimitry Andric     ConstantInt *Low =
37160b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
37170b57cec5SDimitry Andric     Assert(Low, "The lower limit must be an integer!", Low);
37180b57cec5SDimitry Andric     ConstantInt *High =
37190b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
37200b57cec5SDimitry Andric     Assert(High, "The upper limit must be an integer!", High);
37210b57cec5SDimitry Andric     Assert(High->getType() == Low->getType() && High->getType() == Ty,
37220b57cec5SDimitry Andric            "Range types must match instruction type!", &I);
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric     APInt HighV = High->getValue();
37250b57cec5SDimitry Andric     APInt LowV = Low->getValue();
37260b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
37270b57cec5SDimitry Andric     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
37280b57cec5SDimitry Andric            "Range must not be empty!", Range);
37290b57cec5SDimitry Andric     if (i != 0) {
37300b57cec5SDimitry Andric       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
37310b57cec5SDimitry Andric              "Intervals are overlapping", Range);
37320b57cec5SDimitry Andric       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
37330b57cec5SDimitry Andric              Range);
37340b57cec5SDimitry Andric       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
37350b57cec5SDimitry Andric              Range);
37360b57cec5SDimitry Andric     }
37370b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
37380b57cec5SDimitry Andric   }
37390b57cec5SDimitry Andric   if (NumRanges > 2) {
37400b57cec5SDimitry Andric     APInt FirstLow =
37410b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
37420b57cec5SDimitry Andric     APInt FirstHigh =
37430b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
37440b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
37450b57cec5SDimitry Andric     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
37460b57cec5SDimitry Andric            "Intervals are overlapping", Range);
37470b57cec5SDimitry Andric     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
37480b57cec5SDimitry Andric            Range);
37490b57cec5SDimitry Andric   }
37500b57cec5SDimitry Andric }
37510b57cec5SDimitry Andric 
37520b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
37530b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
37540b57cec5SDimitry Andric   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
37550b57cec5SDimitry Andric   Assert(!(Size & (Size - 1)),
37560b57cec5SDimitry Andric          "atomic memory access' operand must have a power-of-two size", Ty, I);
37570b57cec5SDimitry Andric }
37580b57cec5SDimitry Andric 
37590b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
37600b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
37610b57cec5SDimitry Andric   Assert(PTy, "Load operand must be a pointer.", &LI);
37620b57cec5SDimitry Andric   Type *ElTy = LI.getType();
37630eae32dcSDimitry Andric   if (MaybeAlign A = LI.getAlign()) {
37640eae32dcSDimitry Andric     Assert(A->value() <= Value::MaximumAlignment,
37650b57cec5SDimitry Andric            "huge alignment values are unsupported", &LI);
37660eae32dcSDimitry Andric   }
37670b57cec5SDimitry Andric   Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
37680b57cec5SDimitry Andric   if (LI.isAtomic()) {
37690b57cec5SDimitry Andric     Assert(LI.getOrdering() != AtomicOrdering::Release &&
37700b57cec5SDimitry Andric                LI.getOrdering() != AtomicOrdering::AcquireRelease,
37710b57cec5SDimitry Andric            "Load cannot have Release ordering", &LI);
37720b57cec5SDimitry Andric     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
37730b57cec5SDimitry Andric            "atomic load operand must have integer, pointer, or floating point "
37740b57cec5SDimitry Andric            "type!",
37750b57cec5SDimitry Andric            ElTy, &LI);
37760b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
37770b57cec5SDimitry Andric   } else {
37780b57cec5SDimitry Andric     Assert(LI.getSyncScopeID() == SyncScope::System,
37790b57cec5SDimitry Andric            "Non-atomic load cannot have SynchronizationScope specified", &LI);
37800b57cec5SDimitry Andric   }
37810b57cec5SDimitry Andric 
37820b57cec5SDimitry Andric   visitInstruction(LI);
37830b57cec5SDimitry Andric }
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
37860b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
37870b57cec5SDimitry Andric   Assert(PTy, "Store operand must be a pointer.", &SI);
3788fe6060f1SDimitry Andric   Type *ElTy = SI.getOperand(0)->getType();
3789fe6060f1SDimitry Andric   Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
37900b57cec5SDimitry Andric          "Stored value type does not match pointer operand type!", &SI, ElTy);
37910eae32dcSDimitry Andric   if (MaybeAlign A = SI.getAlign()) {
37920eae32dcSDimitry Andric     Assert(A->value() <= Value::MaximumAlignment,
37930b57cec5SDimitry Andric            "huge alignment values are unsupported", &SI);
37940eae32dcSDimitry Andric   }
37950b57cec5SDimitry Andric   Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
37960b57cec5SDimitry Andric   if (SI.isAtomic()) {
37970b57cec5SDimitry Andric     Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
37980b57cec5SDimitry Andric                SI.getOrdering() != AtomicOrdering::AcquireRelease,
37990b57cec5SDimitry Andric            "Store cannot have Acquire ordering", &SI);
38000b57cec5SDimitry Andric     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
38010b57cec5SDimitry Andric            "atomic store operand must have integer, pointer, or floating point "
38020b57cec5SDimitry Andric            "type!",
38030b57cec5SDimitry Andric            ElTy, &SI);
38040b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
38050b57cec5SDimitry Andric   } else {
38060b57cec5SDimitry Andric     Assert(SI.getSyncScopeID() == SyncScope::System,
38070b57cec5SDimitry Andric            "Non-atomic store cannot have SynchronizationScope specified", &SI);
38080b57cec5SDimitry Andric   }
38090b57cec5SDimitry Andric   visitInstruction(SI);
38100b57cec5SDimitry Andric }
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
38130b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
38140b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
3815fe6060f1SDimitry Andric   for (const auto &I : llvm::enumerate(Call.args())) {
3816fe6060f1SDimitry Andric     if (I.value() == SwiftErrorVal) {
3817fe6060f1SDimitry Andric       Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError),
38180b57cec5SDimitry Andric              "swifterror value when used in a callsite should be marked "
38190b57cec5SDimitry Andric              "with swifterror attribute",
38200b57cec5SDimitry Andric              SwiftErrorVal, Call);
38210b57cec5SDimitry Andric     }
38220b57cec5SDimitry Andric   }
38230b57cec5SDimitry Andric }
38240b57cec5SDimitry Andric 
38250b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
38260b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
38270b57cec5SDimitry Andric   // a swifterror argument.
38280b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
38290b57cec5SDimitry Andric     Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
38300b57cec5SDimitry Andric            isa<InvokeInst>(U),
38310b57cec5SDimitry Andric            "swifterror value can only be loaded and stored from, or "
38320b57cec5SDimitry Andric            "as a swifterror argument!",
38330b57cec5SDimitry Andric            SwiftErrorVal, U);
38340b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
38350b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
38360b57cec5SDimitry Andric       Assert(StoreI->getOperand(1) == SwiftErrorVal,
38370b57cec5SDimitry Andric              "swifterror value should be the second operand when used "
38380b57cec5SDimitry Andric              "by stores", SwiftErrorVal, U);
38390b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
38400b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
38410b57cec5SDimitry Andric   }
38420b57cec5SDimitry Andric }
38430b57cec5SDimitry Andric 
38440b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
38450b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
38460b57cec5SDimitry Andric   Assert(AI.getAllocatedType()->isSized(&Visited),
38470b57cec5SDimitry Andric          "Cannot allocate unsized type", &AI);
38480b57cec5SDimitry Andric   Assert(AI.getArraySize()->getType()->isIntegerTy(),
38490b57cec5SDimitry Andric          "Alloca array size must have integer type", &AI);
38500eae32dcSDimitry Andric   if (MaybeAlign A = AI.getAlign()) {
38510eae32dcSDimitry Andric     Assert(A->value() <= Value::MaximumAlignment,
38520b57cec5SDimitry Andric            "huge alignment values are unsupported", &AI);
38530eae32dcSDimitry Andric   }
38540b57cec5SDimitry Andric 
38550b57cec5SDimitry Andric   if (AI.isSwiftError()) {
38560b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
38570b57cec5SDimitry Andric   }
38580b57cec5SDimitry Andric 
38590b57cec5SDimitry Andric   visitInstruction(AI);
38600b57cec5SDimitry Andric }
38610b57cec5SDimitry Andric 
38620b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
3863fe6060f1SDimitry Andric   Type *ElTy = CXI.getOperand(1)->getType();
38640b57cec5SDimitry Andric   Assert(ElTy->isIntOrPtrTy(),
38650b57cec5SDimitry Andric          "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
38660b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
38670b57cec5SDimitry Andric   visitInstruction(CXI);
38680b57cec5SDimitry Andric }
38690b57cec5SDimitry Andric 
38700b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
38710b57cec5SDimitry Andric   Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
38720b57cec5SDimitry Andric          "atomicrmw instructions cannot be unordered.", &RMWI);
38730b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
3874fe6060f1SDimitry Andric   Type *ElTy = RMWI.getOperand(1)->getType();
38750b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
38760b57cec5SDimitry Andric     Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
38770b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
38780b57cec5SDimitry Andric            " operand must have integer or floating point type!",
38790b57cec5SDimitry Andric            &RMWI, ElTy);
38800b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
38810b57cec5SDimitry Andric     Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
38820b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
38830b57cec5SDimitry Andric            " operand must have floating point type!",
38840b57cec5SDimitry Andric            &RMWI, ElTy);
38850b57cec5SDimitry Andric   } else {
38860b57cec5SDimitry Andric     Assert(ElTy->isIntegerTy(), "atomicrmw " +
38870b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
38880b57cec5SDimitry Andric            " operand must have integer type!",
38890b57cec5SDimitry Andric            &RMWI, ElTy);
38900b57cec5SDimitry Andric   }
38910b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
38920b57cec5SDimitry Andric   Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
38930b57cec5SDimitry Andric          "Invalid binary operation!", &RMWI);
38940b57cec5SDimitry Andric   visitInstruction(RMWI);
38950b57cec5SDimitry Andric }
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
38980b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
38990b57cec5SDimitry Andric   Assert(Ordering == AtomicOrdering::Acquire ||
39000b57cec5SDimitry Andric              Ordering == AtomicOrdering::Release ||
39010b57cec5SDimitry Andric              Ordering == AtomicOrdering::AcquireRelease ||
39020b57cec5SDimitry Andric              Ordering == AtomicOrdering::SequentiallyConsistent,
39030b57cec5SDimitry Andric          "fence instructions may only have acquire, release, acq_rel, or "
39040b57cec5SDimitry Andric          "seq_cst ordering.",
39050b57cec5SDimitry Andric          &FI);
39060b57cec5SDimitry Andric   visitInstruction(FI);
39070b57cec5SDimitry Andric }
39080b57cec5SDimitry Andric 
39090b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
39100b57cec5SDimitry Andric   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
39110b57cec5SDimitry Andric                                           EVI.getIndices()) == EVI.getType(),
39120b57cec5SDimitry Andric          "Invalid ExtractValueInst operands!", &EVI);
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   visitInstruction(EVI);
39150b57cec5SDimitry Andric }
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
39180b57cec5SDimitry Andric   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
39190b57cec5SDimitry Andric                                           IVI.getIndices()) ==
39200b57cec5SDimitry Andric              IVI.getOperand(1)->getType(),
39210b57cec5SDimitry Andric          "Invalid InsertValueInst operands!", &IVI);
39220b57cec5SDimitry Andric 
39230b57cec5SDimitry Andric   visitInstruction(IVI);
39240b57cec5SDimitry Andric }
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
39270b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
39280b57cec5SDimitry Andric     return FPI->getParentPad();
39290b57cec5SDimitry Andric 
39300b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
39310b57cec5SDimitry Andric }
39320b57cec5SDimitry Andric 
39330b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
39340b57cec5SDimitry Andric   assert(I.isEHPad());
39350b57cec5SDimitry Andric 
39360b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
39370b57cec5SDimitry Andric   Function *F = BB->getParent();
39380b57cec5SDimitry Andric 
39390b57cec5SDimitry Andric   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
39400b57cec5SDimitry Andric 
39410b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
39420b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
39430b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
39440b57cec5SDimitry Andric     // invoke.
39450b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
39460b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
39470b57cec5SDimitry Andric       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
39480b57cec5SDimitry Andric              "Block containing LandingPadInst must be jumped to "
39490b57cec5SDimitry Andric              "only by the unwind edge of an invoke.",
39500b57cec5SDimitry Andric              LPI);
39510b57cec5SDimitry Andric     }
39520b57cec5SDimitry Andric     return;
39530b57cec5SDimitry Andric   }
39540b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
39550b57cec5SDimitry Andric     if (!pred_empty(BB))
39560b57cec5SDimitry Andric       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
39570b57cec5SDimitry Andric              "Block containg CatchPadInst must be jumped to "
39580b57cec5SDimitry Andric              "only by its catchswitch.",
39590b57cec5SDimitry Andric              CPI);
39600b57cec5SDimitry Andric     Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
39610b57cec5SDimitry Andric            "Catchswitch cannot unwind to one of its catchpads",
39620b57cec5SDimitry Andric            CPI->getCatchSwitch(), CPI);
39630b57cec5SDimitry Andric     return;
39640b57cec5SDimitry Andric   }
39650b57cec5SDimitry Andric 
39660b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
39670b57cec5SDimitry Andric   // pad relationship.
39680b57cec5SDimitry Andric   Instruction *ToPad = &I;
39690b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
39700b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
39710b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
39720b57cec5SDimitry Andric     Value *FromPad;
39730b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
39740b57cec5SDimitry Andric       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
39750b57cec5SDimitry Andric              "EH pad must be jumped to via an unwind edge", ToPad, II);
39760b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
39770b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
39780b57cec5SDimitry Andric       else
39790b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
39800b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
39810b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
39820b57cec5SDimitry Andric       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
39830b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
39840b57cec5SDimitry Andric       FromPad = CSI;
39850b57cec5SDimitry Andric     } else {
39860b57cec5SDimitry Andric       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
39870b57cec5SDimitry Andric     }
39880b57cec5SDimitry Andric 
39890b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
39900b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
39910b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
39920b57cec5SDimitry Andric       Assert(FromPad != ToPad,
39930b57cec5SDimitry Andric              "EH pad cannot handle exceptions raised within it", FromPad, TI);
39940b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
39950b57cec5SDimitry Andric         // This is a legal unwind edge.
39960b57cec5SDimitry Andric         break;
39970b57cec5SDimitry Andric       }
39980b57cec5SDimitry Andric       Assert(!isa<ConstantTokenNone>(FromPad),
39990b57cec5SDimitry Andric              "A single unwind edge may only enter one EH pad", TI);
40000b57cec5SDimitry Andric       Assert(Seen.insert(FromPad).second,
40010b57cec5SDimitry Andric              "EH pad jumps through a cycle of pads", FromPad);
400204eeddc0SDimitry Andric 
400304eeddc0SDimitry Andric       // This will be diagnosed on the corresponding instruction already. We
400404eeddc0SDimitry Andric       // need the extra check here to make sure getParentPad() works.
400504eeddc0SDimitry Andric       Assert(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
400604eeddc0SDimitry Andric              "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
40070b57cec5SDimitry Andric     }
40080b57cec5SDimitry Andric   }
40090b57cec5SDimitry Andric }
40100b57cec5SDimitry Andric 
40110b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
40120b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
40130b57cec5SDimitry Andric   // isn't a cleanup.
40140b57cec5SDimitry Andric   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
40150b57cec5SDimitry Andric          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
40180b57cec5SDimitry Andric 
40190b57cec5SDimitry Andric   if (!LandingPadResultTy)
40200b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
40210b57cec5SDimitry Andric   else
40220b57cec5SDimitry Andric     Assert(LandingPadResultTy == LPI.getType(),
40230b57cec5SDimitry Andric            "The landingpad instruction should have a consistent result type "
40240b57cec5SDimitry Andric            "inside a function.",
40250b57cec5SDimitry Andric            &LPI);
40260b57cec5SDimitry Andric 
40270b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
40280b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
40290b57cec5SDimitry Andric          "LandingPadInst needs to be in a function with a personality.", &LPI);
40300b57cec5SDimitry Andric 
40310b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
40320b57cec5SDimitry Andric   // block.
40330b57cec5SDimitry Andric   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
40340b57cec5SDimitry Andric          "LandingPadInst not the first non-PHI instruction in the block.",
40350b57cec5SDimitry Andric          &LPI);
40360b57cec5SDimitry Andric 
40370b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
40380b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
40390b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
40400b57cec5SDimitry Andric       Assert(isa<PointerType>(Clause->getType()),
40410b57cec5SDimitry Andric              "Catch operand does not have pointer type!", &LPI);
40420b57cec5SDimitry Andric     } else {
40430b57cec5SDimitry Andric       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
40440b57cec5SDimitry Andric       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
40450b57cec5SDimitry Andric              "Filter operand is not an array of constants!", &LPI);
40460b57cec5SDimitry Andric     }
40470b57cec5SDimitry Andric   }
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric   visitInstruction(LPI);
40500b57cec5SDimitry Andric }
40510b57cec5SDimitry Andric 
40520b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
40530b57cec5SDimitry Andric   Assert(RI.getFunction()->hasPersonalityFn(),
40540b57cec5SDimitry Andric          "ResumeInst needs to be in a function with a personality.", &RI);
40550b57cec5SDimitry Andric 
40560b57cec5SDimitry Andric   if (!LandingPadResultTy)
40570b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
40580b57cec5SDimitry Andric   else
40590b57cec5SDimitry Andric     Assert(LandingPadResultTy == RI.getValue()->getType(),
40600b57cec5SDimitry Andric            "The resume instruction should have a consistent result type "
40610b57cec5SDimitry Andric            "inside a function.",
40620b57cec5SDimitry Andric            &RI);
40630b57cec5SDimitry Andric 
40640b57cec5SDimitry Andric   visitTerminator(RI);
40650b57cec5SDimitry Andric }
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
40680b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
40690b57cec5SDimitry Andric 
40700b57cec5SDimitry Andric   Function *F = BB->getParent();
40710b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
40720b57cec5SDimitry Andric          "CatchPadInst needs to be in a function with a personality.", &CPI);
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
40750b57cec5SDimitry Andric          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
40760b57cec5SDimitry Andric          CPI.getParentPad());
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
40790b57cec5SDimitry Andric   // block.
40800b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CPI,
40810b57cec5SDimitry Andric          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
40820b57cec5SDimitry Andric 
40830b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
40840b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
40850b57cec5SDimitry Andric }
40860b57cec5SDimitry Andric 
40870b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
40880b57cec5SDimitry Andric   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
40890b57cec5SDimitry Andric          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
40900b57cec5SDimitry Andric          CatchReturn.getOperand(0));
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric   visitTerminator(CatchReturn);
40930b57cec5SDimitry Andric }
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
40960b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   Function *F = BB->getParent();
40990b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
41000b57cec5SDimitry Andric          "CleanupPadInst needs to be in a function with a personality.", &CPI);
41010b57cec5SDimitry Andric 
41020b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
41030b57cec5SDimitry Andric   // block.
41040b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CPI,
41050b57cec5SDimitry Andric          "CleanupPadInst not the first non-PHI instruction in the block.",
41060b57cec5SDimitry Andric          &CPI);
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
41090b57cec5SDimitry Andric   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
41100b57cec5SDimitry Andric          "CleanupPadInst has an invalid parent.", &CPI);
41110b57cec5SDimitry Andric 
41120b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
41130b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
41140b57cec5SDimitry Andric }
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
41170b57cec5SDimitry Andric   User *FirstUser = nullptr;
41180b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
41190b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
41200b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
41210b57cec5SDimitry Andric 
41220b57cec5SDimitry Andric   while (!Worklist.empty()) {
41230b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
41240b57cec5SDimitry Andric     Assert(Seen.insert(CurrentPad).second,
41250b57cec5SDimitry Andric            "FuncletPadInst must not be nested within itself", CurrentPad);
41260b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
41270b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
41280b57cec5SDimitry Andric       BasicBlock *UnwindDest;
41290b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
41300b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
41310b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
41320b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
41330b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
41340b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
41350b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
41360b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
41370b57cec5SDimitry Andric           continue;
41380b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
41390b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
41400b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
41410b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
41420b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
41430b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
41440b57cec5SDimitry Andric         // such calls to be annotated nounwind.
41450b57cec5SDimitry Andric         continue;
41460b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
41470b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
41480b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
41490b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
41500b57cec5SDimitry Andric         Worklist.push_back(CPI);
41510b57cec5SDimitry Andric         continue;
41520b57cec5SDimitry Andric       } else {
41530b57cec5SDimitry Andric         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
41540b57cec5SDimitry Andric         continue;
41550b57cec5SDimitry Andric       }
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric       Value *UnwindPad;
41580b57cec5SDimitry Andric       bool ExitsFPI;
41590b57cec5SDimitry Andric       if (UnwindDest) {
41600b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
41610b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
41620b57cec5SDimitry Andric           continue;
41630b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
41640b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
41650b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
41660b57cec5SDimitry Andric           continue;
41670b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
41680b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
41690b57cec5SDimitry Andric         // of them are exited so we can stop searching their
41700b57cec5SDimitry Andric         // children.
41710b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
41720b57cec5SDimitry Andric         ExitsFPI = false;
41730b57cec5SDimitry Andric         do {
41740b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
41750b57cec5SDimitry Andric             ExitsFPI = true;
41760b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
41770b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
41780b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
41790b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
41800b57cec5SDimitry Andric             break;
41810b57cec5SDimitry Andric           }
41820b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
41830b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
41840b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
41850b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
41860b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
41870b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
41880b57cec5SDimitry Andric             break;
41890b57cec5SDimitry Andric           }
41900b57cec5SDimitry Andric           ExitedPad = ExitedParent;
41910b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
41920b57cec5SDimitry Andric       } else {
41930b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
41940b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
41950b57cec5SDimitry Andric         ExitsFPI = true;
41960b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
41970b57cec5SDimitry Andric       }
41980b57cec5SDimitry Andric 
41990b57cec5SDimitry Andric       if (ExitsFPI) {
42000b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
42010b57cec5SDimitry Andric         // such edges.
42020b57cec5SDimitry Andric         if (FirstUser) {
42030b57cec5SDimitry Andric           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
42040b57cec5SDimitry Andric                                               "pad must have the same unwind "
42050b57cec5SDimitry Andric                                               "dest",
42060b57cec5SDimitry Andric                  &FPI, U, FirstUser);
42070b57cec5SDimitry Andric         } else {
42080b57cec5SDimitry Andric           FirstUser = U;
42090b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
42100b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
42110b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
42120b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
42130b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
42140b57cec5SDimitry Andric         }
42150b57cec5SDimitry Andric       }
42160b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
42170b57cec5SDimitry Andric       // soon as we know where they unwind to.
42180b57cec5SDimitry Andric       if (CurrentPad != &FPI)
42190b57cec5SDimitry Andric         break;
42200b57cec5SDimitry Andric     }
42210b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
42220b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
42230b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
42240b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
42250b57cec5SDimitry Andric         // all direct uses of FPI.
42260b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
42270b57cec5SDimitry Andric         continue;
42280b57cec5SDimitry Andric       }
42290b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
42300b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
42310b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
42320b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
42330b57cec5SDimitry Andric       // UnresolvedAncestorPad.
42340b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
42350b57cec5SDimitry Andric       while (!Worklist.empty()) {
42360b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
42370b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
42380b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
42390b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
42400b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
42410b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
42420b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
42430b57cec5SDimitry Andric             break;
42440b57cec5SDimitry Andric           }
42450b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
42460b57cec5SDimitry Andric         }
42470b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
42480b57cec5SDimitry Andric         // then the uncle is not yet resolved.
42490b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
42500b57cec5SDimitry Andric           break;
42510b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
42520b57cec5SDimitry Andric         Worklist.pop_back();
42530b57cec5SDimitry Andric       }
42540b57cec5SDimitry Andric     }
42550b57cec5SDimitry Andric   }
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric   if (FirstUnwindPad) {
42580b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
42590b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
42600b57cec5SDimitry Andric       Value *SwitchUnwindPad;
42610b57cec5SDimitry Andric       if (SwitchUnwindDest)
42620b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
42630b57cec5SDimitry Andric       else
42640b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
42650b57cec5SDimitry Andric       Assert(SwitchUnwindPad == FirstUnwindPad,
42660b57cec5SDimitry Andric              "Unwind edges out of a catch must have the same unwind dest as "
42670b57cec5SDimitry Andric              "the parent catchswitch",
42680b57cec5SDimitry Andric              &FPI, FirstUser, CatchSwitch);
42690b57cec5SDimitry Andric     }
42700b57cec5SDimitry Andric   }
42710b57cec5SDimitry Andric 
42720b57cec5SDimitry Andric   visitInstruction(FPI);
42730b57cec5SDimitry Andric }
42740b57cec5SDimitry Andric 
42750b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
42760b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
42770b57cec5SDimitry Andric 
42780b57cec5SDimitry Andric   Function *F = BB->getParent();
42790b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
42800b57cec5SDimitry Andric          "CatchSwitchInst needs to be in a function with a personality.",
42810b57cec5SDimitry Andric          &CatchSwitch);
42820b57cec5SDimitry Andric 
42830b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
42840b57cec5SDimitry Andric   // block.
42850b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CatchSwitch,
42860b57cec5SDimitry Andric          "CatchSwitchInst not the first non-PHI instruction in the block.",
42870b57cec5SDimitry Andric          &CatchSwitch);
42880b57cec5SDimitry Andric 
42890b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
42900b57cec5SDimitry Andric   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
42910b57cec5SDimitry Andric          "CatchSwitchInst has an invalid parent.", ParentPad);
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
42940b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
42950b57cec5SDimitry Andric     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
42960b57cec5SDimitry Andric            "CatchSwitchInst must unwind to an EH block which is not a "
42970b57cec5SDimitry Andric            "landingpad.",
42980b57cec5SDimitry Andric            &CatchSwitch);
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
43010b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
43020b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
43030b57cec5SDimitry Andric   }
43040b57cec5SDimitry Andric 
43050b57cec5SDimitry Andric   Assert(CatchSwitch.getNumHandlers() != 0,
43060b57cec5SDimitry Andric          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
43070b57cec5SDimitry Andric 
43080b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
43090b57cec5SDimitry Andric     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
43100b57cec5SDimitry Andric            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
43110b57cec5SDimitry Andric   }
43120b57cec5SDimitry Andric 
43130b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
43140b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
43150b57cec5SDimitry Andric }
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
43180b57cec5SDimitry Andric   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
43190b57cec5SDimitry Andric          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
43200b57cec5SDimitry Andric          CRI.getOperand(0));
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
43230b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
43240b57cec5SDimitry Andric     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
43250b57cec5SDimitry Andric            "CleanupReturnInst must unwind to an EH block which is not a "
43260b57cec5SDimitry Andric            "landingpad.",
43270b57cec5SDimitry Andric            &CRI);
43280b57cec5SDimitry Andric   }
43290b57cec5SDimitry Andric 
43300b57cec5SDimitry Andric   visitTerminator(CRI);
43310b57cec5SDimitry Andric }
43320b57cec5SDimitry Andric 
43330b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
43340b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
43350b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
43360b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
43370b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
43380b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
43390b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
43400b57cec5SDimitry Andric       return;
43410b57cec5SDimitry Andric   }
43420b57cec5SDimitry Andric 
43430b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
43440b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
43450b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
43460b57cec5SDimitry Andric   //
43470b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
43480b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
43490b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
43500b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
43510b57cec5SDimitry Andric     return;
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
43540b57cec5SDimitry Andric   Assert(DT.dominates(Op, U),
43550b57cec5SDimitry Andric          "Instruction does not dominate all uses!", Op, &I);
43560b57cec5SDimitry Andric }
43570b57cec5SDimitry Andric 
43580b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
43590b57cec5SDimitry Andric   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
43600b57cec5SDimitry Andric          "apply only to pointer types", &I);
43618bcb0991SDimitry Andric   Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
43620b57cec5SDimitry Andric          "dereferenceable, dereferenceable_or_null apply only to load"
43638bcb0991SDimitry Andric          " and inttoptr instructions, use attributes for calls or invokes", &I);
43640b57cec5SDimitry Andric   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
43650b57cec5SDimitry Andric          "take one operand!", &I);
43660b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
43670b57cec5SDimitry Andric   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
43680b57cec5SDimitry Andric          "dereferenceable_or_null metadata value must be an i64!", &I);
43690b57cec5SDimitry Andric }
43700b57cec5SDimitry Andric 
43718bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
43728bcb0991SDimitry Andric   Assert(MD->getNumOperands() >= 2,
43738bcb0991SDimitry Andric          "!prof annotations should have no less than 2 operands", MD);
43748bcb0991SDimitry Andric 
43758bcb0991SDimitry Andric   // Check first operand.
43768bcb0991SDimitry Andric   Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
43778bcb0991SDimitry Andric   Assert(isa<MDString>(MD->getOperand(0)),
43788bcb0991SDimitry Andric          "expected string with name of the !prof annotation", MD);
43798bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
43808bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
43818bcb0991SDimitry Andric 
43828bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
43838bcb0991SDimitry Andric   if (ProfName.equals("branch_weights")) {
43845ffd83dbSDimitry Andric     if (isa<InvokeInst>(&I)) {
43855ffd83dbSDimitry Andric       Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
43865ffd83dbSDimitry Andric              "Wrong number of InvokeInst branch_weights operands", MD);
43875ffd83dbSDimitry Andric     } else {
43888bcb0991SDimitry Andric       unsigned ExpectedNumOperands = 0;
43898bcb0991SDimitry Andric       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
43908bcb0991SDimitry Andric         ExpectedNumOperands = BI->getNumSuccessors();
43918bcb0991SDimitry Andric       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
43928bcb0991SDimitry Andric         ExpectedNumOperands = SI->getNumSuccessors();
43935ffd83dbSDimitry Andric       else if (isa<CallInst>(&I))
43948bcb0991SDimitry Andric         ExpectedNumOperands = 1;
43958bcb0991SDimitry Andric       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
43968bcb0991SDimitry Andric         ExpectedNumOperands = IBI->getNumDestinations();
43978bcb0991SDimitry Andric       else if (isa<SelectInst>(&I))
43988bcb0991SDimitry Andric         ExpectedNumOperands = 2;
43998bcb0991SDimitry Andric       else
44008bcb0991SDimitry Andric         CheckFailed("!prof branch_weights are not allowed for this instruction",
44018bcb0991SDimitry Andric                     MD);
44028bcb0991SDimitry Andric 
44038bcb0991SDimitry Andric       Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
44048bcb0991SDimitry Andric              "Wrong number of operands", MD);
44055ffd83dbSDimitry Andric     }
44068bcb0991SDimitry Andric     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
44078bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
44088bcb0991SDimitry Andric       Assert(MDO, "second operand should not be null", MD);
44098bcb0991SDimitry Andric       Assert(mdconst::dyn_extract<ConstantInt>(MDO),
44108bcb0991SDimitry Andric              "!prof brunch_weights operand is not a const int");
44118bcb0991SDimitry Andric     }
44128bcb0991SDimitry Andric   }
44138bcb0991SDimitry Andric }
44148bcb0991SDimitry Andric 
4415e8d8bef9SDimitry Andric void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
4416e8d8bef9SDimitry Andric   Assert(isa<MDTuple>(Annotation), "annotation must be a tuple");
4417e8d8bef9SDimitry Andric   Assert(Annotation->getNumOperands() >= 1,
4418e8d8bef9SDimitry Andric          "annotation must have at least one operand");
4419e8d8bef9SDimitry Andric   for (const MDOperand &Op : Annotation->operands())
4420e8d8bef9SDimitry Andric     Assert(isa<MDString>(Op.get()), "operands must be strings");
4421e8d8bef9SDimitry Andric }
4422e8d8bef9SDimitry Andric 
4423349cc55cSDimitry Andric void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4424349cc55cSDimitry Andric   unsigned NumOps = MD->getNumOperands();
4425349cc55cSDimitry Andric   Assert(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4426349cc55cSDimitry Andric          MD);
4427349cc55cSDimitry Andric   Assert(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4428349cc55cSDimitry Andric          "first scope operand must be self-referential or string", MD);
4429349cc55cSDimitry Andric   if (NumOps == 3)
4430349cc55cSDimitry Andric     Assert(isa<MDString>(MD->getOperand(2)),
4431349cc55cSDimitry Andric            "third scope operand must be string (if used)", MD);
4432349cc55cSDimitry Andric 
4433349cc55cSDimitry Andric   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
4434349cc55cSDimitry Andric   Assert(Domain != nullptr, "second scope operand must be MDNode", MD);
4435349cc55cSDimitry Andric 
4436349cc55cSDimitry Andric   unsigned NumDomainOps = Domain->getNumOperands();
4437349cc55cSDimitry Andric   Assert(NumDomainOps >= 1 && NumDomainOps <= 2,
4438349cc55cSDimitry Andric          "domain must have one or two operands", Domain);
4439349cc55cSDimitry Andric   Assert(Domain->getOperand(0).get() == Domain ||
4440349cc55cSDimitry Andric              isa<MDString>(Domain->getOperand(0)),
4441349cc55cSDimitry Andric          "first domain operand must be self-referential or string", Domain);
4442349cc55cSDimitry Andric   if (NumDomainOps == 2)
4443349cc55cSDimitry Andric     Assert(isa<MDString>(Domain->getOperand(1)),
4444349cc55cSDimitry Andric            "second domain operand must be string (if used)", Domain);
4445349cc55cSDimitry Andric }
4446349cc55cSDimitry Andric 
4447349cc55cSDimitry Andric void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4448349cc55cSDimitry Andric   for (const MDOperand &Op : MD->operands()) {
4449349cc55cSDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
4450349cc55cSDimitry Andric     Assert(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4451349cc55cSDimitry Andric     visitAliasScopeMetadata(OpMD);
4452349cc55cSDimitry Andric   }
4453349cc55cSDimitry Andric }
4454349cc55cSDimitry Andric 
44550b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
44560b57cec5SDimitry Andric ///
44570b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
44580b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
44590b57cec5SDimitry Andric   Assert(BB, "Instruction not embedded in basic block!", &I);
44600b57cec5SDimitry Andric 
44610b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
44620b57cec5SDimitry Andric     for (User *U : I.users()) {
44630b57cec5SDimitry Andric       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
44640b57cec5SDimitry Andric              "Only PHI nodes may reference their own value!", &I);
44650b57cec5SDimitry Andric     }
44660b57cec5SDimitry Andric   }
44670b57cec5SDimitry Andric 
44680b57cec5SDimitry Andric   // Check that void typed values don't have names
44690b57cec5SDimitry Andric   Assert(!I.getType()->isVoidTy() || !I.hasName(),
44700b57cec5SDimitry Andric          "Instruction has a name, but provides a void value!", &I);
44710b57cec5SDimitry Andric 
44720b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
44730b57cec5SDimitry Andric   // value type.
44740b57cec5SDimitry Andric   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
44750b57cec5SDimitry Andric          "Instruction returns a non-scalar type!", &I);
44760b57cec5SDimitry Andric 
44770b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
44780b57cec5SDimitry Andric   // checked against the callee type.
44790b57cec5SDimitry Andric   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
44800b57cec5SDimitry Andric          "Invalid use of metadata!", &I);
44810b57cec5SDimitry Andric 
44820b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
44830b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
44840b57cec5SDimitry Andric   // instruction, it is an error!
44850b57cec5SDimitry Andric   for (Use &U : I.uses()) {
44860b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
44870b57cec5SDimitry Andric       Assert(Used->getParent() != nullptr,
44880b57cec5SDimitry Andric              "Instruction referencing"
44890b57cec5SDimitry Andric              " instruction not embedded in a basic block!",
44900b57cec5SDimitry Andric              &I, Used);
44910b57cec5SDimitry Andric     else {
44920b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
44930b57cec5SDimitry Andric       return;
44940b57cec5SDimitry Andric     }
44950b57cec5SDimitry Andric   }
44960b57cec5SDimitry Andric 
44970b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
44980b57cec5SDimitry Andric   // call.
44990b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
45000b57cec5SDimitry Andric 
45010b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
45020b57cec5SDimitry Andric     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
45030b57cec5SDimitry Andric 
45040b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
45050b57cec5SDimitry Andric     // instructions.
45060b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
45070b57cec5SDimitry Andric       Assert(false, "Instruction operands must be first-class values!", &I);
45080b57cec5SDimitry Andric     }
45090b57cec5SDimitry Andric 
45100b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4511349cc55cSDimitry Andric       // This code checks whether the function is used as the operand of a
4512349cc55cSDimitry Andric       // clang_arc_attachedcall operand bundle.
4513349cc55cSDimitry Andric       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4514349cc55cSDimitry Andric                                       int Idx) {
4515349cc55cSDimitry Andric         return CBI && CBI->isOperandBundleOfType(
4516349cc55cSDimitry Andric                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4517349cc55cSDimitry Andric       };
4518349cc55cSDimitry Andric 
45190b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
4520349cc55cSDimitry Andric       // taken. Ignore cases where the address of the intrinsic function is used
4521349cc55cSDimitry Andric       // as the argument of operand bundle "clang.arc.attachedcall" as those
4522349cc55cSDimitry Andric       // cases are handled in verifyAttachedCallBundle.
4523349cc55cSDimitry Andric       Assert((!F->isIntrinsic() ||
4524349cc55cSDimitry Andric               (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4525349cc55cSDimitry Andric               IsAttachedCallOperand(F, CBI, i)),
45260b57cec5SDimitry Andric              "Cannot take the address of an intrinsic!", &I);
45270b57cec5SDimitry Andric       Assert(
45280b57cec5SDimitry Andric           !F->isIntrinsic() || isa<CallInst>(I) ||
45290b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::donothing ||
4530fe6060f1SDimitry Andric               F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4531fe6060f1SDimitry Andric               F->getIntrinsicID() == Intrinsic::seh_try_end ||
4532fe6060f1SDimitry Andric               F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4533fe6060f1SDimitry Andric               F->getIntrinsicID() == Intrinsic::seh_scope_end ||
45340b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::coro_resume ||
45350b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::coro_destroy ||
45360b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
45370b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
45380b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4539349cc55cSDimitry Andric               F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4540349cc55cSDimitry Andric               IsAttachedCallOperand(F, CBI, i),
45410b57cec5SDimitry Andric           "Cannot invoke an intrinsic other than donothing, patchpoint, "
4542349cc55cSDimitry Andric           "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
45430b57cec5SDimitry Andric           &I);
45440b57cec5SDimitry Andric       Assert(F->getParent() == &M, "Referencing function in another module!",
45450b57cec5SDimitry Andric              &I, &M, F, F->getParent());
45460b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
45470b57cec5SDimitry Andric       Assert(OpBB->getParent() == BB->getParent(),
45480b57cec5SDimitry Andric              "Referring to a basic block in another function!", &I);
45490b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
45500b57cec5SDimitry Andric       Assert(OpArg->getParent() == BB->getParent(),
45510b57cec5SDimitry Andric              "Referring to an argument in another function!", &I);
45520b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
45530b57cec5SDimitry Andric       Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
45540b57cec5SDimitry Andric              &M, GV, GV->getParent());
45550b57cec5SDimitry Andric     } else if (isa<Instruction>(I.getOperand(i))) {
45560b57cec5SDimitry Andric       verifyDominatesUse(I, i);
45570b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
45580b57cec5SDimitry Andric       Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
45590b57cec5SDimitry Andric              "Cannot take the address of an inline asm!", &I);
45600b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4561fe6060f1SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy()) {
45620b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
4563fe6060f1SDimitry Andric         // illegal bitcast.
45640b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
45650b57cec5SDimitry Andric       }
45660b57cec5SDimitry Andric     }
45670b57cec5SDimitry Andric   }
45680b57cec5SDimitry Andric 
45690b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
45700b57cec5SDimitry Andric     Assert(I.getType()->isFPOrFPVectorTy(),
45710b57cec5SDimitry Andric            "fpmath requires a floating point result!", &I);
45720b57cec5SDimitry Andric     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
45730b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
45740b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
45750b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
45760b57cec5SDimitry Andric       Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
45770b57cec5SDimitry Andric              "fpmath accuracy must have float type", &I);
45780b57cec5SDimitry Andric       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
45790b57cec5SDimitry Andric              "fpmath accuracy not a positive number!", &I);
45800b57cec5SDimitry Andric     } else {
45810b57cec5SDimitry Andric       Assert(false, "invalid fpmath accuracy!", &I);
45820b57cec5SDimitry Andric     }
45830b57cec5SDimitry Andric   }
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
45860b57cec5SDimitry Andric     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
45870b57cec5SDimitry Andric            "Ranges are only for loads, calls and invokes!", &I);
45880b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
45890b57cec5SDimitry Andric   }
45900b57cec5SDimitry Andric 
4591349cc55cSDimitry Andric   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
4592349cc55cSDimitry Andric     Assert(isa<LoadInst>(I) || isa<StoreInst>(I),
4593349cc55cSDimitry Andric            "invariant.group metadata is only for loads and stores", &I);
4594349cc55cSDimitry Andric   }
4595349cc55cSDimitry Andric 
45960b57cec5SDimitry Andric   if (I.getMetadata(LLVMContext::MD_nonnull)) {
45970b57cec5SDimitry Andric     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
45980b57cec5SDimitry Andric            &I);
45990b57cec5SDimitry Andric     Assert(isa<LoadInst>(I),
46000b57cec5SDimitry Andric            "nonnull applies only to load instructions, use attributes"
46010b57cec5SDimitry Andric            " for calls or invokes",
46020b57cec5SDimitry Andric            &I);
46030b57cec5SDimitry Andric   }
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
46060b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
46070b57cec5SDimitry Andric 
46080b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
46090b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
46120b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
46130b57cec5SDimitry Andric 
4614349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
4615349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
4616349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
4617349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
4618349cc55cSDimitry Andric 
46190b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
46200b57cec5SDimitry Andric     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
46210b57cec5SDimitry Andric            &I);
46220b57cec5SDimitry Andric     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
46230b57cec5SDimitry Andric            "use attributes for calls or invokes", &I);
46240b57cec5SDimitry Andric     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
46250b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
46260b57cec5SDimitry Andric     Assert(CI && CI->getType()->isIntegerTy(64),
46270b57cec5SDimitry Andric            "align metadata value must be an i64!", &I);
46280b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
46290b57cec5SDimitry Andric     Assert(isPowerOf2_64(Align),
46300b57cec5SDimitry Andric            "align metadata value must be a power of 2!", &I);
46310b57cec5SDimitry Andric     Assert(Align <= Value::MaximumAlignment,
46320b57cec5SDimitry Andric            "alignment is larger that implementation defined limit", &I);
46330b57cec5SDimitry Andric   }
46340b57cec5SDimitry Andric 
46358bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
46368bcb0991SDimitry Andric     visitProfMetadata(I, MD);
46378bcb0991SDimitry Andric 
4638e8d8bef9SDimitry Andric   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
4639e8d8bef9SDimitry Andric     visitAnnotationMetadata(Annotation);
4640e8d8bef9SDimitry Andric 
46410b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
46420b57cec5SDimitry Andric     AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
46435ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::Yes);
46440b57cec5SDimitry Andric   }
46450b57cec5SDimitry Andric 
46468bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
46470b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
46488bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
46498bcb0991SDimitry Andric   }
46500b57cec5SDimitry Andric 
46515ffd83dbSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
46525ffd83dbSDimitry Andric   I.getAllMetadata(MDs);
46535ffd83dbSDimitry Andric   for (auto Attachment : MDs) {
46545ffd83dbSDimitry Andric     unsigned Kind = Attachment.first;
46555ffd83dbSDimitry Andric     auto AllowLocs =
46565ffd83dbSDimitry Andric         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
46575ffd83dbSDimitry Andric             ? AreDebugLocsAllowed::Yes
46585ffd83dbSDimitry Andric             : AreDebugLocsAllowed::No;
46595ffd83dbSDimitry Andric     visitMDNode(*Attachment.second, AllowLocs);
46605ffd83dbSDimitry Andric   }
46615ffd83dbSDimitry Andric 
46620b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
46630b57cec5SDimitry Andric }
46640b57cec5SDimitry Andric 
46650b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
46660b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
46670b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
46680b57cec5SDimitry Andric   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
46690b57cec5SDimitry Andric          IF);
46700b57cec5SDimitry Andric 
46710b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
46720b57cec5SDimitry Andric   // describe.
46730b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
46740b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
46750b57cec5SDimitry Andric 
46760b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
46770b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
46780b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
46790b57cec5SDimitry Andric 
46800b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
46810b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
46820b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
46830b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
46840b57cec5SDimitry Andric   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
46850b57cec5SDimitry Andric          "Intrinsic has incorrect return type!", IF);
46860b57cec5SDimitry Andric   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
46870b57cec5SDimitry Andric          "Intrinsic has incorrect argument type!", IF);
46880b57cec5SDimitry Andric 
46890b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
46900b57cec5SDimitry Andric   if (IsVarArg)
46910b57cec5SDimitry Andric     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
46920b57cec5SDimitry Andric            "Intrinsic was not defined with variable arguments!", IF);
46930b57cec5SDimitry Andric   else
46940b57cec5SDimitry Andric     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
46950b57cec5SDimitry Andric            "Callsite was not defined with variable arguments!", IF);
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
46980b57cec5SDimitry Andric   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
47010b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
47020b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
47030b57cec5SDimitry Andric   // the name.
4704fe6060f1SDimitry Andric   const std::string ExpectedName =
4705fe6060f1SDimitry Andric       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
47060b57cec5SDimitry Andric   Assert(ExpectedName == IF->getName(),
47070b57cec5SDimitry Andric          "Intrinsic name not mangled correctly for type arguments! "
47080b57cec5SDimitry Andric          "Should be: " +
47090b57cec5SDimitry Andric              ExpectedName,
47100b57cec5SDimitry Andric          IF);
47110b57cec5SDimitry Andric 
47120b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
47130b57cec5SDimitry Andric   // or are local to *this* function.
4714fe6060f1SDimitry Andric   for (Value *V : Call.args()) {
47150b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
47160b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
4717fe6060f1SDimitry Andric     if (auto *Const = dyn_cast<Constant>(V))
4718fe6060f1SDimitry Andric       Assert(!Const->getType()->isX86_AMXTy(),
4719fe6060f1SDimitry Andric              "const x86_amx is not allowed in argument!");
4720fe6060f1SDimitry Andric   }
47210b57cec5SDimitry Andric 
47220b57cec5SDimitry Andric   switch (ID) {
47230b57cec5SDimitry Andric   default:
47240b57cec5SDimitry Andric     break;
47255ffd83dbSDimitry Andric   case Intrinsic::assume: {
47265ffd83dbSDimitry Andric     for (auto &Elem : Call.bundle_op_infos()) {
47275ffd83dbSDimitry Andric       Assert(Elem.Tag->getKey() == "ignore" ||
47285ffd83dbSDimitry Andric                  Attribute::isExistingAttribute(Elem.Tag->getKey()),
4729349cc55cSDimitry Andric              "tags must be valid attribute names", Call);
47305ffd83dbSDimitry Andric       Attribute::AttrKind Kind =
47315ffd83dbSDimitry Andric           Attribute::getAttrKindFromName(Elem.Tag->getKey());
4732e8d8bef9SDimitry Andric       unsigned ArgCount = Elem.End - Elem.Begin;
4733e8d8bef9SDimitry Andric       if (Kind == Attribute::Alignment) {
4734e8d8bef9SDimitry Andric         Assert(ArgCount <= 3 && ArgCount >= 2,
4735349cc55cSDimitry Andric                "alignment assumptions should have 2 or 3 arguments", Call);
4736e8d8bef9SDimitry Andric         Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
4737349cc55cSDimitry Andric                "first argument should be a pointer", Call);
4738e8d8bef9SDimitry Andric         Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
4739349cc55cSDimitry Andric                "second argument should be an integer", Call);
4740e8d8bef9SDimitry Andric         if (ArgCount == 3)
4741e8d8bef9SDimitry Andric           Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
4742349cc55cSDimitry Andric                  "third argument should be an integer if present", Call);
4743e8d8bef9SDimitry Andric         return;
4744e8d8bef9SDimitry Andric       }
4745349cc55cSDimitry Andric       Assert(ArgCount <= 2, "too many arguments", Call);
47465ffd83dbSDimitry Andric       if (Kind == Attribute::None)
47475ffd83dbSDimitry Andric         break;
4748fe6060f1SDimitry Andric       if (Attribute::isIntAttrKind(Kind)) {
4749349cc55cSDimitry Andric         Assert(ArgCount == 2, "this attribute should have 2 arguments", Call);
47505ffd83dbSDimitry Andric         Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
4751349cc55cSDimitry Andric                "the second argument should be a constant integral value", Call);
4752fe6060f1SDimitry Andric       } else if (Attribute::canUseAsParamAttr(Kind)) {
4753349cc55cSDimitry Andric         Assert((ArgCount) == 1, "this attribute should have one argument",
4754349cc55cSDimitry Andric                Call);
4755fe6060f1SDimitry Andric       } else if (Attribute::canUseAsFnAttr(Kind)) {
4756349cc55cSDimitry Andric         Assert((ArgCount) == 0, "this attribute has no argument", Call);
47575ffd83dbSDimitry Andric       }
47585ffd83dbSDimitry Andric     }
47595ffd83dbSDimitry Andric     break;
47605ffd83dbSDimitry Andric   }
47610b57cec5SDimitry Andric   case Intrinsic::coro_id: {
47620b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
47630b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
47640b57cec5SDimitry Andric       break;
47650b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
47660b57cec5SDimitry Andric     Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
4767fe6060f1SDimitry Andric            "info argument of llvm.coro.id must refer to an initialized "
47680b57cec5SDimitry Andric            "constant");
47690b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
47700b57cec5SDimitry Andric     Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4771fe6060f1SDimitry Andric            "info argument of llvm.coro.id must refer to either a struct or "
47720b57cec5SDimitry Andric            "an array");
47730b57cec5SDimitry Andric     break;
47740b57cec5SDimitry Andric   }
47755ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
4776480093f4SDimitry Andric   case Intrinsic::INTRINSIC:
4777480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
47780b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
47790b57cec5SDimitry Andric     break;
47800b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
47810b57cec5SDimitry Andric     Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
47820b57cec5SDimitry Andric            "invalid llvm.dbg.declare intrinsic call 1", Call);
47830b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
47840b57cec5SDimitry Andric     break;
47850b57cec5SDimitry Andric   case Intrinsic::dbg_addr: // llvm.dbg.addr
47860b57cec5SDimitry Andric     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
47870b57cec5SDimitry Andric     break;
47880b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
47890b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
47900b57cec5SDimitry Andric     break;
47910b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
47920b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
47930b57cec5SDimitry Andric     break;
47940b57cec5SDimitry Andric   case Intrinsic::memcpy:
47955ffd83dbSDimitry Andric   case Intrinsic::memcpy_inline:
47960b57cec5SDimitry Andric   case Intrinsic::memmove:
47970b57cec5SDimitry Andric   case Intrinsic::memset: {
47980b57cec5SDimitry Andric     const auto *MI = cast<MemIntrinsic>(&Call);
47990b57cec5SDimitry Andric     auto IsValidAlignment = [&](unsigned Alignment) -> bool {
48000b57cec5SDimitry Andric       return Alignment == 0 || isPowerOf2_32(Alignment);
48010b57cec5SDimitry Andric     };
48020b57cec5SDimitry Andric     Assert(IsValidAlignment(MI->getDestAlignment()),
48030b57cec5SDimitry Andric            "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
48040b57cec5SDimitry Andric            Call);
48050b57cec5SDimitry Andric     if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
48060b57cec5SDimitry Andric       Assert(IsValidAlignment(MTI->getSourceAlignment()),
48070b57cec5SDimitry Andric              "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
48080b57cec5SDimitry Andric              Call);
48090b57cec5SDimitry Andric     }
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric     break;
48120b57cec5SDimitry Andric   }
48130b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
48140b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
48150b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
48160b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
48190b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
48200b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
48210b57cec5SDimitry Andric     Assert(ElementSizeVal.isPowerOf2(),
48220b57cec5SDimitry Andric            "element size of the element-wise atomic memory intrinsic "
48230b57cec5SDimitry Andric            "must be a power of 2",
48240b57cec5SDimitry Andric            Call);
48250b57cec5SDimitry Andric 
48260b57cec5SDimitry Andric     auto IsValidAlignment = [&](uint64_t Alignment) {
48270b57cec5SDimitry Andric       return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
48280b57cec5SDimitry Andric     };
48290b57cec5SDimitry Andric     uint64_t DstAlignment = AMI->getDestAlignment();
48300b57cec5SDimitry Andric     Assert(IsValidAlignment(DstAlignment),
48310b57cec5SDimitry Andric            "incorrect alignment of the destination argument", Call);
48320b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
48330b57cec5SDimitry Andric       uint64_t SrcAlignment = AMT->getSourceAlignment();
48340b57cec5SDimitry Andric       Assert(IsValidAlignment(SrcAlignment),
48350b57cec5SDimitry Andric              "incorrect alignment of the source argument", Call);
48360b57cec5SDimitry Andric     }
48370b57cec5SDimitry Andric     break;
48380b57cec5SDimitry Andric   }
48395ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_setup: {
48405ffd83dbSDimitry Andric     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
48415ffd83dbSDimitry Andric     Assert(NumArgs != nullptr,
48425ffd83dbSDimitry Andric            "llvm.call.preallocated.setup argument must be a constant");
48435ffd83dbSDimitry Andric     bool FoundCall = false;
48445ffd83dbSDimitry Andric     for (User *U : Call.users()) {
48455ffd83dbSDimitry Andric       auto *UseCall = dyn_cast<CallBase>(U);
48465ffd83dbSDimitry Andric       Assert(UseCall != nullptr,
48475ffd83dbSDimitry Andric              "Uses of llvm.call.preallocated.setup must be calls");
48485ffd83dbSDimitry Andric       const Function *Fn = UseCall->getCalledFunction();
48495ffd83dbSDimitry Andric       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
48505ffd83dbSDimitry Andric         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
48515ffd83dbSDimitry Andric         Assert(AllocArgIndex != nullptr,
48525ffd83dbSDimitry Andric                "llvm.call.preallocated.alloc arg index must be a constant");
48535ffd83dbSDimitry Andric         auto AllocArgIndexInt = AllocArgIndex->getValue();
48545ffd83dbSDimitry Andric         Assert(AllocArgIndexInt.sge(0) &&
48555ffd83dbSDimitry Andric                    AllocArgIndexInt.slt(NumArgs->getValue()),
48565ffd83dbSDimitry Andric                "llvm.call.preallocated.alloc arg index must be between 0 and "
48575ffd83dbSDimitry Andric                "corresponding "
48585ffd83dbSDimitry Andric                "llvm.call.preallocated.setup's argument count");
48595ffd83dbSDimitry Andric       } else if (Fn && Fn->getIntrinsicID() ==
48605ffd83dbSDimitry Andric                            Intrinsic::call_preallocated_teardown) {
48615ffd83dbSDimitry Andric         // nothing to do
48625ffd83dbSDimitry Andric       } else {
48635ffd83dbSDimitry Andric         Assert(!FoundCall, "Can have at most one call corresponding to a "
48645ffd83dbSDimitry Andric                            "llvm.call.preallocated.setup");
48655ffd83dbSDimitry Andric         FoundCall = true;
48665ffd83dbSDimitry Andric         size_t NumPreallocatedArgs = 0;
4867349cc55cSDimitry Andric         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
48685ffd83dbSDimitry Andric           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
48695ffd83dbSDimitry Andric             ++NumPreallocatedArgs;
48705ffd83dbSDimitry Andric           }
48715ffd83dbSDimitry Andric         }
48725ffd83dbSDimitry Andric         Assert(NumPreallocatedArgs != 0,
48735ffd83dbSDimitry Andric                "cannot use preallocated intrinsics on a call without "
48745ffd83dbSDimitry Andric                "preallocated arguments");
48755ffd83dbSDimitry Andric         Assert(NumArgs->equalsInt(NumPreallocatedArgs),
48765ffd83dbSDimitry Andric                "llvm.call.preallocated.setup arg size must be equal to number "
48775ffd83dbSDimitry Andric                "of preallocated arguments "
48785ffd83dbSDimitry Andric                "at call site",
48795ffd83dbSDimitry Andric                Call, *UseCall);
48805ffd83dbSDimitry Andric         // getOperandBundle() cannot be called if more than one of the operand
48815ffd83dbSDimitry Andric         // bundle exists. There is already a check elsewhere for this, so skip
48825ffd83dbSDimitry Andric         // here if we see more than one.
48835ffd83dbSDimitry Andric         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
48845ffd83dbSDimitry Andric             1) {
48855ffd83dbSDimitry Andric           return;
48865ffd83dbSDimitry Andric         }
48875ffd83dbSDimitry Andric         auto PreallocatedBundle =
48885ffd83dbSDimitry Andric             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
48895ffd83dbSDimitry Andric         Assert(PreallocatedBundle,
48905ffd83dbSDimitry Andric                "Use of llvm.call.preallocated.setup outside intrinsics "
48915ffd83dbSDimitry Andric                "must be in \"preallocated\" operand bundle");
48925ffd83dbSDimitry Andric         Assert(PreallocatedBundle->Inputs.front().get() == &Call,
48935ffd83dbSDimitry Andric                "preallocated bundle must have token from corresponding "
48945ffd83dbSDimitry Andric                "llvm.call.preallocated.setup");
48955ffd83dbSDimitry Andric       }
48965ffd83dbSDimitry Andric     }
48975ffd83dbSDimitry Andric     break;
48985ffd83dbSDimitry Andric   }
48995ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_arg: {
49005ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
49015ffd83dbSDimitry Andric     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
49025ffd83dbSDimitry Andric                         Intrinsic::call_preallocated_setup,
49035ffd83dbSDimitry Andric            "llvm.call.preallocated.arg token argument must be a "
49045ffd83dbSDimitry Andric            "llvm.call.preallocated.setup");
49055ffd83dbSDimitry Andric     Assert(Call.hasFnAttr(Attribute::Preallocated),
49065ffd83dbSDimitry Andric            "llvm.call.preallocated.arg must be called with a \"preallocated\" "
49075ffd83dbSDimitry Andric            "call site attribute");
49085ffd83dbSDimitry Andric     break;
49095ffd83dbSDimitry Andric   }
49105ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_teardown: {
49115ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
49125ffd83dbSDimitry Andric     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
49135ffd83dbSDimitry Andric                         Intrinsic::call_preallocated_setup,
49145ffd83dbSDimitry Andric            "llvm.call.preallocated.teardown token argument must be a "
49155ffd83dbSDimitry Andric            "llvm.call.preallocated.setup");
49165ffd83dbSDimitry Andric     break;
49175ffd83dbSDimitry Andric   }
49180b57cec5SDimitry Andric   case Intrinsic::gcroot:
49190b57cec5SDimitry Andric   case Intrinsic::gcwrite:
49200b57cec5SDimitry Andric   case Intrinsic::gcread:
49210b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
49220b57cec5SDimitry Andric       AllocaInst *AI =
49230b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
49240b57cec5SDimitry Andric       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
49250b57cec5SDimitry Andric       Assert(isa<Constant>(Call.getArgOperand(1)),
49260b57cec5SDimitry Andric              "llvm.gcroot parameter #2 must be a constant.", Call);
49270b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
49280b57cec5SDimitry Andric         Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
49290b57cec5SDimitry Andric                "llvm.gcroot parameter #1 must either be a pointer alloca, "
49300b57cec5SDimitry Andric                "or argument #2 must be a non-null constant.",
49310b57cec5SDimitry Andric                Call);
49320b57cec5SDimitry Andric       }
49330b57cec5SDimitry Andric     }
49340b57cec5SDimitry Andric 
49350b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
49360b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
49370b57cec5SDimitry Andric     break;
49380b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
49390b57cec5SDimitry Andric     Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
49400b57cec5SDimitry Andric            "llvm.init_trampoline parameter #2 must resolve to a function.",
49410b57cec5SDimitry Andric            Call);
49420b57cec5SDimitry Andric     break;
49430b57cec5SDimitry Andric   case Intrinsic::prefetch:
49440b57cec5SDimitry Andric     Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
49450b57cec5SDimitry Andric            cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
49460b57cec5SDimitry Andric            "invalid arguments to llvm.prefetch", Call);
49470b57cec5SDimitry Andric     break;
49480b57cec5SDimitry Andric   case Intrinsic::stackprotector:
49490b57cec5SDimitry Andric     Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
49500b57cec5SDimitry Andric            "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
49510b57cec5SDimitry Andric     break;
49520b57cec5SDimitry Andric   case Intrinsic::localescape: {
49530b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
49540b57cec5SDimitry Andric     Assert(BB == &BB->getParent()->front(),
49550b57cec5SDimitry Andric            "llvm.localescape used outside of entry block", Call);
49560b57cec5SDimitry Andric     Assert(!SawFrameEscape,
49570b57cec5SDimitry Andric            "multiple calls to llvm.localescape in one function", Call);
49580b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
49590b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
49600b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
49610b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
49620b57cec5SDimitry Andric       Assert(AI && AI->isStaticAlloca(),
49630b57cec5SDimitry Andric              "llvm.localescape only accepts static allocas", Call);
49640b57cec5SDimitry Andric     }
4965349cc55cSDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
49660b57cec5SDimitry Andric     SawFrameEscape = true;
49670b57cec5SDimitry Andric     break;
49680b57cec5SDimitry Andric   }
49690b57cec5SDimitry Andric   case Intrinsic::localrecover: {
49700b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
49710b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
49720b57cec5SDimitry Andric     Assert(Fn && !Fn->isDeclaration(),
49730b57cec5SDimitry Andric            "llvm.localrecover first "
49740b57cec5SDimitry Andric            "argument must be function defined in this module",
49750b57cec5SDimitry Andric            Call);
49760b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
49770b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
49780b57cec5SDimitry Andric     Entry.second = unsigned(
49790b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
49800b57cec5SDimitry Andric     break;
49810b57cec5SDimitry Andric   }
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
49840b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
49850b57cec5SDimitry Andric       Assert(!CI->isInlineAsm(),
49860b57cec5SDimitry Andric              "gc.statepoint support for inline assembly unimplemented", CI);
49870b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
49880b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
49890b57cec5SDimitry Andric 
49900b57cec5SDimitry Andric     verifyStatepoint(Call);
49910b57cec5SDimitry Andric     break;
49920b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
49930b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
49940b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
49950b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
49960b57cec5SDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
49970b57cec5SDimitry Andric     const Function *StatepointFn =
49980b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
49990b57cec5SDimitry Andric     Assert(StatepointFn && StatepointFn->isDeclaration() &&
50000b57cec5SDimitry Andric                StatepointFn->getIntrinsicID() ==
50010b57cec5SDimitry Andric                    Intrinsic::experimental_gc_statepoint,
50020b57cec5SDimitry Andric            "gc.result operand #1 must be from a statepoint", Call,
50030b57cec5SDimitry Andric            Call.getArgOperand(0));
50040b57cec5SDimitry Andric 
50050b57cec5SDimitry Andric     // Assert that result type matches wrapped callee.
50060b57cec5SDimitry Andric     const Value *Target = StatepointCall->getArgOperand(2);
50070b57cec5SDimitry Andric     auto *PT = cast<PointerType>(Target->getType());
500804eeddc0SDimitry Andric     auto *TargetFuncType = cast<FunctionType>(PT->getPointerElementType());
50090b57cec5SDimitry Andric     Assert(Call.getType() == TargetFuncType->getReturnType(),
50100b57cec5SDimitry Andric            "gc.result result type does not match wrapped callee", Call);
50110b57cec5SDimitry Andric     break;
50120b57cec5SDimitry Andric   }
50130b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
5014349cc55cSDimitry Andric     Assert(Call.arg_size() == 3, "wrong number of arguments", Call);
50150b57cec5SDimitry Andric 
50160b57cec5SDimitry Andric     Assert(isa<PointerType>(Call.getType()->getScalarType()),
50170b57cec5SDimitry Andric            "gc.relocate must return a pointer or a vector of pointers", Call);
50180b57cec5SDimitry Andric 
50190b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
50200b57cec5SDimitry Andric 
50210b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
50220b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
50230b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
50240b57cec5SDimitry Andric 
50250b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
50260b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
50270b57cec5SDimitry Andric 
50280b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
50290b57cec5SDimitry Andric       // statepoint terminator
50300b57cec5SDimitry Andric       Assert(InvokeBB, "safepoints should have unique landingpads",
50310b57cec5SDimitry Andric              LandingPad->getParent());
50320b57cec5SDimitry Andric       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
50330b57cec5SDimitry Andric              InvokeBB);
50345ffd83dbSDimitry Andric       Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()),
50350b57cec5SDimitry Andric              "gc relocate should be linked to a statepoint", InvokeBB);
50360b57cec5SDimitry Andric     } else {
50370b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
50380b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
50390b57cec5SDimitry Andric       // relocates of a call statepoint.
50400b57cec5SDimitry Andric       auto Token = Call.getArgOperand(0);
50415ffd83dbSDimitry Andric       Assert(isa<GCStatepointInst>(Token),
50420b57cec5SDimitry Andric              "gc relocate is incorrectly tied to the statepoint", Call, Token);
50430b57cec5SDimitry Andric     }
50440b57cec5SDimitry Andric 
50450b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
50460b57cec5SDimitry Andric     const CallBase &StatepointCall =
50475ffd83dbSDimitry Andric       *cast<GCRelocateInst>(Call).getStatepoint();
50480b57cec5SDimitry Andric 
50490b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
50500b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
50510b57cec5SDimitry Andric     Assert(isa<ConstantInt>(Base),
50520b57cec5SDimitry Andric            "gc.relocate operand #2 must be integer offset", Call);
50530b57cec5SDimitry Andric 
50540b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
50550b57cec5SDimitry Andric     Assert(isa<ConstantInt>(Derived),
50560b57cec5SDimitry Andric            "gc.relocate operand #3 must be integer offset", Call);
50570b57cec5SDimitry Andric 
50585ffd83dbSDimitry Andric     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
50595ffd83dbSDimitry Andric     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
50605ffd83dbSDimitry Andric 
50610b57cec5SDimitry Andric     // Check the bounds
50625ffd83dbSDimitry Andric     if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) {
50635ffd83dbSDimitry Andric       Assert(BaseIndex < Opt->Inputs.size(),
50640b57cec5SDimitry Andric              "gc.relocate: statepoint base index out of bounds", Call);
50655ffd83dbSDimitry Andric       Assert(DerivedIndex < Opt->Inputs.size(),
50665ffd83dbSDimitry Andric              "gc.relocate: statepoint derived index out of bounds", Call);
50675ffd83dbSDimitry Andric     }
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
50700b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
50710b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
50720b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
50730b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
50740b57cec5SDimitry Andric     Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
50750b57cec5SDimitry Andric            "gc.relocate: relocated value must be a gc pointer", Call);
50760b57cec5SDimitry Andric 
50770b57cec5SDimitry Andric     auto ResultType = Call.getType();
50780b57cec5SDimitry Andric     auto DerivedType = Relocate.getDerivedPtr()->getType();
50790b57cec5SDimitry Andric     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
50800b57cec5SDimitry Andric            "gc.relocate: vector relocates to vector and pointer to pointer",
50810b57cec5SDimitry Andric            Call);
50820b57cec5SDimitry Andric     Assert(
50830b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
50840b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
50850b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
50860b57cec5SDimitry Andric         Call);
50870b57cec5SDimitry Andric     break;
50880b57cec5SDimitry Andric   }
50890b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
50900b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
50910b57cec5SDimitry Andric     Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
50920b57cec5SDimitry Andric            "eh.exceptionpointer argument must be a catchpad", Call);
50930b57cec5SDimitry Andric     break;
50940b57cec5SDimitry Andric   }
50955ffd83dbSDimitry Andric   case Intrinsic::get_active_lane_mask: {
50965ffd83dbSDimitry Andric     Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a "
50975ffd83dbSDimitry Andric            "vector", Call);
50985ffd83dbSDimitry Andric     auto *ElemTy = Call.getType()->getScalarType();
50995ffd83dbSDimitry Andric     Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not "
51005ffd83dbSDimitry Andric            "i1", Call);
51015ffd83dbSDimitry Andric     break;
51025ffd83dbSDimitry Andric   }
51030b57cec5SDimitry Andric   case Intrinsic::masked_load: {
51040b57cec5SDimitry Andric     Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
51050b57cec5SDimitry Andric            Call);
51060b57cec5SDimitry Andric 
51070b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(0);
51080b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
51090b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
51100b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
51110b57cec5SDimitry Andric     Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
51120b57cec5SDimitry Andric            Call);
51130b57cec5SDimitry Andric     Assert(Alignment->getValue().isPowerOf2(),
51140b57cec5SDimitry Andric            "masked_load: alignment must be a power of 2", Call);
51150b57cec5SDimitry Andric 
5116fe6060f1SDimitry Andric     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5117fe6060f1SDimitry Andric     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),
51180b57cec5SDimitry Andric            "masked_load: return must match pointer type", Call);
5119fe6060f1SDimitry Andric     Assert(PassThru->getType() == Call.getType(),
5120fe6060f1SDimitry Andric            "masked_load: pass through and return type must match", Call);
51215ffd83dbSDimitry Andric     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5122fe6060f1SDimitry Andric                cast<VectorType>(Call.getType())->getElementCount(),
5123fe6060f1SDimitry Andric            "masked_load: vector mask must be same length as return", Call);
51240b57cec5SDimitry Andric     break;
51250b57cec5SDimitry Andric   }
51260b57cec5SDimitry Andric   case Intrinsic::masked_store: {
51270b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
51280b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(1);
51290b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
51300b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
51310b57cec5SDimitry Andric     Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
51320b57cec5SDimitry Andric            Call);
51330b57cec5SDimitry Andric     Assert(Alignment->getValue().isPowerOf2(),
51340b57cec5SDimitry Andric            "masked_store: alignment must be a power of 2", Call);
51350b57cec5SDimitry Andric 
5136fe6060f1SDimitry Andric     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5137fe6060f1SDimitry Andric     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),
51380b57cec5SDimitry Andric            "masked_store: storee must match pointer type", Call);
51395ffd83dbSDimitry Andric     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5140fe6060f1SDimitry Andric                cast<VectorType>(Val->getType())->getElementCount(),
5141fe6060f1SDimitry Andric            "masked_store: vector mask must be same length as value", Call);
51420b57cec5SDimitry Andric     break;
51430b57cec5SDimitry Andric   }
51440b57cec5SDimitry Andric 
51455ffd83dbSDimitry Andric   case Intrinsic::masked_gather: {
51465ffd83dbSDimitry Andric     const APInt &Alignment =
51475ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
5148349cc55cSDimitry Andric     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
51495ffd83dbSDimitry Andric            "masked_gather: alignment must be 0 or a power of 2", Call);
51505ffd83dbSDimitry Andric     break;
51515ffd83dbSDimitry Andric   }
51525ffd83dbSDimitry Andric   case Intrinsic::masked_scatter: {
51535ffd83dbSDimitry Andric     const APInt &Alignment =
51545ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
5155349cc55cSDimitry Andric     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
51565ffd83dbSDimitry Andric            "masked_scatter: alignment must be 0 or a power of 2", Call);
51575ffd83dbSDimitry Andric     break;
51585ffd83dbSDimitry Andric   }
51595ffd83dbSDimitry Andric 
51600b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
51610b57cec5SDimitry Andric     Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
51620b57cec5SDimitry Andric     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
51630b57cec5SDimitry Andric            "experimental_guard must have exactly one "
51640b57cec5SDimitry Andric            "\"deopt\" operand bundle");
51650b57cec5SDimitry Andric     break;
51660b57cec5SDimitry Andric   }
51670b57cec5SDimitry Andric 
51680b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
51690b57cec5SDimitry Andric     Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
51700b57cec5SDimitry Andric            Call);
51710b57cec5SDimitry Andric     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
51720b57cec5SDimitry Andric            "experimental_deoptimize must have exactly one "
51730b57cec5SDimitry Andric            "\"deopt\" operand bundle");
51740b57cec5SDimitry Andric     Assert(Call.getType() == Call.getFunction()->getReturnType(),
51750b57cec5SDimitry Andric            "experimental_deoptimize return type must match caller return type");
51760b57cec5SDimitry Andric 
51770b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
51780b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
51790b57cec5SDimitry Andric       Assert(RI,
51800b57cec5SDimitry Andric              "calls to experimental_deoptimize must be followed by a return");
51810b57cec5SDimitry Andric 
51820b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
51830b57cec5SDimitry Andric         Assert(RI->getReturnValue() == &Call,
51840b57cec5SDimitry Andric                "calls to experimental_deoptimize must be followed by a return "
51850b57cec5SDimitry Andric                "of the value computed by experimental_deoptimize");
51860b57cec5SDimitry Andric     }
51870b57cec5SDimitry Andric 
51880b57cec5SDimitry Andric     break;
51890b57cec5SDimitry Andric   }
5190fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_and:
5191fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_or:
5192fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_xor:
5193fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_add:
5194fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_mul:
5195fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smax:
5196fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smin:
5197fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umax:
5198fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umin: {
5199fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
5200fe6060f1SDimitry Andric     Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5201fe6060f1SDimitry Andric            "Intrinsic has incorrect argument type!");
5202fe6060f1SDimitry Andric     break;
5203fe6060f1SDimitry Andric   }
5204fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmax:
5205fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmin: {
5206fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
5207fe6060f1SDimitry Andric     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5208fe6060f1SDimitry Andric            "Intrinsic has incorrect argument type!");
5209fe6060f1SDimitry Andric     break;
5210fe6060f1SDimitry Andric   }
5211fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fadd:
5212fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmul: {
5213fe6060f1SDimitry Andric     // Unlike the other reductions, the first argument is a start value. The
5214fe6060f1SDimitry Andric     // second argument is the vector to be reduced.
5215fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(1)->getType();
5216fe6060f1SDimitry Andric     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5217fe6060f1SDimitry Andric            "Intrinsic has incorrect argument type!");
52180b57cec5SDimitry Andric     break;
52190b57cec5SDimitry Andric   }
52200b57cec5SDimitry Andric   case Intrinsic::smul_fix:
52210b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
52228bcb0991SDimitry Andric   case Intrinsic::umul_fix:
5223480093f4SDimitry Andric   case Intrinsic::umul_fix_sat:
5224480093f4SDimitry Andric   case Intrinsic::sdiv_fix:
52255ffd83dbSDimitry Andric   case Intrinsic::sdiv_fix_sat:
52265ffd83dbSDimitry Andric   case Intrinsic::udiv_fix:
52275ffd83dbSDimitry Andric   case Intrinsic::udiv_fix_sat: {
52280b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
52290b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
52300b57cec5SDimitry Andric     Assert(Op1->getType()->isIntOrIntVectorTy(),
5231480093f4SDimitry Andric            "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5232480093f4SDimitry Andric            "vector of ints");
52330b57cec5SDimitry Andric     Assert(Op2->getType()->isIntOrIntVectorTy(),
5234480093f4SDimitry Andric            "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5235480093f4SDimitry Andric            "vector of ints");
52360b57cec5SDimitry Andric 
52370b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
52380b57cec5SDimitry Andric     Assert(Op3->getType()->getBitWidth() <= 32,
5239480093f4SDimitry Andric            "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
52400b57cec5SDimitry Andric 
5241480093f4SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
52425ffd83dbSDimitry Andric         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
52430b57cec5SDimitry Andric       Assert(
52440b57cec5SDimitry Andric           Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5245480093f4SDimitry Andric           "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5246480093f4SDimitry Andric           "the operands");
52470b57cec5SDimitry Andric     } else {
52480b57cec5SDimitry Andric       Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5249480093f4SDimitry Andric              "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5250480093f4SDimitry Andric              "to the width of the operands");
52510b57cec5SDimitry Andric     }
52520b57cec5SDimitry Andric     break;
52530b57cec5SDimitry Andric   }
52540b57cec5SDimitry Andric   case Intrinsic::lround:
52550b57cec5SDimitry Andric   case Intrinsic::llround:
52560b57cec5SDimitry Andric   case Intrinsic::lrint:
52570b57cec5SDimitry Andric   case Intrinsic::llrint: {
52580b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
52590b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
52600b57cec5SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
52610b57cec5SDimitry Andric            "Intrinsic does not support vectors", &Call);
52620b57cec5SDimitry Andric     break;
52630b57cec5SDimitry Andric   }
52645ffd83dbSDimitry Andric   case Intrinsic::bswap: {
52655ffd83dbSDimitry Andric     Type *Ty = Call.getType();
52665ffd83dbSDimitry Andric     unsigned Size = Ty->getScalarSizeInBits();
52675ffd83dbSDimitry Andric     Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
52685ffd83dbSDimitry Andric     break;
52695ffd83dbSDimitry Andric   }
5270e8d8bef9SDimitry Andric   case Intrinsic::invariant_start: {
5271e8d8bef9SDimitry Andric     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
5272e8d8bef9SDimitry Andric     Assert(InvariantSize &&
5273e8d8bef9SDimitry Andric                (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5274e8d8bef9SDimitry Andric            "invariant_start parameter must be -1, 0 or a positive number",
5275e8d8bef9SDimitry Andric            &Call);
5276e8d8bef9SDimitry Andric     break;
5277e8d8bef9SDimitry Andric   }
52785ffd83dbSDimitry Andric   case Intrinsic::matrix_multiply:
52795ffd83dbSDimitry Andric   case Intrinsic::matrix_transpose:
52805ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_load:
52815ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_store: {
52825ffd83dbSDimitry Andric     Function *IF = Call.getCalledFunction();
52835ffd83dbSDimitry Andric     ConstantInt *Stride = nullptr;
52845ffd83dbSDimitry Andric     ConstantInt *NumRows;
52855ffd83dbSDimitry Andric     ConstantInt *NumColumns;
52865ffd83dbSDimitry Andric     VectorType *ResultTy;
52875ffd83dbSDimitry Andric     Type *Op0ElemTy = nullptr;
52885ffd83dbSDimitry Andric     Type *Op1ElemTy = nullptr;
52895ffd83dbSDimitry Andric     switch (ID) {
52905ffd83dbSDimitry Andric     case Intrinsic::matrix_multiply:
52915ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
52925ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
52935ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
52945ffd83dbSDimitry Andric       Op0ElemTy =
52955ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
52965ffd83dbSDimitry Andric       Op1ElemTy =
52975ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
52985ffd83dbSDimitry Andric       break;
52995ffd83dbSDimitry Andric     case Intrinsic::matrix_transpose:
53005ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
53015ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
53025ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
53035ffd83dbSDimitry Andric       Op0ElemTy =
53045ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
53055ffd83dbSDimitry Andric       break;
53064824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_load: {
53075ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
53085ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
53095ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
53105ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
53114824e7fdSDimitry Andric 
53124824e7fdSDimitry Andric       PointerType *Op0PtrTy =
53134824e7fdSDimitry Andric           cast<PointerType>(Call.getArgOperand(0)->getType());
53144824e7fdSDimitry Andric       if (!Op0PtrTy->isOpaque())
531504eeddc0SDimitry Andric         Op0ElemTy = Op0PtrTy->getNonOpaquePointerElementType();
53165ffd83dbSDimitry Andric       break;
53174824e7fdSDimitry Andric     }
53184824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_store: {
53195ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
53205ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
53215ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
53225ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
53235ffd83dbSDimitry Andric       Op0ElemTy =
53245ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
53254824e7fdSDimitry Andric 
53264824e7fdSDimitry Andric       PointerType *Op1PtrTy =
53274824e7fdSDimitry Andric           cast<PointerType>(Call.getArgOperand(1)->getType());
53284824e7fdSDimitry Andric       if (!Op1PtrTy->isOpaque())
532904eeddc0SDimitry Andric         Op1ElemTy = Op1PtrTy->getNonOpaquePointerElementType();
53305ffd83dbSDimitry Andric       break;
53314824e7fdSDimitry Andric     }
53325ffd83dbSDimitry Andric     default:
53335ffd83dbSDimitry Andric       llvm_unreachable("unexpected intrinsic");
53345ffd83dbSDimitry Andric     }
53355ffd83dbSDimitry Andric 
53365ffd83dbSDimitry Andric     Assert(ResultTy->getElementType()->isIntegerTy() ||
53375ffd83dbSDimitry Andric            ResultTy->getElementType()->isFloatingPointTy(),
53385ffd83dbSDimitry Andric            "Result type must be an integer or floating-point type!", IF);
53395ffd83dbSDimitry Andric 
53404824e7fdSDimitry Andric     if (Op0ElemTy)
53415ffd83dbSDimitry Andric       Assert(ResultTy->getElementType() == Op0ElemTy,
53425ffd83dbSDimitry Andric              "Vector element type mismatch of the result and first operand "
53435ffd83dbSDimitry Andric              "vector!", IF);
53445ffd83dbSDimitry Andric 
53455ffd83dbSDimitry Andric     if (Op1ElemTy)
53465ffd83dbSDimitry Andric       Assert(ResultTy->getElementType() == Op1ElemTy,
53475ffd83dbSDimitry Andric              "Vector element type mismatch of the result and second operand "
53485ffd83dbSDimitry Andric              "vector!", IF);
53495ffd83dbSDimitry Andric 
5350e8d8bef9SDimitry Andric     Assert(cast<FixedVectorType>(ResultTy)->getNumElements() ==
53515ffd83dbSDimitry Andric                NumRows->getZExtValue() * NumColumns->getZExtValue(),
53525ffd83dbSDimitry Andric            "Result of a matrix operation does not fit in the returned vector!");
53535ffd83dbSDimitry Andric 
53545ffd83dbSDimitry Andric     if (Stride)
53555ffd83dbSDimitry Andric       Assert(Stride->getZExtValue() >= NumRows->getZExtValue(),
53565ffd83dbSDimitry Andric              "Stride must be greater or equal than the number of rows!", IF);
53575ffd83dbSDimitry Andric 
53585ffd83dbSDimitry Andric     break;
53595ffd83dbSDimitry Andric   }
536004eeddc0SDimitry Andric   case Intrinsic::experimental_vector_splice: {
536104eeddc0SDimitry Andric     VectorType *VecTy = cast<VectorType>(Call.getType());
536204eeddc0SDimitry Andric     int64_t Idx = cast<ConstantInt>(Call.getArgOperand(2))->getSExtValue();
536304eeddc0SDimitry Andric     int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
536404eeddc0SDimitry Andric     if (Call.getParent() && Call.getParent()->getParent()) {
536504eeddc0SDimitry Andric       AttributeList Attrs = Call.getParent()->getParent()->getAttributes();
536604eeddc0SDimitry Andric       if (Attrs.hasFnAttr(Attribute::VScaleRange))
536704eeddc0SDimitry Andric         KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
536804eeddc0SDimitry Andric     }
536904eeddc0SDimitry Andric     Assert((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
537004eeddc0SDimitry Andric                (Idx >= 0 && Idx < KnownMinNumElements),
537104eeddc0SDimitry Andric            "The splice index exceeds the range [-VL, VL-1] where VL is the "
537204eeddc0SDimitry Andric            "known minimum number of elements in the vector. For scalable "
537304eeddc0SDimitry Andric            "vectors the minimum number of elements is determined from "
537404eeddc0SDimitry Andric            "vscale_range.",
537504eeddc0SDimitry Andric            &Call);
537604eeddc0SDimitry Andric     break;
537704eeddc0SDimitry Andric   }
5378fe6060f1SDimitry Andric   case Intrinsic::experimental_stepvector: {
5379fe6060f1SDimitry Andric     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
5380fe6060f1SDimitry Andric     Assert(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5381fe6060f1SDimitry Andric                VecTy->getScalarSizeInBits() >= 8,
5382fe6060f1SDimitry Andric            "experimental_stepvector only supported for vectors of integers "
5383fe6060f1SDimitry Andric            "with a bitwidth of at least 8.",
5384fe6060f1SDimitry Andric            &Call);
5385fe6060f1SDimitry Andric     break;
5386fe6060f1SDimitry Andric   }
5387e8d8bef9SDimitry Andric   case Intrinsic::experimental_vector_insert: {
5388fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5389fe6060f1SDimitry Andric     Value *SubVec = Call.getArgOperand(1);
5390fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(2);
5391fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5392e8d8bef9SDimitry Andric 
5393fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5394fe6060f1SDimitry Andric     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5395fe6060f1SDimitry Andric 
5396fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5397fe6060f1SDimitry Andric     ElementCount SubVecEC = SubVecTy->getElementCount();
5398e8d8bef9SDimitry Andric     Assert(VecTy->getElementType() == SubVecTy->getElementType(),
5399e8d8bef9SDimitry Andric            "experimental_vector_insert parameters must have the same element "
5400e8d8bef9SDimitry Andric            "type.",
5401e8d8bef9SDimitry Andric            &Call);
5402fe6060f1SDimitry Andric     Assert(IdxN % SubVecEC.getKnownMinValue() == 0,
5403fe6060f1SDimitry Andric            "experimental_vector_insert index must be a constant multiple of "
5404fe6060f1SDimitry Andric            "the subvector's known minimum vector length.");
5405fe6060f1SDimitry Andric 
5406fe6060f1SDimitry Andric     // If this insertion is not the 'mixed' case where a fixed vector is
5407fe6060f1SDimitry Andric     // inserted into a scalable vector, ensure that the insertion of the
5408fe6060f1SDimitry Andric     // subvector does not overrun the parent vector.
5409fe6060f1SDimitry Andric     if (VecEC.isScalable() == SubVecEC.isScalable()) {
5410fe6060f1SDimitry Andric       Assert(
5411fe6060f1SDimitry Andric           IdxN < VecEC.getKnownMinValue() &&
5412fe6060f1SDimitry Andric               IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5413fe6060f1SDimitry Andric           "subvector operand of experimental_vector_insert would overrun the "
5414fe6060f1SDimitry Andric           "vector being inserted into.");
5415fe6060f1SDimitry Andric     }
5416e8d8bef9SDimitry Andric     break;
5417e8d8bef9SDimitry Andric   }
5418e8d8bef9SDimitry Andric   case Intrinsic::experimental_vector_extract: {
5419fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5420fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(1);
5421fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5422fe6060f1SDimitry Andric 
5423e8d8bef9SDimitry Andric     VectorType *ResultTy = cast<VectorType>(Call.getType());
5424fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5425fe6060f1SDimitry Andric 
5426fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5427fe6060f1SDimitry Andric     ElementCount ResultEC = ResultTy->getElementCount();
5428e8d8bef9SDimitry Andric 
5429e8d8bef9SDimitry Andric     Assert(ResultTy->getElementType() == VecTy->getElementType(),
5430e8d8bef9SDimitry Andric            "experimental_vector_extract result must have the same element "
5431e8d8bef9SDimitry Andric            "type as the input vector.",
5432e8d8bef9SDimitry Andric            &Call);
5433fe6060f1SDimitry Andric     Assert(IdxN % ResultEC.getKnownMinValue() == 0,
5434fe6060f1SDimitry Andric            "experimental_vector_extract index must be a constant multiple of "
5435fe6060f1SDimitry Andric            "the result type's known minimum vector length.");
5436fe6060f1SDimitry Andric 
5437fe6060f1SDimitry Andric     // If this extraction is not the 'mixed' case where a fixed vector is is
5438fe6060f1SDimitry Andric     // extracted from a scalable vector, ensure that the extraction does not
5439fe6060f1SDimitry Andric     // overrun the parent vector.
5440fe6060f1SDimitry Andric     if (VecEC.isScalable() == ResultEC.isScalable()) {
5441fe6060f1SDimitry Andric       Assert(IdxN < VecEC.getKnownMinValue() &&
5442fe6060f1SDimitry Andric                  IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5443fe6060f1SDimitry Andric              "experimental_vector_extract would overrun.");
5444fe6060f1SDimitry Andric     }
5445e8d8bef9SDimitry Andric     break;
5446e8d8bef9SDimitry Andric   }
5447e8d8bef9SDimitry Andric   case Intrinsic::experimental_noalias_scope_decl: {
5448e8d8bef9SDimitry Andric     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5449e8d8bef9SDimitry Andric     break;
5450e8d8bef9SDimitry Andric   }
5451fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
5452fe6060f1SDimitry Andric   case Intrinsic::preserve_struct_access_index: {
5453fe6060f1SDimitry Andric     Type *ElemTy = Call.getAttributes().getParamElementType(0);
5454fe6060f1SDimitry Andric     Assert(ElemTy,
5455fe6060f1SDimitry Andric            "Intrinsic requires elementtype attribute on first argument.",
5456fe6060f1SDimitry Andric            &Call);
5457fe6060f1SDimitry Andric     break;
5458fe6060f1SDimitry Andric   }
54590b57cec5SDimitry Andric   };
54600b57cec5SDimitry Andric }
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
54630b57cec5SDimitry Andric ///
54640b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
54650b57cec5SDimitry Andric /// built-in assertions that would typically fire.
54660b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
54670b57cec5SDimitry Andric   if (!LocalScope)
54680b57cec5SDimitry Andric     return nullptr;
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
54710b57cec5SDimitry Andric     return SP;
54720b57cec5SDimitry Andric 
54730b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
54740b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
54770b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
54780b57cec5SDimitry Andric   return nullptr;
54790b57cec5SDimitry Andric }
54800b57cec5SDimitry Andric 
54810b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5482480093f4SDimitry Andric   unsigned NumOperands;
5483480093f4SDimitry Andric   bool HasRoundingMD;
54840b57cec5SDimitry Andric   switch (FPI.getIntrinsicID()) {
54855ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
5486480093f4SDimitry Andric   case Intrinsic::INTRINSIC:                                                   \
5487480093f4SDimitry Andric     NumOperands = NARG;                                                        \
5488480093f4SDimitry Andric     HasRoundingMD = ROUND_MODE;                                                \
54890b57cec5SDimitry Andric     break;
5490480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
5491480093f4SDimitry Andric   default:
5492480093f4SDimitry Andric     llvm_unreachable("Invalid constrained FP intrinsic!");
5493480093f4SDimitry Andric   }
5494480093f4SDimitry Andric   NumOperands += (1 + HasRoundingMD);
5495480093f4SDimitry Andric   // Compare intrinsics carry an extra predicate metadata operand.
5496480093f4SDimitry Andric   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5497480093f4SDimitry Andric     NumOperands += 1;
5498349cc55cSDimitry Andric   Assert((FPI.arg_size() == NumOperands),
5499480093f4SDimitry Andric          "invalid arguments for constrained FP intrinsic", &FPI);
55000b57cec5SDimitry Andric 
5501480093f4SDimitry Andric   switch (FPI.getIntrinsicID()) {
55028bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
55038bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
55048bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
55058bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
55068bcb0991SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
55078bcb0991SDimitry Andric            "Intrinsic does not support vectors", &FPI);
55088bcb0991SDimitry Andric   }
55098bcb0991SDimitry Andric     break;
55108bcb0991SDimitry Andric 
55118bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
55128bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
55138bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
55148bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
55158bcb0991SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
55168bcb0991SDimitry Andric            "Intrinsic does not support vectors", &FPI);
55178bcb0991SDimitry Andric     break;
55188bcb0991SDimitry Andric   }
55198bcb0991SDimitry Andric 
5520480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmp:
5521480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmps: {
5522480093f4SDimitry Andric     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
5523480093f4SDimitry Andric     Assert(CmpInst::isFPPredicate(Pred),
5524480093f4SDimitry Andric            "invalid predicate for constrained FP comparison intrinsic", &FPI);
55250b57cec5SDimitry Andric     break;
5526480093f4SDimitry Andric   }
55270b57cec5SDimitry Andric 
55288bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
55298bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
55308bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
55318bcb0991SDimitry Andric     uint64_t NumSrcElem = 0;
55328bcb0991SDimitry Andric     Assert(Operand->getType()->isFPOrFPVectorTy(),
55338bcb0991SDimitry Andric            "Intrinsic first argument must be floating point", &FPI);
55348bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5535e8d8bef9SDimitry Andric       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
55368bcb0991SDimitry Andric     }
55378bcb0991SDimitry Andric 
55388bcb0991SDimitry Andric     Operand = &FPI;
55398bcb0991SDimitry Andric     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
55408bcb0991SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
55418bcb0991SDimitry Andric     Assert(Operand->getType()->isIntOrIntVectorTy(),
55428bcb0991SDimitry Andric            "Intrinsic result must be an integer", &FPI);
55438bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5544e8d8bef9SDimitry Andric       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
55458bcb0991SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
55468bcb0991SDimitry Andric              &FPI);
55478bcb0991SDimitry Andric     }
55488bcb0991SDimitry Andric   }
55498bcb0991SDimitry Andric     break;
55508bcb0991SDimitry Andric 
5551480093f4SDimitry Andric   case Intrinsic::experimental_constrained_sitofp:
5552480093f4SDimitry Andric   case Intrinsic::experimental_constrained_uitofp: {
5553480093f4SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
5554480093f4SDimitry Andric     uint64_t NumSrcElem = 0;
5555480093f4SDimitry Andric     Assert(Operand->getType()->isIntOrIntVectorTy(),
5556480093f4SDimitry Andric            "Intrinsic first argument must be integer", &FPI);
5557480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5558e8d8bef9SDimitry Andric       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5559480093f4SDimitry Andric     }
5560480093f4SDimitry Andric 
5561480093f4SDimitry Andric     Operand = &FPI;
5562480093f4SDimitry Andric     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5563480093f4SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
5564480093f4SDimitry Andric     Assert(Operand->getType()->isFPOrFPVectorTy(),
5565480093f4SDimitry Andric            "Intrinsic result must be a floating point", &FPI);
5566480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5567e8d8bef9SDimitry Andric       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5568480093f4SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
5569480093f4SDimitry Andric              &FPI);
5570480093f4SDimitry Andric     }
5571480093f4SDimitry Andric   } break;
5572480093f4SDimitry Andric 
55730b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
55740b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
55750b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
55760b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
55770b57cec5SDimitry Andric     Value *Result = &FPI;
55780b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
55790b57cec5SDimitry Andric     Assert(OperandTy->isFPOrFPVectorTy(),
55800b57cec5SDimitry Andric            "Intrinsic first argument must be FP or FP vector", &FPI);
55810b57cec5SDimitry Andric     Assert(ResultTy->isFPOrFPVectorTy(),
55820b57cec5SDimitry Andric            "Intrinsic result must be FP or FP vector", &FPI);
55830b57cec5SDimitry Andric     Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
55840b57cec5SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
55850b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
5586e8d8bef9SDimitry Andric       Assert(cast<FixedVectorType>(OperandTy)->getNumElements() ==
5587e8d8bef9SDimitry Andric                  cast<FixedVectorType>(ResultTy)->getNumElements(),
55880b57cec5SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
55890b57cec5SDimitry Andric              &FPI);
55900b57cec5SDimitry Andric     }
55910b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
55920b57cec5SDimitry Andric       Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
55930b57cec5SDimitry Andric              "Intrinsic first argument's type must be larger than result type",
55940b57cec5SDimitry Andric              &FPI);
55950b57cec5SDimitry Andric     } else {
55960b57cec5SDimitry Andric       Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
55970b57cec5SDimitry Andric              "Intrinsic first argument's type must be smaller than result type",
55980b57cec5SDimitry Andric              &FPI);
55990b57cec5SDimitry Andric     }
56000b57cec5SDimitry Andric   }
56010b57cec5SDimitry Andric     break;
56020b57cec5SDimitry Andric 
56030b57cec5SDimitry Andric   default:
5604480093f4SDimitry Andric     break;
56050b57cec5SDimitry Andric   }
56060b57cec5SDimitry Andric 
56070b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
56080b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
56090b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
56100b57cec5SDimitry Andric   // argument type check is needed here.
56110b57cec5SDimitry Andric 
56120b57cec5SDimitry Andric   Assert(FPI.getExceptionBehavior().hasValue(),
56130b57cec5SDimitry Andric          "invalid exception behavior argument", &FPI);
56140b57cec5SDimitry Andric   if (HasRoundingMD) {
56150b57cec5SDimitry Andric     Assert(FPI.getRoundingMode().hasValue(),
56160b57cec5SDimitry Andric            "invalid rounding mode argument", &FPI);
56170b57cec5SDimitry Andric   }
56180b57cec5SDimitry Andric }
56190b57cec5SDimitry Andric 
56200b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
5621fe6060f1SDimitry Andric   auto *MD = DII.getRawLocation();
5622fe6060f1SDimitry Andric   AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
56230b57cec5SDimitry Andric                (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
56240b57cec5SDimitry Andric            "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
56250b57cec5SDimitry Andric   AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
56260b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
56270b57cec5SDimitry Andric          DII.getRawVariable());
56280b57cec5SDimitry Andric   AssertDI(isa<DIExpression>(DII.getRawExpression()),
56290b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
56300b57cec5SDimitry Andric          DII.getRawExpression());
56310b57cec5SDimitry Andric 
56320b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
56330b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
56340b57cec5SDimitry Andric     if (!isa<DILocation>(N))
56350b57cec5SDimitry Andric       return;
56360b57cec5SDimitry Andric 
56370b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
56380b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
56390b57cec5SDimitry Andric 
56400b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
56410b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
56420b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
56430b57cec5SDimitry Andric   AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
56440b57cec5SDimitry Andric            &DII, BB, F);
56450b57cec5SDimitry Andric 
56460b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
56470b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
56480b57cec5SDimitry Andric   if (!VarSP || !LocSP)
56490b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
56500b57cec5SDimitry Andric 
56510b57cec5SDimitry Andric   AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
56520b57cec5SDimitry Andric                                " variable and !dbg attachment",
56530b57cec5SDimitry Andric            &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
56540b57cec5SDimitry Andric            Loc->getScope()->getSubprogram());
56550b57cec5SDimitry Andric 
56560b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
56570b57cec5SDimitry Andric   AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
56580b57cec5SDimitry Andric            Var->getRawType());
56590b57cec5SDimitry Andric   verifyFnArgs(DII);
56600b57cec5SDimitry Andric }
56610b57cec5SDimitry Andric 
56620b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
56630b57cec5SDimitry Andric   AssertDI(isa<DILabel>(DLI.getRawLabel()),
56640b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
56650b57cec5SDimitry Andric          DLI.getRawLabel());
56660b57cec5SDimitry Andric 
56670b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
56680b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
56690b57cec5SDimitry Andric     if (!isa<DILocation>(N))
56700b57cec5SDimitry Andric       return;
56710b57cec5SDimitry Andric 
56720b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
56730b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
56740b57cec5SDimitry Andric 
56750b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
56760b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
56770b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
56780b57cec5SDimitry Andric   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
56790b57cec5SDimitry Andric          &DLI, BB, F);
56800b57cec5SDimitry Andric 
56810b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
56820b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
56830b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
56840b57cec5SDimitry Andric     return;
56850b57cec5SDimitry Andric 
56860b57cec5SDimitry Andric   AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
56870b57cec5SDimitry Andric                              " label and !dbg attachment",
56880b57cec5SDimitry Andric            &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
56890b57cec5SDimitry Andric            Loc->getScope()->getSubprogram());
56900b57cec5SDimitry Andric }
56910b57cec5SDimitry Andric 
56920b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
56930b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
56940b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
56950b57cec5SDimitry Andric 
56960b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
56970b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
56980b57cec5SDimitry Andric     return;
56990b57cec5SDimitry Andric 
57000b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
57010b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
57020b57cec5SDimitry Andric   if (!Fragment)
57030b57cec5SDimitry Andric     return;
57040b57cec5SDimitry Andric 
57050b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
57060b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
57070b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
57080b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
57090b57cec5SDimitry Andric   // variable and this check fails.
57100b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
57110b57cec5SDimitry Andric   if (V->isArtificial())
57120b57cec5SDimitry Andric     return;
57130b57cec5SDimitry Andric 
57140b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
57150b57cec5SDimitry Andric }
57160b57cec5SDimitry Andric 
57170b57cec5SDimitry Andric template <typename ValueOrMetadata>
57180b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
57190b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
57200b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
57210b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
57220b57cec5SDimitry Andric   // elsewhere.
57230b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
57240b57cec5SDimitry Andric   if (!VarSize)
57250b57cec5SDimitry Andric     return;
57260b57cec5SDimitry Andric 
57270b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
57280b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
57290b57cec5SDimitry Andric   AssertDI(FragSize + FragOffset <= *VarSize,
57300b57cec5SDimitry Andric          "fragment is larger than or outside of variable", Desc, &V);
57310b57cec5SDimitry Andric   AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
57320b57cec5SDimitry Andric }
57330b57cec5SDimitry Andric 
57340b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
57350b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
57360b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
57370b57cec5SDimitry Andric   // contain inlined debug intrinsics.
57380b57cec5SDimitry Andric   if (!HasDebugInfo)
57390b57cec5SDimitry Andric     return;
57400b57cec5SDimitry Andric 
57410b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
57420b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
57430b57cec5SDimitry Andric     return;
57440b57cec5SDimitry Andric 
57450b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
57460b57cec5SDimitry Andric   AssertDI(Var, "dbg intrinsic without variable");
57470b57cec5SDimitry Andric 
57480b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
57490b57cec5SDimitry Andric   if (!ArgNo)
57500b57cec5SDimitry Andric     return;
57510b57cec5SDimitry Andric 
57520b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
57530b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
57540b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
57550b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
57560b57cec5SDimitry Andric 
57570b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
57580b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
57590b57cec5SDimitry Andric   AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
57600b57cec5SDimitry Andric            Prev, Var);
57610b57cec5SDimitry Andric }
57620b57cec5SDimitry Andric 
57638bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
57648bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
57658bcb0991SDimitry Andric 
57668bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
57678bcb0991SDimitry Andric   if (!E || !E->isValid())
57688bcb0991SDimitry Andric     return;
57698bcb0991SDimitry Andric 
57708bcb0991SDimitry Andric   AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
57718bcb0991SDimitry Andric }
57728bcb0991SDimitry Andric 
57730b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
57740b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
57750b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
57760b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
57770b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
57780b57cec5SDimitry Andric     return;
57790b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
57800b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
57810b57cec5SDimitry Andric   if (CUs)
57820b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
57830b57cec5SDimitry Andric   for (auto *CU : CUVisited)
57840b57cec5SDimitry Andric     AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
57850b57cec5SDimitry Andric   CUVisited.clear();
57860b57cec5SDimitry Andric }
57870b57cec5SDimitry Andric 
57880b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
57890b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
57900b57cec5SDimitry Andric     return;
57910b57cec5SDimitry Andric 
57920b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
57930b57cec5SDimitry Andric   for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
57940b57cec5SDimitry Andric     Assert(First->getCallingConv() == F->getCallingConv(),
57950b57cec5SDimitry Andric            "All llvm.experimental.deoptimize declarations must have the same "
57960b57cec5SDimitry Andric            "calling convention",
57970b57cec5SDimitry Andric            First, F);
57980b57cec5SDimitry Andric   }
57990b57cec5SDimitry Andric }
58000b57cec5SDimitry Andric 
5801349cc55cSDimitry Andric void Verifier::verifyAttachedCallBundle(const CallBase &Call,
5802349cc55cSDimitry Andric                                         const OperandBundleUse &BU) {
5803349cc55cSDimitry Andric   FunctionType *FTy = Call.getFunctionType();
5804349cc55cSDimitry Andric 
5805349cc55cSDimitry Andric   Assert((FTy->getReturnType()->isPointerTy() ||
5806349cc55cSDimitry Andric           (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
5807349cc55cSDimitry Andric          "a call with operand bundle \"clang.arc.attachedcall\" must call a "
5808349cc55cSDimitry Andric          "function returning a pointer or a non-returning function that has a "
5809349cc55cSDimitry Andric          "void return type",
5810349cc55cSDimitry Andric          Call);
5811349cc55cSDimitry Andric 
5812*1fd87a68SDimitry Andric   Assert(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
5813*1fd87a68SDimitry Andric          "operand bundle \"clang.arc.attachedcall\" requires one function as "
5814*1fd87a68SDimitry Andric          "an argument",
5815349cc55cSDimitry Andric          Call);
5816349cc55cSDimitry Andric 
5817349cc55cSDimitry Andric   auto *Fn = cast<Function>(BU.Inputs.front());
5818349cc55cSDimitry Andric   Intrinsic::ID IID = Fn->getIntrinsicID();
5819349cc55cSDimitry Andric 
5820349cc55cSDimitry Andric   if (IID) {
5821349cc55cSDimitry Andric     Assert((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
5822349cc55cSDimitry Andric             IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
5823349cc55cSDimitry Andric            "invalid function argument", Call);
5824349cc55cSDimitry Andric   } else {
5825349cc55cSDimitry Andric     StringRef FnName = Fn->getName();
5826349cc55cSDimitry Andric     Assert((FnName == "objc_retainAutoreleasedReturnValue" ||
5827349cc55cSDimitry Andric             FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
5828349cc55cSDimitry Andric            "invalid function argument", Call);
5829349cc55cSDimitry Andric   }
5830349cc55cSDimitry Andric }
5831349cc55cSDimitry Andric 
58320b57cec5SDimitry Andric void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
58330b57cec5SDimitry Andric   bool HasSource = F.getSource().hasValue();
58340b57cec5SDimitry Andric   if (!HasSourceDebugInfo.count(&U))
58350b57cec5SDimitry Andric     HasSourceDebugInfo[&U] = HasSource;
58360b57cec5SDimitry Andric   AssertDI(HasSource == HasSourceDebugInfo[&U],
58370b57cec5SDimitry Andric            "inconsistent use of embedded source");
58380b57cec5SDimitry Andric }
58390b57cec5SDimitry Andric 
5840e8d8bef9SDimitry Andric void Verifier::verifyNoAliasScopeDecl() {
5841e8d8bef9SDimitry Andric   if (NoAliasScopeDecls.empty())
5842e8d8bef9SDimitry Andric     return;
5843e8d8bef9SDimitry Andric 
5844e8d8bef9SDimitry Andric   // only a single scope must be declared at a time.
5845e8d8bef9SDimitry Andric   for (auto *II : NoAliasScopeDecls) {
5846e8d8bef9SDimitry Andric     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
5847e8d8bef9SDimitry Andric            "Not a llvm.experimental.noalias.scope.decl ?");
5848e8d8bef9SDimitry Andric     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
5849e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5850e8d8bef9SDimitry Andric     Assert(ScopeListMV != nullptr,
5851e8d8bef9SDimitry Andric            "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
5852e8d8bef9SDimitry Andric            "argument",
5853e8d8bef9SDimitry Andric            II);
5854e8d8bef9SDimitry Andric 
5855e8d8bef9SDimitry Andric     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
5856e8d8bef9SDimitry Andric     Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode",
5857e8d8bef9SDimitry Andric            II);
5858e8d8bef9SDimitry Andric     Assert(ScopeListMD->getNumOperands() == 1,
5859e8d8bef9SDimitry Andric            "!id.scope.list must point to a list with a single scope", II);
5860349cc55cSDimitry Andric     visitAliasScopeListMetadata(ScopeListMD);
5861e8d8bef9SDimitry Andric   }
5862e8d8bef9SDimitry Andric 
5863e8d8bef9SDimitry Andric   // Only check the domination rule when requested. Once all passes have been
5864e8d8bef9SDimitry Andric   // adapted this option can go away.
5865e8d8bef9SDimitry Andric   if (!VerifyNoAliasScopeDomination)
5866e8d8bef9SDimitry Andric     return;
5867e8d8bef9SDimitry Andric 
5868e8d8bef9SDimitry Andric   // Now sort the intrinsics based on the scope MDNode so that declarations of
5869e8d8bef9SDimitry Andric   // the same scopes are next to each other.
5870e8d8bef9SDimitry Andric   auto GetScope = [](IntrinsicInst *II) {
5871e8d8bef9SDimitry Andric     const auto *ScopeListMV = cast<MetadataAsValue>(
5872e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5873e8d8bef9SDimitry Andric     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
5874e8d8bef9SDimitry Andric   };
5875e8d8bef9SDimitry Andric 
5876e8d8bef9SDimitry Andric   // We are sorting on MDNode pointers here. For valid input IR this is ok.
5877e8d8bef9SDimitry Andric   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
5878e8d8bef9SDimitry Andric   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
5879e8d8bef9SDimitry Andric     return GetScope(Lhs) < GetScope(Rhs);
5880e8d8bef9SDimitry Andric   };
5881e8d8bef9SDimitry Andric 
5882e8d8bef9SDimitry Andric   llvm::sort(NoAliasScopeDecls, Compare);
5883e8d8bef9SDimitry Andric 
5884e8d8bef9SDimitry Andric   // Go over the intrinsics and check that for the same scope, they are not
5885e8d8bef9SDimitry Andric   // dominating each other.
5886e8d8bef9SDimitry Andric   auto ItCurrent = NoAliasScopeDecls.begin();
5887e8d8bef9SDimitry Andric   while (ItCurrent != NoAliasScopeDecls.end()) {
5888e8d8bef9SDimitry Andric     auto CurScope = GetScope(*ItCurrent);
5889e8d8bef9SDimitry Andric     auto ItNext = ItCurrent;
5890e8d8bef9SDimitry Andric     do {
5891e8d8bef9SDimitry Andric       ++ItNext;
5892e8d8bef9SDimitry Andric     } while (ItNext != NoAliasScopeDecls.end() &&
5893e8d8bef9SDimitry Andric              GetScope(*ItNext) == CurScope);
5894e8d8bef9SDimitry Andric 
5895e8d8bef9SDimitry Andric     // [ItCurrent, ItNext) represents the declarations for the same scope.
5896e8d8bef9SDimitry Andric     // Ensure they are not dominating each other.. but only if it is not too
5897e8d8bef9SDimitry Andric     // expensive.
5898e8d8bef9SDimitry Andric     if (ItNext - ItCurrent < 32)
5899e8d8bef9SDimitry Andric       for (auto *I : llvm::make_range(ItCurrent, ItNext))
5900e8d8bef9SDimitry Andric         for (auto *J : llvm::make_range(ItCurrent, ItNext))
5901e8d8bef9SDimitry Andric           if (I != J)
5902e8d8bef9SDimitry Andric             Assert(!DT.dominates(I, J),
5903e8d8bef9SDimitry Andric                    "llvm.experimental.noalias.scope.decl dominates another one "
5904e8d8bef9SDimitry Andric                    "with the same scope",
5905e8d8bef9SDimitry Andric                    I);
5906e8d8bef9SDimitry Andric     ItCurrent = ItNext;
5907e8d8bef9SDimitry Andric   }
5908e8d8bef9SDimitry Andric }
5909e8d8bef9SDimitry Andric 
59100b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
59110b57cec5SDimitry Andric //  Implement the public interfaces to this file...
59120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
59130b57cec5SDimitry Andric 
59140b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
59150b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
59160b57cec5SDimitry Andric 
59170b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
59180b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
59190b57cec5SDimitry Andric 
59200b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
59210b57cec5SDimitry Andric   // expect of a function called "verify".
59220b57cec5SDimitry Andric   return !V.verify(F);
59230b57cec5SDimitry Andric }
59240b57cec5SDimitry Andric 
59250b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
59260b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
59270b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
59280b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
59290b57cec5SDimitry Andric 
59300b57cec5SDimitry Andric   bool Broken = false;
59310b57cec5SDimitry Andric   for (const Function &F : M)
59320b57cec5SDimitry Andric     Broken |= !V.verify(F);
59330b57cec5SDimitry Andric 
59340b57cec5SDimitry Andric   Broken |= !V.verify();
59350b57cec5SDimitry Andric   if (BrokenDebugInfo)
59360b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
59370b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
59380b57cec5SDimitry Andric   // expect of a function called "verify".
59390b57cec5SDimitry Andric   return Broken;
59400b57cec5SDimitry Andric }
59410b57cec5SDimitry Andric 
59420b57cec5SDimitry Andric namespace {
59430b57cec5SDimitry Andric 
59440b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
59450b57cec5SDimitry Andric   static char ID;
59460b57cec5SDimitry Andric 
59470b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
59480b57cec5SDimitry Andric   bool FatalErrors = true;
59490b57cec5SDimitry Andric 
59500b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
59510b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
59520b57cec5SDimitry Andric   }
59530b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
59540b57cec5SDimitry Andric       : FunctionPass(ID),
59550b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
59560b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
59570b57cec5SDimitry Andric   }
59580b57cec5SDimitry Andric 
59590b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
59608bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
59610b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
59620b57cec5SDimitry Andric     return false;
59630b57cec5SDimitry Andric   }
59640b57cec5SDimitry Andric 
59650b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
59660b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
59670b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
59680b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
59690b57cec5SDimitry Andric     }
59700b57cec5SDimitry Andric     return false;
59710b57cec5SDimitry Andric   }
59720b57cec5SDimitry Andric 
59730b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
59740b57cec5SDimitry Andric     bool HasErrors = false;
59750b57cec5SDimitry Andric     for (Function &F : M)
59760b57cec5SDimitry Andric       if (F.isDeclaration())
59770b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
59780b57cec5SDimitry Andric 
59790b57cec5SDimitry Andric     HasErrors |= !V->verify();
59800b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
59810b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
59820b57cec5SDimitry Andric     return false;
59830b57cec5SDimitry Andric   }
59840b57cec5SDimitry Andric 
59850b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
59860b57cec5SDimitry Andric     AU.setPreservesAll();
59870b57cec5SDimitry Andric   }
59880b57cec5SDimitry Andric };
59890b57cec5SDimitry Andric 
59900b57cec5SDimitry Andric } // end anonymous namespace
59910b57cec5SDimitry Andric 
59920b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
59930b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
59940b57cec5SDimitry Andric   if (Diagnostic)
59950b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
59960b57cec5SDimitry Andric }
59970b57cec5SDimitry Andric 
59980b57cec5SDimitry Andric #define AssertTBAA(C, ...)                                                     \
59990b57cec5SDimitry Andric   do {                                                                         \
60000b57cec5SDimitry Andric     if (!(C)) {                                                                \
60010b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
60020b57cec5SDimitry Andric       return false;                                                            \
60030b57cec5SDimitry Andric     }                                                                          \
60040b57cec5SDimitry Andric   } while (false)
60050b57cec5SDimitry Andric 
60060b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
60070b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
60080b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
60090b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
60100b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
60110b57cec5SDimitry Andric                                  bool IsNewFormat) {
60120b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
60130b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
60140b57cec5SDimitry Andric     return {true, ~0u};
60150b57cec5SDimitry Andric   }
60160b57cec5SDimitry Andric 
60170b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
60180b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
60190b57cec5SDimitry Andric     return Itr->second;
60200b57cec5SDimitry Andric 
60210b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
60220b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
60230b57cec5SDimitry Andric   (void)InsertResult;
60240b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
60250b57cec5SDimitry Andric   return Result;
60260b57cec5SDimitry Andric }
60270b57cec5SDimitry Andric 
60280b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
60290b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
60300b57cec5SDimitry Andric                                      bool IsNewFormat) {
60310b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
60340b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
60350b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
60360b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
60370b57cec5SDimitry Andric                : InvalidNode;
60380b57cec5SDimitry Andric   }
60390b57cec5SDimitry Andric 
60400b57cec5SDimitry Andric   if (IsNewFormat) {
60410b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
60420b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
60430b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
60440b57cec5SDimitry Andric       return InvalidNode;
60450b57cec5SDimitry Andric     }
60460b57cec5SDimitry Andric   } else {
60470b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
60480b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
60490b57cec5SDimitry Andric                   BaseNode);
60500b57cec5SDimitry Andric       return InvalidNode;
60510b57cec5SDimitry Andric     }
60520b57cec5SDimitry Andric   }
60530b57cec5SDimitry Andric 
60540b57cec5SDimitry Andric   // Check the type size field.
60550b57cec5SDimitry Andric   if (IsNewFormat) {
60560b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
60570b57cec5SDimitry Andric         BaseNode->getOperand(1));
60580b57cec5SDimitry Andric     if (!TypeSizeNode) {
60590b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
60600b57cec5SDimitry Andric       return InvalidNode;
60610b57cec5SDimitry Andric     }
60620b57cec5SDimitry Andric   }
60630b57cec5SDimitry Andric 
60640b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
60650b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
60660b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
60670b57cec5SDimitry Andric                 BaseNode);
60680b57cec5SDimitry Andric     return InvalidNode;
60690b57cec5SDimitry Andric   }
60700b57cec5SDimitry Andric 
60710b57cec5SDimitry Andric   bool Failed = false;
60720b57cec5SDimitry Andric 
60730b57cec5SDimitry Andric   Optional<APInt> PrevOffset;
60740b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
60750b57cec5SDimitry Andric 
60760b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
60770b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
60780b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
60790b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
60800b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
60810b57cec5SDimitry Andric            Idx += NumOpsPerField) {
60820b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
60830b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
60840b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
60850b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
60860b57cec5SDimitry Andric       Failed = true;
60870b57cec5SDimitry Andric       continue;
60880b57cec5SDimitry Andric     }
60890b57cec5SDimitry Andric 
60900b57cec5SDimitry Andric     auto *OffsetEntryCI =
60910b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
60920b57cec5SDimitry Andric     if (!OffsetEntryCI) {
60930b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
60940b57cec5SDimitry Andric       Failed = true;
60950b57cec5SDimitry Andric       continue;
60960b57cec5SDimitry Andric     }
60970b57cec5SDimitry Andric 
60980b57cec5SDimitry Andric     if (BitWidth == ~0u)
60990b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
61000b57cec5SDimitry Andric 
61010b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
61020b57cec5SDimitry Andric       CheckFailed(
61030b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
61040b57cec5SDimitry Andric           BaseNode);
61050b57cec5SDimitry Andric       Failed = true;
61060b57cec5SDimitry Andric       continue;
61070b57cec5SDimitry Andric     }
61080b57cec5SDimitry Andric 
61090b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
61100b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
61110b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
61120b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
61130b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
61140b57cec5SDimitry Andric     bool IsAscending =
61150b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
61160b57cec5SDimitry Andric 
61170b57cec5SDimitry Andric     if (!IsAscending) {
61180b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
61190b57cec5SDimitry Andric       Failed = true;
61200b57cec5SDimitry Andric     }
61210b57cec5SDimitry Andric 
61220b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
61230b57cec5SDimitry Andric 
61240b57cec5SDimitry Andric     if (IsNewFormat) {
61250b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
61260b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
61270b57cec5SDimitry Andric       if (!MemberSizeNode) {
61280b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
61290b57cec5SDimitry Andric         Failed = true;
61300b57cec5SDimitry Andric         continue;
61310b57cec5SDimitry Andric       }
61320b57cec5SDimitry Andric     }
61330b57cec5SDimitry Andric   }
61340b57cec5SDimitry Andric 
61350b57cec5SDimitry Andric   return Failed ? InvalidNode
61360b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
61370b57cec5SDimitry Andric }
61380b57cec5SDimitry Andric 
61390b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
61400b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
61410b57cec5SDimitry Andric }
61420b57cec5SDimitry Andric 
61430b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
61440b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
61450b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
61460b57cec5SDimitry Andric     return false;
61470b57cec5SDimitry Andric 
61480b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
61490b57cec5SDimitry Andric     return false;
61500b57cec5SDimitry Andric 
61510b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
61520b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
61530b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
61540b57cec5SDimitry Andric       return false;
61550b57cec5SDimitry Andric   }
61560b57cec5SDimitry Andric 
61570b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
61580b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
61590b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
61600b57cec5SDimitry Andric }
61610b57cec5SDimitry Andric 
61620b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
61630b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
61640b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
61650b57cec5SDimitry Andric     return ResultIt->second;
61660b57cec5SDimitry Andric 
61670b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
61680b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
61690b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
61700b57cec5SDimitry Andric   (void)InsertResult;
61710b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
61720b57cec5SDimitry Andric 
61730b57cec5SDimitry Andric   return Result;
61740b57cec5SDimitry Andric }
61750b57cec5SDimitry Andric 
61760b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
61770b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
61780b57cec5SDimitry Andric ///
61790b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
61800b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
61810b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
61820b57cec5SDimitry Andric                                                    APInt &Offset,
61830b57cec5SDimitry Andric                                                    bool IsNewFormat) {
61840b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
61850b57cec5SDimitry Andric 
61860b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
61870b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
61880b57cec5SDimitry Andric   // to Assert that.
61890b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
61900b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
61910b57cec5SDimitry Andric 
61920b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
61930b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
61940b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
61950b57cec5SDimitry Andric            Idx += NumOpsPerField) {
61960b57cec5SDimitry Andric     auto *OffsetEntryCI =
61970b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
61980b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
61990b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
62000b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
62010b57cec5SDimitry Andric                     BaseNode, &Offset);
62020b57cec5SDimitry Andric         return nullptr;
62030b57cec5SDimitry Andric       }
62040b57cec5SDimitry Andric 
62050b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
62060b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
62070b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
62080b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
62090b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
62100b57cec5SDimitry Andric     }
62110b57cec5SDimitry Andric   }
62120b57cec5SDimitry Andric 
62130b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
62140b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
62150b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
62160b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
62170b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
62180b57cec5SDimitry Andric }
62190b57cec5SDimitry Andric 
62200b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
62210b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
62220b57cec5SDimitry Andric     return false;
62230b57cec5SDimitry Andric 
62240b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
62250b57cec5SDimitry Andric   // its first operand.
6226349cc55cSDimitry Andric   return isa_and_nonnull<MDNode>(Type->getOperand(0));
62270b57cec5SDimitry Andric }
62280b57cec5SDimitry Andric 
62290b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
62300b57cec5SDimitry Andric   AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
62310b57cec5SDimitry Andric                  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
62320b57cec5SDimitry Andric                  isa<AtomicCmpXchgInst>(I),
62330b57cec5SDimitry Andric              "This instruction shall not have a TBAA access tag!", &I);
62340b57cec5SDimitry Andric 
62350b57cec5SDimitry Andric   bool IsStructPathTBAA =
62360b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
62370b57cec5SDimitry Andric 
62380b57cec5SDimitry Andric   AssertTBAA(
62390b57cec5SDimitry Andric       IsStructPathTBAA,
62400b57cec5SDimitry Andric       "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
62410b57cec5SDimitry Andric 
62420b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
62430b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
62440b57cec5SDimitry Andric 
62450b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
62460b57cec5SDimitry Andric 
62470b57cec5SDimitry Andric   if (IsNewFormat) {
62480b57cec5SDimitry Andric     AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
62490b57cec5SDimitry Andric                "Access tag metadata must have either 4 or 5 operands", &I, MD);
62500b57cec5SDimitry Andric   } else {
62510b57cec5SDimitry Andric     AssertTBAA(MD->getNumOperands() < 5,
62520b57cec5SDimitry Andric                "Struct tag metadata must have either 3 or 4 operands", &I, MD);
62530b57cec5SDimitry Andric   }
62540b57cec5SDimitry Andric 
62550b57cec5SDimitry Andric   // Check the access size field.
62560b57cec5SDimitry Andric   if (IsNewFormat) {
62570b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
62580b57cec5SDimitry Andric         MD->getOperand(3));
62590b57cec5SDimitry Andric     AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
62600b57cec5SDimitry Andric   }
62610b57cec5SDimitry Andric 
62620b57cec5SDimitry Andric   // Check the immutability flag.
62630b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
62640b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
62650b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
62660b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
62670b57cec5SDimitry Andric     AssertTBAA(IsImmutableCI,
62680b57cec5SDimitry Andric                "Immutability tag on struct tag metadata must be a constant",
62690b57cec5SDimitry Andric                &I, MD);
62700b57cec5SDimitry Andric     AssertTBAA(
62710b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
62720b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
62730b57cec5SDimitry Andric         &I, MD);
62740b57cec5SDimitry Andric   }
62750b57cec5SDimitry Andric 
62760b57cec5SDimitry Andric   AssertTBAA(BaseNode && AccessType,
62770b57cec5SDimitry Andric              "Malformed struct tag metadata: base and access-type "
62780b57cec5SDimitry Andric              "should be non-null and point to Metadata nodes",
62790b57cec5SDimitry Andric              &I, MD, BaseNode, AccessType);
62800b57cec5SDimitry Andric 
62810b57cec5SDimitry Andric   if (!IsNewFormat) {
62820b57cec5SDimitry Andric     AssertTBAA(isValidScalarTBAANode(AccessType),
62830b57cec5SDimitry Andric                "Access type node must be a valid scalar type", &I, MD,
62840b57cec5SDimitry Andric                AccessType);
62850b57cec5SDimitry Andric   }
62860b57cec5SDimitry Andric 
62870b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
62880b57cec5SDimitry Andric   AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
62890b57cec5SDimitry Andric 
62900b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
62910b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
62920b57cec5SDimitry Andric 
62930b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
62940b57cec5SDimitry Andric 
62950b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
62960b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
62970b57cec5SDimitry Andric                                                IsNewFormat)) {
62980b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
62990b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
63000b57cec5SDimitry Andric       return false;
63010b57cec5SDimitry Andric     }
63020b57cec5SDimitry Andric 
63030b57cec5SDimitry Andric     bool Invalid;
63040b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
63050b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
63060b57cec5SDimitry Andric                                                              IsNewFormat);
63070b57cec5SDimitry Andric 
63080b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
63090b57cec5SDimitry Andric     // errors we wanted to print.
63100b57cec5SDimitry Andric     if (Invalid)
63110b57cec5SDimitry Andric       return false;
63120b57cec5SDimitry Andric 
63130b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
63140b57cec5SDimitry Andric 
63150b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
63160b57cec5SDimitry Andric       AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
63170b57cec5SDimitry Andric                  &I, MD, &Offset);
63180b57cec5SDimitry Andric 
63190b57cec5SDimitry Andric     AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
63200b57cec5SDimitry Andric                    (BaseNodeBitWidth == 0 && Offset == 0) ||
63210b57cec5SDimitry Andric                    (IsNewFormat && BaseNodeBitWidth == ~0u),
63220b57cec5SDimitry Andric                "Access bit-width not the same as description bit-width", &I, MD,
63230b57cec5SDimitry Andric                BaseNodeBitWidth, Offset.getBitWidth());
63240b57cec5SDimitry Andric 
63250b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
63260b57cec5SDimitry Andric       break;
63270b57cec5SDimitry Andric   }
63280b57cec5SDimitry Andric 
63290b57cec5SDimitry Andric   AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
63300b57cec5SDimitry Andric              &I, MD);
63310b57cec5SDimitry Andric   return true;
63320b57cec5SDimitry Andric }
63330b57cec5SDimitry Andric 
63340b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
63350b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
63360b57cec5SDimitry Andric 
63370b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
63380b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
63390b57cec5SDimitry Andric }
63400b57cec5SDimitry Andric 
63410b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
63420b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
63430b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
63440b57cec5SDimitry Andric   Result Res;
63450b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
63460b57cec5SDimitry Andric   return Res;
63470b57cec5SDimitry Andric }
63480b57cec5SDimitry Andric 
63490b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
63500b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
63510b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
63520b57cec5SDimitry Andric }
63530b57cec5SDimitry Andric 
63540b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
63550b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
63560b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
63570b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
63580b57cec5SDimitry Andric 
63590b57cec5SDimitry Andric   return PreservedAnalyses::all();
63600b57cec5SDimitry Andric }
63610b57cec5SDimitry Andric 
63620b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
63630b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
63640b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
63650b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
63660b57cec5SDimitry Andric 
63670b57cec5SDimitry Andric   return PreservedAnalyses::all();
63680b57cec5SDimitry Andric }
6369