xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
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
100b57cec5SDimitry Andric // sanity 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/ADT/ilist.h"
620b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
630b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
640b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
650b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
660b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
670b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
680b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
690b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
700b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
710b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
720b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
730b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
740b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
750b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
760b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
770b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
780b57cec5SDimitry Andric #include "llvm/IR/Function.h"
790b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
800b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
810b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
820b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
830b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
840b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
850b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
860b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
870b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
880b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
89480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
900b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
910b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
920b57cec5SDimitry Andric #include "llvm/IR/Module.h"
930b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
940b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
950b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
960b57cec5SDimitry Andric #include "llvm/IR/Type.h"
970b57cec5SDimitry Andric #include "llvm/IR/Use.h"
980b57cec5SDimitry Andric #include "llvm/IR/User.h"
990b57cec5SDimitry Andric #include "llvm/IR/Value.h"
100480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1010b57cec5SDimitry Andric #include "llvm/Pass.h"
1020b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1030b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1040b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1050b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
1060b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1070b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
1080b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1090b57cec5SDimitry Andric #include <algorithm>
1100b57cec5SDimitry Andric #include <cassert>
1110b57cec5SDimitry Andric #include <cstdint>
1120b57cec5SDimitry Andric #include <memory>
1130b57cec5SDimitry Andric #include <string>
1140b57cec5SDimitry Andric #include <utility>
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric using namespace llvm;
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric namespace llvm {
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric struct VerifierSupport {
1210b57cec5SDimitry Andric   raw_ostream *OS;
1220b57cec5SDimitry Andric   const Module &M;
1230b57cec5SDimitry Andric   ModuleSlotTracker MST;
1248bcb0991SDimitry Andric   Triple TT;
1250b57cec5SDimitry Andric   const DataLayout &DL;
1260b57cec5SDimitry Andric   LLVMContext &Context;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1290b57cec5SDimitry Andric   bool Broken = false;
1300b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1310b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1320b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1330b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
1368bcb0991SDimitry Andric       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
1378bcb0991SDimitry Andric         Context(M.getContext()) {}
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric private:
1400b57cec5SDimitry Andric   void Write(const Module *M) {
1410b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1420b57cec5SDimitry Andric   }
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   void Write(const Value *V) {
1450b57cec5SDimitry Andric     if (V)
1460b57cec5SDimitry Andric       Write(*V);
1470b57cec5SDimitry Andric   }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   void Write(const Value &V) {
1500b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1510b57cec5SDimitry Andric       V.print(*OS, MST);
1520b57cec5SDimitry Andric       *OS << '\n';
1530b57cec5SDimitry Andric     } else {
1540b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1550b57cec5SDimitry Andric       *OS << '\n';
1560b57cec5SDimitry Andric     }
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   void Write(const Metadata *MD) {
1600b57cec5SDimitry Andric     if (!MD)
1610b57cec5SDimitry Andric       return;
1620b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
1630b57cec5SDimitry Andric     *OS << '\n';
1640b57cec5SDimitry Andric   }
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
1670b57cec5SDimitry Andric     Write(MD.get());
1680b57cec5SDimitry Andric   }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
1710b57cec5SDimitry Andric     if (!NMD)
1720b57cec5SDimitry Andric       return;
1730b57cec5SDimitry Andric     NMD->print(*OS, MST);
1740b57cec5SDimitry Andric     *OS << '\n';
1750b57cec5SDimitry Andric   }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   void Write(Type *T) {
1780b57cec5SDimitry Andric     if (!T)
1790b57cec5SDimitry Andric       return;
1800b57cec5SDimitry Andric     *OS << ' ' << *T;
1810b57cec5SDimitry Andric   }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   void Write(const Comdat *C) {
1840b57cec5SDimitry Andric     if (!C)
1850b57cec5SDimitry Andric       return;
1860b57cec5SDimitry Andric     *OS << *C;
1870b57cec5SDimitry Andric   }
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   void Write(const APInt *AI) {
1900b57cec5SDimitry Andric     if (!AI)
1910b57cec5SDimitry Andric       return;
1920b57cec5SDimitry Andric     *OS << *AI << '\n';
1930b57cec5SDimitry Andric   }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
1980b57cec5SDimitry Andric     for (const T &V : Vs)
1990b57cec5SDimitry Andric       Write(V);
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2030b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2040b57cec5SDimitry Andric     Write(V1);
2050b57cec5SDimitry Andric     WriteTs(Vs...);
2060b57cec5SDimitry Andric   }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric public:
2110b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2120b57cec5SDimitry Andric   ///
2130b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2140b57cec5SDimitry Andric   /// something is not correct.
2150b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2160b57cec5SDimitry Andric     if (OS)
2170b57cec5SDimitry Andric       *OS << Message << '\n';
2180b57cec5SDimitry Andric     Broken = true;
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   /// A check failed (with values to print).
2220b57cec5SDimitry Andric   ///
2230b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2240b57cec5SDimitry Andric   /// breakpoint on.
2250b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2260b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2270b57cec5SDimitry Andric     CheckFailed(Message);
2280b57cec5SDimitry Andric     if (OS)
2290b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   /// A debug info check failed.
2330b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
2340b57cec5SDimitry Andric     if (OS)
2350b57cec5SDimitry Andric       *OS << Message << '\n';
2360b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
2370b57cec5SDimitry Andric     BrokenDebugInfo = true;
2380b57cec5SDimitry Andric   }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
2410b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2420b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
2430b57cec5SDimitry Andric                             const Ts &... Vs) {
2440b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
2450b57cec5SDimitry Andric     if (OS)
2460b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2470b57cec5SDimitry Andric   }
2480b57cec5SDimitry Andric };
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric } // namespace llvm
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric namespace {
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
2550b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   DominatorTree DT;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
2600b57cec5SDimitry Andric   /// instructions we have seen so far.
2610b57cec5SDimitry Andric   ///
2620b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
2630b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
2640b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
2670b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
2700b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
2730b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   /// The result type for a landingpad.
2760b57cec5SDimitry Andric   Type *LandingPadResultTy;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
2790b57cec5SDimitry Andric   /// already.
2800b57cec5SDimitry Andric   bool SawFrameEscape;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
2830b57cec5SDimitry Andric   bool HasDebugInfo = false;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   /// Whether source was present on the first DIFile encountered in each CU.
2860b57cec5SDimitry Andric   DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
2890b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
2900b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
2930b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
2940b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
2970b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
3000b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3030b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3040b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3050b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3060b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3090b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric public:
3160b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3170b57cec5SDimitry Andric                     const Module &M)
3180b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3190b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3200b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3210b57cec5SDimitry Andric   }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric   bool verify(const Function &F) {
3260b57cec5SDimitry Andric     assert(F.getParent() == &M &&
3270b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
3300b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
3310b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
3320b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
3330b57cec5SDimitry Andric     // this code outside of a pass manager.
3340b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
3350b57cec5SDimitry Andric     if (!F.empty())
3360b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
3390b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
3400b57cec5SDimitry Andric         continue;
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric       if (OS) {
3430b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
3440b57cec5SDimitry Andric             << "' does not have terminator!\n";
3450b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
3460b57cec5SDimitry Andric         *OS << "\n";
3470b57cec5SDimitry Andric       }
3480b57cec5SDimitry Andric       return false;
3490b57cec5SDimitry Andric     }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric     Broken = false;
3520b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
3530b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
3540b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
3550b57cec5SDimitry Andric     InstsInThisBlock.clear();
3560b57cec5SDimitry Andric     DebugFnArgs.clear();
3570b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
3580b57cec5SDimitry Andric     SawFrameEscape = false;
3590b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     return !Broken;
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
3650b57cec5SDimitry Andric   bool verify() {
3660b57cec5SDimitry Andric     Broken = false;
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
3690b57cec5SDimitry Andric     for (const Function &F : M)
3700b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
3710b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
3740b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
3750b57cec5SDimitry Andric     verifyFrameRecoverIndices();
3760b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
3770b57cec5SDimitry Andric       visitGlobalVariable(GV);
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
3800b57cec5SDimitry Andric       visitGlobalAlias(GA);
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
3830b57cec5SDimitry Andric       visitNamedMDNode(NMD);
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
3860b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric     visitModuleFlags(M);
3890b57cec5SDimitry Andric     visitModuleIdents(M);
3900b57cec5SDimitry Andric     visitModuleCommandLines(M);
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric     verifyCompileUnits();
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
3950b57cec5SDimitry Andric     DISubprogramAttachments.clear();
3960b57cec5SDimitry Andric     return !Broken;
3970b57cec5SDimitry Andric   }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric private:
400*5ffd83dbSDimitry Andric   /// Whether a metadata node is allowed to be, or contain, a DILocation.
401*5ffd83dbSDimitry Andric   enum class AreDebugLocsAllowed { No, Yes };
402*5ffd83dbSDimitry Andric 
4030b57cec5SDimitry Andric   // Verification methods...
4040b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4050b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4060b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
4070b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
4080b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
4090b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
4100b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
411*5ffd83dbSDimitry Andric   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
4120b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
4130b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
4140b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
4150b57cec5SDimitry Andric   void visitModuleIdents(const Module &M);
4160b57cec5SDimitry Andric   void visitModuleCommandLines(const Module &M);
4170b57cec5SDimitry Andric   void visitModuleFlags(const Module &M);
4180b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
4190b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
4200b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
4210b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
4220b57cec5SDimitry Andric   void visitFunction(const Function &F);
4230b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
4240b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
4250b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
4268bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
4290b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
4300b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
4310b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
4320b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
4330b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
4340b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   // InstVisitor overrides...
4390b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
4400b57cec5SDimitry Andric   void visit(Instruction &I);
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
4430b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
4440b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
4450b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
4460b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
4470b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
4480b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
4490b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
4500b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
4510b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
4520b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
4530b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
4540b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
4550b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
4560b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
4570b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
4580b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
4590b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
4600b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
4610b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
4620b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
4630b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
4640b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
4650b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
4660b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
4670b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
4680b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
4690b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
4700b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
4710b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
4720b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
4730b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
4740b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
4750b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
4760b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
4770b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
4780b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
4790b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
4800b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
4810b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
4820b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
4830b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
4840b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
4850b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
4860b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
4870b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
4880b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
4890b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
4900b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
4910b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
4920b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
4930b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
4940b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
4950b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
4960b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
4970b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
4980b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
4990b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
5020b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
5030b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
5040b57cec5SDimitry Andric   bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
5050b57cec5SDimitry Andric                         unsigned ArgNo, std::string &Suffix);
5060b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
5070b57cec5SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
5080b57cec5SDimitry Andric                             const Value *V);
5090b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
5100b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
5110b57cec5SDimitry Andric                            const Value *V, bool IsIntrinsic);
5120b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
5150b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
5160b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
5170b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
5180b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
5210b57cec5SDimitry Andric   template <typename ValueOrMetadata>
5220b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
5230b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
5240b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
5250b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
5268bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   /// Module-level debug info verification...
5290b57cec5SDimitry Andric   void verifyCompileUnits();
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
5320b57cec5SDimitry Andric   /// declarations share the same calling convention.
5330b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   /// Verify all-or-nothing property of DIFile source attribute within a CU.
5360b57cec5SDimitry Andric   void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
5370b57cec5SDimitry Andric };
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric } // end anonymous namespace
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
5420b57cec5SDimitry Andric #define Assert(C, ...) \
5430b57cec5SDimitry Andric   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
5460b57cec5SDimitry Andric /// an error message.
5470b57cec5SDimitry Andric #define AssertDI(C, ...) \
5480b57cec5SDimitry Andric   do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
5510b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
5520b57cec5SDimitry Andric     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
5530b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
5540b57cec5SDimitry Andric }
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric // Helper to recursively iterate over indirect users. By
5570b57cec5SDimitry Andric // returning false, the callback can ask to stop recursing
5580b57cec5SDimitry Andric // further.
5590b57cec5SDimitry Andric static void forEachUser(const Value *User,
5600b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
5610b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
5620b57cec5SDimitry Andric   if (!Visited.insert(User).second)
5630b57cec5SDimitry Andric     return;
5640b57cec5SDimitry Andric   for (const Value *TheNextUser : User->materialized_users())
5650b57cec5SDimitry Andric     if (Callback(TheNextUser))
5660b57cec5SDimitry Andric       forEachUser(TheNextUser, Visited, Callback);
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
5700b57cec5SDimitry Andric   Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
5710b57cec5SDimitry Andric          "Global is external, but doesn't have external or weak linkage!", &GV);
5720b57cec5SDimitry Andric 
573*5ffd83dbSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV))
574*5ffd83dbSDimitry Andric     Assert(GO->getAlignment() <= Value::MaximumAlignment,
575*5ffd83dbSDimitry Andric            "huge alignment values are unsupported", GO);
5760b57cec5SDimitry Andric   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
5770b57cec5SDimitry Andric          "Only global variables can have appending linkage!", &GV);
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
5800b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
5810b57cec5SDimitry Andric     Assert(GVar && GVar->getValueType()->isArrayTy(),
5820b57cec5SDimitry Andric            "Only global arrays can have appending linkage!", GVar);
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
5860b57cec5SDimitry Andric     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
5890b57cec5SDimitry Andric     Assert(!GV.isDSOLocal(),
5900b57cec5SDimitry Andric            "GlobalValue with DLLImport Storage is dso_local!", &GV);
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric     Assert((GV.isDeclaration() && GV.hasExternalLinkage()) ||
5930b57cec5SDimitry Andric                GV.hasAvailableExternallyLinkage(),
5940b57cec5SDimitry Andric            "Global is marked as dllimport, but not external", &GV);
5950b57cec5SDimitry Andric   }
5960b57cec5SDimitry Andric 
597*5ffd83dbSDimitry Andric   if (GV.isImplicitDSOLocal())
5980b57cec5SDimitry Andric     Assert(GV.isDSOLocal(),
599*5ffd83dbSDimitry Andric            "GlobalValue with local linkage or non-default "
600*5ffd83dbSDimitry Andric            "visibility must be dso_local!",
6010b57cec5SDimitry Andric            &GV);
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
6040b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
6050b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
6060b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
6070b57cec5SDimitry Andric                     I);
6080b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
6090b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
6100b57cec5SDimitry Andric                     I->getParent()->getParent(),
6110b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
6120b57cec5SDimitry Andric       return false;
6130b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
6140b57cec5SDimitry Andric       if (F->getParent() != &M)
6150b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
6160b57cec5SDimitry Andric                     F, F->getParent());
6170b57cec5SDimitry Andric       return false;
6180b57cec5SDimitry Andric     }
6190b57cec5SDimitry Andric     return true;
6200b57cec5SDimitry Andric   });
6210b57cec5SDimitry Andric }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
6240b57cec5SDimitry Andric   if (GV.hasInitializer()) {
6250b57cec5SDimitry Andric     Assert(GV.getInitializer()->getType() == GV.getValueType(),
6260b57cec5SDimitry Andric            "Global variable initializer type does not match global "
6270b57cec5SDimitry Andric            "variable type!",
6280b57cec5SDimitry Andric            &GV);
6290b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
6300b57cec5SDimitry Andric     // cannot be constant.
6310b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
6320b57cec5SDimitry Andric       Assert(GV.getInitializer()->isNullValue(),
6330b57cec5SDimitry Andric              "'common' global must have a zero initializer!", &GV);
6340b57cec5SDimitry Andric       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
6350b57cec5SDimitry Andric              &GV);
6360b57cec5SDimitry Andric       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
6370b57cec5SDimitry Andric     }
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
6410b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
6420b57cec5SDimitry Andric     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
6430b57cec5SDimitry Andric            "invalid linkage for intrinsic global variable", &GV);
6440b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
6450b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
6460b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
6470b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
6480b57cec5SDimitry Andric       PointerType *FuncPtrTy =
6490b57cec5SDimitry Andric           FunctionType::get(Type::getVoidTy(Context), false)->
6500b57cec5SDimitry Andric           getPointerTo(DL.getProgramAddressSpace());
6510b57cec5SDimitry Andric       Assert(STy &&
6520b57cec5SDimitry Andric                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
6530b57cec5SDimitry Andric                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
6540b57cec5SDimitry Andric                  STy->getTypeAtIndex(1) == FuncPtrTy,
6550b57cec5SDimitry Andric              "wrong type for intrinsic global variable", &GV);
6560b57cec5SDimitry Andric       Assert(STy->getNumElements() == 3,
6570b57cec5SDimitry Andric              "the third field of the element type is mandatory, "
6580b57cec5SDimitry Andric              "specify i8* null to migrate from the obsoleted 2-field form");
6590b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
6600b57cec5SDimitry Andric       Assert(ETy->isPointerTy() &&
6610b57cec5SDimitry Andric                  cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
6620b57cec5SDimitry Andric              "wrong type for intrinsic global variable", &GV);
6630b57cec5SDimitry Andric     }
6640b57cec5SDimitry Andric   }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
6670b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
6680b57cec5SDimitry Andric     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
6690b57cec5SDimitry Andric            "invalid linkage for intrinsic global variable", &GV);
6700b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
6710b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
6720b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
6730b57cec5SDimitry Andric       Assert(PTy, "wrong type for intrinsic global variable", &GV);
6740b57cec5SDimitry Andric       if (GV.hasInitializer()) {
6750b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
6760b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
6770b57cec5SDimitry Andric         Assert(InitArray, "wrong initalizer for intrinsic global variable",
6780b57cec5SDimitry Andric                Init);
6790b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
6808bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
6810b57cec5SDimitry Andric           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
6820b57cec5SDimitry Andric                      isa<GlobalAlias>(V),
6830b57cec5SDimitry Andric                  "invalid llvm.used member", V);
6840b57cec5SDimitry Andric           Assert(V->hasName(), "members of llvm.used must be named", V);
6850b57cec5SDimitry Andric         }
6860b57cec5SDimitry Andric       }
6870b57cec5SDimitry Andric     }
6880b57cec5SDimitry Andric   }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   // Visit any debug info attachments.
6910b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
6920b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
6930b57cec5SDimitry Andric   for (auto *MD : MDs) {
6940b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
6950b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
6960b57cec5SDimitry Andric     else
6970b57cec5SDimitry Andric       AssertDI(false, "!dbg attachment of global variable must be a "
6980b57cec5SDimitry Andric                       "DIGlobalVariableExpression");
6990b57cec5SDimitry Andric   }
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
7020b57cec5SDimitry Andric   // the runtime size. If the global is a struct or an array containing
7030b57cec5SDimitry Andric   // scalable vectors, that will be caught by the isValidElementType methods
7040b57cec5SDimitry Andric   // in StructType or ArrayType instead.
705*5ffd83dbSDimitry Andric   Assert(!isa<ScalableVectorType>(GV.getValueType()),
706*5ffd83dbSDimitry Andric          "Globals cannot contain scalable vectors", &GV);
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
7090b57cec5SDimitry Andric     visitGlobalValue(GV);
7100b57cec5SDimitry Andric     return;
7110b57cec5SDimitry Andric   }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
7140b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   visitGlobalValue(GV);
7170b57cec5SDimitry Andric }
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
7200b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
7210b57cec5SDimitry Andric   Visited.insert(&GA);
7220b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
7230b57cec5SDimitry Andric }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
7260b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
7270b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
7280b57cec5SDimitry Andric     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
7290b57cec5SDimitry Andric            &GA);
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
7320b57cec5SDimitry Andric       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric       Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
7350b57cec5SDimitry Andric              &GA);
7360b57cec5SDimitry Andric     } else {
7370b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
7380b57cec5SDimitry Andric       // Do not recurse into global initializers.
7390b57cec5SDimitry Andric       return;
7400b57cec5SDimitry Andric     }
7410b57cec5SDimitry Andric   }
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
7440b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
7470b57cec5SDimitry Andric     Value *V = &*U;
7480b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
7490b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
7500b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
7510b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
7520b57cec5SDimitry Andric   }
7530b57cec5SDimitry Andric }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
7560b57cec5SDimitry Andric   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
7570b57cec5SDimitry Andric          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
7580b57cec5SDimitry Andric          "weak_odr, or external linkage!",
7590b57cec5SDimitry Andric          &GA);
7600b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
7610b57cec5SDimitry Andric   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
7620b57cec5SDimitry Andric   Assert(GA.getType() == Aliasee->getType(),
7630b57cec5SDimitry Andric          "Alias and aliasee types should match!", &GA);
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
7660b57cec5SDimitry Andric          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   visitGlobalValue(GA);
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
7740b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
7750b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
7760b57cec5SDimitry Andric   if (NMD.getName().startswith("llvm.dbg."))
7770b57cec5SDimitry Andric     AssertDI(NMD.getName() == "llvm.dbg.cu",
7780b57cec5SDimitry Andric              "unrecognized named metadata node in the llvm.dbg namespace",
7790b57cec5SDimitry Andric              &NMD);
7800b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
7810b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
7820b57cec5SDimitry Andric       AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     if (!MD)
7850b57cec5SDimitry Andric       continue;
7860b57cec5SDimitry Andric 
787*5ffd83dbSDimitry Andric     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
7880b57cec5SDimitry Andric   }
7890b57cec5SDimitry Andric }
7900b57cec5SDimitry Andric 
791*5ffd83dbSDimitry Andric void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
7920b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
7930b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
7940b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
7950b57cec5SDimitry Andric     return;
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
7980b57cec5SDimitry Andric   default:
7990b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
8000b57cec5SDimitry Andric   case Metadata::MDTupleKind:
8010b57cec5SDimitry Andric     break;
8020b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
8030b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
8040b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
8050b57cec5SDimitry Andric     break;
8060b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
8100b57cec5SDimitry Andric     if (!Op)
8110b57cec5SDimitry Andric       continue;
8120b57cec5SDimitry Andric     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
8130b57cec5SDimitry Andric            &MD, Op);
814*5ffd83dbSDimitry Andric     AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
815*5ffd83dbSDimitry Andric              "DILocation not allowed within this metadata node", &MD, Op);
8160b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
817*5ffd83dbSDimitry Andric       visitMDNode(*N, AllowLocs);
8180b57cec5SDimitry Andric       continue;
8190b57cec5SDimitry Andric     }
8200b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
8210b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
8220b57cec5SDimitry Andric       continue;
8230b57cec5SDimitry Andric     }
8240b57cec5SDimitry Andric   }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
8270b57cec5SDimitry Andric   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
8280b57cec5SDimitry Andric   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
8290b57cec5SDimitry Andric }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
8320b57cec5SDimitry Andric   Assert(MD.getValue(), "Expected valid value", &MD);
8330b57cec5SDimitry Andric   Assert(!MD.getValue()->getType()->isMetadataTy(),
8340b57cec5SDimitry Andric          "Unexpected metadata round-trip through values", &MD, MD.getValue());
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
8370b57cec5SDimitry Andric   if (!L)
8380b57cec5SDimitry Andric     return;
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   Assert(F, "function-local metadata used outside a function", L);
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
8430b57cec5SDimitry Andric   // function that we expect.
8440b57cec5SDimitry Andric   Function *ActualF = nullptr;
8450b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
8460b57cec5SDimitry Andric     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
8470b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
8480b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
8490b57cec5SDimitry Andric     ActualF = BB->getParent();
8500b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
8510b57cec5SDimitry Andric     ActualF = A->getParent();
8520b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   Assert(ActualF == F, "function-local metadata used in wrong function", L);
8550b57cec5SDimitry Andric }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
8580b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
8590b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
860*5ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::No);
8610b57cec5SDimitry Andric     return;
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
8650b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
8660b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
8670b57cec5SDimitry Andric     return;
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
8700b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
8710b57cec5SDimitry Andric }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
8740b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
8750b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
8780b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
8790b57cec5SDimitry Andric            "location requires a valid scope", &N, N.getRawScope());
8800b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
8810b57cec5SDimitry Andric     AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
8820b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
8830b57cec5SDimitry Andric     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
8840b57cec5SDimitry Andric }
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
8870b57cec5SDimitry Andric   AssertDI(N.getTag(), "invalid tag", &N);
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
8910b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
8920b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
8930b57cec5SDimitry Andric }
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
8960b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
897*5ffd83dbSDimitry Andric   AssertDI(N.getRawCountNode() || N.getRawUpperBound(),
898*5ffd83dbSDimitry Andric            "Subrange must contain count or upperBound", &N);
899*5ffd83dbSDimitry Andric   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
900*5ffd83dbSDimitry Andric            "Subrange can have any one of count or upperBound", &N);
901*5ffd83dbSDimitry Andric   AssertDI(!N.getRawCountNode() || N.getCount(),
902*5ffd83dbSDimitry Andric            "Count must either be a signed constant or a DIVariable", &N);
9030b57cec5SDimitry Andric   auto Count = N.getCount();
904*5ffd83dbSDimitry Andric   AssertDI(!Count || !Count.is<ConstantInt *>() ||
9050b57cec5SDimitry Andric                Count.get<ConstantInt *>()->getSExtValue() >= -1,
9060b57cec5SDimitry Andric            "invalid subrange count", &N);
907*5ffd83dbSDimitry Andric   auto *LBound = N.getRawLowerBound();
908*5ffd83dbSDimitry Andric   AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
909*5ffd83dbSDimitry Andric                isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
910*5ffd83dbSDimitry Andric            "LowerBound must be signed constant or DIVariable or DIExpression",
911*5ffd83dbSDimitry Andric            &N);
912*5ffd83dbSDimitry Andric   auto *UBound = N.getRawUpperBound();
913*5ffd83dbSDimitry Andric   AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
914*5ffd83dbSDimitry Andric                isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
915*5ffd83dbSDimitry Andric            "UpperBound must be signed constant or DIVariable or DIExpression",
916*5ffd83dbSDimitry Andric            &N);
917*5ffd83dbSDimitry Andric   auto *Stride = N.getRawStride();
918*5ffd83dbSDimitry Andric   AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
919*5ffd83dbSDimitry Andric                isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
920*5ffd83dbSDimitry Andric            "Stride must be signed constant or DIVariable or DIExpression", &N);
9210b57cec5SDimitry Andric }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
9240b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
9250b57cec5SDimitry Andric }
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
9280b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
9290b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_unspecified_type,
9300b57cec5SDimitry Andric            "invalid tag", &N);
9310b57cec5SDimitry Andric   AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
9320b57cec5SDimitry Andric             "has conflicting flags", &N);
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
9360b57cec5SDimitry Andric   // Common scope checks.
9370b57cec5SDimitry Andric   visitDIScope(N);
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
9400b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_pointer_type ||
9410b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
9420b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_reference_type ||
9430b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
9440b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_const_type ||
9450b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_volatile_type ||
9460b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_restrict_type ||
9470b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_atomic_type ||
9480b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_member ||
9490b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_inheritance ||
9500b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_friend,
9510b57cec5SDimitry Andric            "invalid tag", &N);
9520b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
9530b57cec5SDimitry Andric     AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
9540b57cec5SDimitry Andric              N.getRawExtraData());
9550b57cec5SDimitry Andric   }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
9580b57cec5SDimitry Andric   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
9590b57cec5SDimitry Andric            N.getRawBaseType());
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
9620b57cec5SDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
9630b57cec5SDimitry Andric                  N.getTag() == dwarf::DW_TAG_reference_type ||
9640b57cec5SDimitry Andric                  N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
9650b57cec5SDimitry Andric              "DWARF address space only applies to pointer or reference types",
9660b57cec5SDimitry Andric              &N);
9670b57cec5SDimitry Andric   }
9680b57cec5SDimitry Andric }
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric /// Detect mutually exclusive flags.
9710b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
9720b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
9730b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
9740b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
9750b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
9790b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
9800b57cec5SDimitry Andric   AssertDI(Params, "invalid template params", &N, &RawParams);
9810b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
9820b57cec5SDimitry Andric     AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
9830b57cec5SDimitry Andric              &N, Params, Op);
9840b57cec5SDimitry Andric   }
9850b57cec5SDimitry Andric }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
9880b57cec5SDimitry Andric   // Common scope checks.
9890b57cec5SDimitry Andric   visitDIScope(N);
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
9920b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_structure_type ||
9930b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_union_type ||
9940b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_enumeration_type ||
9950b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_class_type ||
9960b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_variant_part,
9970b57cec5SDimitry Andric            "invalid tag", &N);
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
10000b57cec5SDimitry Andric   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
10010b57cec5SDimitry Andric            N.getRawBaseType());
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
10040b57cec5SDimitry Andric            "invalid composite elements", &N, N.getRawElements());
10050b57cec5SDimitry Andric   AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
10060b57cec5SDimitry Andric            N.getRawVTableHolder());
10070b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
10080b57cec5SDimitry Andric            "invalid reference flags", &N);
10098bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
10108bcb0991SDimitry Andric   AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,
10118bcb0991SDimitry Andric            "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   if (N.isVector()) {
10140b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
10150b57cec5SDimitry Andric     AssertDI(Elements.size() == 1 &&
10160b57cec5SDimitry Andric              Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
10170b57cec5SDimitry Andric              "invalid vector, expected one element of type subrange", &N);
10180b57cec5SDimitry Andric   }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
10210b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_class_type ||
10240b57cec5SDimitry Andric       N.getTag() == dwarf::DW_TAG_union_type) {
10250b57cec5SDimitry Andric     AssertDI(N.getFile() && !N.getFile()->getFilename().empty(),
10260b57cec5SDimitry Andric              "class/union requires a filename", &N, N.getFile());
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
10300b57cec5SDimitry Andric     AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
10310b57cec5SDimitry Andric              "discriminator can only appear on variant part");
10320b57cec5SDimitry Andric   }
1033*5ffd83dbSDimitry Andric 
1034*5ffd83dbSDimitry Andric   if (N.getRawDataLocation()) {
1035*5ffd83dbSDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1036*5ffd83dbSDimitry Andric              "dataLocation can only appear in array type");
1037*5ffd83dbSDimitry Andric   }
10380b57cec5SDimitry Andric }
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
10410b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
10420b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
10430b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
10440b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
10450b57cec5SDimitry Andric       AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
10460b57cec5SDimitry Andric     }
10470b57cec5SDimitry Andric   }
10480b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
10490b57cec5SDimitry Andric            "invalid reference flags", &N);
10500b57cec5SDimitry Andric }
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
10530b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
10540b57cec5SDimitry Andric   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
10550b57cec5SDimitry Andric   if (Checksum) {
10560b57cec5SDimitry Andric     AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
10570b57cec5SDimitry Andric              "invalid checksum kind", &N);
10580b57cec5SDimitry Andric     size_t Size;
10590b57cec5SDimitry Andric     switch (Checksum->Kind) {
10600b57cec5SDimitry Andric     case DIFile::CSK_MD5:
10610b57cec5SDimitry Andric       Size = 32;
10620b57cec5SDimitry Andric       break;
10630b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
10640b57cec5SDimitry Andric       Size = 40;
10650b57cec5SDimitry Andric       break;
1066*5ffd83dbSDimitry Andric     case DIFile::CSK_SHA256:
1067*5ffd83dbSDimitry Andric       Size = 64;
1068*5ffd83dbSDimitry Andric       break;
10690b57cec5SDimitry Andric     }
10700b57cec5SDimitry Andric     AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
10710b57cec5SDimitry Andric     AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
10720b57cec5SDimitry Andric              "invalid checksum", &N);
10730b57cec5SDimitry Andric   }
10740b57cec5SDimitry Andric }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
10770b57cec5SDimitry Andric   AssertDI(N.isDistinct(), "compile units must be distinct", &N);
10780b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
10810b57cec5SDimitry Andric   // as those could be empty.
10820b57cec5SDimitry Andric   AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
10830b57cec5SDimitry Andric            N.getRawFile());
10840b57cec5SDimitry Andric   AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
10850b57cec5SDimitry Andric            N.getFile());
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   verifySourceDebugInfo(N, *N.getFile());
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
10900b57cec5SDimitry Andric            "invalid emission kind", &N);
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
10930b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
10940b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
10950b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
10960b57cec5SDimitry Andric       AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
10970b57cec5SDimitry Andric                "invalid enum type", &N, N.getEnumTypes(), Op);
10980b57cec5SDimitry Andric     }
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
11010b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
11020b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
11030b57cec5SDimitry Andric       AssertDI(Op && (isa<DIType>(Op) ||
11040b57cec5SDimitry Andric                       (isa<DISubprogram>(Op) &&
11050b57cec5SDimitry Andric                        !cast<DISubprogram>(Op)->isDefinition())),
11060b57cec5SDimitry Andric                "invalid retained type", &N, Op);
11070b57cec5SDimitry Andric     }
11080b57cec5SDimitry Andric   }
11090b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
11100b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
11110b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
11120b57cec5SDimitry Andric       AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
11130b57cec5SDimitry Andric                "invalid global variable ref", &N, Op);
11140b57cec5SDimitry Andric     }
11150b57cec5SDimitry Andric   }
11160b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
11170b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
11180b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
11190b57cec5SDimitry Andric       AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
11200b57cec5SDimitry Andric                &N, Op);
11210b57cec5SDimitry Andric     }
11220b57cec5SDimitry Andric   }
11230b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
11240b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
11250b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
11260b57cec5SDimitry Andric       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
11270b57cec5SDimitry Andric     }
11280b57cec5SDimitry Andric   }
11290b57cec5SDimitry Andric   CUVisited.insert(&N);
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
11330b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
11340b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
11350b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
11360b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
11370b57cec5SDimitry Andric   else
11380b57cec5SDimitry Andric     AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
11390b57cec5SDimitry Andric   if (auto *T = N.getRawType())
11400b57cec5SDimitry Andric     AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
11410b57cec5SDimitry Andric   AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
11420b57cec5SDimitry Andric            N.getRawContainingType());
11430b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
11440b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
11450b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
11460b57cec5SDimitry Andric     AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
11470b57cec5SDimitry Andric              "invalid subprogram declaration", &N, S);
11480b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
11490b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
11500b57cec5SDimitry Andric     AssertDI(Node, "invalid retained nodes list", &N, RawNode);
11510b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
11520b57cec5SDimitry Andric       AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
11530b57cec5SDimitry Andric                "invalid retained nodes, expected DILocalVariable or DILabel",
11540b57cec5SDimitry Andric                &N, Node, Op);
11550b57cec5SDimitry Andric     }
11560b57cec5SDimitry Andric   }
11570b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
11580b57cec5SDimitry Andric            "invalid reference flags", &N);
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
11610b57cec5SDimitry Andric   if (N.isDefinition()) {
11620b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
11630b57cec5SDimitry Andric     AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
11640b57cec5SDimitry Andric     AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
11650b57cec5SDimitry Andric     AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
11660b57cec5SDimitry Andric     if (N.getFile())
11670b57cec5SDimitry Andric       verifySourceDebugInfo(*N.getUnit(), *N.getFile());
11680b57cec5SDimitry Andric   } else {
11690b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
11700b57cec5SDimitry Andric     AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
11710b57cec5SDimitry Andric   }
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
11740b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
11750b57cec5SDimitry Andric     AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
11760b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
11770b57cec5SDimitry Andric       AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
11780b57cec5SDimitry Andric                Op);
11790b57cec5SDimitry Andric   }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
11820b57cec5SDimitry Andric     AssertDI(N.isDefinition(),
11830b57cec5SDimitry Andric              "DIFlagAllCallsDescribed must be attached to a definition");
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
11870b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
11880b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
11890b57cec5SDimitry Andric            "invalid local scope", &N, N.getRawScope());
11900b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
11910b57cec5SDimitry Andric     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
11920b57cec5SDimitry Andric }
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
11950b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   AssertDI(N.getLine() || !N.getColumn(),
11980b57cec5SDimitry Andric            "cannot have column info without line info", &N);
11990b57cec5SDimitry Andric }
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
12020b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
12030b57cec5SDimitry Andric }
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
12060b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
12070b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
12080b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
12090b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
12100b57cec5SDimitry Andric     AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
12110b57cec5SDimitry Andric }
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
12140b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
12150b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
12160b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
12170b57cec5SDimitry Andric }
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
12200b57cec5SDimitry Andric   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
12210b57cec5SDimitry Andric                N.getMacinfoType() == dwarf::DW_MACINFO_undef,
12220b57cec5SDimitry Andric            "invalid macinfo type", &N);
12230b57cec5SDimitry Andric   AssertDI(!N.getName().empty(), "anonymous macro", &N);
12240b57cec5SDimitry Andric   if (!N.getValue().empty()) {
12250b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
12260b57cec5SDimitry Andric   }
12270b57cec5SDimitry Andric }
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
12300b57cec5SDimitry Andric   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
12310b57cec5SDimitry Andric            "invalid macinfo type", &N);
12320b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
12330b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
12360b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
12370b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
12380b57cec5SDimitry Andric       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
12390b57cec5SDimitry Andric     }
12400b57cec5SDimitry Andric   }
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
12440b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
12450b57cec5SDimitry Andric   AssertDI(!N.getName().empty(), "anonymous module", &N);
12460b57cec5SDimitry Andric }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
12490b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
12530b57cec5SDimitry Andric   visitDITemplateParameter(N);
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
12560b57cec5SDimitry Andric            &N);
12570b57cec5SDimitry Andric }
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
12600b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
12610b57cec5SDimitry Andric   visitDITemplateParameter(N);
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
12640b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
12650b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
12660b57cec5SDimitry Andric            "invalid tag", &N);
12670b57cec5SDimitry Andric }
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
12700b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
12710b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
12720b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
12730b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
12740b57cec5SDimitry Andric }
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
12770b57cec5SDimitry Andric   // Checks common to all variables.
12780b57cec5SDimitry Andric   visitDIVariable(N);
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
12810b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1282*5ffd83dbSDimitry Andric   // Assert only if the global variable is not an extern
1283*5ffd83dbSDimitry Andric   if (N.isDefinition())
12840b57cec5SDimitry Andric     AssertDI(N.getType(), "missing global variable type", &N);
12850b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
12860b57cec5SDimitry Andric     AssertDI(isa<DIDerivedType>(Member),
12870b57cec5SDimitry Andric              "invalid static data member declaration", &N, Member);
12880b57cec5SDimitry Andric   }
12890b57cec5SDimitry Andric }
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
12920b57cec5SDimitry Andric   // Checks common to all variables.
12930b57cec5SDimitry Andric   visitDIVariable(N);
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
12960b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
12970b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
12980b57cec5SDimitry Andric            "local variable requires a valid scope", &N, N.getRawScope());
12990b57cec5SDimitry Andric   if (auto Ty = N.getType())
13000b57cec5SDimitry Andric     AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
13010b57cec5SDimitry Andric }
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
13040b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
13050b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
13060b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
13070b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
13100b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
13110b57cec5SDimitry Andric            "label requires a valid scope", &N, N.getRawScope());
13120b57cec5SDimitry Andric }
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
13150b57cec5SDimitry Andric   AssertDI(N.isValid(), "invalid expression", &N);
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
13190b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
13200b57cec5SDimitry Andric   AssertDI(GVE.getVariable(), "missing variable");
13210b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
13220b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
13230b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
13240b57cec5SDimitry Andric     visitDIExpression(*Expr);
13250b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
13260b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
13270b57cec5SDimitry Andric   }
13280b57cec5SDimitry Andric }
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
13310b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
13320b57cec5SDimitry Andric   if (auto *T = N.getRawType())
13330b57cec5SDimitry Andric     AssertDI(isType(T), "invalid type ref", &N, T);
13340b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
13350b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
13360b57cec5SDimitry Andric }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
13390b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
13400b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_imported_declaration,
13410b57cec5SDimitry Andric            "invalid tag", &N);
13420b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
13430b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
13440b57cec5SDimitry Andric   AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
13450b57cec5SDimitry Andric            N.getRawEntity());
13460b57cec5SDimitry Andric }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
13498bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
13508bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
13518bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
13520b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
13538bcb0991SDimitry Andric       Assert(!GV->hasPrivateLinkage(),
13548bcb0991SDimitry Andric              "comdat global value has private linkage", GV);
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric void Verifier::visitModuleIdents(const Module &M) {
13580b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
13590b57cec5SDimitry Andric   if (!Idents)
13600b57cec5SDimitry Andric     return;
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
13630b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
13640b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
13650b57cec5SDimitry Andric     Assert(N->getNumOperands() == 1,
13660b57cec5SDimitry Andric            "incorrect number of operands in llvm.ident metadata", N);
13670b57cec5SDimitry Andric     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
13680b57cec5SDimitry Andric            ("invalid value for llvm.ident metadata entry operand"
13690b57cec5SDimitry Andric             "(the operand should be a string)"),
13700b57cec5SDimitry Andric            N->getOperand(0));
13710b57cec5SDimitry Andric   }
13720b57cec5SDimitry Andric }
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric void Verifier::visitModuleCommandLines(const Module &M) {
13750b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
13760b57cec5SDimitry Andric   if (!CommandLines)
13770b57cec5SDimitry Andric     return;
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
13800b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
13810b57cec5SDimitry Andric   // requirement is met.
13820b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
13830b57cec5SDimitry Andric     Assert(N->getNumOperands() == 1,
13840b57cec5SDimitry Andric            "incorrect number of operands in llvm.commandline metadata", N);
13850b57cec5SDimitry Andric     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
13860b57cec5SDimitry Andric            ("invalid value for llvm.commandline metadata entry operand"
13870b57cec5SDimitry Andric             "(the operand should be a string)"),
13880b57cec5SDimitry Andric            N->getOperand(0));
13890b57cec5SDimitry Andric   }
13900b57cec5SDimitry Andric }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric void Verifier::visitModuleFlags(const Module &M) {
13930b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
13940b57cec5SDimitry Andric   if (!Flags) return;
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
13970b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
13980b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
13990b57cec5SDimitry Andric   for (const MDNode *MDN : Flags->operands())
14000b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
14030b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
14040b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
14050b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
14080b57cec5SDimitry Andric     if (!Op) {
14090b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
14100b57cec5SDimitry Andric                   Flag);
14110b57cec5SDimitry Andric       continue;
14120b57cec5SDimitry Andric     }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
14150b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
14160b57cec5SDimitry Andric                    "flag does not have the required value"),
14170b57cec5SDimitry Andric                   Flag);
14180b57cec5SDimitry Andric       continue;
14190b57cec5SDimitry Andric     }
14200b57cec5SDimitry Andric   }
14210b57cec5SDimitry Andric }
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric void
14240b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
14250b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
14260b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
14270b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
14280b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
14290b57cec5SDimitry Andric   Assert(Op->getNumOperands() == 3,
14300b57cec5SDimitry Andric          "incorrect number of operands in module flag", Op);
14310b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
14320b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
14330b57cec5SDimitry Andric     Assert(
14340b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
14350b57cec5SDimitry Andric         "invalid behavior operand in module flag (expected constant integer)",
14360b57cec5SDimitry Andric         Op->getOperand(0));
14370b57cec5SDimitry Andric     Assert(false,
14380b57cec5SDimitry Andric            "invalid behavior operand in module flag (unexpected constant)",
14390b57cec5SDimitry Andric            Op->getOperand(0));
14400b57cec5SDimitry Andric   }
14410b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
14420b57cec5SDimitry Andric   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
14430b57cec5SDimitry Andric          Op->getOperand(1));
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   // Sanity check the values for behaviors with additional requirements.
14460b57cec5SDimitry Andric   switch (MFB) {
14470b57cec5SDimitry Andric   case Module::Error:
14480b57cec5SDimitry Andric   case Module::Warning:
14490b57cec5SDimitry Andric   case Module::Override:
14500b57cec5SDimitry Andric     // These behavior types accept any value.
14510b57cec5SDimitry Andric     break;
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   case Module::Max: {
14540b57cec5SDimitry Andric     Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
14550b57cec5SDimitry Andric            "invalid value for 'max' module flag (expected constant integer)",
14560b57cec5SDimitry Andric            Op->getOperand(2));
14570b57cec5SDimitry Andric     break;
14580b57cec5SDimitry Andric   }
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   case Module::Require: {
14610b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
14620b57cec5SDimitry Andric     // MDString), and a value.
14630b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
14640b57cec5SDimitry Andric     Assert(Value && Value->getNumOperands() == 2,
14650b57cec5SDimitry Andric            "invalid value for 'require' module flag (expected metadata pair)",
14660b57cec5SDimitry Andric            Op->getOperand(2));
14670b57cec5SDimitry Andric     Assert(isa<MDString>(Value->getOperand(0)),
14680b57cec5SDimitry Andric            ("invalid value for 'require' module flag "
14690b57cec5SDimitry Andric             "(first value operand should be a string)"),
14700b57cec5SDimitry Andric            Value->getOperand(0));
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
14730b57cec5SDimitry Andric     // scanned.
14740b57cec5SDimitry Andric     Requirements.push_back(Value);
14750b57cec5SDimitry Andric     break;
14760b57cec5SDimitry Andric   }
14770b57cec5SDimitry Andric 
14780b57cec5SDimitry Andric   case Module::Append:
14790b57cec5SDimitry Andric   case Module::AppendUnique: {
14800b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
14810b57cec5SDimitry Andric     Assert(isa<MDNode>(Op->getOperand(2)),
14820b57cec5SDimitry Andric            "invalid value for 'append'-type module flag "
14830b57cec5SDimitry Andric            "(expected a metadata node)",
14840b57cec5SDimitry Andric            Op->getOperand(2));
14850b57cec5SDimitry Andric     break;
14860b57cec5SDimitry Andric   }
14870b57cec5SDimitry Andric   }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
14900b57cec5SDimitry Andric   if (MFB != Module::Require) {
14910b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
14920b57cec5SDimitry Andric     Assert(Inserted,
14930b57cec5SDimitry Andric            "module flag identifiers must be unique (or of 'require' type)", ID);
14940b57cec5SDimitry Andric   }
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
14970b57cec5SDimitry Andric     ConstantInt *Value
14980b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
14990b57cec5SDimitry Andric     Assert(Value, "wchar_size metadata requires constant integer argument");
15000b57cec5SDimitry Andric   }
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
15030b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
15040b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
15050b57cec5SDimitry Andric     // have been created by a client directly.
15060b57cec5SDimitry Andric     Assert(M.getNamedMetadata("llvm.linker.options"),
15070b57cec5SDimitry Andric            "'Linker Options' named metadata no longer supported");
15080b57cec5SDimitry Andric   }
15090b57cec5SDimitry Andric 
1510*5ffd83dbSDimitry Andric   if (ID->getString() == "SemanticInterposition") {
1511*5ffd83dbSDimitry Andric     ConstantInt *Value =
1512*5ffd83dbSDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1513*5ffd83dbSDimitry Andric     Assert(Value,
1514*5ffd83dbSDimitry Andric            "SemanticInterposition metadata requires constant integer argument");
1515*5ffd83dbSDimitry Andric   }
1516*5ffd83dbSDimitry Andric 
15170b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
15180b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
15190b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
15200b57cec5SDimitry Andric   }
15210b57cec5SDimitry Andric }
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
15240b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
15250b57cec5SDimitry Andric     if (!FuncMDO)
15260b57cec5SDimitry Andric       return;
15270b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
15280b57cec5SDimitry Andric     Assert(F && isa<Function>(F->getValue()), "expected a Function or null",
15290b57cec5SDimitry Andric            FuncMDO);
15300b57cec5SDimitry Andric   };
15310b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
15320b57cec5SDimitry Andric   Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
15330b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
15340b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
15350b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
15360b57cec5SDimitry Andric   Assert(Count && Count->getType()->isIntegerTy(),
15370b57cec5SDimitry Andric          "expected an integer constant", Node->getOperand(2));
15380b57cec5SDimitry Andric }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric /// Return true if this attribute kind only applies to functions.
15410b57cec5SDimitry Andric static bool isFuncOnlyAttr(Attribute::AttrKind Kind) {
15420b57cec5SDimitry Andric   switch (Kind) {
1543*5ffd83dbSDimitry Andric   case Attribute::NoMerge:
15440b57cec5SDimitry Andric   case Attribute::NoReturn:
15450b57cec5SDimitry Andric   case Attribute::NoSync:
15460b57cec5SDimitry Andric   case Attribute::WillReturn:
15470b57cec5SDimitry Andric   case Attribute::NoCfCheck:
15480b57cec5SDimitry Andric   case Attribute::NoUnwind:
15490b57cec5SDimitry Andric   case Attribute::NoInline:
15500b57cec5SDimitry Andric   case Attribute::AlwaysInline:
15510b57cec5SDimitry Andric   case Attribute::OptimizeForSize:
15520b57cec5SDimitry Andric   case Attribute::StackProtect:
15530b57cec5SDimitry Andric   case Attribute::StackProtectReq:
15540b57cec5SDimitry Andric   case Attribute::StackProtectStrong:
15550b57cec5SDimitry Andric   case Attribute::SafeStack:
15560b57cec5SDimitry Andric   case Attribute::ShadowCallStack:
15570b57cec5SDimitry Andric   case Attribute::NoRedZone:
15580b57cec5SDimitry Andric   case Attribute::NoImplicitFloat:
15590b57cec5SDimitry Andric   case Attribute::Naked:
15600b57cec5SDimitry Andric   case Attribute::InlineHint:
15610b57cec5SDimitry Andric   case Attribute::StackAlignment:
15620b57cec5SDimitry Andric   case Attribute::UWTable:
15630b57cec5SDimitry Andric   case Attribute::NonLazyBind:
15640b57cec5SDimitry Andric   case Attribute::ReturnsTwice:
15650b57cec5SDimitry Andric   case Attribute::SanitizeAddress:
15660b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress:
15670b57cec5SDimitry Andric   case Attribute::SanitizeMemTag:
15680b57cec5SDimitry Andric   case Attribute::SanitizeThread:
15690b57cec5SDimitry Andric   case Attribute::SanitizeMemory:
15700b57cec5SDimitry Andric   case Attribute::MinSize:
15710b57cec5SDimitry Andric   case Attribute::NoDuplicate:
15720b57cec5SDimitry Andric   case Attribute::Builtin:
15730b57cec5SDimitry Andric   case Attribute::NoBuiltin:
15740b57cec5SDimitry Andric   case Attribute::Cold:
15750b57cec5SDimitry Andric   case Attribute::OptForFuzzing:
15760b57cec5SDimitry Andric   case Attribute::OptimizeNone:
15770b57cec5SDimitry Andric   case Attribute::JumpTable:
15780b57cec5SDimitry Andric   case Attribute::Convergent:
15790b57cec5SDimitry Andric   case Attribute::ArgMemOnly:
15800b57cec5SDimitry Andric   case Attribute::NoRecurse:
15810b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:
15820b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly:
15830b57cec5SDimitry Andric   case Attribute::AllocSize:
15840b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
15850b57cec5SDimitry Andric   case Attribute::Speculatable:
15860b57cec5SDimitry Andric   case Attribute::StrictFP:
1587*5ffd83dbSDimitry Andric   case Attribute::NullPointerIsValid:
15880b57cec5SDimitry Andric     return true;
15890b57cec5SDimitry Andric   default:
15900b57cec5SDimitry Andric     break;
15910b57cec5SDimitry Andric   }
15920b57cec5SDimitry Andric   return false;
15930b57cec5SDimitry Andric }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric /// Return true if this is a function attribute that can also appear on
15960b57cec5SDimitry Andric /// arguments.
15970b57cec5SDimitry Andric static bool isFuncOrArgAttr(Attribute::AttrKind Kind) {
15980b57cec5SDimitry Andric   return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly ||
1599*5ffd83dbSDimitry Andric          Kind == Attribute::ReadNone || Kind == Attribute::NoFree ||
1600*5ffd83dbSDimitry Andric          Kind == Attribute::Preallocated;
16010b57cec5SDimitry Andric }
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
16040b57cec5SDimitry Andric                                     const Value *V) {
16050b57cec5SDimitry Andric   for (Attribute A : Attrs) {
16060b57cec5SDimitry Andric     if (A.isStringAttribute())
16070b57cec5SDimitry Andric       continue;
16080b57cec5SDimitry Andric 
1609*5ffd83dbSDimitry Andric     if (A.isIntAttribute() !=
1610*5ffd83dbSDimitry Andric         Attribute::doesAttrKindHaveArgument(A.getKindAsEnum())) {
1611*5ffd83dbSDimitry Andric       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
1612*5ffd83dbSDimitry Andric                   V);
1613*5ffd83dbSDimitry Andric       return;
1614*5ffd83dbSDimitry Andric     }
1615*5ffd83dbSDimitry Andric 
16160b57cec5SDimitry Andric     if (isFuncOnlyAttr(A.getKindAsEnum())) {
16170b57cec5SDimitry Andric       if (!IsFunction) {
16180b57cec5SDimitry Andric         CheckFailed("Attribute '" + A.getAsString() +
16190b57cec5SDimitry Andric                         "' only applies to functions!",
16200b57cec5SDimitry Andric                     V);
16210b57cec5SDimitry Andric         return;
16220b57cec5SDimitry Andric       }
16230b57cec5SDimitry Andric     } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) {
16240b57cec5SDimitry Andric       CheckFailed("Attribute '" + A.getAsString() +
16250b57cec5SDimitry Andric                       "' does not apply to functions!",
16260b57cec5SDimitry Andric                   V);
16270b57cec5SDimitry Andric       return;
16280b57cec5SDimitry Andric     }
16290b57cec5SDimitry Andric   }
16300b57cec5SDimitry Andric }
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
16330b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
16340b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
16350b57cec5SDimitry Andric                                     const Value *V) {
16360b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
16370b57cec5SDimitry Andric     return;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   verifyAttributeTypes(Attrs, /*IsFunction=*/false, V);
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
16420b57cec5SDimitry Andric     Assert(Attrs.getNumAttributes() == 1,
16430b57cec5SDimitry Andric            "Attribute 'immarg' is incompatible with other attributes", V);
16440b57cec5SDimitry Andric   }
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
16470b57cec5SDimitry Andric   // sret.
16480b57cec5SDimitry Andric   unsigned AttrCount = 0;
16490b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
16500b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1651*5ffd83dbSDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
16520b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
16530b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
16540b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1655*5ffd83dbSDimitry Andric   Assert(AttrCount <= 1,
1656*5ffd83dbSDimitry Andric          "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
16570b57cec5SDimitry Andric          "and 'sret' are incompatible!",
16580b57cec5SDimitry Andric          V);
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
16610b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::ReadOnly)),
16620b57cec5SDimitry Andric          "Attributes "
16630b57cec5SDimitry Andric          "'inalloca and readonly' are incompatible!",
16640b57cec5SDimitry Andric          V);
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
16670b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::Returned)),
16680b57cec5SDimitry Andric          "Attributes "
16690b57cec5SDimitry Andric          "'sret and returned' are incompatible!",
16700b57cec5SDimitry Andric          V);
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
16730b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::SExt)),
16740b57cec5SDimitry Andric          "Attributes "
16750b57cec5SDimitry Andric          "'zeroext and signext' are incompatible!",
16760b57cec5SDimitry Andric          V);
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
16790b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::ReadOnly)),
16800b57cec5SDimitry Andric          "Attributes "
16810b57cec5SDimitry Andric          "'readnone and readonly' are incompatible!",
16820b57cec5SDimitry Andric          V);
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
16850b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::WriteOnly)),
16860b57cec5SDimitry Andric          "Attributes "
16870b57cec5SDimitry Andric          "'readnone and writeonly' are incompatible!",
16880b57cec5SDimitry Andric          V);
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
16910b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::WriteOnly)),
16920b57cec5SDimitry Andric          "Attributes "
16930b57cec5SDimitry Andric          "'readonly and writeonly' are incompatible!",
16940b57cec5SDimitry Andric          V);
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
16970b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::AlwaysInline)),
16980b57cec5SDimitry Andric          "Attributes "
16990b57cec5SDimitry Andric          "'noinline and alwaysinline' are incompatible!",
17000b57cec5SDimitry Andric          V);
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
17030b57cec5SDimitry Andric     Assert(Attrs.getByValType() == cast<PointerType>(Ty)->getElementType(),
17040b57cec5SDimitry Andric            "Attribute 'byval' type does not match parameter!", V);
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
1707*5ffd83dbSDimitry Andric   if (Attrs.hasAttribute(Attribute::Preallocated)) {
1708*5ffd83dbSDimitry Andric     Assert(Attrs.getPreallocatedType() ==
1709*5ffd83dbSDimitry Andric                cast<PointerType>(Ty)->getElementType(),
1710*5ffd83dbSDimitry Andric            "Attribute 'preallocated' type does not match parameter!", V);
1711*5ffd83dbSDimitry Andric   }
1712*5ffd83dbSDimitry Andric 
17130b57cec5SDimitry Andric   AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
17140b57cec5SDimitry Andric   Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs),
17150b57cec5SDimitry Andric          "Wrong types for attribute: " +
17160b57cec5SDimitry Andric              AttributeSet::get(Context, IncompatibleAttrs).getAsString(),
17170b57cec5SDimitry Andric          V);
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
17200b57cec5SDimitry Andric     SmallPtrSet<Type*, 4> Visited;
17210b57cec5SDimitry Andric     if (!PTy->getElementType()->isSized(&Visited)) {
17220b57cec5SDimitry Andric       Assert(!Attrs.hasAttribute(Attribute::ByVal) &&
1723*5ffd83dbSDimitry Andric                  !Attrs.hasAttribute(Attribute::InAlloca) &&
1724*5ffd83dbSDimitry Andric                  !Attrs.hasAttribute(Attribute::Preallocated),
1725*5ffd83dbSDimitry Andric              "Attributes 'byval', 'inalloca', and 'preallocated' do not "
1726*5ffd83dbSDimitry Andric              "support unsized types!",
17270b57cec5SDimitry Andric              V);
17280b57cec5SDimitry Andric     }
17290b57cec5SDimitry Andric     if (!isa<PointerType>(PTy->getElementType()))
17300b57cec5SDimitry Andric       Assert(!Attrs.hasAttribute(Attribute::SwiftError),
17310b57cec5SDimitry Andric              "Attribute 'swifterror' only applies to parameters "
17320b57cec5SDimitry Andric              "with pointer to pointer type!",
17330b57cec5SDimitry Andric              V);
17340b57cec5SDimitry Andric   } else {
17350b57cec5SDimitry Andric     Assert(!Attrs.hasAttribute(Attribute::ByVal),
17360b57cec5SDimitry Andric            "Attribute 'byval' only applies to parameters with pointer type!",
17370b57cec5SDimitry Andric            V);
17380b57cec5SDimitry Andric     Assert(!Attrs.hasAttribute(Attribute::SwiftError),
17390b57cec5SDimitry Andric            "Attribute 'swifterror' only applies to parameters "
17400b57cec5SDimitry Andric            "with pointer type!",
17410b57cec5SDimitry Andric            V);
17420b57cec5SDimitry Andric   }
17430b57cec5SDimitry Andric }
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric // Check parameter attributes against a function type.
17460b57cec5SDimitry Andric // The value V is printed in error messages.
17470b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
17480b57cec5SDimitry Andric                                    const Value *V, bool IsIntrinsic) {
17490b57cec5SDimitry Andric   if (Attrs.isEmpty())
17500b57cec5SDimitry Andric     return;
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric   bool SawNest = false;
17530b57cec5SDimitry Andric   bool SawReturned = false;
17540b57cec5SDimitry Andric   bool SawSRet = false;
17550b57cec5SDimitry Andric   bool SawSwiftSelf = false;
17560b57cec5SDimitry Andric   bool SawSwiftError = false;
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   // Verify return value attributes.
17590b57cec5SDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttributes();
17600b57cec5SDimitry Andric   Assert((!RetAttrs.hasAttribute(Attribute::ByVal) &&
17610b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::Nest) &&
17620b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::StructRet) &&
17630b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::NoCapture) &&
1764480093f4SDimitry Andric           !RetAttrs.hasAttribute(Attribute::NoFree) &&
17650b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::Returned) &&
17660b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::InAlloca) &&
1767*5ffd83dbSDimitry Andric           !RetAttrs.hasAttribute(Attribute::Preallocated) &&
17680b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::SwiftSelf) &&
17690b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::SwiftError)),
1770*5ffd83dbSDimitry Andric          "Attributes 'byval', 'inalloca', 'preallocated', 'nest', 'sret', "
1771*5ffd83dbSDimitry Andric          "'nocapture', 'nofree', "
17720b57cec5SDimitry Andric          "'returned', 'swiftself', and 'swifterror' do not apply to return "
17730b57cec5SDimitry Andric          "values!",
17740b57cec5SDimitry Andric          V);
17750b57cec5SDimitry Andric   Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) &&
17760b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::WriteOnly) &&
17770b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::ReadNone)),
17780b57cec5SDimitry Andric          "Attribute '" + RetAttrs.getAsString() +
17790b57cec5SDimitry Andric              "' does not apply to function returns",
17800b57cec5SDimitry Andric          V);
17810b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric   // Verify parameter attributes.
17840b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
17850b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
17860b57cec5SDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttributes(i);
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric     if (!IsIntrinsic) {
17890b57cec5SDimitry Andric       Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),
17900b57cec5SDimitry Andric              "immarg attribute only applies to intrinsics",V);
17910b57cec5SDimitry Andric     }
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
17960b57cec5SDimitry Andric       Assert(!SawNest, "More than one parameter has attribute nest!", V);
17970b57cec5SDimitry Andric       SawNest = true;
17980b57cec5SDimitry Andric     }
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
18010b57cec5SDimitry Andric       Assert(!SawReturned, "More than one parameter has attribute returned!",
18020b57cec5SDimitry Andric              V);
18030b57cec5SDimitry Andric       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
18040b57cec5SDimitry Andric              "Incompatible argument and return types for 'returned' attribute",
18050b57cec5SDimitry Andric              V);
18060b57cec5SDimitry Andric       SawReturned = true;
18070b57cec5SDimitry Andric     }
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
18100b57cec5SDimitry Andric       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
18110b57cec5SDimitry Andric       Assert(i == 0 || i == 1,
18120b57cec5SDimitry Andric              "Attribute 'sret' is not on first or second parameter!", V);
18130b57cec5SDimitry Andric       SawSRet = true;
18140b57cec5SDimitry Andric     }
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
18170b57cec5SDimitry Andric       Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
18180b57cec5SDimitry Andric       SawSwiftSelf = true;
18190b57cec5SDimitry Andric     }
18200b57cec5SDimitry Andric 
18210b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
18220b57cec5SDimitry Andric       Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
18230b57cec5SDimitry Andric              V);
18240b57cec5SDimitry Andric       SawSwiftError = true;
18250b57cec5SDimitry Andric     }
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
18280b57cec5SDimitry Andric       Assert(i == FT->getNumParams() - 1,
18290b57cec5SDimitry Andric              "inalloca isn't on the last parameter!", V);
18300b57cec5SDimitry Andric     }
18310b57cec5SDimitry Andric   }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric   if (!Attrs.hasAttributes(AttributeList::FunctionIndex))
18340b57cec5SDimitry Andric     return;
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric   verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V);
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
18390b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::ReadOnly)),
18400b57cec5SDimitry Andric          "Attributes 'readnone and readonly' are incompatible!", V);
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
18430b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::WriteOnly)),
18440b57cec5SDimitry Andric          "Attributes 'readnone and writeonly' are incompatible!", V);
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
18470b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::WriteOnly)),
18480b57cec5SDimitry Andric          "Attributes 'readonly and writeonly' are incompatible!", V);
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
18510b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)),
18520b57cec5SDimitry Andric          "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
18530b57cec5SDimitry Andric          "incompatible!",
18540b57cec5SDimitry Andric          V);
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
18570b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)),
18580b57cec5SDimitry Andric          "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
18610b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::AlwaysInline)),
18620b57cec5SDimitry Andric          "Attributes 'noinline and alwaysinline' are incompatible!", V);
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) {
18650b57cec5SDimitry Andric     Assert(Attrs.hasFnAttribute(Attribute::NoInline),
18660b57cec5SDimitry Andric            "Attribute 'optnone' requires 'noinline'!", V);
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric     Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize),
18690b57cec5SDimitry Andric            "Attributes 'optsize and optnone' are incompatible!", V);
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric     Assert(!Attrs.hasFnAttribute(Attribute::MinSize),
18720b57cec5SDimitry Andric            "Attributes 'minsize and optnone' are incompatible!", V);
18730b57cec5SDimitry Andric   }
18740b57cec5SDimitry Andric 
18750b57cec5SDimitry Andric   if (Attrs.hasFnAttribute(Attribute::JumpTable)) {
18760b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
18770b57cec5SDimitry Andric     Assert(GV->hasGlobalUnnamedAddr(),
18780b57cec5SDimitry Andric            "Attribute 'jumptable' requires 'unnamed_addr'", V);
18790b57cec5SDimitry Andric   }
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric   if (Attrs.hasFnAttribute(Attribute::AllocSize)) {
18820b57cec5SDimitry Andric     std::pair<unsigned, Optional<unsigned>> Args =
18830b57cec5SDimitry Andric         Attrs.getAllocSizeArgs(AttributeList::FunctionIndex);
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
18860b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
18870b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
18880b57cec5SDimitry Andric         return false;
18890b57cec5SDimitry Andric       }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
18920b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
18930b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
18940b57cec5SDimitry Andric                     V);
18950b57cec5SDimitry Andric         return false;
18960b57cec5SDimitry Andric       }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric       return true;
18990b57cec5SDimitry Andric     };
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric     if (!CheckParam("element size", Args.first))
19020b57cec5SDimitry Andric       return;
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric     if (Args.second && !CheckParam("number of elements", *Args.second))
19050b57cec5SDimitry Andric       return;
19060b57cec5SDimitry Andric   }
1907480093f4SDimitry Andric 
1908480093f4SDimitry Andric   if (Attrs.hasFnAttribute("frame-pointer")) {
1909480093f4SDimitry Andric     StringRef FP = Attrs.getAttribute(AttributeList::FunctionIndex,
1910480093f4SDimitry Andric                                       "frame-pointer").getValueAsString();
1911480093f4SDimitry Andric     if (FP != "all" && FP != "non-leaf" && FP != "none")
1912480093f4SDimitry Andric       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
1913480093f4SDimitry Andric   }
1914480093f4SDimitry Andric 
191555e4f9d5SDimitry Andric   if (Attrs.hasFnAttribute("patchable-function-prefix")) {
191655e4f9d5SDimitry Andric     StringRef S = Attrs
1917480093f4SDimitry Andric                       .getAttribute(AttributeList::FunctionIndex,
191855e4f9d5SDimitry Andric                                     "patchable-function-prefix")
1919480093f4SDimitry Andric                       .getValueAsString();
1920480093f4SDimitry Andric     unsigned N;
1921480093f4SDimitry Andric     if (S.getAsInteger(10, N))
1922480093f4SDimitry Andric       CheckFailed(
192355e4f9d5SDimitry Andric           "\"patchable-function-prefix\" takes an unsigned integer: " + S, V);
192455e4f9d5SDimitry Andric   }
192555e4f9d5SDimitry Andric   if (Attrs.hasFnAttribute("patchable-function-entry")) {
192655e4f9d5SDimitry Andric     StringRef S = Attrs
192755e4f9d5SDimitry Andric                       .getAttribute(AttributeList::FunctionIndex,
192855e4f9d5SDimitry Andric                                     "patchable-function-entry")
192955e4f9d5SDimitry Andric                       .getValueAsString();
193055e4f9d5SDimitry Andric     unsigned N;
193155e4f9d5SDimitry Andric     if (S.getAsInteger(10, N))
193255e4f9d5SDimitry Andric       CheckFailed(
193355e4f9d5SDimitry Andric           "\"patchable-function-entry\" takes an unsigned integer: " + S, V);
1934480093f4SDimitry Andric   }
19350b57cec5SDimitry Andric }
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
19380b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
19390b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
19400b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
19410b57cec5SDimitry Andric       MDNode *MD = Pair.second;
19420b57cec5SDimitry Andric       Assert(MD->getNumOperands() >= 2,
19430b57cec5SDimitry Andric              "!prof annotations should have no less than 2 operands", MD);
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric       // Check first operand.
19460b57cec5SDimitry Andric       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
19470b57cec5SDimitry Andric              MD);
19480b57cec5SDimitry Andric       Assert(isa<MDString>(MD->getOperand(0)),
19490b57cec5SDimitry Andric              "expected string with name of the !prof annotation", MD);
19500b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
19510b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
19520b57cec5SDimitry Andric       Assert(ProfName.equals("function_entry_count") ||
19530b57cec5SDimitry Andric                  ProfName.equals("synthetic_function_entry_count"),
19540b57cec5SDimitry Andric              "first operand should be 'function_entry_count'"
19550b57cec5SDimitry Andric              " or 'synthetic_function_entry_count'",
19560b57cec5SDimitry Andric              MD);
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric       // Check second operand.
19590b57cec5SDimitry Andric       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
19600b57cec5SDimitry Andric              MD);
19610b57cec5SDimitry Andric       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
19620b57cec5SDimitry Andric              "expected integer argument to function_entry_count", MD);
19630b57cec5SDimitry Andric     }
19640b57cec5SDimitry Andric   }
19650b57cec5SDimitry Andric }
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
19680b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
19690b57cec5SDimitry Andric     return;
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
19720b57cec5SDimitry Andric   Stack.push_back(EntryC);
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   while (!Stack.empty()) {
19750b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
19760b57cec5SDimitry Andric 
19770b57cec5SDimitry Andric     // Check this constant expression.
19780b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
19790b57cec5SDimitry Andric       visitConstantExpr(CE);
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
19820b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
19830b57cec5SDimitry Andric       // that the global value is in the correct module
19840b57cec5SDimitry Andric       Assert(GV->getParent() == &M, "Referencing global in another module!",
19850b57cec5SDimitry Andric              EntryC, &M, GV, GV->getParent());
19860b57cec5SDimitry Andric       continue;
19870b57cec5SDimitry Andric     }
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric     // Visit all sub-expressions.
19900b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
19910b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
19920b57cec5SDimitry Andric       if (!OpC)
19930b57cec5SDimitry Andric         continue;
19940b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
19950b57cec5SDimitry Andric         continue;
19960b57cec5SDimitry Andric       Stack.push_back(OpC);
19970b57cec5SDimitry Andric     }
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
20020b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
20030b57cec5SDimitry Andric     Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
20040b57cec5SDimitry Andric                                  CE->getType()),
20050b57cec5SDimitry Andric            "Invalid bitcast", CE);
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::IntToPtr ||
20080b57cec5SDimitry Andric       CE->getOpcode() == Instruction::PtrToInt) {
20090b57cec5SDimitry Andric     auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr
20100b57cec5SDimitry Andric                       ? CE->getType()
20110b57cec5SDimitry Andric                       : CE->getOperand(0)->getType();
20120b57cec5SDimitry Andric     StringRef Msg = CE->getOpcode() == Instruction::IntToPtr
20130b57cec5SDimitry Andric                         ? "inttoptr not supported for non-integral pointers"
20140b57cec5SDimitry Andric                         : "ptrtoint not supported for non-integral pointers";
20150b57cec5SDimitry Andric     Assert(
20160b57cec5SDimitry Andric         !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())),
20170b57cec5SDimitry Andric         Msg);
20180b57cec5SDimitry Andric   }
20190b57cec5SDimitry Andric }
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
20220b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
20230b57cec5SDimitry Andric   // function and return value.
20240b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
20250b57cec5SDimitry Andric }
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
20280b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
20290b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
20300b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
20310b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
20340b57cec5SDimitry Andric              !Call.onlyAccessesArgMemory(),
20350b57cec5SDimitry Andric          "gc.statepoint must read and write all memory to preserve "
20360b57cec5SDimitry Andric          "reordering restrictions required by safepoint semantics",
20370b57cec5SDimitry Andric          Call);
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric   const int64_t NumPatchBytes =
20400b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
20410b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
20420b57cec5SDimitry Andric   Assert(NumPatchBytes >= 0,
20430b57cec5SDimitry Andric          "gc.statepoint number of patchable bytes must be "
20440b57cec5SDimitry Andric          "positive",
20450b57cec5SDimitry Andric          Call);
20460b57cec5SDimitry Andric 
20470b57cec5SDimitry Andric   const Value *Target = Call.getArgOperand(2);
20480b57cec5SDimitry Andric   auto *PT = dyn_cast<PointerType>(Target->getType());
20490b57cec5SDimitry Andric   Assert(PT && PT->getElementType()->isFunctionTy(),
20500b57cec5SDimitry Andric          "gc.statepoint callee must be of function pointer type", Call, Target);
20510b57cec5SDimitry Andric   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
20520b57cec5SDimitry Andric 
20530b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
20540b57cec5SDimitry Andric   Assert(NumCallArgs >= 0,
20550b57cec5SDimitry Andric          "gc.statepoint number of arguments to underlying call "
20560b57cec5SDimitry Andric          "must be positive",
20570b57cec5SDimitry Andric          Call);
20580b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
20590b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
20600b57cec5SDimitry Andric     Assert(NumCallArgs >= NumParams,
20610b57cec5SDimitry Andric            "gc.statepoint mismatch in number of vararg call args", Call);
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric     // TODO: Remove this limitation
20640b57cec5SDimitry Andric     Assert(TargetFuncType->getReturnType()->isVoidTy(),
20650b57cec5SDimitry Andric            "gc.statepoint doesn't support wrapping non-void "
20660b57cec5SDimitry Andric            "vararg functions yet",
20670b57cec5SDimitry Andric            Call);
20680b57cec5SDimitry Andric   } else
20690b57cec5SDimitry Andric     Assert(NumCallArgs == NumParams,
20700b57cec5SDimitry Andric            "gc.statepoint mismatch in number of call args", Call);
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric   const uint64_t Flags
20730b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
20740b57cec5SDimitry Andric   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
20750b57cec5SDimitry Andric          "unknown flag used in gc.statepoint flags argument", Call);
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
20780b57cec5SDimitry Andric   // the type of the wrapped callee.
20790b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
20800b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
20810b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
20820b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
20830b57cec5SDimitry Andric     Assert(ArgType == ParamType,
20840b57cec5SDimitry Andric            "gc.statepoint call argument does not match wrapped "
20850b57cec5SDimitry Andric            "function type",
20860b57cec5SDimitry Andric            Call);
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
20890b57cec5SDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i);
20900b57cec5SDimitry Andric       Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
20910b57cec5SDimitry Andric              "Attribute 'sret' cannot be used for vararg call arguments!",
20920b57cec5SDimitry Andric              Call);
20930b57cec5SDimitry Andric     }
20940b57cec5SDimitry Andric   }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
20990b57cec5SDimitry Andric   Assert(isa<ConstantInt>(NumTransitionArgsV),
21000b57cec5SDimitry Andric          "gc.statepoint number of transition arguments "
21010b57cec5SDimitry Andric          "must be constant integer",
21020b57cec5SDimitry Andric          Call);
21030b57cec5SDimitry Andric   const int NumTransitionArgs =
21040b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
21050b57cec5SDimitry Andric   Assert(NumTransitionArgs >= 0,
21060b57cec5SDimitry Andric          "gc.statepoint number of transition arguments must be positive", Call);
21070b57cec5SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
21080b57cec5SDimitry Andric 
2109*5ffd83dbSDimitry Andric   // We're migrating away from inline operands to operand bundles, enforce
2110*5ffd83dbSDimitry Andric   // the either/or property during transition.
2111*5ffd83dbSDimitry Andric   if (Call.getOperandBundle(LLVMContext::OB_gc_transition)) {
2112*5ffd83dbSDimitry Andric     Assert(NumTransitionArgs == 0,
2113*5ffd83dbSDimitry Andric            "can't use both deopt operands and deopt bundle on a statepoint");
2114*5ffd83dbSDimitry Andric   }
2115*5ffd83dbSDimitry Andric 
21160b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
21170b57cec5SDimitry Andric   Assert(isa<ConstantInt>(NumDeoptArgsV),
21180b57cec5SDimitry Andric          "gc.statepoint number of deoptimization arguments "
21190b57cec5SDimitry Andric          "must be constant integer",
21200b57cec5SDimitry Andric          Call);
21210b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
21220b57cec5SDimitry Andric   Assert(NumDeoptArgs >= 0,
21230b57cec5SDimitry Andric          "gc.statepoint number of deoptimization arguments "
21240b57cec5SDimitry Andric          "must be positive",
21250b57cec5SDimitry Andric          Call);
21260b57cec5SDimitry Andric 
2127*5ffd83dbSDimitry Andric   // We're migrating away from inline operands to operand bundles, enforce
2128*5ffd83dbSDimitry Andric   // the either/or property during transition.
2129*5ffd83dbSDimitry Andric   if (Call.getOperandBundle(LLVMContext::OB_deopt)) {
2130*5ffd83dbSDimitry Andric     Assert(NumDeoptArgs == 0,
2131*5ffd83dbSDimitry Andric            "can't use both deopt operands and deopt bundle on a statepoint");
2132*5ffd83dbSDimitry Andric   }
2133*5ffd83dbSDimitry Andric 
21340b57cec5SDimitry Andric   const int ExpectedNumArgs =
21350b57cec5SDimitry Andric       7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
21360b57cec5SDimitry Andric   Assert(ExpectedNumArgs <= (int)Call.arg_size(),
21370b57cec5SDimitry Andric          "gc.statepoint too few arguments according to length fields", Call);
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
21400b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
21410b57cec5SDimitry Andric   // of the same statepoint sequence
21420b57cec5SDimitry Andric   for (const User *U : Call.users()) {
21430b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
21440b57cec5SDimitry Andric     Assert(UserCall, "illegal use of statepoint token", Call, U);
21450b57cec5SDimitry Andric     if (!UserCall)
21460b57cec5SDimitry Andric       continue;
21470b57cec5SDimitry Andric     Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
21480b57cec5SDimitry Andric            "gc.result or gc.relocate are the only value uses "
21490b57cec5SDimitry Andric            "of a gc.statepoint",
21500b57cec5SDimitry Andric            Call, U);
21510b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
21520b57cec5SDimitry Andric       Assert(UserCall->getArgOperand(0) == &Call,
21530b57cec5SDimitry Andric              "gc.result connected to wrong gc.statepoint", Call, UserCall);
21540b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
21550b57cec5SDimitry Andric       Assert(UserCall->getArgOperand(0) == &Call,
21560b57cec5SDimitry Andric              "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
21570b57cec5SDimitry Andric     }
21580b57cec5SDimitry Andric   }
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
21610b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
21620b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
21630b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
21640b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
21650b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
21660b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
21670b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
21680b57cec5SDimitry Andric }
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
21710b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
21720b57cec5SDimitry Andric     Function *F = Counts.first;
21730b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
21740b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
21750b57cec5SDimitry Andric     Assert(MaxRecoveredIndex <= EscapedObjectCount,
21760b57cec5SDimitry Andric            "all indices passed to llvm.localrecover must be less than the "
21770b57cec5SDimitry Andric            "number of arguments passed to llvm.localescape in the parent "
21780b57cec5SDimitry Andric            "function",
21790b57cec5SDimitry Andric            F);
21800b57cec5SDimitry Andric   }
21810b57cec5SDimitry Andric }
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
21840b57cec5SDimitry Andric   BasicBlock *UnwindDest;
21850b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
21860b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
21870b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
21880b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
21890b57cec5SDimitry Andric   else
21900b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
21910b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
21920b57cec5SDimitry Andric }
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
21950b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
21960b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
21970b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
21980b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
21990b57cec5SDimitry Andric     if (Visited.count(PredPad))
22000b57cec5SDimitry Andric       continue;
22010b57cec5SDimitry Andric     Active.insert(PredPad);
22020b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
22030b57cec5SDimitry Andric     do {
22040b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
22050b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
22060b57cec5SDimitry Andric         // Found a cycle; report error
22070b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
22080b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
22090b57cec5SDimitry Andric         do {
22100b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
22110b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
22120b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
22130b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
22140b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
22150b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
22160b57cec5SDimitry Andric         Assert(false, "EH pads can't handle each other's exceptions",
22170b57cec5SDimitry Andric                ArrayRef<Instruction *>(CycleNodes));
22180b57cec5SDimitry Andric       }
22190b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
22200b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
22210b57cec5SDimitry Andric         break;
22220b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
22230b57cec5SDimitry Andric       PredPad = SuccPad;
22240b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
22250b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
22260b57cec5SDimitry Andric         break;
22270b57cec5SDimitry Andric       Terminator = TermI->second;
22280b57cec5SDimitry Andric       Active.insert(PredPad);
22290b57cec5SDimitry Andric     } while (true);
22300b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
22310b57cec5SDimitry Andric     // nodes' successors.
22320b57cec5SDimitry Andric     Active.clear();
22330b57cec5SDimitry Andric   }
22340b57cec5SDimitry Andric }
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
22370b57cec5SDimitry Andric //
22380b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
22390b57cec5SDimitry Andric   visitGlobalValue(F);
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric   // Check function arguments.
22420b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
22430b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric   Assert(&Context == &F.getContext(),
22460b57cec5SDimitry Andric          "Function context does not match Module context!", &F);
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
22490b57cec5SDimitry Andric   Assert(FT->getNumParams() == NumArgs,
22500b57cec5SDimitry Andric          "# formal arguments must match # of arguments for function type!", &F,
22510b57cec5SDimitry Andric          FT);
22520b57cec5SDimitry Andric   Assert(F.getReturnType()->isFirstClassType() ||
22530b57cec5SDimitry Andric              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
22540b57cec5SDimitry Andric          "Functions cannot return aggregate values!", &F);
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
22570b57cec5SDimitry Andric          "Invalid struct return type!", &F);
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
22600b57cec5SDimitry Andric 
22610b57cec5SDimitry Andric   Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
22620b57cec5SDimitry Andric          "Attribute after last parameter!", &F);
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   bool isLLVMdotName = F.getName().size() >= 5 &&
22650b57cec5SDimitry Andric                        F.getName().substr(0, 5) == "llvm.";
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric   // Check function attributes.
22680b57cec5SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName);
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
22710b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
22720b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
22730b57cec5SDimitry Andric   Assert(!Attrs.hasFnAttribute(Attribute::Builtin),
22740b57cec5SDimitry Andric          "Attribute 'builtin' can only be applied to a callsite.", &F);
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
22770b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
22780b57cec5SDimitry Andric   // restrictions can be lifted.
22790b57cec5SDimitry Andric   switch (F.getCallingConv()) {
22800b57cec5SDimitry Andric   default:
22810b57cec5SDimitry Andric   case CallingConv::C:
22820b57cec5SDimitry Andric     break;
22830b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
22840b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
22850b57cec5SDimitry Andric     Assert(F.getReturnType()->isVoidTy(),
22860b57cec5SDimitry Andric            "Calling convention requires void return type", &F);
22870b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
22880b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
22890b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
22900b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
22910b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
22920b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
22930b57cec5SDimitry Andric     Assert(!F.hasStructRetAttr(),
22940b57cec5SDimitry Andric            "Calling convention does not allow sret", &F);
22950b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
22960b57cec5SDimitry Andric   case CallingConv::Fast:
22970b57cec5SDimitry Andric   case CallingConv::Cold:
22980b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
22990b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
23000b57cec5SDimitry Andric   case CallingConv::PTX_Device:
23010b57cec5SDimitry Andric     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
23020b57cec5SDimitry Andric                           "perfect forwarding!",
23030b57cec5SDimitry Andric            &F);
23040b57cec5SDimitry Andric     break;
23050b57cec5SDimitry Andric   }
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
23080b57cec5SDimitry Andric   unsigned i = 0;
23090b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
23100b57cec5SDimitry Andric     Assert(Arg.getType() == FT->getParamType(i),
23110b57cec5SDimitry Andric            "Argument value does not match function argument type!", &Arg,
23120b57cec5SDimitry Andric            FT->getParamType(i));
23130b57cec5SDimitry Andric     Assert(Arg.getType()->isFirstClassType(),
23140b57cec5SDimitry Andric            "Function arguments must have first-class types!", &Arg);
23150b57cec5SDimitry Andric     if (!isLLVMdotName) {
23160b57cec5SDimitry Andric       Assert(!Arg.getType()->isMetadataTy(),
23170b57cec5SDimitry Andric              "Function takes metadata but isn't an intrinsic", &Arg, &F);
23180b57cec5SDimitry Andric       Assert(!Arg.getType()->isTokenTy(),
23190b57cec5SDimitry Andric              "Function takes token but isn't an intrinsic", &Arg, &F);
23200b57cec5SDimitry Andric     }
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
23230b57cec5SDimitry Andric     if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
23240b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
23250b57cec5SDimitry Andric     }
23260b57cec5SDimitry Andric     ++i;
23270b57cec5SDimitry Andric   }
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   if (!isLLVMdotName)
23300b57cec5SDimitry Andric     Assert(!F.getReturnType()->isTokenTy(),
23310b57cec5SDimitry Andric            "Functions returns a token but isn't an intrinsic", &F);
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric   // Get the function metadata attachments.
23340b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
23350b57cec5SDimitry Andric   F.getAllMetadata(MDs);
23360b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
23370b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   // Check validity of the personality function
23400b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
23410b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
23420b57cec5SDimitry Andric     if (Per)
23430b57cec5SDimitry Andric       Assert(Per->getParent() == F.getParent(),
23440b57cec5SDimitry Andric              "Referencing personality function in another module!",
23450b57cec5SDimitry Andric              &F, F.getParent(), Per, Per->getParent());
23460b57cec5SDimitry Andric   }
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric   if (F.isMaterializable()) {
23490b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
23500b57cec5SDimitry Andric     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
23510b57cec5SDimitry Andric            MDs.empty() ? nullptr : MDs.front().second);
23520b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
23530b57cec5SDimitry Andric     for (const auto &I : MDs) {
23540b57cec5SDimitry Andric       // This is used for call site debug information.
23550b57cec5SDimitry Andric       AssertDI(I.first != LLVMContext::MD_dbg ||
23560b57cec5SDimitry Andric                    !cast<DISubprogram>(I.second)->isDistinct(),
23570b57cec5SDimitry Andric                "function declaration may only have a unique !dbg attachment",
23580b57cec5SDimitry Andric                &F);
23590b57cec5SDimitry Andric       Assert(I.first != LLVMContext::MD_prof,
23600b57cec5SDimitry Andric              "function declaration may not have a !prof attachment", &F);
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric       // Verify the metadata itself.
2363*5ffd83dbSDimitry Andric       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
23640b57cec5SDimitry Andric     }
23650b57cec5SDimitry Andric     Assert(!F.hasPersonalityFn(),
23660b57cec5SDimitry Andric            "Function declaration shouldn't have a personality routine", &F);
23670b57cec5SDimitry Andric   } else {
23680b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
23690b57cec5SDimitry Andric     // is not legal to define intrinsics.
23700b57cec5SDimitry Andric     Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric     // Check the entry node
23730b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
23740b57cec5SDimitry Andric     Assert(pred_empty(Entry),
23750b57cec5SDimitry Andric            "Entry block to function must not have predecessors!", Entry);
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
23780b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
23790b57cec5SDimitry Andric       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
23800b57cec5SDimitry Andric              "blockaddress may not be used with the entry block!", Entry);
23810b57cec5SDimitry Andric     }
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
23840b57cec5SDimitry Andric     // Visit metadata attachments.
23850b57cec5SDimitry Andric     for (const auto &I : MDs) {
23860b57cec5SDimitry Andric       // Verify that the attachment is legal.
2387*5ffd83dbSDimitry Andric       auto AllowLocs = AreDebugLocsAllowed::No;
23880b57cec5SDimitry Andric       switch (I.first) {
23890b57cec5SDimitry Andric       default:
23900b57cec5SDimitry Andric         break;
23910b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
23920b57cec5SDimitry Andric         ++NumDebugAttachments;
23930b57cec5SDimitry Andric         AssertDI(NumDebugAttachments == 1,
23940b57cec5SDimitry Andric                  "function must have a single !dbg attachment", &F, I.second);
23950b57cec5SDimitry Andric         AssertDI(isa<DISubprogram>(I.second),
23960b57cec5SDimitry Andric                  "function !dbg attachment must be a subprogram", &F, I.second);
23970b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
23980b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
23990b57cec5SDimitry Andric         AssertDI(!AttachedTo || AttachedTo == &F,
24000b57cec5SDimitry Andric                  "DISubprogram attached to more than one function", SP, &F);
24010b57cec5SDimitry Andric         AttachedTo = &F;
2402*5ffd83dbSDimitry Andric         AllowLocs = AreDebugLocsAllowed::Yes;
24030b57cec5SDimitry Andric         break;
24040b57cec5SDimitry Andric       }
24050b57cec5SDimitry Andric       case LLVMContext::MD_prof:
24060b57cec5SDimitry Andric         ++NumProfAttachments;
24070b57cec5SDimitry Andric         Assert(NumProfAttachments == 1,
24080b57cec5SDimitry Andric                "function must have a single !prof attachment", &F, I.second);
24090b57cec5SDimitry Andric         break;
24100b57cec5SDimitry Andric       }
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric       // Verify the metadata itself.
2413*5ffd83dbSDimitry Andric       visitMDNode(*I.second, AllowLocs);
24140b57cec5SDimitry Andric     }
24150b57cec5SDimitry Andric   }
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
24180b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
24190b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
24200b57cec5SDimitry Andric   // uses.
24210b57cec5SDimitry Andric   if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
24220b57cec5SDimitry Andric     const User *U;
24230b57cec5SDimitry Andric     if (F.hasAddressTaken(&U))
24240b57cec5SDimitry Andric       Assert(false, "Invalid user of intrinsic instruction!", U);
24250b57cec5SDimitry Andric   }
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric   auto *N = F.getSubprogram();
24280b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
24290b57cec5SDimitry Andric   if (!HasDebugInfo)
24300b57cec5SDimitry Andric     return;
24310b57cec5SDimitry Andric 
2432*5ffd83dbSDimitry Andric   // Check that all !dbg attachments lead to back to N.
24330b57cec5SDimitry Andric   //
24340b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
24350b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
24360b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
24370b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
24380b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
24390b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
24400b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
24410b57cec5SDimitry Andric     if (!DL)
24420b57cec5SDimitry Andric       return;
24430b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
24440b57cec5SDimitry Andric       return;
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
24470b57cec5SDimitry Andric     AssertDI(Parent && isa<DILocalScope>(Parent),
24480b57cec5SDimitry Andric              "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
24490b57cec5SDimitry Andric              Parent);
2450*5ffd83dbSDimitry Andric 
24510b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
2452*5ffd83dbSDimitry Andric     Assert(Scope, "Failed to find DILocalScope", DL);
2453*5ffd83dbSDimitry Andric 
2454*5ffd83dbSDimitry Andric     if (!Seen.insert(Scope).second)
24550b57cec5SDimitry Andric       return;
24560b57cec5SDimitry Andric 
2457*5ffd83dbSDimitry Andric     DISubprogram *SP = Scope->getSubprogram();
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
24600b57cec5SDimitry Andric     // validation in that case
24610b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
24620b57cec5SDimitry Andric       return;
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric     AssertDI(SP->describes(&F),
24650b57cec5SDimitry Andric              "!dbg attachment points at wrong subprogram for function", N, &F,
24660b57cec5SDimitry Andric              &I, DL, Scope, SP);
24670b57cec5SDimitry Andric   };
24680b57cec5SDimitry Andric   for (auto &BB : F)
24690b57cec5SDimitry Andric     for (auto &I : BB) {
24700b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
24710b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
24720b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
24730b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
24740b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
24750b57cec5SDimitry Andric       if (BrokenDebugInfo)
24760b57cec5SDimitry Andric         return;
24770b57cec5SDimitry Andric     }
24780b57cec5SDimitry Andric }
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
24810b57cec5SDimitry Andric //
24820b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
24830b57cec5SDimitry Andric   InstsInThisBlock.clear();
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
24860b57cec5SDimitry Andric   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
24890b57cec5SDimitry Andric   // it.
24900b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
24910b57cec5SDimitry Andric     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
24920b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
24930b57cec5SDimitry Andric     llvm::sort(Preds);
24940b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
24950b57cec5SDimitry Andric       // Ensure that PHI nodes have at least one entry!
24960b57cec5SDimitry Andric       Assert(PN.getNumIncomingValues() != 0,
24970b57cec5SDimitry Andric              "PHI nodes must have at least one entry.  If the block is dead, "
24980b57cec5SDimitry Andric              "the PHI should be removed!",
24990b57cec5SDimitry Andric              &PN);
25000b57cec5SDimitry Andric       Assert(PN.getNumIncomingValues() == Preds.size(),
25010b57cec5SDimitry Andric              "PHINode should have one entry for each predecessor of its "
25020b57cec5SDimitry Andric              "parent basic block!",
25030b57cec5SDimitry Andric              &PN);
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
25060b57cec5SDimitry Andric       Values.clear();
25070b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
25080b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
25090b57cec5SDimitry Andric         Values.push_back(
25100b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
25110b57cec5SDimitry Andric       llvm::sort(Values);
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
25140b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
25150b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
25160b57cec5SDimitry Andric         // all identical.
25170b57cec5SDimitry Andric         //
25180b57cec5SDimitry Andric         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
25190b57cec5SDimitry Andric                    Values[i].second == Values[i - 1].second,
25200b57cec5SDimitry Andric                "PHI node has multiple entries for the same basic block with "
25210b57cec5SDimitry Andric                "different incoming values!",
25220b57cec5SDimitry Andric                &PN, Values[i].first, Values[i].second, Values[i - 1].second);
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
25250b57cec5SDimitry Andric         // matched up.
25260b57cec5SDimitry Andric         Assert(Values[i].first == Preds[i],
25270b57cec5SDimitry Andric                "PHI node entries do not match predecessors!", &PN,
25280b57cec5SDimitry Andric                Values[i].first, Preds[i]);
25290b57cec5SDimitry Andric       }
25300b57cec5SDimitry Andric     }
25310b57cec5SDimitry Andric   }
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
25340b57cec5SDimitry Andric   for (auto &I : BB)
25350b57cec5SDimitry Andric   {
25360b57cec5SDimitry Andric     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
25370b57cec5SDimitry Andric   }
25380b57cec5SDimitry Andric }
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
25410b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
25420b57cec5SDimitry Andric   Assert(&I == I.getParent()->getTerminator(),
25430b57cec5SDimitry Andric          "Terminator found in the middle of a basic block!", I.getParent());
25440b57cec5SDimitry Andric   visitInstruction(I);
25450b57cec5SDimitry Andric }
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
25480b57cec5SDimitry Andric   if (BI.isConditional()) {
25490b57cec5SDimitry Andric     Assert(BI.getCondition()->getType()->isIntegerTy(1),
25500b57cec5SDimitry Andric            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
25510b57cec5SDimitry Andric   }
25520b57cec5SDimitry Andric   visitTerminator(BI);
25530b57cec5SDimitry Andric }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
25560b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
25570b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
25580b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
25590b57cec5SDimitry Andric     Assert(N == 0,
25600b57cec5SDimitry Andric            "Found return instr that returns non-void in Function of void "
25610b57cec5SDimitry Andric            "return type!",
25620b57cec5SDimitry Andric            &RI, F->getReturnType());
25630b57cec5SDimitry Andric   else
25640b57cec5SDimitry Andric     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
25650b57cec5SDimitry Andric            "Function return type does not match operand "
25660b57cec5SDimitry Andric            "type of return inst!",
25670b57cec5SDimitry Andric            &RI, F->getReturnType());
25680b57cec5SDimitry Andric 
25690b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
25700b57cec5SDimitry Andric   // terminators...
25710b57cec5SDimitry Andric   visitTerminator(RI);
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
25750b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
25760b57cec5SDimitry Andric   // have the same type as the switched-on value.
25770b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
25780b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
25790b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
25800b57cec5SDimitry Andric     Assert(Case.getCaseValue()->getType() == SwitchTy,
25810b57cec5SDimitry Andric            "Switch constants must all be same type as switch value!", &SI);
25820b57cec5SDimitry Andric     Assert(Constants.insert(Case.getCaseValue()).second,
25830b57cec5SDimitry Andric            "Duplicate integer as switch case", &SI, Case.getCaseValue());
25840b57cec5SDimitry Andric   }
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   visitTerminator(SI);
25870b57cec5SDimitry Andric }
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
25900b57cec5SDimitry Andric   Assert(BI.getAddress()->getType()->isPointerTy(),
25910b57cec5SDimitry Andric          "Indirectbr operand must have pointer type!", &BI);
25920b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
25930b57cec5SDimitry Andric     Assert(BI.getDestination(i)->getType()->isLabelTy(),
25940b57cec5SDimitry Andric            "Indirectbr destinations must all have pointer type!", &BI);
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   visitTerminator(BI);
25970b57cec5SDimitry Andric }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
26000b57cec5SDimitry Andric   Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
26010b57cec5SDimitry Andric          &CBI);
26020b57cec5SDimitry Andric   for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
26030b57cec5SDimitry Andric     Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
26040b57cec5SDimitry Andric            "Callbr successors must all have pointer type!", &CBI);
26050b57cec5SDimitry Andric   for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
26060b57cec5SDimitry Andric     Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)),
26070b57cec5SDimitry Andric            "Using an unescaped label as a callbr argument!", &CBI);
26080b57cec5SDimitry Andric     if (isa<BasicBlock>(CBI.getOperand(i)))
26090b57cec5SDimitry Andric       for (unsigned j = i + 1; j != e; ++j)
26100b57cec5SDimitry Andric         Assert(CBI.getOperand(i) != CBI.getOperand(j),
26110b57cec5SDimitry Andric                "Duplicate callbr destination!", &CBI);
26120b57cec5SDimitry Andric   }
26138bcb0991SDimitry Andric   {
26148bcb0991SDimitry Andric     SmallPtrSet<BasicBlock *, 4> ArgBBs;
26158bcb0991SDimitry Andric     for (Value *V : CBI.args())
26168bcb0991SDimitry Andric       if (auto *BA = dyn_cast<BlockAddress>(V))
26178bcb0991SDimitry Andric         ArgBBs.insert(BA->getBasicBlock());
26188bcb0991SDimitry Andric     for (BasicBlock *BB : CBI.getIndirectDests())
2619*5ffd83dbSDimitry Andric       Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI);
26208bcb0991SDimitry Andric   }
26210b57cec5SDimitry Andric 
26220b57cec5SDimitry Andric   visitTerminator(CBI);
26230b57cec5SDimitry Andric }
26240b57cec5SDimitry Andric 
26250b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
26260b57cec5SDimitry Andric   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
26270b57cec5SDimitry Andric                                          SI.getOperand(2)),
26280b57cec5SDimitry Andric          "Invalid operands for select instruction!", &SI);
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric   Assert(SI.getTrueValue()->getType() == SI.getType(),
26310b57cec5SDimitry Andric          "Select values must have same type as select instruction!", &SI);
26320b57cec5SDimitry Andric   visitInstruction(SI);
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
26360b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
26370b57cec5SDimitry Andric ///
26380b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
26390b57cec5SDimitry Andric   Assert(false, "User-defined operators should not live outside of a pass!", &I);
26400b57cec5SDimitry Andric }
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
26430b57cec5SDimitry Andric   // Get the source and destination types
26440b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26450b57cec5SDimitry Andric   Type *DestTy = I.getType();
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
26480b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
26490b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
26520b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
26530b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
26540b57cec5SDimitry Andric          "trunc source and destination must both be a vector or neither", &I);
26550b57cec5SDimitry Andric   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric   visitInstruction(I);
26580b57cec5SDimitry Andric }
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
26610b57cec5SDimitry Andric   // Get the source and destination types
26620b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26630b57cec5SDimitry Andric   Type *DestTy = I.getType();
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
26660b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
26670b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
26680b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
26690b57cec5SDimitry Andric          "zext source and destination must both be a vector or neither", &I);
26700b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
26710b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
26720b57cec5SDimitry Andric 
26730b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
26740b57cec5SDimitry Andric 
26750b57cec5SDimitry Andric   visitInstruction(I);
26760b57cec5SDimitry Andric }
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
26790b57cec5SDimitry Andric   // Get the source and destination types
26800b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26810b57cec5SDimitry Andric   Type *DestTy = I.getType();
26820b57cec5SDimitry Andric 
26830b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
26840b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
26850b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
26860b57cec5SDimitry Andric 
26870b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
26880b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
26890b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
26900b57cec5SDimitry Andric          "sext source and destination must both be a vector or neither", &I);
26910b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
26920b57cec5SDimitry Andric 
26930b57cec5SDimitry Andric   visitInstruction(I);
26940b57cec5SDimitry Andric }
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
26970b57cec5SDimitry Andric   // Get the source and destination types
26980b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26990b57cec5SDimitry Andric   Type *DestTy = I.getType();
27000b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
27010b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
27020b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
27050b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
27060b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
27070b57cec5SDimitry Andric          "fptrunc source and destination must both be a vector or neither", &I);
27080b57cec5SDimitry Andric   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
27090b57cec5SDimitry Andric 
27100b57cec5SDimitry Andric   visitInstruction(I);
27110b57cec5SDimitry Andric }
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
27140b57cec5SDimitry Andric   // Get the source and destination types
27150b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27160b57cec5SDimitry Andric   Type *DestTy = I.getType();
27170b57cec5SDimitry Andric 
27180b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
27190b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
27200b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
27230b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
27240b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
27250b57cec5SDimitry Andric          "fpext source and destination must both be a vector or neither", &I);
27260b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   visitInstruction(I);
27290b57cec5SDimitry Andric }
27300b57cec5SDimitry Andric 
27310b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
27320b57cec5SDimitry Andric   // Get the source and destination types
27330b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27340b57cec5SDimitry Andric   Type *DestTy = I.getType();
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
27370b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
27380b57cec5SDimitry Andric 
27390b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
27400b57cec5SDimitry Andric          "UIToFP source and dest must both be vector or scalar", &I);
27410b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
27420b57cec5SDimitry Andric          "UIToFP source must be integer or integer vector", &I);
27430b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
27440b57cec5SDimitry Andric          &I);
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric   if (SrcVec && DstVec)
2747*5ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2748*5ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
27490b57cec5SDimitry Andric            "UIToFP source and dest vector length mismatch", &I);
27500b57cec5SDimitry Andric 
27510b57cec5SDimitry Andric   visitInstruction(I);
27520b57cec5SDimitry Andric }
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
27550b57cec5SDimitry Andric   // Get the source and destination types
27560b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27570b57cec5SDimitry Andric   Type *DestTy = I.getType();
27580b57cec5SDimitry Andric 
27590b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
27600b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
27630b57cec5SDimitry Andric          "SIToFP source and dest must both be vector or scalar", &I);
27640b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
27650b57cec5SDimitry Andric          "SIToFP source must be integer or integer vector", &I);
27660b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
27670b57cec5SDimitry Andric          &I);
27680b57cec5SDimitry Andric 
27690b57cec5SDimitry Andric   if (SrcVec && DstVec)
2770*5ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2771*5ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
27720b57cec5SDimitry Andric            "SIToFP source and dest vector length mismatch", &I);
27730b57cec5SDimitry Andric 
27740b57cec5SDimitry Andric   visitInstruction(I);
27750b57cec5SDimitry Andric }
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
27780b57cec5SDimitry Andric   // Get the source and destination types
27790b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27800b57cec5SDimitry Andric   Type *DestTy = I.getType();
27810b57cec5SDimitry Andric 
27820b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
27830b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
27840b57cec5SDimitry Andric 
27850b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
27860b57cec5SDimitry Andric          "FPToUI source and dest must both be vector or scalar", &I);
27870b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
27880b57cec5SDimitry Andric          &I);
27890b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(),
27900b57cec5SDimitry Andric          "FPToUI result must be integer or integer vector", &I);
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric   if (SrcVec && DstVec)
2793*5ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2794*5ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
27950b57cec5SDimitry Andric            "FPToUI source and dest vector length mismatch", &I);
27960b57cec5SDimitry Andric 
27970b57cec5SDimitry Andric   visitInstruction(I);
27980b57cec5SDimitry Andric }
27990b57cec5SDimitry Andric 
28000b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &I) {
28010b57cec5SDimitry Andric   // Get the source and destination types
28020b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28030b57cec5SDimitry Andric   Type *DestTy = I.getType();
28040b57cec5SDimitry Andric 
28050b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
28060b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
28070b57cec5SDimitry Andric 
28080b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
28090b57cec5SDimitry Andric          "FPToSI source and dest must both be vector or scalar", &I);
28100b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
28110b57cec5SDimitry Andric          &I);
28120b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(),
28130b57cec5SDimitry Andric          "FPToSI result must be integer or integer vector", &I);
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric   if (SrcVec && DstVec)
2816*5ffd83dbSDimitry Andric     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2817*5ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getElementCount(),
28180b57cec5SDimitry Andric            "FPToSI source and dest vector length mismatch", &I);
28190b57cec5SDimitry Andric 
28200b57cec5SDimitry Andric   visitInstruction(I);
28210b57cec5SDimitry Andric }
28220b57cec5SDimitry Andric 
28230b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
28240b57cec5SDimitry Andric   // Get the source and destination types
28250b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28260b57cec5SDimitry Andric   Type *DestTy = I.getType();
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType()))
28310b57cec5SDimitry Andric     Assert(!DL.isNonIntegralPointerType(PTy),
28320b57cec5SDimitry Andric            "ptrtoint not supported for non-integral pointers");
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
28350b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
28360b57cec5SDimitry Andric          &I);
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
2839*5ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
2840*5ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
2841*5ffd83dbSDimitry Andric     Assert(VSrc->getElementCount() == VDest->getElementCount(),
28420b57cec5SDimitry Andric            "PtrToInt Vector width mismatch", &I);
28430b57cec5SDimitry Andric   }
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   visitInstruction(I);
28460b57cec5SDimitry Andric }
28470b57cec5SDimitry Andric 
28480b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
28490b57cec5SDimitry Andric   // Get the source and destination types
28500b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28510b57cec5SDimitry Andric   Type *DestTy = I.getType();
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
28540b57cec5SDimitry Andric          "IntToPtr source must be an integral", &I);
28550b57cec5SDimitry Andric   Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType()))
28580b57cec5SDimitry Andric     Assert(!DL.isNonIntegralPointerType(PTy),
28590b57cec5SDimitry Andric            "inttoptr not supported for non-integral pointers");
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
28620b57cec5SDimitry Andric          &I);
28630b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
2864*5ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
2865*5ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
2866*5ffd83dbSDimitry Andric     Assert(VSrc->getElementCount() == VDest->getElementCount(),
28670b57cec5SDimitry Andric            "IntToPtr Vector width mismatch", &I);
28680b57cec5SDimitry Andric   }
28690b57cec5SDimitry Andric   visitInstruction(I);
28700b57cec5SDimitry Andric }
28710b57cec5SDimitry Andric 
28720b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
28730b57cec5SDimitry Andric   Assert(
28740b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
28750b57cec5SDimitry Andric       "Invalid bitcast", &I);
28760b57cec5SDimitry Andric   visitInstruction(I);
28770b57cec5SDimitry Andric }
28780b57cec5SDimitry Andric 
28790b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
28800b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
28810b57cec5SDimitry Andric   Type *DestTy = I.getType();
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
28840b57cec5SDimitry Andric          &I);
28850b57cec5SDimitry Andric   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
28860b57cec5SDimitry Andric          &I);
28870b57cec5SDimitry Andric   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
28880b57cec5SDimitry Andric          "AddrSpaceCast must be between different address spaces", &I);
2889*5ffd83dbSDimitry Andric   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
2890*5ffd83dbSDimitry Andric     Assert(SrcVTy->getNumElements() ==
2891*5ffd83dbSDimitry Andric                cast<VectorType>(DestTy)->getNumElements(),
28920b57cec5SDimitry Andric            "AddrSpaceCast vector pointer number of elements mismatch", &I);
28930b57cec5SDimitry Andric   visitInstruction(I);
28940b57cec5SDimitry Andric }
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
28970b57cec5SDimitry Andric ///
28980b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
28990b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
29000b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
29010b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
29020b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
29030b57cec5SDimitry Andric   Assert(&PN == &PN.getParent()->front() ||
29040b57cec5SDimitry Andric              isa<PHINode>(--BasicBlock::iterator(&PN)),
29050b57cec5SDimitry Andric          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
29080b57cec5SDimitry Andric   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
29090b57cec5SDimitry Andric 
29100b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
29110b57cec5SDimitry Andric   // result, and that the incoming blocks are really basic blocks.
29120b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
29130b57cec5SDimitry Andric     Assert(PN.getType() == IncValue->getType(),
29140b57cec5SDimitry Andric            "PHI node operands are not the same type as the result!", &PN);
29150b57cec5SDimitry Andric   }
29160b57cec5SDimitry Andric 
29170b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
29180b57cec5SDimitry Andric 
29190b57cec5SDimitry Andric   visitInstruction(PN);
29200b57cec5SDimitry Andric }
29210b57cec5SDimitry Andric 
29220b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
2923*5ffd83dbSDimitry Andric   Assert(Call.getCalledOperand()->getType()->isPointerTy(),
29240b57cec5SDimitry Andric          "Called function must be a pointer!", Call);
2925*5ffd83dbSDimitry Andric   PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric   Assert(FPTy->getElementType()->isFunctionTy(),
29280b57cec5SDimitry Andric          "Called function is not pointer to function type!", Call);
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   Assert(FPTy->getElementType() == Call.getFunctionType(),
29310b57cec5SDimitry Andric          "Called function is not the same type as the call!", Call);
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
29340b57cec5SDimitry Andric 
29350b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
29360b57cec5SDimitry Andric   if (FTy->isVarArg())
29370b57cec5SDimitry Andric     Assert(Call.arg_size() >= FTy->getNumParams(),
29380b57cec5SDimitry Andric            "Called function requires more parameters than were provided!",
29390b57cec5SDimitry Andric            Call);
29400b57cec5SDimitry Andric   else
29410b57cec5SDimitry Andric     Assert(Call.arg_size() == FTy->getNumParams(),
29420b57cec5SDimitry Andric            "Incorrect number of arguments passed to called function!", Call);
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
29450b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
29460b57cec5SDimitry Andric     Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
29470b57cec5SDimitry Andric            "Call parameter type does not match function signature!",
29480b57cec5SDimitry Andric            Call.getArgOperand(i), FTy->getParamType(i), Call);
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
29510b57cec5SDimitry Andric 
29520b57cec5SDimitry Andric   Assert(verifyAttributeCount(Attrs, Call.arg_size()),
29530b57cec5SDimitry Andric          "Attribute after last parameter!", Call);
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   bool IsIntrinsic = Call.getCalledFunction() &&
29560b57cec5SDimitry Andric                      Call.getCalledFunction()->getName().startswith("llvm.");
29570b57cec5SDimitry Andric 
2958*5ffd83dbSDimitry Andric   Function *Callee =
2959*5ffd83dbSDimitry Andric       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
29600b57cec5SDimitry Andric 
2961*5ffd83dbSDimitry Andric   if (Attrs.hasFnAttribute(Attribute::Speculatable)) {
29620b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
29630b57cec5SDimitry Andric     // declaration is also speculatable.
29640b57cec5SDimitry Andric     Assert(Callee && Callee->isSpeculatable(),
29650b57cec5SDimitry Andric            "speculatable attribute may not apply to call sites", Call);
29660b57cec5SDimitry Andric   }
29670b57cec5SDimitry Andric 
2968*5ffd83dbSDimitry Andric   if (Attrs.hasFnAttribute(Attribute::Preallocated)) {
2969*5ffd83dbSDimitry Andric     Assert(Call.getCalledFunction()->getIntrinsicID() ==
2970*5ffd83dbSDimitry Andric                Intrinsic::call_preallocated_arg,
2971*5ffd83dbSDimitry Andric            "preallocated as a call site attribute can only be on "
2972*5ffd83dbSDimitry Andric            "llvm.call.preallocated.arg");
2973*5ffd83dbSDimitry Andric   }
2974*5ffd83dbSDimitry Andric 
29750b57cec5SDimitry Andric   // Verify call attributes.
29760b57cec5SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
29790b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
29800b57cec5SDimitry Andric   // inalloca.
29810b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
29820b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
29830b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
29840b57cec5SDimitry Andric       Assert(AI->isUsedWithInAlloca(),
29850b57cec5SDimitry Andric              "inalloca argument for call has mismatched alloca", AI, Call);
29860b57cec5SDimitry Andric   }
29870b57cec5SDimitry Andric 
29880b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
29890b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
29900b57cec5SDimitry Andric   // well.
29910b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
29920b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
29930b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
29940b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
29950b57cec5SDimitry Andric         Assert(AI->isSwiftError(),
29960b57cec5SDimitry Andric                "swifterror argument for call has mismatched alloca", AI, Call);
29970b57cec5SDimitry Andric         continue;
29980b57cec5SDimitry Andric       }
29990b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
30000b57cec5SDimitry Andric       Assert(ArgI,
30010b57cec5SDimitry Andric              "swifterror argument should come from an alloca or parameter",
30020b57cec5SDimitry Andric              SwiftErrorArg, Call);
30030b57cec5SDimitry Andric       Assert(ArgI->hasSwiftErrorAttr(),
30040b57cec5SDimitry Andric              "swifterror argument for call has mismatched parameter", ArgI,
30050b57cec5SDimitry Andric              Call);
30060b57cec5SDimitry Andric     }
30070b57cec5SDimitry Andric 
30080b57cec5SDimitry Andric     if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) {
30090b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
30100b57cec5SDimitry Andric       // also has the matching immarg.
30110b57cec5SDimitry Andric       Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
30120b57cec5SDimitry Andric              "immarg may not apply only to call sites",
30130b57cec5SDimitry Andric              Call.getArgOperand(i), Call);
30140b57cec5SDimitry Andric     }
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
30170b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
30180b57cec5SDimitry Andric       Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
30190b57cec5SDimitry Andric              "immarg operand has non-immediate parameter", ArgVal, Call);
30200b57cec5SDimitry Andric     }
3021*5ffd83dbSDimitry Andric 
3022*5ffd83dbSDimitry Andric     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3023*5ffd83dbSDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
3024*5ffd83dbSDimitry Andric       bool hasOB =
3025*5ffd83dbSDimitry Andric           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3026*5ffd83dbSDimitry Andric       bool isMustTail = Call.isMustTailCall();
3027*5ffd83dbSDimitry Andric       Assert(hasOB != isMustTail,
3028*5ffd83dbSDimitry Andric              "preallocated operand either requires a preallocated bundle or "
3029*5ffd83dbSDimitry Andric              "the call to be musttail (but not both)",
3030*5ffd83dbSDimitry Andric              ArgVal, Call);
3031*5ffd83dbSDimitry Andric     }
30320b57cec5SDimitry Andric   }
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric   if (FTy->isVarArg()) {
30350b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
30360b57cec5SDimitry Andric     bool SawNest = false;
30370b57cec5SDimitry Andric     bool SawReturned = false;
30380b57cec5SDimitry Andric 
30390b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
30400b57cec5SDimitry Andric       if (Attrs.hasParamAttribute(Idx, Attribute::Nest))
30410b57cec5SDimitry Andric         SawNest = true;
30420b57cec5SDimitry Andric       if (Attrs.hasParamAttribute(Idx, Attribute::Returned))
30430b57cec5SDimitry Andric         SawReturned = true;
30440b57cec5SDimitry Andric     }
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric     // Check attributes on the varargs part.
30470b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
30480b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
30490b57cec5SDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx);
30500b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
30530b57cec5SDimitry Andric         Assert(!SawNest, "More than one parameter has attribute nest!", Call);
30540b57cec5SDimitry Andric         SawNest = true;
30550b57cec5SDimitry Andric       }
30560b57cec5SDimitry Andric 
30570b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
30580b57cec5SDimitry Andric         Assert(!SawReturned, "More than one parameter has attribute returned!",
30590b57cec5SDimitry Andric                Call);
30600b57cec5SDimitry Andric         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
30610b57cec5SDimitry Andric                "Incompatible argument and return types for 'returned' "
30620b57cec5SDimitry Andric                "attribute",
30630b57cec5SDimitry Andric                Call);
30640b57cec5SDimitry Andric         SawReturned = true;
30650b57cec5SDimitry Andric       }
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
30680b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
30690b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
30700b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
30710b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
30720b57cec5SDimitry Andric         Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
30730b57cec5SDimitry Andric                "Attribute 'sret' cannot be used for vararg call arguments!",
30740b57cec5SDimitry Andric                Call);
30750b57cec5SDimitry Andric 
30760b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
30770b57cec5SDimitry Andric         Assert(Idx == Call.arg_size() - 1,
30780b57cec5SDimitry Andric                "inalloca isn't on the last argument!", Call);
30790b57cec5SDimitry Andric     }
30800b57cec5SDimitry Andric   }
30810b57cec5SDimitry Andric 
30820b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
30830b57cec5SDimitry Andric   if (!IsIntrinsic) {
30840b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
30850b57cec5SDimitry Andric       Assert(!ParamTy->isMetadataTy(),
30860b57cec5SDimitry Andric              "Function has metadata parameter but isn't an intrinsic", Call);
30870b57cec5SDimitry Andric       Assert(!ParamTy->isTokenTy(),
30880b57cec5SDimitry Andric              "Function has token parameter but isn't an intrinsic", Call);
30890b57cec5SDimitry Andric     }
30900b57cec5SDimitry Andric   }
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
30930b57cec5SDimitry Andric   if (!Call.getCalledFunction())
30940b57cec5SDimitry Andric     Assert(!FTy->getReturnType()->isTokenTy(),
30950b57cec5SDimitry Andric            "Return type cannot be token for indirect call!");
30960b57cec5SDimitry Andric 
30970b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
30980b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
30990b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
31000b57cec5SDimitry Andric 
3101480093f4SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet", at
3102*5ffd83dbSDimitry Andric   // most one "gc-transition", at most one "cfguardtarget",
3103*5ffd83dbSDimitry Andric   // and at most one "preallocated" operand bundle.
31040b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3105*5ffd83dbSDimitry Andric        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3106*5ffd83dbSDimitry Andric        FoundPreallocatedBundle = false, FoundGCLiveBundle = false;;
31070b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
31080b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
31090b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
31100b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
31110b57cec5SDimitry Andric       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
31120b57cec5SDimitry Andric       FoundDeoptBundle = true;
31130b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
31140b57cec5SDimitry Andric       Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
31150b57cec5SDimitry Andric              Call);
31160b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
31170b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
31180b57cec5SDimitry Andric       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
31190b57cec5SDimitry Andric       FoundFuncletBundle = true;
31200b57cec5SDimitry Andric       Assert(BU.Inputs.size() == 1,
31210b57cec5SDimitry Andric              "Expected exactly one funclet bundle operand", Call);
31220b57cec5SDimitry Andric       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
31230b57cec5SDimitry Andric              "Funclet bundle operands should correspond to a FuncletPadInst",
31240b57cec5SDimitry Andric              Call);
3125480093f4SDimitry Andric     } else if (Tag == LLVMContext::OB_cfguardtarget) {
3126480093f4SDimitry Andric       Assert(!FoundCFGuardTargetBundle,
3127480093f4SDimitry Andric              "Multiple CFGuardTarget operand bundles", Call);
3128480093f4SDimitry Andric       FoundCFGuardTargetBundle = true;
3129480093f4SDimitry Andric       Assert(BU.Inputs.size() == 1,
3130480093f4SDimitry Andric              "Expected exactly one cfguardtarget bundle operand", Call);
3131*5ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_preallocated) {
3132*5ffd83dbSDimitry Andric       Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
3133*5ffd83dbSDimitry Andric              Call);
3134*5ffd83dbSDimitry Andric       FoundPreallocatedBundle = true;
3135*5ffd83dbSDimitry Andric       Assert(BU.Inputs.size() == 1,
3136*5ffd83dbSDimitry Andric              "Expected exactly one preallocated bundle operand", Call);
3137*5ffd83dbSDimitry Andric       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3138*5ffd83dbSDimitry Andric       Assert(Input &&
3139*5ffd83dbSDimitry Andric                  Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3140*5ffd83dbSDimitry Andric              "\"preallocated\" argument must be a token from "
3141*5ffd83dbSDimitry Andric              "llvm.call.preallocated.setup",
3142*5ffd83dbSDimitry Andric              Call);
3143*5ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_gc_live) {
3144*5ffd83dbSDimitry Andric       Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles",
3145*5ffd83dbSDimitry Andric              Call);
3146*5ffd83dbSDimitry Andric       FoundGCLiveBundle = true;
31470b57cec5SDimitry Andric     }
31480b57cec5SDimitry Andric   }
31490b57cec5SDimitry Andric 
31500b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
31510b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
31520b57cec5SDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info.
31530b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
31540b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
31550b57cec5SDimitry Andric     AssertDI(Call.getDebugLoc(),
31560b57cec5SDimitry Andric              "inlinable function call in a function with "
31570b57cec5SDimitry Andric              "debug info must have a !dbg location",
31580b57cec5SDimitry Andric              Call);
31590b57cec5SDimitry Andric 
31600b57cec5SDimitry Andric   visitInstruction(Call);
31610b57cec5SDimitry Andric }
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
31640b57cec5SDimitry Andric /// types with different pointee types and the same address space.
31650b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
31660b57cec5SDimitry Andric   if (L == R)
31670b57cec5SDimitry Andric     return true;
31680b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
31690b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
31700b57cec5SDimitry Andric   if (!PL || !PR)
31710b57cec5SDimitry Andric     return false;
31720b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
31730b57cec5SDimitry Andric }
31740b57cec5SDimitry Andric 
31750b57cec5SDimitry Andric static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) {
31760b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
31770b57cec5SDimitry Andric       Attribute::StructRet,   Attribute::ByVal,     Attribute::InAlloca,
3178*5ffd83dbSDimitry Andric       Attribute::InReg,       Attribute::SwiftSelf, Attribute::SwiftError,
3179*5ffd83dbSDimitry Andric       Attribute::Preallocated};
31800b57cec5SDimitry Andric   AttrBuilder Copy;
31810b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
31820b57cec5SDimitry Andric     if (Attrs.hasParamAttribute(I, AK))
31830b57cec5SDimitry Andric       Copy.addAttribute(AK);
31840b57cec5SDimitry Andric   }
3185*5ffd83dbSDimitry Andric   // `align` is ABI-affecting only in combination with `byval`.
3186*5ffd83dbSDimitry Andric   if (Attrs.hasParamAttribute(I, Attribute::Alignment) &&
3187*5ffd83dbSDimitry Andric       Attrs.hasParamAttribute(I, Attribute::ByVal))
31880b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
31890b57cec5SDimitry Andric   return Copy;
31900b57cec5SDimitry Andric }
31910b57cec5SDimitry Andric 
31920b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
31930b57cec5SDimitry Andric   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
31960b57cec5SDimitry Andric   //   parameters or return types may differ in pointee type, but not
31970b57cec5SDimitry Andric   //   address space.
31980b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
31990b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
32000b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
32010b57cec5SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
32020b57cec5SDimitry Andric     Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
32030b57cec5SDimitry Andric            "cannot guarantee tail call due to mismatched parameter counts",
32040b57cec5SDimitry Andric            &CI);
32050b57cec5SDimitry Andric     for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
32060b57cec5SDimitry Andric       Assert(
32070b57cec5SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
32080b57cec5SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
32090b57cec5SDimitry Andric     }
32100b57cec5SDimitry Andric   }
32110b57cec5SDimitry Andric   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
32120b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched varargs", &CI);
32130b57cec5SDimitry Andric   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
32140b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched return types", &CI);
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
32170b57cec5SDimitry Andric   Assert(F->getCallingConv() == CI.getCallingConv(),
32180b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched calling conv", &CI);
32190b57cec5SDimitry Andric 
32200b57cec5SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3221*5ffd83dbSDimitry Andric   //   returned, preallocated, and inalloca, must match.
32220b57cec5SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
32230b57cec5SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
32240b57cec5SDimitry Andric   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
32250b57cec5SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
32260b57cec5SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
32270b57cec5SDimitry Andric     Assert(CallerABIAttrs == CalleeABIAttrs,
32280b57cec5SDimitry Andric            "cannot guarantee tail call due to mismatched ABI impacting "
32290b57cec5SDimitry Andric            "function attributes",
32300b57cec5SDimitry Andric            &CI, CI.getOperand(I));
32310b57cec5SDimitry Andric   }
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
32340b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
32350b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
32360b57cec5SDimitry Andric   //   produced by the call or void.
32370b57cec5SDimitry Andric   Value *RetVal = &CI;
32380b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric   // Handle the optional bitcast.
32410b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
32420b57cec5SDimitry Andric     Assert(BI->getOperand(0) == RetVal,
32430b57cec5SDimitry Andric            "bitcast following musttail call must use the call", BI);
32440b57cec5SDimitry Andric     RetVal = BI;
32450b57cec5SDimitry Andric     Next = BI->getNextNode();
32460b57cec5SDimitry Andric   }
32470b57cec5SDimitry Andric 
32480b57cec5SDimitry Andric   // Check the return.
32490b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
32500b57cec5SDimitry Andric   Assert(Ret, "musttail call must precede a ret with an optional bitcast",
32510b57cec5SDimitry Andric          &CI);
32520b57cec5SDimitry Andric   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
32530b57cec5SDimitry Andric          "musttail call result must be returned", Ret);
32540b57cec5SDimitry Andric }
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
32570b57cec5SDimitry Andric   visitCallBase(CI);
32580b57cec5SDimitry Andric 
32590b57cec5SDimitry Andric   if (CI.isMustTailCall())
32600b57cec5SDimitry Andric     verifyMustTailCall(CI);
32610b57cec5SDimitry Andric }
32620b57cec5SDimitry Andric 
32630b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
32640b57cec5SDimitry Andric   visitCallBase(II);
32650b57cec5SDimitry Andric 
32660b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
32670b57cec5SDimitry Andric   // exception handling instruction.
32680b57cec5SDimitry Andric   Assert(
32690b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
32700b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
32710b57cec5SDimitry Andric       &II);
32720b57cec5SDimitry Andric 
32730b57cec5SDimitry Andric   visitTerminator(II);
32740b57cec5SDimitry Andric }
32750b57cec5SDimitry Andric 
32760b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
32770b57cec5SDimitry Andric ///
32780b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
32790b57cec5SDimitry Andric   Assert(U.getType() == U.getOperand(0)->getType(),
32800b57cec5SDimitry Andric          "Unary operators must have same type for"
32810b57cec5SDimitry Andric          "operands and result!",
32820b57cec5SDimitry Andric          &U);
32830b57cec5SDimitry Andric 
32840b57cec5SDimitry Andric   switch (U.getOpcode()) {
32850b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
32860b57cec5SDimitry Andric   // floating-point operands.
32870b57cec5SDimitry Andric   case Instruction::FNeg:
32880b57cec5SDimitry Andric     Assert(U.getType()->isFPOrFPVectorTy(),
32890b57cec5SDimitry Andric            "FNeg operator only works with float types!", &U);
32900b57cec5SDimitry Andric     break;
32910b57cec5SDimitry Andric   default:
32920b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
32930b57cec5SDimitry Andric   }
32940b57cec5SDimitry Andric 
32950b57cec5SDimitry Andric   visitInstruction(U);
32960b57cec5SDimitry Andric }
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
32990b57cec5SDimitry Andric /// of the same type!
33000b57cec5SDimitry Andric ///
33010b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
33020b57cec5SDimitry Andric   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
33030b57cec5SDimitry Andric          "Both operands to a binary operator are not of the same type!", &B);
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric   switch (B.getOpcode()) {
33060b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
33070b57cec5SDimitry Andric   // integral operands.
33080b57cec5SDimitry Andric   case Instruction::Add:
33090b57cec5SDimitry Andric   case Instruction::Sub:
33100b57cec5SDimitry Andric   case Instruction::Mul:
33110b57cec5SDimitry Andric   case Instruction::SDiv:
33120b57cec5SDimitry Andric   case Instruction::UDiv:
33130b57cec5SDimitry Andric   case Instruction::SRem:
33140b57cec5SDimitry Andric   case Instruction::URem:
33150b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
33160b57cec5SDimitry Andric            "Integer arithmetic operators only work with integral types!", &B);
33170b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
33180b57cec5SDimitry Andric            "Integer arithmetic operators must have same type "
33190b57cec5SDimitry Andric            "for operands and result!",
33200b57cec5SDimitry Andric            &B);
33210b57cec5SDimitry Andric     break;
33220b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
33230b57cec5SDimitry Andric   // floating-point operands.
33240b57cec5SDimitry Andric   case Instruction::FAdd:
33250b57cec5SDimitry Andric   case Instruction::FSub:
33260b57cec5SDimitry Andric   case Instruction::FMul:
33270b57cec5SDimitry Andric   case Instruction::FDiv:
33280b57cec5SDimitry Andric   case Instruction::FRem:
33290b57cec5SDimitry Andric     Assert(B.getType()->isFPOrFPVectorTy(),
33300b57cec5SDimitry Andric            "Floating-point arithmetic operators only work with "
33310b57cec5SDimitry Andric            "floating-point types!",
33320b57cec5SDimitry Andric            &B);
33330b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
33340b57cec5SDimitry Andric            "Floating-point arithmetic operators must have same type "
33350b57cec5SDimitry Andric            "for operands and result!",
33360b57cec5SDimitry Andric            &B);
33370b57cec5SDimitry Andric     break;
33380b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
33390b57cec5SDimitry Andric   case Instruction::And:
33400b57cec5SDimitry Andric   case Instruction::Or:
33410b57cec5SDimitry Andric   case Instruction::Xor:
33420b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
33430b57cec5SDimitry Andric            "Logical operators only work with integral types!", &B);
33440b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
33450b57cec5SDimitry Andric            "Logical operators must have same type for operands and result!",
33460b57cec5SDimitry Andric            &B);
33470b57cec5SDimitry Andric     break;
33480b57cec5SDimitry Andric   case Instruction::Shl:
33490b57cec5SDimitry Andric   case Instruction::LShr:
33500b57cec5SDimitry Andric   case Instruction::AShr:
33510b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
33520b57cec5SDimitry Andric            "Shifts only work with integral types!", &B);
33530b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
33540b57cec5SDimitry Andric            "Shift return type must be same as operands!", &B);
33550b57cec5SDimitry Andric     break;
33560b57cec5SDimitry Andric   default:
33570b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
33580b57cec5SDimitry Andric   }
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric   visitInstruction(B);
33610b57cec5SDimitry Andric }
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
33640b57cec5SDimitry Andric   // Check that the operands are the same type
33650b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
33660b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
33670b57cec5SDimitry Andric   Assert(Op0Ty == Op1Ty,
33680b57cec5SDimitry Andric          "Both operands to ICmp instruction are not of the same type!", &IC);
33690b57cec5SDimitry Andric   // Check that the operands are the right type
33700b57cec5SDimitry Andric   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
33710b57cec5SDimitry Andric          "Invalid operand types for ICmp instruction", &IC);
33720b57cec5SDimitry Andric   // Check that the predicate is valid.
33730b57cec5SDimitry Andric   Assert(IC.isIntPredicate(),
33740b57cec5SDimitry Andric          "Invalid predicate in ICmp instruction!", &IC);
33750b57cec5SDimitry Andric 
33760b57cec5SDimitry Andric   visitInstruction(IC);
33770b57cec5SDimitry Andric }
33780b57cec5SDimitry Andric 
33790b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
33800b57cec5SDimitry Andric   // Check that the operands are the same type
33810b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
33820b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
33830b57cec5SDimitry Andric   Assert(Op0Ty == Op1Ty,
33840b57cec5SDimitry Andric          "Both operands to FCmp instruction are not of the same type!", &FC);
33850b57cec5SDimitry Andric   // Check that the operands are the right type
33860b57cec5SDimitry Andric   Assert(Op0Ty->isFPOrFPVectorTy(),
33870b57cec5SDimitry Andric          "Invalid operand types for FCmp instruction", &FC);
33880b57cec5SDimitry Andric   // Check that the predicate is valid.
33890b57cec5SDimitry Andric   Assert(FC.isFPPredicate(),
33900b57cec5SDimitry Andric          "Invalid predicate in FCmp instruction!", &FC);
33910b57cec5SDimitry Andric 
33920b57cec5SDimitry Andric   visitInstruction(FC);
33930b57cec5SDimitry Andric }
33940b57cec5SDimitry Andric 
33950b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
33960b57cec5SDimitry Andric   Assert(
33970b57cec5SDimitry Andric       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
33980b57cec5SDimitry Andric       "Invalid extractelement operands!", &EI);
33990b57cec5SDimitry Andric   visitInstruction(EI);
34000b57cec5SDimitry Andric }
34010b57cec5SDimitry Andric 
34020b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
34030b57cec5SDimitry Andric   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
34040b57cec5SDimitry Andric                                             IE.getOperand(2)),
34050b57cec5SDimitry Andric          "Invalid insertelement operands!", &IE);
34060b57cec5SDimitry Andric   visitInstruction(IE);
34070b57cec5SDimitry Andric }
34080b57cec5SDimitry Andric 
34090b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
34100b57cec5SDimitry Andric   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
3411*5ffd83dbSDimitry Andric                                             SV.getShuffleMask()),
34120b57cec5SDimitry Andric          "Invalid shufflevector operands!", &SV);
34130b57cec5SDimitry Andric   visitInstruction(SV);
34140b57cec5SDimitry Andric }
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
34170b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
34180b57cec5SDimitry Andric 
34190b57cec5SDimitry Andric   Assert(isa<PointerType>(TargetTy),
34200b57cec5SDimitry Andric          "GEP base pointer is not a vector or a vector of pointers", &GEP);
34210b57cec5SDimitry Andric   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
34220b57cec5SDimitry Andric 
34230b57cec5SDimitry Andric   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
34240b57cec5SDimitry Andric   Assert(all_of(
34250b57cec5SDimitry Andric       Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
34260b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
34270b57cec5SDimitry Andric   Type *ElTy =
34280b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
34290b57cec5SDimitry Andric   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
34300b57cec5SDimitry Andric 
34310b57cec5SDimitry Andric   Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
34320b57cec5SDimitry Andric              GEP.getResultElementType() == ElTy,
34330b57cec5SDimitry Andric          "GEP is not of right type for indices!", &GEP, ElTy);
34340b57cec5SDimitry Andric 
3435*5ffd83dbSDimitry Andric   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
34360b57cec5SDimitry Andric     // Additional checks for vector GEPs.
3437*5ffd83dbSDimitry Andric     ElementCount GEPWidth = GEPVTy->getElementCount();
34380b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
3439*5ffd83dbSDimitry Andric       Assert(
3440*5ffd83dbSDimitry Andric           GEPWidth ==
3441*5ffd83dbSDimitry Andric               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
34420b57cec5SDimitry Andric           "Vector GEP result width doesn't match operand's", &GEP);
34430b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
34440b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
3445*5ffd83dbSDimitry Andric       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3446*5ffd83dbSDimitry Andric         ElementCount IndexWidth = IndexVTy->getElementCount();
34470b57cec5SDimitry Andric         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
34480b57cec5SDimitry Andric       }
34490b57cec5SDimitry Andric       Assert(IndexTy->isIntOrIntVectorTy(),
34500b57cec5SDimitry Andric              "All GEP indices should be of integer type");
34510b57cec5SDimitry Andric     }
34520b57cec5SDimitry Andric   }
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
34550b57cec5SDimitry Andric     Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
34560b57cec5SDimitry Andric            "GEP address space doesn't match type", &GEP);
34570b57cec5SDimitry Andric   }
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric   visitInstruction(GEP);
34600b57cec5SDimitry Andric }
34610b57cec5SDimitry Andric 
34620b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
34630b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
34640b57cec5SDimitry Andric }
34650b57cec5SDimitry Andric 
34660b57cec5SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
34670b57cec5SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
34680b57cec5SDimitry Andric          "precondition violation");
34690b57cec5SDimitry Andric 
34700b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
34710b57cec5SDimitry Andric   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
34720b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
34730b57cec5SDimitry Andric   Assert(NumRanges >= 1, "It should have at least one range!", Range);
34740b57cec5SDimitry Andric 
34750b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
34760b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
34770b57cec5SDimitry Andric     ConstantInt *Low =
34780b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
34790b57cec5SDimitry Andric     Assert(Low, "The lower limit must be an integer!", Low);
34800b57cec5SDimitry Andric     ConstantInt *High =
34810b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
34820b57cec5SDimitry Andric     Assert(High, "The upper limit must be an integer!", High);
34830b57cec5SDimitry Andric     Assert(High->getType() == Low->getType() && High->getType() == Ty,
34840b57cec5SDimitry Andric            "Range types must match instruction type!", &I);
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric     APInt HighV = High->getValue();
34870b57cec5SDimitry Andric     APInt LowV = Low->getValue();
34880b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
34890b57cec5SDimitry Andric     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
34900b57cec5SDimitry Andric            "Range must not be empty!", Range);
34910b57cec5SDimitry Andric     if (i != 0) {
34920b57cec5SDimitry Andric       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
34930b57cec5SDimitry Andric              "Intervals are overlapping", Range);
34940b57cec5SDimitry Andric       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
34950b57cec5SDimitry Andric              Range);
34960b57cec5SDimitry Andric       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
34970b57cec5SDimitry Andric              Range);
34980b57cec5SDimitry Andric     }
34990b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
35000b57cec5SDimitry Andric   }
35010b57cec5SDimitry Andric   if (NumRanges > 2) {
35020b57cec5SDimitry Andric     APInt FirstLow =
35030b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
35040b57cec5SDimitry Andric     APInt FirstHigh =
35050b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
35060b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
35070b57cec5SDimitry Andric     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
35080b57cec5SDimitry Andric            "Intervals are overlapping", Range);
35090b57cec5SDimitry Andric     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
35100b57cec5SDimitry Andric            Range);
35110b57cec5SDimitry Andric   }
35120b57cec5SDimitry Andric }
35130b57cec5SDimitry Andric 
35140b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
35150b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
35160b57cec5SDimitry Andric   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
35170b57cec5SDimitry Andric   Assert(!(Size & (Size - 1)),
35180b57cec5SDimitry Andric          "atomic memory access' operand must have a power-of-two size", Ty, I);
35190b57cec5SDimitry Andric }
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
35220b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
35230b57cec5SDimitry Andric   Assert(PTy, "Load operand must be a pointer.", &LI);
35240b57cec5SDimitry Andric   Type *ElTy = LI.getType();
35250b57cec5SDimitry Andric   Assert(LI.getAlignment() <= Value::MaximumAlignment,
35260b57cec5SDimitry Andric          "huge alignment values are unsupported", &LI);
35270b57cec5SDimitry Andric   Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
35280b57cec5SDimitry Andric   if (LI.isAtomic()) {
35290b57cec5SDimitry Andric     Assert(LI.getOrdering() != AtomicOrdering::Release &&
35300b57cec5SDimitry Andric                LI.getOrdering() != AtomicOrdering::AcquireRelease,
35310b57cec5SDimitry Andric            "Load cannot have Release ordering", &LI);
35320b57cec5SDimitry Andric     Assert(LI.getAlignment() != 0,
35330b57cec5SDimitry Andric            "Atomic load must specify explicit alignment", &LI);
35340b57cec5SDimitry Andric     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
35350b57cec5SDimitry Andric            "atomic load operand must have integer, pointer, or floating point "
35360b57cec5SDimitry Andric            "type!",
35370b57cec5SDimitry Andric            ElTy, &LI);
35380b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
35390b57cec5SDimitry Andric   } else {
35400b57cec5SDimitry Andric     Assert(LI.getSyncScopeID() == SyncScope::System,
35410b57cec5SDimitry Andric            "Non-atomic load cannot have SynchronizationScope specified", &LI);
35420b57cec5SDimitry Andric   }
35430b57cec5SDimitry Andric 
35440b57cec5SDimitry Andric   visitInstruction(LI);
35450b57cec5SDimitry Andric }
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
35480b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
35490b57cec5SDimitry Andric   Assert(PTy, "Store operand must be a pointer.", &SI);
35500b57cec5SDimitry Andric   Type *ElTy = PTy->getElementType();
35510b57cec5SDimitry Andric   Assert(ElTy == SI.getOperand(0)->getType(),
35520b57cec5SDimitry Andric          "Stored value type does not match pointer operand type!", &SI, ElTy);
35530b57cec5SDimitry Andric   Assert(SI.getAlignment() <= Value::MaximumAlignment,
35540b57cec5SDimitry Andric          "huge alignment values are unsupported", &SI);
35550b57cec5SDimitry Andric   Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
35560b57cec5SDimitry Andric   if (SI.isAtomic()) {
35570b57cec5SDimitry Andric     Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
35580b57cec5SDimitry Andric                SI.getOrdering() != AtomicOrdering::AcquireRelease,
35590b57cec5SDimitry Andric            "Store cannot have Acquire ordering", &SI);
35600b57cec5SDimitry Andric     Assert(SI.getAlignment() != 0,
35610b57cec5SDimitry Andric            "Atomic store must specify explicit alignment", &SI);
35620b57cec5SDimitry Andric     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
35630b57cec5SDimitry Andric            "atomic store operand must have integer, pointer, or floating point "
35640b57cec5SDimitry Andric            "type!",
35650b57cec5SDimitry Andric            ElTy, &SI);
35660b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
35670b57cec5SDimitry Andric   } else {
35680b57cec5SDimitry Andric     Assert(SI.getSyncScopeID() == SyncScope::System,
35690b57cec5SDimitry Andric            "Non-atomic store cannot have SynchronizationScope specified", &SI);
35700b57cec5SDimitry Andric   }
35710b57cec5SDimitry Andric   visitInstruction(SI);
35720b57cec5SDimitry Andric }
35730b57cec5SDimitry Andric 
35740b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
35750b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
35760b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
35770b57cec5SDimitry Andric   unsigned Idx = 0;
35780b57cec5SDimitry Andric   for (auto I = Call.arg_begin(), E = Call.arg_end(); I != E; ++I, ++Idx) {
35790b57cec5SDimitry Andric     if (*I == SwiftErrorVal) {
35800b57cec5SDimitry Andric       Assert(Call.paramHasAttr(Idx, Attribute::SwiftError),
35810b57cec5SDimitry Andric              "swifterror value when used in a callsite should be marked "
35820b57cec5SDimitry Andric              "with swifterror attribute",
35830b57cec5SDimitry Andric              SwiftErrorVal, Call);
35840b57cec5SDimitry Andric     }
35850b57cec5SDimitry Andric   }
35860b57cec5SDimitry Andric }
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
35890b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
35900b57cec5SDimitry Andric   // a swifterror argument.
35910b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
35920b57cec5SDimitry Andric     Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
35930b57cec5SDimitry Andric            isa<InvokeInst>(U),
35940b57cec5SDimitry Andric            "swifterror value can only be loaded and stored from, or "
35950b57cec5SDimitry Andric            "as a swifterror argument!",
35960b57cec5SDimitry Andric            SwiftErrorVal, U);
35970b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
35980b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
35990b57cec5SDimitry Andric       Assert(StoreI->getOperand(1) == SwiftErrorVal,
36000b57cec5SDimitry Andric              "swifterror value should be the second operand when used "
36010b57cec5SDimitry Andric              "by stores", SwiftErrorVal, U);
36020b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
36030b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
36040b57cec5SDimitry Andric   }
36050b57cec5SDimitry Andric }
36060b57cec5SDimitry Andric 
36070b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
36080b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
36090b57cec5SDimitry Andric   PointerType *PTy = AI.getType();
36100b57cec5SDimitry Andric   // TODO: Relax this restriction?
36110b57cec5SDimitry Andric   Assert(PTy->getAddressSpace() == DL.getAllocaAddrSpace(),
36120b57cec5SDimitry Andric          "Allocation instruction pointer not in the stack address space!",
36130b57cec5SDimitry Andric          &AI);
36140b57cec5SDimitry Andric   Assert(AI.getAllocatedType()->isSized(&Visited),
36150b57cec5SDimitry Andric          "Cannot allocate unsized type", &AI);
36160b57cec5SDimitry Andric   Assert(AI.getArraySize()->getType()->isIntegerTy(),
36170b57cec5SDimitry Andric          "Alloca array size must have integer type", &AI);
36180b57cec5SDimitry Andric   Assert(AI.getAlignment() <= Value::MaximumAlignment,
36190b57cec5SDimitry Andric          "huge alignment values are unsupported", &AI);
36200b57cec5SDimitry Andric 
36210b57cec5SDimitry Andric   if (AI.isSwiftError()) {
36220b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
36230b57cec5SDimitry Andric   }
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric   visitInstruction(AI);
36260b57cec5SDimitry Andric }
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric   // FIXME: more conditions???
36310b57cec5SDimitry Andric   Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic,
36320b57cec5SDimitry Andric          "cmpxchg instructions must be atomic.", &CXI);
36330b57cec5SDimitry Andric   Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic,
36340b57cec5SDimitry Andric          "cmpxchg instructions must be atomic.", &CXI);
36350b57cec5SDimitry Andric   Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered,
36360b57cec5SDimitry Andric          "cmpxchg instructions cannot be unordered.", &CXI);
36370b57cec5SDimitry Andric   Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered,
36380b57cec5SDimitry Andric          "cmpxchg instructions cannot be unordered.", &CXI);
36390b57cec5SDimitry Andric   Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()),
36400b57cec5SDimitry Andric          "cmpxchg instructions failure argument shall be no stronger than the "
36410b57cec5SDimitry Andric          "success argument",
36420b57cec5SDimitry Andric          &CXI);
36430b57cec5SDimitry Andric   Assert(CXI.getFailureOrdering() != AtomicOrdering::Release &&
36440b57cec5SDimitry Andric              CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease,
36450b57cec5SDimitry Andric          "cmpxchg failure ordering cannot include release semantics", &CXI);
36460b57cec5SDimitry Andric 
36470b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
36480b57cec5SDimitry Andric   Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
36490b57cec5SDimitry Andric   Type *ElTy = PTy->getElementType();
36500b57cec5SDimitry Andric   Assert(ElTy->isIntOrPtrTy(),
36510b57cec5SDimitry Andric          "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
36520b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
36530b57cec5SDimitry Andric   Assert(ElTy == CXI.getOperand(1)->getType(),
36540b57cec5SDimitry Andric          "Expected value type does not match pointer operand type!", &CXI,
36550b57cec5SDimitry Andric          ElTy);
36560b57cec5SDimitry Andric   Assert(ElTy == CXI.getOperand(2)->getType(),
36570b57cec5SDimitry Andric          "Stored value type does not match pointer operand type!", &CXI, ElTy);
36580b57cec5SDimitry Andric   visitInstruction(CXI);
36590b57cec5SDimitry Andric }
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
36620b57cec5SDimitry Andric   Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic,
36630b57cec5SDimitry Andric          "atomicrmw instructions must be atomic.", &RMWI);
36640b57cec5SDimitry Andric   Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
36650b57cec5SDimitry Andric          "atomicrmw instructions cannot be unordered.", &RMWI);
36660b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
36670b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
36680b57cec5SDimitry Andric   Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
36690b57cec5SDimitry Andric   Type *ElTy = PTy->getElementType();
36700b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
36710b57cec5SDimitry Andric     Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
36720b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
36730b57cec5SDimitry Andric            " operand must have integer or floating point type!",
36740b57cec5SDimitry Andric            &RMWI, ElTy);
36750b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
36760b57cec5SDimitry Andric     Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
36770b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
36780b57cec5SDimitry Andric            " operand must have floating point type!",
36790b57cec5SDimitry Andric            &RMWI, ElTy);
36800b57cec5SDimitry Andric   } else {
36810b57cec5SDimitry Andric     Assert(ElTy->isIntegerTy(), "atomicrmw " +
36820b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
36830b57cec5SDimitry Andric            " operand must have integer type!",
36840b57cec5SDimitry Andric            &RMWI, ElTy);
36850b57cec5SDimitry Andric   }
36860b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
36870b57cec5SDimitry Andric   Assert(ElTy == RMWI.getOperand(1)->getType(),
36880b57cec5SDimitry Andric          "Argument value type does not match pointer operand type!", &RMWI,
36890b57cec5SDimitry Andric          ElTy);
36900b57cec5SDimitry Andric   Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
36910b57cec5SDimitry Andric          "Invalid binary operation!", &RMWI);
36920b57cec5SDimitry Andric   visitInstruction(RMWI);
36930b57cec5SDimitry Andric }
36940b57cec5SDimitry Andric 
36950b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
36960b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
36970b57cec5SDimitry Andric   Assert(Ordering == AtomicOrdering::Acquire ||
36980b57cec5SDimitry Andric              Ordering == AtomicOrdering::Release ||
36990b57cec5SDimitry Andric              Ordering == AtomicOrdering::AcquireRelease ||
37000b57cec5SDimitry Andric              Ordering == AtomicOrdering::SequentiallyConsistent,
37010b57cec5SDimitry Andric          "fence instructions may only have acquire, release, acq_rel, or "
37020b57cec5SDimitry Andric          "seq_cst ordering.",
37030b57cec5SDimitry Andric          &FI);
37040b57cec5SDimitry Andric   visitInstruction(FI);
37050b57cec5SDimitry Andric }
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
37080b57cec5SDimitry Andric   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
37090b57cec5SDimitry Andric                                           EVI.getIndices()) == EVI.getType(),
37100b57cec5SDimitry Andric          "Invalid ExtractValueInst operands!", &EVI);
37110b57cec5SDimitry Andric 
37120b57cec5SDimitry Andric   visitInstruction(EVI);
37130b57cec5SDimitry Andric }
37140b57cec5SDimitry Andric 
37150b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
37160b57cec5SDimitry Andric   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
37170b57cec5SDimitry Andric                                           IVI.getIndices()) ==
37180b57cec5SDimitry Andric              IVI.getOperand(1)->getType(),
37190b57cec5SDimitry Andric          "Invalid InsertValueInst operands!", &IVI);
37200b57cec5SDimitry Andric 
37210b57cec5SDimitry Andric   visitInstruction(IVI);
37220b57cec5SDimitry Andric }
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
37250b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
37260b57cec5SDimitry Andric     return FPI->getParentPad();
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
37290b57cec5SDimitry Andric }
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
37320b57cec5SDimitry Andric   assert(I.isEHPad());
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
37350b57cec5SDimitry Andric   Function *F = BB->getParent();
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
37380b57cec5SDimitry Andric 
37390b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
37400b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
37410b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
37420b57cec5SDimitry Andric     // invoke.
37430b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
37440b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
37450b57cec5SDimitry Andric       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
37460b57cec5SDimitry Andric              "Block containing LandingPadInst must be jumped to "
37470b57cec5SDimitry Andric              "only by the unwind edge of an invoke.",
37480b57cec5SDimitry Andric              LPI);
37490b57cec5SDimitry Andric     }
37500b57cec5SDimitry Andric     return;
37510b57cec5SDimitry Andric   }
37520b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
37530b57cec5SDimitry Andric     if (!pred_empty(BB))
37540b57cec5SDimitry Andric       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
37550b57cec5SDimitry Andric              "Block containg CatchPadInst must be jumped to "
37560b57cec5SDimitry Andric              "only by its catchswitch.",
37570b57cec5SDimitry Andric              CPI);
37580b57cec5SDimitry Andric     Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
37590b57cec5SDimitry Andric            "Catchswitch cannot unwind to one of its catchpads",
37600b57cec5SDimitry Andric            CPI->getCatchSwitch(), CPI);
37610b57cec5SDimitry Andric     return;
37620b57cec5SDimitry Andric   }
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
37650b57cec5SDimitry Andric   // pad relationship.
37660b57cec5SDimitry Andric   Instruction *ToPad = &I;
37670b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
37680b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
37690b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
37700b57cec5SDimitry Andric     Value *FromPad;
37710b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
37720b57cec5SDimitry Andric       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
37730b57cec5SDimitry Andric              "EH pad must be jumped to via an unwind edge", ToPad, II);
37740b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
37750b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
37760b57cec5SDimitry Andric       else
37770b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
37780b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
37790b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
37800b57cec5SDimitry Andric       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
37810b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
37820b57cec5SDimitry Andric       FromPad = CSI;
37830b57cec5SDimitry Andric     } else {
37840b57cec5SDimitry Andric       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
37850b57cec5SDimitry Andric     }
37860b57cec5SDimitry Andric 
37870b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
37880b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
37890b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
37900b57cec5SDimitry Andric       Assert(FromPad != ToPad,
37910b57cec5SDimitry Andric              "EH pad cannot handle exceptions raised within it", FromPad, TI);
37920b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
37930b57cec5SDimitry Andric         // This is a legal unwind edge.
37940b57cec5SDimitry Andric         break;
37950b57cec5SDimitry Andric       }
37960b57cec5SDimitry Andric       Assert(!isa<ConstantTokenNone>(FromPad),
37970b57cec5SDimitry Andric              "A single unwind edge may only enter one EH pad", TI);
37980b57cec5SDimitry Andric       Assert(Seen.insert(FromPad).second,
37990b57cec5SDimitry Andric              "EH pad jumps through a cycle of pads", FromPad);
38000b57cec5SDimitry Andric     }
38010b57cec5SDimitry Andric   }
38020b57cec5SDimitry Andric }
38030b57cec5SDimitry Andric 
38040b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
38050b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
38060b57cec5SDimitry Andric   // isn't a cleanup.
38070b57cec5SDimitry Andric   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
38080b57cec5SDimitry Andric          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
38090b57cec5SDimitry Andric 
38100b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric   if (!LandingPadResultTy)
38130b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
38140b57cec5SDimitry Andric   else
38150b57cec5SDimitry Andric     Assert(LandingPadResultTy == LPI.getType(),
38160b57cec5SDimitry Andric            "The landingpad instruction should have a consistent result type "
38170b57cec5SDimitry Andric            "inside a function.",
38180b57cec5SDimitry Andric            &LPI);
38190b57cec5SDimitry Andric 
38200b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
38210b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
38220b57cec5SDimitry Andric          "LandingPadInst needs to be in a function with a personality.", &LPI);
38230b57cec5SDimitry Andric 
38240b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
38250b57cec5SDimitry Andric   // block.
38260b57cec5SDimitry Andric   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
38270b57cec5SDimitry Andric          "LandingPadInst not the first non-PHI instruction in the block.",
38280b57cec5SDimitry Andric          &LPI);
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
38310b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
38320b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
38330b57cec5SDimitry Andric       Assert(isa<PointerType>(Clause->getType()),
38340b57cec5SDimitry Andric              "Catch operand does not have pointer type!", &LPI);
38350b57cec5SDimitry Andric     } else {
38360b57cec5SDimitry Andric       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
38370b57cec5SDimitry Andric       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
38380b57cec5SDimitry Andric              "Filter operand is not an array of constants!", &LPI);
38390b57cec5SDimitry Andric     }
38400b57cec5SDimitry Andric   }
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   visitInstruction(LPI);
38430b57cec5SDimitry Andric }
38440b57cec5SDimitry Andric 
38450b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
38460b57cec5SDimitry Andric   Assert(RI.getFunction()->hasPersonalityFn(),
38470b57cec5SDimitry Andric          "ResumeInst needs to be in a function with a personality.", &RI);
38480b57cec5SDimitry Andric 
38490b57cec5SDimitry Andric   if (!LandingPadResultTy)
38500b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
38510b57cec5SDimitry Andric   else
38520b57cec5SDimitry Andric     Assert(LandingPadResultTy == RI.getValue()->getType(),
38530b57cec5SDimitry Andric            "The resume instruction should have a consistent result type "
38540b57cec5SDimitry Andric            "inside a function.",
38550b57cec5SDimitry Andric            &RI);
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric   visitTerminator(RI);
38580b57cec5SDimitry Andric }
38590b57cec5SDimitry Andric 
38600b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
38610b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
38620b57cec5SDimitry Andric 
38630b57cec5SDimitry Andric   Function *F = BB->getParent();
38640b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
38650b57cec5SDimitry Andric          "CatchPadInst needs to be in a function with a personality.", &CPI);
38660b57cec5SDimitry Andric 
38670b57cec5SDimitry Andric   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
38680b57cec5SDimitry Andric          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
38690b57cec5SDimitry Andric          CPI.getParentPad());
38700b57cec5SDimitry Andric 
38710b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
38720b57cec5SDimitry Andric   // block.
38730b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CPI,
38740b57cec5SDimitry Andric          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
38770b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
38780b57cec5SDimitry Andric }
38790b57cec5SDimitry Andric 
38800b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
38810b57cec5SDimitry Andric   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
38820b57cec5SDimitry Andric          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
38830b57cec5SDimitry Andric          CatchReturn.getOperand(0));
38840b57cec5SDimitry Andric 
38850b57cec5SDimitry Andric   visitTerminator(CatchReturn);
38860b57cec5SDimitry Andric }
38870b57cec5SDimitry Andric 
38880b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
38890b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
38900b57cec5SDimitry Andric 
38910b57cec5SDimitry Andric   Function *F = BB->getParent();
38920b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
38930b57cec5SDimitry Andric          "CleanupPadInst needs to be in a function with a personality.", &CPI);
38940b57cec5SDimitry Andric 
38950b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
38960b57cec5SDimitry Andric   // block.
38970b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CPI,
38980b57cec5SDimitry Andric          "CleanupPadInst not the first non-PHI instruction in the block.",
38990b57cec5SDimitry Andric          &CPI);
39000b57cec5SDimitry Andric 
39010b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
39020b57cec5SDimitry Andric   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
39030b57cec5SDimitry Andric          "CleanupPadInst has an invalid parent.", &CPI);
39040b57cec5SDimitry Andric 
39050b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
39060b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
39070b57cec5SDimitry Andric }
39080b57cec5SDimitry Andric 
39090b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
39100b57cec5SDimitry Andric   User *FirstUser = nullptr;
39110b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
39120b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
39130b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
39140b57cec5SDimitry Andric 
39150b57cec5SDimitry Andric   while (!Worklist.empty()) {
39160b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
39170b57cec5SDimitry Andric     Assert(Seen.insert(CurrentPad).second,
39180b57cec5SDimitry Andric            "FuncletPadInst must not be nested within itself", CurrentPad);
39190b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
39200b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
39210b57cec5SDimitry Andric       BasicBlock *UnwindDest;
39220b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
39230b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
39240b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
39250b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
39260b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
39270b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
39280b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
39290b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
39300b57cec5SDimitry Andric           continue;
39310b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
39320b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
39330b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
39340b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
39350b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
39360b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
39370b57cec5SDimitry Andric         // such calls to be annotated nounwind.
39380b57cec5SDimitry Andric         continue;
39390b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
39400b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
39410b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
39420b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
39430b57cec5SDimitry Andric         Worklist.push_back(CPI);
39440b57cec5SDimitry Andric         continue;
39450b57cec5SDimitry Andric       } else {
39460b57cec5SDimitry Andric         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
39470b57cec5SDimitry Andric         continue;
39480b57cec5SDimitry Andric       }
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric       Value *UnwindPad;
39510b57cec5SDimitry Andric       bool ExitsFPI;
39520b57cec5SDimitry Andric       if (UnwindDest) {
39530b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
39540b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
39550b57cec5SDimitry Andric           continue;
39560b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
39570b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
39580b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
39590b57cec5SDimitry Andric           continue;
39600b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
39610b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
39620b57cec5SDimitry Andric         // of them are exited so we can stop searching their
39630b57cec5SDimitry Andric         // children.
39640b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
39650b57cec5SDimitry Andric         ExitsFPI = false;
39660b57cec5SDimitry Andric         do {
39670b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
39680b57cec5SDimitry Andric             ExitsFPI = true;
39690b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
39700b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
39710b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
39720b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
39730b57cec5SDimitry Andric             break;
39740b57cec5SDimitry Andric           }
39750b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
39760b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
39770b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
39780b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
39790b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
39800b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
39810b57cec5SDimitry Andric             break;
39820b57cec5SDimitry Andric           }
39830b57cec5SDimitry Andric           ExitedPad = ExitedParent;
39840b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
39850b57cec5SDimitry Andric       } else {
39860b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
39870b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
39880b57cec5SDimitry Andric         ExitsFPI = true;
39890b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
39900b57cec5SDimitry Andric       }
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric       if (ExitsFPI) {
39930b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
39940b57cec5SDimitry Andric         // such edges.
39950b57cec5SDimitry Andric         if (FirstUser) {
39960b57cec5SDimitry Andric           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
39970b57cec5SDimitry Andric                                               "pad must have the same unwind "
39980b57cec5SDimitry Andric                                               "dest",
39990b57cec5SDimitry Andric                  &FPI, U, FirstUser);
40000b57cec5SDimitry Andric         } else {
40010b57cec5SDimitry Andric           FirstUser = U;
40020b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
40030b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
40040b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
40050b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
40060b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
40070b57cec5SDimitry Andric         }
40080b57cec5SDimitry Andric       }
40090b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
40100b57cec5SDimitry Andric       // soon as we know where they unwind to.
40110b57cec5SDimitry Andric       if (CurrentPad != &FPI)
40120b57cec5SDimitry Andric         break;
40130b57cec5SDimitry Andric     }
40140b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
40150b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
40160b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
40170b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
40180b57cec5SDimitry Andric         // all direct uses of FPI.
40190b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
40200b57cec5SDimitry Andric         continue;
40210b57cec5SDimitry Andric       }
40220b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
40230b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
40240b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
40250b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
40260b57cec5SDimitry Andric       // UnresolvedAncestorPad.
40270b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
40280b57cec5SDimitry Andric       while (!Worklist.empty()) {
40290b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
40300b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
40310b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
40320b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
40330b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
40340b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
40350b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
40360b57cec5SDimitry Andric             break;
40370b57cec5SDimitry Andric           }
40380b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
40390b57cec5SDimitry Andric         }
40400b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
40410b57cec5SDimitry Andric         // then the uncle is not yet resolved.
40420b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
40430b57cec5SDimitry Andric           break;
40440b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
40450b57cec5SDimitry Andric         Worklist.pop_back();
40460b57cec5SDimitry Andric       }
40470b57cec5SDimitry Andric     }
40480b57cec5SDimitry Andric   }
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   if (FirstUnwindPad) {
40510b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
40520b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
40530b57cec5SDimitry Andric       Value *SwitchUnwindPad;
40540b57cec5SDimitry Andric       if (SwitchUnwindDest)
40550b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
40560b57cec5SDimitry Andric       else
40570b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
40580b57cec5SDimitry Andric       Assert(SwitchUnwindPad == FirstUnwindPad,
40590b57cec5SDimitry Andric              "Unwind edges out of a catch must have the same unwind dest as "
40600b57cec5SDimitry Andric              "the parent catchswitch",
40610b57cec5SDimitry Andric              &FPI, FirstUser, CatchSwitch);
40620b57cec5SDimitry Andric     }
40630b57cec5SDimitry Andric   }
40640b57cec5SDimitry Andric 
40650b57cec5SDimitry Andric   visitInstruction(FPI);
40660b57cec5SDimitry Andric }
40670b57cec5SDimitry Andric 
40680b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
40690b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
40700b57cec5SDimitry Andric 
40710b57cec5SDimitry Andric   Function *F = BB->getParent();
40720b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
40730b57cec5SDimitry Andric          "CatchSwitchInst needs to be in a function with a personality.",
40740b57cec5SDimitry Andric          &CatchSwitch);
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
40770b57cec5SDimitry Andric   // block.
40780b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CatchSwitch,
40790b57cec5SDimitry Andric          "CatchSwitchInst not the first non-PHI instruction in the block.",
40800b57cec5SDimitry Andric          &CatchSwitch);
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
40830b57cec5SDimitry Andric   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
40840b57cec5SDimitry Andric          "CatchSwitchInst has an invalid parent.", ParentPad);
40850b57cec5SDimitry Andric 
40860b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
40870b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
40880b57cec5SDimitry Andric     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
40890b57cec5SDimitry Andric            "CatchSwitchInst must unwind to an EH block which is not a "
40900b57cec5SDimitry Andric            "landingpad.",
40910b57cec5SDimitry Andric            &CatchSwitch);
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
40940b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
40950b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
40960b57cec5SDimitry Andric   }
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   Assert(CatchSwitch.getNumHandlers() != 0,
40990b57cec5SDimitry Andric          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
41000b57cec5SDimitry Andric 
41010b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
41020b57cec5SDimitry Andric     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
41030b57cec5SDimitry Andric            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
41040b57cec5SDimitry Andric   }
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
41070b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
41080b57cec5SDimitry Andric }
41090b57cec5SDimitry Andric 
41100b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
41110b57cec5SDimitry Andric   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
41120b57cec5SDimitry Andric          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
41130b57cec5SDimitry Andric          CRI.getOperand(0));
41140b57cec5SDimitry Andric 
41150b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
41160b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
41170b57cec5SDimitry Andric     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
41180b57cec5SDimitry Andric            "CleanupReturnInst must unwind to an EH block which is not a "
41190b57cec5SDimitry Andric            "landingpad.",
41200b57cec5SDimitry Andric            &CRI);
41210b57cec5SDimitry Andric   }
41220b57cec5SDimitry Andric 
41230b57cec5SDimitry Andric   visitTerminator(CRI);
41240b57cec5SDimitry Andric }
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
41270b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
41280b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
41290b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
41300b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
41310b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
41320b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
41330b57cec5SDimitry Andric       return;
41340b57cec5SDimitry Andric   }
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
41370b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
41380b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
41390b57cec5SDimitry Andric   //
41400b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
41410b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
41420b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
41430b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
41440b57cec5SDimitry Andric     return;
41450b57cec5SDimitry Andric 
41460b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
41470b57cec5SDimitry Andric   Assert(DT.dominates(Op, U),
41480b57cec5SDimitry Andric          "Instruction does not dominate all uses!", Op, &I);
41490b57cec5SDimitry Andric }
41500b57cec5SDimitry Andric 
41510b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
41520b57cec5SDimitry Andric   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
41530b57cec5SDimitry Andric          "apply only to pointer types", &I);
41548bcb0991SDimitry Andric   Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
41550b57cec5SDimitry Andric          "dereferenceable, dereferenceable_or_null apply only to load"
41568bcb0991SDimitry Andric          " and inttoptr instructions, use attributes for calls or invokes", &I);
41570b57cec5SDimitry Andric   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
41580b57cec5SDimitry Andric          "take one operand!", &I);
41590b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
41600b57cec5SDimitry Andric   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
41610b57cec5SDimitry Andric          "dereferenceable_or_null metadata value must be an i64!", &I);
41620b57cec5SDimitry Andric }
41630b57cec5SDimitry Andric 
41648bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
41658bcb0991SDimitry Andric   Assert(MD->getNumOperands() >= 2,
41668bcb0991SDimitry Andric          "!prof annotations should have no less than 2 operands", MD);
41678bcb0991SDimitry Andric 
41688bcb0991SDimitry Andric   // Check first operand.
41698bcb0991SDimitry Andric   Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
41708bcb0991SDimitry Andric   Assert(isa<MDString>(MD->getOperand(0)),
41718bcb0991SDimitry Andric          "expected string with name of the !prof annotation", MD);
41728bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
41738bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
41748bcb0991SDimitry Andric 
41758bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
41768bcb0991SDimitry Andric   if (ProfName.equals("branch_weights")) {
4177*5ffd83dbSDimitry Andric     if (isa<InvokeInst>(&I)) {
4178*5ffd83dbSDimitry Andric       Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
4179*5ffd83dbSDimitry Andric              "Wrong number of InvokeInst branch_weights operands", MD);
4180*5ffd83dbSDimitry Andric     } else {
41818bcb0991SDimitry Andric       unsigned ExpectedNumOperands = 0;
41828bcb0991SDimitry Andric       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
41838bcb0991SDimitry Andric         ExpectedNumOperands = BI->getNumSuccessors();
41848bcb0991SDimitry Andric       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
41858bcb0991SDimitry Andric         ExpectedNumOperands = SI->getNumSuccessors();
4186*5ffd83dbSDimitry Andric       else if (isa<CallInst>(&I))
41878bcb0991SDimitry Andric         ExpectedNumOperands = 1;
41888bcb0991SDimitry Andric       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
41898bcb0991SDimitry Andric         ExpectedNumOperands = IBI->getNumDestinations();
41908bcb0991SDimitry Andric       else if (isa<SelectInst>(&I))
41918bcb0991SDimitry Andric         ExpectedNumOperands = 2;
41928bcb0991SDimitry Andric       else
41938bcb0991SDimitry Andric         CheckFailed("!prof branch_weights are not allowed for this instruction",
41948bcb0991SDimitry Andric                     MD);
41958bcb0991SDimitry Andric 
41968bcb0991SDimitry Andric       Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
41978bcb0991SDimitry Andric              "Wrong number of operands", MD);
4198*5ffd83dbSDimitry Andric     }
41998bcb0991SDimitry Andric     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
42008bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
42018bcb0991SDimitry Andric       Assert(MDO, "second operand should not be null", MD);
42028bcb0991SDimitry Andric       Assert(mdconst::dyn_extract<ConstantInt>(MDO),
42038bcb0991SDimitry Andric              "!prof brunch_weights operand is not a const int");
42048bcb0991SDimitry Andric     }
42058bcb0991SDimitry Andric   }
42068bcb0991SDimitry Andric }
42078bcb0991SDimitry Andric 
42080b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
42090b57cec5SDimitry Andric ///
42100b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
42110b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
42120b57cec5SDimitry Andric   Assert(BB, "Instruction not embedded in basic block!", &I);
42130b57cec5SDimitry Andric 
42140b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
42150b57cec5SDimitry Andric     for (User *U : I.users()) {
42160b57cec5SDimitry Andric       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
42170b57cec5SDimitry Andric              "Only PHI nodes may reference their own value!", &I);
42180b57cec5SDimitry Andric     }
42190b57cec5SDimitry Andric   }
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   // Check that void typed values don't have names
42220b57cec5SDimitry Andric   Assert(!I.getType()->isVoidTy() || !I.hasName(),
42230b57cec5SDimitry Andric          "Instruction has a name, but provides a void value!", &I);
42240b57cec5SDimitry Andric 
42250b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
42260b57cec5SDimitry Andric   // value type.
42270b57cec5SDimitry Andric   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
42280b57cec5SDimitry Andric          "Instruction returns a non-scalar type!", &I);
42290b57cec5SDimitry Andric 
42300b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
42310b57cec5SDimitry Andric   // checked against the callee type.
42320b57cec5SDimitry Andric   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
42330b57cec5SDimitry Andric          "Invalid use of metadata!", &I);
42340b57cec5SDimitry Andric 
42350b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
42360b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
42370b57cec5SDimitry Andric   // instruction, it is an error!
42380b57cec5SDimitry Andric   for (Use &U : I.uses()) {
42390b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
42400b57cec5SDimitry Andric       Assert(Used->getParent() != nullptr,
42410b57cec5SDimitry Andric              "Instruction referencing"
42420b57cec5SDimitry Andric              " instruction not embedded in a basic block!",
42430b57cec5SDimitry Andric              &I, Used);
42440b57cec5SDimitry Andric     else {
42450b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
42460b57cec5SDimitry Andric       return;
42470b57cec5SDimitry Andric     }
42480b57cec5SDimitry Andric   }
42490b57cec5SDimitry Andric 
42500b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
42510b57cec5SDimitry Andric   // call.
42520b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
42550b57cec5SDimitry Andric     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
42580b57cec5SDimitry Andric     // instructions.
42590b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
42600b57cec5SDimitry Andric       Assert(false, "Instruction operands must be first-class values!", &I);
42610b57cec5SDimitry Andric     }
42620b57cec5SDimitry Andric 
42630b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
42640b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
42650b57cec5SDimitry Andric       // taken.
42660b57cec5SDimitry Andric       Assert(!F->isIntrinsic() ||
42670b57cec5SDimitry Andric                  (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)),
42680b57cec5SDimitry Andric              "Cannot take the address of an intrinsic!", &I);
42690b57cec5SDimitry Andric       Assert(
42700b57cec5SDimitry Andric           !F->isIntrinsic() || isa<CallInst>(I) ||
42710b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::donothing ||
42720b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::coro_resume ||
42730b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::coro_destroy ||
42740b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
42750b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
42760b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
42770b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::wasm_rethrow_in_catch,
42780b57cec5SDimitry Andric           "Cannot invoke an intrinsic other than donothing, patchpoint, "
42790b57cec5SDimitry Andric           "statepoint, coro_resume or coro_destroy",
42800b57cec5SDimitry Andric           &I);
42810b57cec5SDimitry Andric       Assert(F->getParent() == &M, "Referencing function in another module!",
42820b57cec5SDimitry Andric              &I, &M, F, F->getParent());
42830b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
42840b57cec5SDimitry Andric       Assert(OpBB->getParent() == BB->getParent(),
42850b57cec5SDimitry Andric              "Referring to a basic block in another function!", &I);
42860b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
42870b57cec5SDimitry Andric       Assert(OpArg->getParent() == BB->getParent(),
42880b57cec5SDimitry Andric              "Referring to an argument in another function!", &I);
42890b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
42900b57cec5SDimitry Andric       Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
42910b57cec5SDimitry Andric              &M, GV, GV->getParent());
42920b57cec5SDimitry Andric     } else if (isa<Instruction>(I.getOperand(i))) {
42930b57cec5SDimitry Andric       verifyDominatesUse(I, i);
42940b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
42950b57cec5SDimitry Andric       Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
42960b57cec5SDimitry Andric              "Cannot take the address of an inline asm!", &I);
42970b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
42980b57cec5SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy() ||
42990b57cec5SDimitry Andric           !DL.getNonIntegralAddressSpaces().empty()) {
43000b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
43010b57cec5SDimitry Andric         // illegal bitcast.  If the datalayout string specifies non-integral
43020b57cec5SDimitry Andric         // address spaces then we also need to check for illegal ptrtoint and
43030b57cec5SDimitry Andric         // inttoptr expressions.
43040b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
43050b57cec5SDimitry Andric       }
43060b57cec5SDimitry Andric     }
43070b57cec5SDimitry Andric   }
43080b57cec5SDimitry Andric 
43090b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
43100b57cec5SDimitry Andric     Assert(I.getType()->isFPOrFPVectorTy(),
43110b57cec5SDimitry Andric            "fpmath requires a floating point result!", &I);
43120b57cec5SDimitry Andric     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
43130b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
43140b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
43150b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
43160b57cec5SDimitry Andric       Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
43170b57cec5SDimitry Andric              "fpmath accuracy must have float type", &I);
43180b57cec5SDimitry Andric       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
43190b57cec5SDimitry Andric              "fpmath accuracy not a positive number!", &I);
43200b57cec5SDimitry Andric     } else {
43210b57cec5SDimitry Andric       Assert(false, "invalid fpmath accuracy!", &I);
43220b57cec5SDimitry Andric     }
43230b57cec5SDimitry Andric   }
43240b57cec5SDimitry Andric 
43250b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
43260b57cec5SDimitry Andric     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
43270b57cec5SDimitry Andric            "Ranges are only for loads, calls and invokes!", &I);
43280b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
43290b57cec5SDimitry Andric   }
43300b57cec5SDimitry Andric 
43310b57cec5SDimitry Andric   if (I.getMetadata(LLVMContext::MD_nonnull)) {
43320b57cec5SDimitry Andric     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
43330b57cec5SDimitry Andric            &I);
43340b57cec5SDimitry Andric     Assert(isa<LoadInst>(I),
43350b57cec5SDimitry Andric            "nonnull applies only to load instructions, use attributes"
43360b57cec5SDimitry Andric            " for calls or invokes",
43370b57cec5SDimitry Andric            &I);
43380b57cec5SDimitry Andric   }
43390b57cec5SDimitry Andric 
43400b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
43410b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
43420b57cec5SDimitry Andric 
43430b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
43440b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
43450b57cec5SDimitry Andric 
43460b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
43470b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
43480b57cec5SDimitry Andric 
43490b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
43500b57cec5SDimitry Andric     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
43510b57cec5SDimitry Andric            &I);
43520b57cec5SDimitry Andric     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
43530b57cec5SDimitry Andric            "use attributes for calls or invokes", &I);
43540b57cec5SDimitry Andric     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
43550b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
43560b57cec5SDimitry Andric     Assert(CI && CI->getType()->isIntegerTy(64),
43570b57cec5SDimitry Andric            "align metadata value must be an i64!", &I);
43580b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
43590b57cec5SDimitry Andric     Assert(isPowerOf2_64(Align),
43600b57cec5SDimitry Andric            "align metadata value must be a power of 2!", &I);
43610b57cec5SDimitry Andric     Assert(Align <= Value::MaximumAlignment,
43620b57cec5SDimitry Andric            "alignment is larger that implementation defined limit", &I);
43630b57cec5SDimitry Andric   }
43640b57cec5SDimitry Andric 
43658bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
43668bcb0991SDimitry Andric     visitProfMetadata(I, MD);
43678bcb0991SDimitry Andric 
43680b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
43690b57cec5SDimitry Andric     AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
4370*5ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::Yes);
43710b57cec5SDimitry Andric   }
43720b57cec5SDimitry Andric 
43738bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
43740b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
43758bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
43768bcb0991SDimitry Andric   }
43770b57cec5SDimitry Andric 
4378*5ffd83dbSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4379*5ffd83dbSDimitry Andric   I.getAllMetadata(MDs);
4380*5ffd83dbSDimitry Andric   for (auto Attachment : MDs) {
4381*5ffd83dbSDimitry Andric     unsigned Kind = Attachment.first;
4382*5ffd83dbSDimitry Andric     auto AllowLocs =
4383*5ffd83dbSDimitry Andric         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
4384*5ffd83dbSDimitry Andric             ? AreDebugLocsAllowed::Yes
4385*5ffd83dbSDimitry Andric             : AreDebugLocsAllowed::No;
4386*5ffd83dbSDimitry Andric     visitMDNode(*Attachment.second, AllowLocs);
4387*5ffd83dbSDimitry Andric   }
4388*5ffd83dbSDimitry Andric 
43890b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
43900b57cec5SDimitry Andric }
43910b57cec5SDimitry Andric 
43920b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
43930b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
43940b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
43950b57cec5SDimitry Andric   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
43960b57cec5SDimitry Andric          IF);
43970b57cec5SDimitry Andric 
43980b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
43990b57cec5SDimitry Andric   // describe.
44000b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
44010b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
44020b57cec5SDimitry Andric 
44030b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
44040b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
44050b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
44060b57cec5SDimitry Andric 
44070b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
44080b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
44090b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
44100b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
44110b57cec5SDimitry Andric   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
44120b57cec5SDimitry Andric          "Intrinsic has incorrect return type!", IF);
44130b57cec5SDimitry Andric   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
44140b57cec5SDimitry Andric          "Intrinsic has incorrect argument type!", IF);
44150b57cec5SDimitry Andric 
44160b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
44170b57cec5SDimitry Andric   if (IsVarArg)
44180b57cec5SDimitry Andric     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
44190b57cec5SDimitry Andric            "Intrinsic was not defined with variable arguments!", IF);
44200b57cec5SDimitry Andric   else
44210b57cec5SDimitry Andric     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
44220b57cec5SDimitry Andric            "Callsite was not defined with variable arguments!", IF);
44230b57cec5SDimitry Andric 
44240b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
44250b57cec5SDimitry Andric   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
44260b57cec5SDimitry Andric 
44270b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
44280b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
44290b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
44300b57cec5SDimitry Andric   // the name.
44310b57cec5SDimitry Andric   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
44320b57cec5SDimitry Andric   Assert(ExpectedName == IF->getName(),
44330b57cec5SDimitry Andric          "Intrinsic name not mangled correctly for type arguments! "
44340b57cec5SDimitry Andric          "Should be: " +
44350b57cec5SDimitry Andric              ExpectedName,
44360b57cec5SDimitry Andric          IF);
44370b57cec5SDimitry Andric 
44380b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
44390b57cec5SDimitry Andric   // or are local to *this* function.
44400b57cec5SDimitry Andric   for (Value *V : Call.args())
44410b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
44420b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
44430b57cec5SDimitry Andric 
44440b57cec5SDimitry Andric   switch (ID) {
44450b57cec5SDimitry Andric   default:
44460b57cec5SDimitry Andric     break;
4447*5ffd83dbSDimitry Andric   case Intrinsic::assume: {
4448*5ffd83dbSDimitry Andric     for (auto &Elem : Call.bundle_op_infos()) {
4449*5ffd83dbSDimitry Andric       Assert(Elem.Tag->getKey() == "ignore" ||
4450*5ffd83dbSDimitry Andric                  Attribute::isExistingAttribute(Elem.Tag->getKey()),
4451*5ffd83dbSDimitry Andric              "tags must be valid attribute names");
4452*5ffd83dbSDimitry Andric       Attribute::AttrKind Kind =
4453*5ffd83dbSDimitry Andric           Attribute::getAttrKindFromName(Elem.Tag->getKey());
4454*5ffd83dbSDimitry Andric       unsigned ArgCount = Elem.End - Elem.Begin;
4455*5ffd83dbSDimitry Andric       if (Kind == Attribute::Alignment) {
4456*5ffd83dbSDimitry Andric         Assert(ArgCount <= 3 && ArgCount >= 2,
4457*5ffd83dbSDimitry Andric                "alignment assumptions should have 2 or 3 arguments");
4458*5ffd83dbSDimitry Andric         Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
4459*5ffd83dbSDimitry Andric                "first argument should be a pointer");
4460*5ffd83dbSDimitry Andric         Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
4461*5ffd83dbSDimitry Andric                "second argument should be an integer");
4462*5ffd83dbSDimitry Andric         if (ArgCount == 3)
4463*5ffd83dbSDimitry Andric           Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
4464*5ffd83dbSDimitry Andric                  "third argument should be an integer if present");
4465*5ffd83dbSDimitry Andric         return;
4466*5ffd83dbSDimitry Andric       }
4467*5ffd83dbSDimitry Andric       Assert(ArgCount <= 2, "to many arguments");
4468*5ffd83dbSDimitry Andric       if (Kind == Attribute::None)
4469*5ffd83dbSDimitry Andric         break;
4470*5ffd83dbSDimitry Andric       if (Attribute::doesAttrKindHaveArgument(Kind)) {
4471*5ffd83dbSDimitry Andric         Assert(ArgCount == 2, "this attribute should have 2 arguments");
4472*5ffd83dbSDimitry Andric         Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
4473*5ffd83dbSDimitry Andric                "the second argument should be a constant integral value");
4474*5ffd83dbSDimitry Andric       } else if (isFuncOnlyAttr(Kind)) {
4475*5ffd83dbSDimitry Andric         Assert((ArgCount) == 0, "this attribute has no argument");
4476*5ffd83dbSDimitry Andric       } else if (!isFuncOrArgAttr(Kind)) {
4477*5ffd83dbSDimitry Andric         Assert((ArgCount) == 1, "this attribute should have one argument");
4478*5ffd83dbSDimitry Andric       }
4479*5ffd83dbSDimitry Andric     }
4480*5ffd83dbSDimitry Andric     break;
4481*5ffd83dbSDimitry Andric   }
44820b57cec5SDimitry Andric   case Intrinsic::coro_id: {
44830b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
44840b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
44850b57cec5SDimitry Andric       break;
44860b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
44870b57cec5SDimitry Andric     Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
44880b57cec5SDimitry Andric       "info argument of llvm.coro.begin must refer to an initialized "
44890b57cec5SDimitry Andric       "constant");
44900b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
44910b57cec5SDimitry Andric     Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
44920b57cec5SDimitry Andric       "info argument of llvm.coro.begin must refer to either a struct or "
44930b57cec5SDimitry Andric       "an array");
44940b57cec5SDimitry Andric     break;
44950b57cec5SDimitry Andric   }
4496*5ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
4497480093f4SDimitry Andric   case Intrinsic::INTRINSIC:
4498480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
44990b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
45000b57cec5SDimitry Andric     break;
45010b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
45020b57cec5SDimitry Andric     Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
45030b57cec5SDimitry Andric            "invalid llvm.dbg.declare intrinsic call 1", Call);
45040b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
45050b57cec5SDimitry Andric     break;
45060b57cec5SDimitry Andric   case Intrinsic::dbg_addr: // llvm.dbg.addr
45070b57cec5SDimitry Andric     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
45080b57cec5SDimitry Andric     break;
45090b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
45100b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
45110b57cec5SDimitry Andric     break;
45120b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
45130b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
45140b57cec5SDimitry Andric     break;
45150b57cec5SDimitry Andric   case Intrinsic::memcpy:
4516*5ffd83dbSDimitry Andric   case Intrinsic::memcpy_inline:
45170b57cec5SDimitry Andric   case Intrinsic::memmove:
45180b57cec5SDimitry Andric   case Intrinsic::memset: {
45190b57cec5SDimitry Andric     const auto *MI = cast<MemIntrinsic>(&Call);
45200b57cec5SDimitry Andric     auto IsValidAlignment = [&](unsigned Alignment) -> bool {
45210b57cec5SDimitry Andric       return Alignment == 0 || isPowerOf2_32(Alignment);
45220b57cec5SDimitry Andric     };
45230b57cec5SDimitry Andric     Assert(IsValidAlignment(MI->getDestAlignment()),
45240b57cec5SDimitry Andric            "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
45250b57cec5SDimitry Andric            Call);
45260b57cec5SDimitry Andric     if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
45270b57cec5SDimitry Andric       Assert(IsValidAlignment(MTI->getSourceAlignment()),
45280b57cec5SDimitry Andric              "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
45290b57cec5SDimitry Andric              Call);
45300b57cec5SDimitry Andric     }
45310b57cec5SDimitry Andric 
45320b57cec5SDimitry Andric     break;
45330b57cec5SDimitry Andric   }
45340b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
45350b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
45360b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
45370b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
45380b57cec5SDimitry Andric 
45390b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
45400b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
45410b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
45420b57cec5SDimitry Andric     Assert(ElementSizeVal.isPowerOf2(),
45430b57cec5SDimitry Andric            "element size of the element-wise atomic memory intrinsic "
45440b57cec5SDimitry Andric            "must be a power of 2",
45450b57cec5SDimitry Andric            Call);
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric     auto IsValidAlignment = [&](uint64_t Alignment) {
45480b57cec5SDimitry Andric       return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
45490b57cec5SDimitry Andric     };
45500b57cec5SDimitry Andric     uint64_t DstAlignment = AMI->getDestAlignment();
45510b57cec5SDimitry Andric     Assert(IsValidAlignment(DstAlignment),
45520b57cec5SDimitry Andric            "incorrect alignment of the destination argument", Call);
45530b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
45540b57cec5SDimitry Andric       uint64_t SrcAlignment = AMT->getSourceAlignment();
45550b57cec5SDimitry Andric       Assert(IsValidAlignment(SrcAlignment),
45560b57cec5SDimitry Andric              "incorrect alignment of the source argument", Call);
45570b57cec5SDimitry Andric     }
45580b57cec5SDimitry Andric     break;
45590b57cec5SDimitry Andric   }
4560*5ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_setup: {
4561*5ffd83dbSDimitry Andric     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
4562*5ffd83dbSDimitry Andric     Assert(NumArgs != nullptr,
4563*5ffd83dbSDimitry Andric            "llvm.call.preallocated.setup argument must be a constant");
4564*5ffd83dbSDimitry Andric     bool FoundCall = false;
4565*5ffd83dbSDimitry Andric     for (User *U : Call.users()) {
4566*5ffd83dbSDimitry Andric       auto *UseCall = dyn_cast<CallBase>(U);
4567*5ffd83dbSDimitry Andric       Assert(UseCall != nullptr,
4568*5ffd83dbSDimitry Andric              "Uses of llvm.call.preallocated.setup must be calls");
4569*5ffd83dbSDimitry Andric       const Function *Fn = UseCall->getCalledFunction();
4570*5ffd83dbSDimitry Andric       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
4571*5ffd83dbSDimitry Andric         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
4572*5ffd83dbSDimitry Andric         Assert(AllocArgIndex != nullptr,
4573*5ffd83dbSDimitry Andric                "llvm.call.preallocated.alloc arg index must be a constant");
4574*5ffd83dbSDimitry Andric         auto AllocArgIndexInt = AllocArgIndex->getValue();
4575*5ffd83dbSDimitry Andric         Assert(AllocArgIndexInt.sge(0) &&
4576*5ffd83dbSDimitry Andric                    AllocArgIndexInt.slt(NumArgs->getValue()),
4577*5ffd83dbSDimitry Andric                "llvm.call.preallocated.alloc arg index must be between 0 and "
4578*5ffd83dbSDimitry Andric                "corresponding "
4579*5ffd83dbSDimitry Andric                "llvm.call.preallocated.setup's argument count");
4580*5ffd83dbSDimitry Andric       } else if (Fn && Fn->getIntrinsicID() ==
4581*5ffd83dbSDimitry Andric                            Intrinsic::call_preallocated_teardown) {
4582*5ffd83dbSDimitry Andric         // nothing to do
4583*5ffd83dbSDimitry Andric       } else {
4584*5ffd83dbSDimitry Andric         Assert(!FoundCall, "Can have at most one call corresponding to a "
4585*5ffd83dbSDimitry Andric                            "llvm.call.preallocated.setup");
4586*5ffd83dbSDimitry Andric         FoundCall = true;
4587*5ffd83dbSDimitry Andric         size_t NumPreallocatedArgs = 0;
4588*5ffd83dbSDimitry Andric         for (unsigned i = 0; i < UseCall->getNumArgOperands(); i++) {
4589*5ffd83dbSDimitry Andric           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
4590*5ffd83dbSDimitry Andric             ++NumPreallocatedArgs;
4591*5ffd83dbSDimitry Andric           }
4592*5ffd83dbSDimitry Andric         }
4593*5ffd83dbSDimitry Andric         Assert(NumPreallocatedArgs != 0,
4594*5ffd83dbSDimitry Andric                "cannot use preallocated intrinsics on a call without "
4595*5ffd83dbSDimitry Andric                "preallocated arguments");
4596*5ffd83dbSDimitry Andric         Assert(NumArgs->equalsInt(NumPreallocatedArgs),
4597*5ffd83dbSDimitry Andric                "llvm.call.preallocated.setup arg size must be equal to number "
4598*5ffd83dbSDimitry Andric                "of preallocated arguments "
4599*5ffd83dbSDimitry Andric                "at call site",
4600*5ffd83dbSDimitry Andric                Call, *UseCall);
4601*5ffd83dbSDimitry Andric         // getOperandBundle() cannot be called if more than one of the operand
4602*5ffd83dbSDimitry Andric         // bundle exists. There is already a check elsewhere for this, so skip
4603*5ffd83dbSDimitry Andric         // here if we see more than one.
4604*5ffd83dbSDimitry Andric         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
4605*5ffd83dbSDimitry Andric             1) {
4606*5ffd83dbSDimitry Andric           return;
4607*5ffd83dbSDimitry Andric         }
4608*5ffd83dbSDimitry Andric         auto PreallocatedBundle =
4609*5ffd83dbSDimitry Andric             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
4610*5ffd83dbSDimitry Andric         Assert(PreallocatedBundle,
4611*5ffd83dbSDimitry Andric                "Use of llvm.call.preallocated.setup outside intrinsics "
4612*5ffd83dbSDimitry Andric                "must be in \"preallocated\" operand bundle");
4613*5ffd83dbSDimitry Andric         Assert(PreallocatedBundle->Inputs.front().get() == &Call,
4614*5ffd83dbSDimitry Andric                "preallocated bundle must have token from corresponding "
4615*5ffd83dbSDimitry Andric                "llvm.call.preallocated.setup");
4616*5ffd83dbSDimitry Andric       }
4617*5ffd83dbSDimitry Andric     }
4618*5ffd83dbSDimitry Andric     break;
4619*5ffd83dbSDimitry Andric   }
4620*5ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_arg: {
4621*5ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4622*5ffd83dbSDimitry Andric     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4623*5ffd83dbSDimitry Andric                         Intrinsic::call_preallocated_setup,
4624*5ffd83dbSDimitry Andric            "llvm.call.preallocated.arg token argument must be a "
4625*5ffd83dbSDimitry Andric            "llvm.call.preallocated.setup");
4626*5ffd83dbSDimitry Andric     Assert(Call.hasFnAttr(Attribute::Preallocated),
4627*5ffd83dbSDimitry Andric            "llvm.call.preallocated.arg must be called with a \"preallocated\" "
4628*5ffd83dbSDimitry Andric            "call site attribute");
4629*5ffd83dbSDimitry Andric     break;
4630*5ffd83dbSDimitry Andric   }
4631*5ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_teardown: {
4632*5ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4633*5ffd83dbSDimitry Andric     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4634*5ffd83dbSDimitry Andric                         Intrinsic::call_preallocated_setup,
4635*5ffd83dbSDimitry Andric            "llvm.call.preallocated.teardown token argument must be a "
4636*5ffd83dbSDimitry Andric            "llvm.call.preallocated.setup");
4637*5ffd83dbSDimitry Andric     break;
4638*5ffd83dbSDimitry Andric   }
46390b57cec5SDimitry Andric   case Intrinsic::gcroot:
46400b57cec5SDimitry Andric   case Intrinsic::gcwrite:
46410b57cec5SDimitry Andric   case Intrinsic::gcread:
46420b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
46430b57cec5SDimitry Andric       AllocaInst *AI =
46440b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
46450b57cec5SDimitry Andric       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
46460b57cec5SDimitry Andric       Assert(isa<Constant>(Call.getArgOperand(1)),
46470b57cec5SDimitry Andric              "llvm.gcroot parameter #2 must be a constant.", Call);
46480b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
46490b57cec5SDimitry Andric         Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
46500b57cec5SDimitry Andric                "llvm.gcroot parameter #1 must either be a pointer alloca, "
46510b57cec5SDimitry Andric                "or argument #2 must be a non-null constant.",
46520b57cec5SDimitry Andric                Call);
46530b57cec5SDimitry Andric       }
46540b57cec5SDimitry Andric     }
46550b57cec5SDimitry Andric 
46560b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
46570b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
46580b57cec5SDimitry Andric     break;
46590b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
46600b57cec5SDimitry Andric     Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
46610b57cec5SDimitry Andric            "llvm.init_trampoline parameter #2 must resolve to a function.",
46620b57cec5SDimitry Andric            Call);
46630b57cec5SDimitry Andric     break;
46640b57cec5SDimitry Andric   case Intrinsic::prefetch:
46650b57cec5SDimitry Andric     Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
46660b57cec5SDimitry Andric            cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
46670b57cec5SDimitry Andric            "invalid arguments to llvm.prefetch", Call);
46680b57cec5SDimitry Andric     break;
46690b57cec5SDimitry Andric   case Intrinsic::stackprotector:
46700b57cec5SDimitry Andric     Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
46710b57cec5SDimitry Andric            "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
46720b57cec5SDimitry Andric     break;
46730b57cec5SDimitry Andric   case Intrinsic::localescape: {
46740b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
46750b57cec5SDimitry Andric     Assert(BB == &BB->getParent()->front(),
46760b57cec5SDimitry Andric            "llvm.localescape used outside of entry block", Call);
46770b57cec5SDimitry Andric     Assert(!SawFrameEscape,
46780b57cec5SDimitry Andric            "multiple calls to llvm.localescape in one function", Call);
46790b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
46800b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
46810b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
46820b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
46830b57cec5SDimitry Andric       Assert(AI && AI->isStaticAlloca(),
46840b57cec5SDimitry Andric              "llvm.localescape only accepts static allocas", Call);
46850b57cec5SDimitry Andric     }
46860b57cec5SDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands();
46870b57cec5SDimitry Andric     SawFrameEscape = true;
46880b57cec5SDimitry Andric     break;
46890b57cec5SDimitry Andric   }
46900b57cec5SDimitry Andric   case Intrinsic::localrecover: {
46910b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
46920b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
46930b57cec5SDimitry Andric     Assert(Fn && !Fn->isDeclaration(),
46940b57cec5SDimitry Andric            "llvm.localrecover first "
46950b57cec5SDimitry Andric            "argument must be function defined in this module",
46960b57cec5SDimitry Andric            Call);
46970b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
46980b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
46990b57cec5SDimitry Andric     Entry.second = unsigned(
47000b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
47010b57cec5SDimitry Andric     break;
47020b57cec5SDimitry Andric   }
47030b57cec5SDimitry Andric 
47040b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
47050b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
47060b57cec5SDimitry Andric       Assert(!CI->isInlineAsm(),
47070b57cec5SDimitry Andric              "gc.statepoint support for inline assembly unimplemented", CI);
47080b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
47090b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric     verifyStatepoint(Call);
47120b57cec5SDimitry Andric     break;
47130b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
47140b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
47150b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
47160b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
47170b57cec5SDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
47180b57cec5SDimitry Andric     const Function *StatepointFn =
47190b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
47200b57cec5SDimitry Andric     Assert(StatepointFn && StatepointFn->isDeclaration() &&
47210b57cec5SDimitry Andric                StatepointFn->getIntrinsicID() ==
47220b57cec5SDimitry Andric                    Intrinsic::experimental_gc_statepoint,
47230b57cec5SDimitry Andric            "gc.result operand #1 must be from a statepoint", Call,
47240b57cec5SDimitry Andric            Call.getArgOperand(0));
47250b57cec5SDimitry Andric 
47260b57cec5SDimitry Andric     // Assert that result type matches wrapped callee.
47270b57cec5SDimitry Andric     const Value *Target = StatepointCall->getArgOperand(2);
47280b57cec5SDimitry Andric     auto *PT = cast<PointerType>(Target->getType());
47290b57cec5SDimitry Andric     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
47300b57cec5SDimitry Andric     Assert(Call.getType() == TargetFuncType->getReturnType(),
47310b57cec5SDimitry Andric            "gc.result result type does not match wrapped callee", Call);
47320b57cec5SDimitry Andric     break;
47330b57cec5SDimitry Andric   }
47340b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
47350b57cec5SDimitry Andric     Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call);
47360b57cec5SDimitry Andric 
47370b57cec5SDimitry Andric     Assert(isa<PointerType>(Call.getType()->getScalarType()),
47380b57cec5SDimitry Andric            "gc.relocate must return a pointer or a vector of pointers", Call);
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
47410b57cec5SDimitry Andric 
47420b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
47430b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
47440b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
47450b57cec5SDimitry Andric 
47460b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
47470b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
47500b57cec5SDimitry Andric       // statepoint terminator
47510b57cec5SDimitry Andric       Assert(InvokeBB, "safepoints should have unique landingpads",
47520b57cec5SDimitry Andric              LandingPad->getParent());
47530b57cec5SDimitry Andric       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
47540b57cec5SDimitry Andric              InvokeBB);
4755*5ffd83dbSDimitry Andric       Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()),
47560b57cec5SDimitry Andric              "gc relocate should be linked to a statepoint", InvokeBB);
47570b57cec5SDimitry Andric     } else {
47580b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
47590b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
47600b57cec5SDimitry Andric       // relocates of a call statepoint.
47610b57cec5SDimitry Andric       auto Token = Call.getArgOperand(0);
4762*5ffd83dbSDimitry Andric       Assert(isa<GCStatepointInst>(Token),
47630b57cec5SDimitry Andric              "gc relocate is incorrectly tied to the statepoint", Call, Token);
47640b57cec5SDimitry Andric     }
47650b57cec5SDimitry Andric 
47660b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
47670b57cec5SDimitry Andric     const CallBase &StatepointCall =
4768*5ffd83dbSDimitry Andric       *cast<GCRelocateInst>(Call).getStatepoint();
47690b57cec5SDimitry Andric 
47700b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
47710b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
47720b57cec5SDimitry Andric     Assert(isa<ConstantInt>(Base),
47730b57cec5SDimitry Andric            "gc.relocate operand #2 must be integer offset", Call);
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
47760b57cec5SDimitry Andric     Assert(isa<ConstantInt>(Derived),
47770b57cec5SDimitry Andric            "gc.relocate operand #3 must be integer offset", Call);
47780b57cec5SDimitry Andric 
4779*5ffd83dbSDimitry Andric     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
4780*5ffd83dbSDimitry Andric     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
4781*5ffd83dbSDimitry Andric 
47820b57cec5SDimitry Andric     // Check the bounds
4783*5ffd83dbSDimitry Andric     if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) {
4784*5ffd83dbSDimitry Andric       Assert(BaseIndex < Opt->Inputs.size(),
47850b57cec5SDimitry Andric              "gc.relocate: statepoint base index out of bounds", Call);
4786*5ffd83dbSDimitry Andric       Assert(DerivedIndex < Opt->Inputs.size(),
4787*5ffd83dbSDimitry Andric              "gc.relocate: statepoint derived index out of bounds", Call);
4788*5ffd83dbSDimitry Andric     } else {
4789*5ffd83dbSDimitry Andric       Assert(BaseIndex < StatepointCall.arg_size(),
4790*5ffd83dbSDimitry Andric              "gc.relocate: statepoint base index out of bounds", Call);
4791*5ffd83dbSDimitry Andric       Assert(DerivedIndex < StatepointCall.arg_size(),
47920b57cec5SDimitry Andric              "gc.relocate: statepoint derived index out of bounds", Call);
47930b57cec5SDimitry Andric 
47940b57cec5SDimitry Andric       // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
47950b57cec5SDimitry Andric       // section of the statepoint's argument.
47960b57cec5SDimitry Andric       Assert(StatepointCall.arg_size() > 0,
47970b57cec5SDimitry Andric              "gc.statepoint: insufficient arguments");
47980b57cec5SDimitry Andric       Assert(isa<ConstantInt>(StatepointCall.getArgOperand(3)),
47990b57cec5SDimitry Andric              "gc.statement: number of call arguments must be constant integer");
4800*5ffd83dbSDimitry Andric       const uint64_t NumCallArgs =
48010b57cec5SDimitry Andric         cast<ConstantInt>(StatepointCall.getArgOperand(3))->getZExtValue();
48020b57cec5SDimitry Andric       Assert(StatepointCall.arg_size() > NumCallArgs + 5,
48030b57cec5SDimitry Andric              "gc.statepoint: mismatch in number of call arguments");
48040b57cec5SDimitry Andric       Assert(isa<ConstantInt>(StatepointCall.getArgOperand(NumCallArgs + 5)),
48050b57cec5SDimitry Andric              "gc.statepoint: number of transition arguments must be "
48060b57cec5SDimitry Andric              "a constant integer");
4807*5ffd83dbSDimitry Andric       const uint64_t NumTransitionArgs =
48080b57cec5SDimitry Andric           cast<ConstantInt>(StatepointCall.getArgOperand(NumCallArgs + 5))
48090b57cec5SDimitry Andric               ->getZExtValue();
4810*5ffd83dbSDimitry Andric       const uint64_t DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
48110b57cec5SDimitry Andric       Assert(isa<ConstantInt>(StatepointCall.getArgOperand(DeoptArgsStart)),
48120b57cec5SDimitry Andric              "gc.statepoint: number of deoptimization arguments must be "
48130b57cec5SDimitry Andric              "a constant integer");
4814*5ffd83dbSDimitry Andric       const uint64_t NumDeoptArgs =
48150b57cec5SDimitry Andric           cast<ConstantInt>(StatepointCall.getArgOperand(DeoptArgsStart))
48160b57cec5SDimitry Andric               ->getZExtValue();
4817*5ffd83dbSDimitry Andric       const uint64_t GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
4818*5ffd83dbSDimitry Andric       const uint64_t GCParamArgsEnd = StatepointCall.arg_size();
48190b57cec5SDimitry Andric       Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
48200b57cec5SDimitry Andric              "gc.relocate: statepoint base index doesn't fall within the "
48210b57cec5SDimitry Andric              "'gc parameters' section of the statepoint call",
48220b57cec5SDimitry Andric              Call);
48230b57cec5SDimitry Andric       Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
48240b57cec5SDimitry Andric              "gc.relocate: statepoint derived index doesn't fall within the "
48250b57cec5SDimitry Andric              "'gc parameters' section of the statepoint call",
48260b57cec5SDimitry Andric              Call);
4827*5ffd83dbSDimitry Andric     }
48280b57cec5SDimitry Andric 
48290b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
48300b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
48310b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
48320b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
48330b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
48340b57cec5SDimitry Andric     Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
48350b57cec5SDimitry Andric            "gc.relocate: relocated value must be a gc pointer", Call);
48360b57cec5SDimitry Andric 
48370b57cec5SDimitry Andric     auto ResultType = Call.getType();
48380b57cec5SDimitry Andric     auto DerivedType = Relocate.getDerivedPtr()->getType();
48390b57cec5SDimitry Andric     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
48400b57cec5SDimitry Andric            "gc.relocate: vector relocates to vector and pointer to pointer",
48410b57cec5SDimitry Andric            Call);
48420b57cec5SDimitry Andric     Assert(
48430b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
48440b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
48450b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
48460b57cec5SDimitry Andric         Call);
48470b57cec5SDimitry Andric     break;
48480b57cec5SDimitry Andric   }
48490b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
48500b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
48510b57cec5SDimitry Andric     Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
48520b57cec5SDimitry Andric            "eh.exceptionpointer argument must be a catchpad", Call);
48530b57cec5SDimitry Andric     break;
48540b57cec5SDimitry Andric   }
4855*5ffd83dbSDimitry Andric   case Intrinsic::get_active_lane_mask: {
4856*5ffd83dbSDimitry Andric     Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a "
4857*5ffd83dbSDimitry Andric            "vector", Call);
4858*5ffd83dbSDimitry Andric     auto *ElemTy = Call.getType()->getScalarType();
4859*5ffd83dbSDimitry Andric     Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not "
4860*5ffd83dbSDimitry Andric            "i1", Call);
4861*5ffd83dbSDimitry Andric     break;
4862*5ffd83dbSDimitry Andric   }
48630b57cec5SDimitry Andric   case Intrinsic::masked_load: {
48640b57cec5SDimitry Andric     Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
48650b57cec5SDimitry Andric            Call);
48660b57cec5SDimitry Andric 
48670b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(0);
48680b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
48690b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
48700b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
48710b57cec5SDimitry Andric     Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
48720b57cec5SDimitry Andric            Call);
48730b57cec5SDimitry Andric     Assert(Alignment->getValue().isPowerOf2(),
48740b57cec5SDimitry Andric            "masked_load: alignment must be a power of 2", Call);
48750b57cec5SDimitry Andric 
48760b57cec5SDimitry Andric     // DataTy is the overloaded type
48770b57cec5SDimitry Andric     Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
48780b57cec5SDimitry Andric     Assert(DataTy == Call.getType(),
48790b57cec5SDimitry Andric            "masked_load: return must match pointer type", Call);
48800b57cec5SDimitry Andric     Assert(PassThru->getType() == DataTy,
48810b57cec5SDimitry Andric            "masked_load: pass through and data type must match", Call);
4882*5ffd83dbSDimitry Andric     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
4883*5ffd83dbSDimitry Andric                cast<VectorType>(DataTy)->getElementCount(),
48840b57cec5SDimitry Andric            "masked_load: vector mask must be same length as data", Call);
48850b57cec5SDimitry Andric     break;
48860b57cec5SDimitry Andric   }
48870b57cec5SDimitry Andric   case Intrinsic::masked_store: {
48880b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
48890b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(1);
48900b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
48910b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
48920b57cec5SDimitry Andric     Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
48930b57cec5SDimitry Andric            Call);
48940b57cec5SDimitry Andric     Assert(Alignment->getValue().isPowerOf2(),
48950b57cec5SDimitry Andric            "masked_store: alignment must be a power of 2", Call);
48960b57cec5SDimitry Andric 
48970b57cec5SDimitry Andric     // DataTy is the overloaded type
48980b57cec5SDimitry Andric     Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
48990b57cec5SDimitry Andric     Assert(DataTy == Val->getType(),
49000b57cec5SDimitry Andric            "masked_store: storee must match pointer type", Call);
4901*5ffd83dbSDimitry Andric     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
4902*5ffd83dbSDimitry Andric                cast<VectorType>(DataTy)->getElementCount(),
49030b57cec5SDimitry Andric            "masked_store: vector mask must be same length as data", Call);
49040b57cec5SDimitry Andric     break;
49050b57cec5SDimitry Andric   }
49060b57cec5SDimitry Andric 
4907*5ffd83dbSDimitry Andric   case Intrinsic::masked_gather: {
4908*5ffd83dbSDimitry Andric     const APInt &Alignment =
4909*5ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
4910*5ffd83dbSDimitry Andric     Assert(Alignment.isNullValue() || Alignment.isPowerOf2(),
4911*5ffd83dbSDimitry Andric            "masked_gather: alignment must be 0 or a power of 2", Call);
4912*5ffd83dbSDimitry Andric     break;
4913*5ffd83dbSDimitry Andric   }
4914*5ffd83dbSDimitry Andric   case Intrinsic::masked_scatter: {
4915*5ffd83dbSDimitry Andric     const APInt &Alignment =
4916*5ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
4917*5ffd83dbSDimitry Andric     Assert(Alignment.isNullValue() || Alignment.isPowerOf2(),
4918*5ffd83dbSDimitry Andric            "masked_scatter: alignment must be 0 or a power of 2", Call);
4919*5ffd83dbSDimitry Andric     break;
4920*5ffd83dbSDimitry Andric   }
4921*5ffd83dbSDimitry Andric 
49220b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
49230b57cec5SDimitry Andric     Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
49240b57cec5SDimitry Andric     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
49250b57cec5SDimitry Andric            "experimental_guard must have exactly one "
49260b57cec5SDimitry Andric            "\"deopt\" operand bundle");
49270b57cec5SDimitry Andric     break;
49280b57cec5SDimitry Andric   }
49290b57cec5SDimitry Andric 
49300b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
49310b57cec5SDimitry Andric     Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
49320b57cec5SDimitry Andric            Call);
49330b57cec5SDimitry Andric     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
49340b57cec5SDimitry Andric            "experimental_deoptimize must have exactly one "
49350b57cec5SDimitry Andric            "\"deopt\" operand bundle");
49360b57cec5SDimitry Andric     Assert(Call.getType() == Call.getFunction()->getReturnType(),
49370b57cec5SDimitry Andric            "experimental_deoptimize return type must match caller return type");
49380b57cec5SDimitry Andric 
49390b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
49400b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
49410b57cec5SDimitry Andric       Assert(RI,
49420b57cec5SDimitry Andric              "calls to experimental_deoptimize must be followed by a return");
49430b57cec5SDimitry Andric 
49440b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
49450b57cec5SDimitry Andric         Assert(RI->getReturnValue() == &Call,
49460b57cec5SDimitry Andric                "calls to experimental_deoptimize must be followed by a return "
49470b57cec5SDimitry Andric                "of the value computed by experimental_deoptimize");
49480b57cec5SDimitry Andric     }
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric     break;
49510b57cec5SDimitry Andric   }
49520b57cec5SDimitry Andric   case Intrinsic::sadd_sat:
49530b57cec5SDimitry Andric   case Intrinsic::uadd_sat:
49540b57cec5SDimitry Andric   case Intrinsic::ssub_sat:
49550b57cec5SDimitry Andric   case Intrinsic::usub_sat: {
49560b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
49570b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
49580b57cec5SDimitry Andric     Assert(Op1->getType()->isIntOrIntVectorTy(),
49590b57cec5SDimitry Andric            "first operand of [us][add|sub]_sat must be an int type or vector "
49600b57cec5SDimitry Andric            "of ints");
49610b57cec5SDimitry Andric     Assert(Op2->getType()->isIntOrIntVectorTy(),
49620b57cec5SDimitry Andric            "second operand of [us][add|sub]_sat must be an int type or vector "
49630b57cec5SDimitry Andric            "of ints");
49640b57cec5SDimitry Andric     break;
49650b57cec5SDimitry Andric   }
49660b57cec5SDimitry Andric   case Intrinsic::smul_fix:
49670b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
49688bcb0991SDimitry Andric   case Intrinsic::umul_fix:
4969480093f4SDimitry Andric   case Intrinsic::umul_fix_sat:
4970480093f4SDimitry Andric   case Intrinsic::sdiv_fix:
4971*5ffd83dbSDimitry Andric   case Intrinsic::sdiv_fix_sat:
4972*5ffd83dbSDimitry Andric   case Intrinsic::udiv_fix:
4973*5ffd83dbSDimitry Andric   case Intrinsic::udiv_fix_sat: {
49740b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
49750b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
49760b57cec5SDimitry Andric     Assert(Op1->getType()->isIntOrIntVectorTy(),
4977480093f4SDimitry Andric            "first operand of [us][mul|div]_fix[_sat] must be an int type or "
4978480093f4SDimitry Andric            "vector of ints");
49790b57cec5SDimitry Andric     Assert(Op2->getType()->isIntOrIntVectorTy(),
4980480093f4SDimitry Andric            "second operand of [us][mul|div]_fix[_sat] must be an int type or "
4981480093f4SDimitry Andric            "vector of ints");
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
49840b57cec5SDimitry Andric     Assert(Op3->getType()->getBitWidth() <= 32,
4985480093f4SDimitry Andric            "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
49860b57cec5SDimitry Andric 
4987480093f4SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
4988*5ffd83dbSDimitry Andric         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
49890b57cec5SDimitry Andric       Assert(
49900b57cec5SDimitry Andric           Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
4991480093f4SDimitry Andric           "the scale of s[mul|div]_fix[_sat] must be less than the width of "
4992480093f4SDimitry Andric           "the operands");
49930b57cec5SDimitry Andric     } else {
49940b57cec5SDimitry Andric       Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
4995480093f4SDimitry Andric              "the scale of u[mul|div]_fix[_sat] must be less than or equal "
4996480093f4SDimitry Andric              "to the width of the operands");
49970b57cec5SDimitry Andric     }
49980b57cec5SDimitry Andric     break;
49990b57cec5SDimitry Andric   }
50000b57cec5SDimitry Andric   case Intrinsic::lround:
50010b57cec5SDimitry Andric   case Intrinsic::llround:
50020b57cec5SDimitry Andric   case Intrinsic::lrint:
50030b57cec5SDimitry Andric   case Intrinsic::llrint: {
50040b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
50050b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
50060b57cec5SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
50070b57cec5SDimitry Andric            "Intrinsic does not support vectors", &Call);
50080b57cec5SDimitry Andric     break;
50090b57cec5SDimitry Andric   }
5010*5ffd83dbSDimitry Andric   case Intrinsic::bswap: {
5011*5ffd83dbSDimitry Andric     Type *Ty = Call.getType();
5012*5ffd83dbSDimitry Andric     unsigned Size = Ty->getScalarSizeInBits();
5013*5ffd83dbSDimitry Andric     Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
5014*5ffd83dbSDimitry Andric     break;
5015*5ffd83dbSDimitry Andric   }
5016*5ffd83dbSDimitry Andric   case Intrinsic::matrix_multiply:
5017*5ffd83dbSDimitry Andric   case Intrinsic::matrix_transpose:
5018*5ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_load:
5019*5ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_store: {
5020*5ffd83dbSDimitry Andric     Function *IF = Call.getCalledFunction();
5021*5ffd83dbSDimitry Andric     ConstantInt *Stride = nullptr;
5022*5ffd83dbSDimitry Andric     ConstantInt *NumRows;
5023*5ffd83dbSDimitry Andric     ConstantInt *NumColumns;
5024*5ffd83dbSDimitry Andric     VectorType *ResultTy;
5025*5ffd83dbSDimitry Andric     Type *Op0ElemTy = nullptr;
5026*5ffd83dbSDimitry Andric     Type *Op1ElemTy = nullptr;
5027*5ffd83dbSDimitry Andric     switch (ID) {
5028*5ffd83dbSDimitry Andric     case Intrinsic::matrix_multiply:
5029*5ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
5030*5ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5031*5ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
5032*5ffd83dbSDimitry Andric       Op0ElemTy =
5033*5ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5034*5ffd83dbSDimitry Andric       Op1ElemTy =
5035*5ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
5036*5ffd83dbSDimitry Andric       break;
5037*5ffd83dbSDimitry Andric     case Intrinsic::matrix_transpose:
5038*5ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
5039*5ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
5040*5ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
5041*5ffd83dbSDimitry Andric       Op0ElemTy =
5042*5ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5043*5ffd83dbSDimitry Andric       break;
5044*5ffd83dbSDimitry Andric     case Intrinsic::matrix_column_major_load:
5045*5ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
5046*5ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
5047*5ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5048*5ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
5049*5ffd83dbSDimitry Andric       Op0ElemTy =
5050*5ffd83dbSDimitry Andric           cast<PointerType>(Call.getArgOperand(0)->getType())->getElementType();
5051*5ffd83dbSDimitry Andric       break;
5052*5ffd83dbSDimitry Andric     case Intrinsic::matrix_column_major_store:
5053*5ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
5054*5ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
5055*5ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
5056*5ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
5057*5ffd83dbSDimitry Andric       Op0ElemTy =
5058*5ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5059*5ffd83dbSDimitry Andric       Op1ElemTy =
5060*5ffd83dbSDimitry Andric           cast<PointerType>(Call.getArgOperand(1)->getType())->getElementType();
5061*5ffd83dbSDimitry Andric       break;
5062*5ffd83dbSDimitry Andric     default:
5063*5ffd83dbSDimitry Andric       llvm_unreachable("unexpected intrinsic");
5064*5ffd83dbSDimitry Andric     }
5065*5ffd83dbSDimitry Andric 
5066*5ffd83dbSDimitry Andric     Assert(ResultTy->getElementType()->isIntegerTy() ||
5067*5ffd83dbSDimitry Andric            ResultTy->getElementType()->isFloatingPointTy(),
5068*5ffd83dbSDimitry Andric            "Result type must be an integer or floating-point type!", IF);
5069*5ffd83dbSDimitry Andric 
5070*5ffd83dbSDimitry Andric     Assert(ResultTy->getElementType() == Op0ElemTy,
5071*5ffd83dbSDimitry Andric            "Vector element type mismatch of the result and first operand "
5072*5ffd83dbSDimitry Andric            "vector!", IF);
5073*5ffd83dbSDimitry Andric 
5074*5ffd83dbSDimitry Andric     if (Op1ElemTy)
5075*5ffd83dbSDimitry Andric       Assert(ResultTy->getElementType() == Op1ElemTy,
5076*5ffd83dbSDimitry Andric              "Vector element type mismatch of the result and second operand "
5077*5ffd83dbSDimitry Andric              "vector!", IF);
5078*5ffd83dbSDimitry Andric 
5079*5ffd83dbSDimitry Andric     Assert(ResultTy->getNumElements() ==
5080*5ffd83dbSDimitry Andric                NumRows->getZExtValue() * NumColumns->getZExtValue(),
5081*5ffd83dbSDimitry Andric            "Result of a matrix operation does not fit in the returned vector!");
5082*5ffd83dbSDimitry Andric 
5083*5ffd83dbSDimitry Andric     if (Stride)
5084*5ffd83dbSDimitry Andric       Assert(Stride->getZExtValue() >= NumRows->getZExtValue(),
5085*5ffd83dbSDimitry Andric              "Stride must be greater or equal than the number of rows!", IF);
5086*5ffd83dbSDimitry Andric 
5087*5ffd83dbSDimitry Andric     break;
5088*5ffd83dbSDimitry Andric   }
50890b57cec5SDimitry Andric   };
50900b57cec5SDimitry Andric }
50910b57cec5SDimitry Andric 
50920b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
50930b57cec5SDimitry Andric ///
50940b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
50950b57cec5SDimitry Andric /// built-in assertions that would typically fire.
50960b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
50970b57cec5SDimitry Andric   if (!LocalScope)
50980b57cec5SDimitry Andric     return nullptr;
50990b57cec5SDimitry Andric 
51000b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
51010b57cec5SDimitry Andric     return SP;
51020b57cec5SDimitry Andric 
51030b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
51040b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
51050b57cec5SDimitry Andric 
51060b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
51070b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
51080b57cec5SDimitry Andric   return nullptr;
51090b57cec5SDimitry Andric }
51100b57cec5SDimitry Andric 
51110b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5112480093f4SDimitry Andric   unsigned NumOperands;
5113480093f4SDimitry Andric   bool HasRoundingMD;
51140b57cec5SDimitry Andric   switch (FPI.getIntrinsicID()) {
5115*5ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
5116480093f4SDimitry Andric   case Intrinsic::INTRINSIC:                                                   \
5117480093f4SDimitry Andric     NumOperands = NARG;                                                        \
5118480093f4SDimitry Andric     HasRoundingMD = ROUND_MODE;                                                \
51190b57cec5SDimitry Andric     break;
5120480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
5121480093f4SDimitry Andric   default:
5122480093f4SDimitry Andric     llvm_unreachable("Invalid constrained FP intrinsic!");
5123480093f4SDimitry Andric   }
5124480093f4SDimitry Andric   NumOperands += (1 + HasRoundingMD);
5125480093f4SDimitry Andric   // Compare intrinsics carry an extra predicate metadata operand.
5126480093f4SDimitry Andric   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5127480093f4SDimitry Andric     NumOperands += 1;
5128480093f4SDimitry Andric   Assert((FPI.getNumArgOperands() == NumOperands),
5129480093f4SDimitry Andric          "invalid arguments for constrained FP intrinsic", &FPI);
51300b57cec5SDimitry Andric 
5131480093f4SDimitry Andric   switch (FPI.getIntrinsicID()) {
51328bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
51338bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
51348bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
51358bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
51368bcb0991SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
51378bcb0991SDimitry Andric            "Intrinsic does not support vectors", &FPI);
51388bcb0991SDimitry Andric   }
51398bcb0991SDimitry Andric     break;
51408bcb0991SDimitry Andric 
51418bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
51428bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
51438bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
51448bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
51458bcb0991SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
51468bcb0991SDimitry Andric            "Intrinsic does not support vectors", &FPI);
51478bcb0991SDimitry Andric     break;
51488bcb0991SDimitry Andric   }
51498bcb0991SDimitry Andric 
5150480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmp:
5151480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmps: {
5152480093f4SDimitry Andric     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
5153480093f4SDimitry Andric     Assert(CmpInst::isFPPredicate(Pred),
5154480093f4SDimitry Andric            "invalid predicate for constrained FP comparison intrinsic", &FPI);
51550b57cec5SDimitry Andric     break;
5156480093f4SDimitry Andric   }
51570b57cec5SDimitry Andric 
51588bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
51598bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
51608bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
51618bcb0991SDimitry Andric     uint64_t NumSrcElem = 0;
51628bcb0991SDimitry Andric     Assert(Operand->getType()->isFPOrFPVectorTy(),
51638bcb0991SDimitry Andric            "Intrinsic first argument must be floating point", &FPI);
51648bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
51658bcb0991SDimitry Andric       NumSrcElem = OperandT->getNumElements();
51668bcb0991SDimitry Andric     }
51678bcb0991SDimitry Andric 
51688bcb0991SDimitry Andric     Operand = &FPI;
51698bcb0991SDimitry Andric     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
51708bcb0991SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
51718bcb0991SDimitry Andric     Assert(Operand->getType()->isIntOrIntVectorTy(),
51728bcb0991SDimitry Andric            "Intrinsic result must be an integer", &FPI);
51738bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
51748bcb0991SDimitry Andric       Assert(NumSrcElem == OperandT->getNumElements(),
51758bcb0991SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
51768bcb0991SDimitry Andric              &FPI);
51778bcb0991SDimitry Andric     }
51788bcb0991SDimitry Andric   }
51798bcb0991SDimitry Andric     break;
51808bcb0991SDimitry Andric 
5181480093f4SDimitry Andric   case Intrinsic::experimental_constrained_sitofp:
5182480093f4SDimitry Andric   case Intrinsic::experimental_constrained_uitofp: {
5183480093f4SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
5184480093f4SDimitry Andric     uint64_t NumSrcElem = 0;
5185480093f4SDimitry Andric     Assert(Operand->getType()->isIntOrIntVectorTy(),
5186480093f4SDimitry Andric            "Intrinsic first argument must be integer", &FPI);
5187480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5188480093f4SDimitry Andric       NumSrcElem = OperandT->getNumElements();
5189480093f4SDimitry Andric     }
5190480093f4SDimitry Andric 
5191480093f4SDimitry Andric     Operand = &FPI;
5192480093f4SDimitry Andric     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5193480093f4SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
5194480093f4SDimitry Andric     Assert(Operand->getType()->isFPOrFPVectorTy(),
5195480093f4SDimitry Andric            "Intrinsic result must be a floating point", &FPI);
5196480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5197480093f4SDimitry Andric       Assert(NumSrcElem == OperandT->getNumElements(),
5198480093f4SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
5199480093f4SDimitry Andric              &FPI);
5200480093f4SDimitry Andric     }
5201480093f4SDimitry Andric   } break;
5202480093f4SDimitry Andric 
52030b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
52040b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
52050b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
52060b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
52070b57cec5SDimitry Andric     Value *Result = &FPI;
52080b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
52090b57cec5SDimitry Andric     Assert(OperandTy->isFPOrFPVectorTy(),
52100b57cec5SDimitry Andric            "Intrinsic first argument must be FP or FP vector", &FPI);
52110b57cec5SDimitry Andric     Assert(ResultTy->isFPOrFPVectorTy(),
52120b57cec5SDimitry Andric            "Intrinsic result must be FP or FP vector", &FPI);
52130b57cec5SDimitry Andric     Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
52140b57cec5SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
52150b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
52160b57cec5SDimitry Andric       auto *OperandVecTy = cast<VectorType>(OperandTy);
52170b57cec5SDimitry Andric       auto *ResultVecTy = cast<VectorType>(ResultTy);
52180b57cec5SDimitry Andric       Assert(OperandVecTy->getNumElements() == ResultVecTy->getNumElements(),
52190b57cec5SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
52200b57cec5SDimitry Andric              &FPI);
52210b57cec5SDimitry Andric     }
52220b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
52230b57cec5SDimitry Andric       Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
52240b57cec5SDimitry Andric              "Intrinsic first argument's type must be larger than result type",
52250b57cec5SDimitry Andric              &FPI);
52260b57cec5SDimitry Andric     } else {
52270b57cec5SDimitry Andric       Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
52280b57cec5SDimitry Andric              "Intrinsic first argument's type must be smaller than result type",
52290b57cec5SDimitry Andric              &FPI);
52300b57cec5SDimitry Andric     }
52310b57cec5SDimitry Andric   }
52320b57cec5SDimitry Andric     break;
52330b57cec5SDimitry Andric 
52340b57cec5SDimitry Andric   default:
5235480093f4SDimitry Andric     break;
52360b57cec5SDimitry Andric   }
52370b57cec5SDimitry Andric 
52380b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
52390b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
52400b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
52410b57cec5SDimitry Andric   // argument type check is needed here.
52420b57cec5SDimitry Andric 
52430b57cec5SDimitry Andric   Assert(FPI.getExceptionBehavior().hasValue(),
52440b57cec5SDimitry Andric          "invalid exception behavior argument", &FPI);
52450b57cec5SDimitry Andric   if (HasRoundingMD) {
52460b57cec5SDimitry Andric     Assert(FPI.getRoundingMode().hasValue(),
52470b57cec5SDimitry Andric            "invalid rounding mode argument", &FPI);
52480b57cec5SDimitry Andric   }
52490b57cec5SDimitry Andric }
52500b57cec5SDimitry Andric 
52510b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
52520b57cec5SDimitry Andric   auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
52530b57cec5SDimitry Andric   AssertDI(isa<ValueAsMetadata>(MD) ||
52540b57cec5SDimitry Andric              (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
52550b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
52560b57cec5SDimitry Andric   AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
52570b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
52580b57cec5SDimitry Andric          DII.getRawVariable());
52590b57cec5SDimitry Andric   AssertDI(isa<DIExpression>(DII.getRawExpression()),
52600b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
52610b57cec5SDimitry Andric          DII.getRawExpression());
52620b57cec5SDimitry Andric 
52630b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
52640b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
52650b57cec5SDimitry Andric     if (!isa<DILocation>(N))
52660b57cec5SDimitry Andric       return;
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
52690b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
52700b57cec5SDimitry Andric 
52710b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
52720b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
52730b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
52740b57cec5SDimitry Andric   AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
52750b57cec5SDimitry Andric            &DII, BB, F);
52760b57cec5SDimitry Andric 
52770b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
52780b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
52790b57cec5SDimitry Andric   if (!VarSP || !LocSP)
52800b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
52810b57cec5SDimitry Andric 
52820b57cec5SDimitry Andric   AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
52830b57cec5SDimitry Andric                                " variable and !dbg attachment",
52840b57cec5SDimitry Andric            &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
52850b57cec5SDimitry Andric            Loc->getScope()->getSubprogram());
52860b57cec5SDimitry Andric 
52870b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
52880b57cec5SDimitry Andric   AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
52890b57cec5SDimitry Andric            Var->getRawType());
52900b57cec5SDimitry Andric   verifyFnArgs(DII);
52910b57cec5SDimitry Andric }
52920b57cec5SDimitry Andric 
52930b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
52940b57cec5SDimitry Andric   AssertDI(isa<DILabel>(DLI.getRawLabel()),
52950b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
52960b57cec5SDimitry Andric          DLI.getRawLabel());
52970b57cec5SDimitry Andric 
52980b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
52990b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
53000b57cec5SDimitry Andric     if (!isa<DILocation>(N))
53010b57cec5SDimitry Andric       return;
53020b57cec5SDimitry Andric 
53030b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
53040b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
53050b57cec5SDimitry Andric 
53060b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
53070b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
53080b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
53090b57cec5SDimitry Andric   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
53100b57cec5SDimitry Andric          &DLI, BB, F);
53110b57cec5SDimitry Andric 
53120b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
53130b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
53140b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
53150b57cec5SDimitry Andric     return;
53160b57cec5SDimitry Andric 
53170b57cec5SDimitry Andric   AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
53180b57cec5SDimitry Andric                              " label and !dbg attachment",
53190b57cec5SDimitry Andric            &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
53200b57cec5SDimitry Andric            Loc->getScope()->getSubprogram());
53210b57cec5SDimitry Andric }
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
53240b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
53250b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
53260b57cec5SDimitry Andric 
53270b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
53280b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
53290b57cec5SDimitry Andric     return;
53300b57cec5SDimitry Andric 
53310b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
53320b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
53330b57cec5SDimitry Andric   if (!Fragment)
53340b57cec5SDimitry Andric     return;
53350b57cec5SDimitry Andric 
53360b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
53370b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
53380b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
53390b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
53400b57cec5SDimitry Andric   // variable and this check fails.
53410b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
53420b57cec5SDimitry Andric   if (V->isArtificial())
53430b57cec5SDimitry Andric     return;
53440b57cec5SDimitry Andric 
53450b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
53460b57cec5SDimitry Andric }
53470b57cec5SDimitry Andric 
53480b57cec5SDimitry Andric template <typename ValueOrMetadata>
53490b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
53500b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
53510b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
53520b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
53530b57cec5SDimitry Andric   // elsewhere.
53540b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
53550b57cec5SDimitry Andric   if (!VarSize)
53560b57cec5SDimitry Andric     return;
53570b57cec5SDimitry Andric 
53580b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
53590b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
53600b57cec5SDimitry Andric   AssertDI(FragSize + FragOffset <= *VarSize,
53610b57cec5SDimitry Andric          "fragment is larger than or outside of variable", Desc, &V);
53620b57cec5SDimitry Andric   AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
53630b57cec5SDimitry Andric }
53640b57cec5SDimitry Andric 
53650b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
53660b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
53670b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
53680b57cec5SDimitry Andric   // contain inlined debug intrinsics.
53690b57cec5SDimitry Andric   if (!HasDebugInfo)
53700b57cec5SDimitry Andric     return;
53710b57cec5SDimitry Andric 
53720b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
53730b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
53740b57cec5SDimitry Andric     return;
53750b57cec5SDimitry Andric 
53760b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
53770b57cec5SDimitry Andric   AssertDI(Var, "dbg intrinsic without variable");
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
53800b57cec5SDimitry Andric   if (!ArgNo)
53810b57cec5SDimitry Andric     return;
53820b57cec5SDimitry Andric 
53830b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
53840b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
53850b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
53860b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
53870b57cec5SDimitry Andric 
53880b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
53890b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
53900b57cec5SDimitry Andric   AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
53910b57cec5SDimitry Andric            Prev, Var);
53920b57cec5SDimitry Andric }
53930b57cec5SDimitry Andric 
53948bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
53958bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
53968bcb0991SDimitry Andric 
53978bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
53988bcb0991SDimitry Andric   if (!E || !E->isValid())
53998bcb0991SDimitry Andric     return;
54008bcb0991SDimitry Andric 
54018bcb0991SDimitry Andric   AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
54028bcb0991SDimitry Andric }
54038bcb0991SDimitry Andric 
54040b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
54050b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
54060b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
54070b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
54080b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
54090b57cec5SDimitry Andric     return;
54100b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
54110b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
54120b57cec5SDimitry Andric   if (CUs)
54130b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
54140b57cec5SDimitry Andric   for (auto *CU : CUVisited)
54150b57cec5SDimitry Andric     AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
54160b57cec5SDimitry Andric   CUVisited.clear();
54170b57cec5SDimitry Andric }
54180b57cec5SDimitry Andric 
54190b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
54200b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
54210b57cec5SDimitry Andric     return;
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
54240b57cec5SDimitry Andric   for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
54250b57cec5SDimitry Andric     Assert(First->getCallingConv() == F->getCallingConv(),
54260b57cec5SDimitry Andric            "All llvm.experimental.deoptimize declarations must have the same "
54270b57cec5SDimitry Andric            "calling convention",
54280b57cec5SDimitry Andric            First, F);
54290b57cec5SDimitry Andric   }
54300b57cec5SDimitry Andric }
54310b57cec5SDimitry Andric 
54320b57cec5SDimitry Andric void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
54330b57cec5SDimitry Andric   bool HasSource = F.getSource().hasValue();
54340b57cec5SDimitry Andric   if (!HasSourceDebugInfo.count(&U))
54350b57cec5SDimitry Andric     HasSourceDebugInfo[&U] = HasSource;
54360b57cec5SDimitry Andric   AssertDI(HasSource == HasSourceDebugInfo[&U],
54370b57cec5SDimitry Andric            "inconsistent use of embedded source");
54380b57cec5SDimitry Andric }
54390b57cec5SDimitry Andric 
54400b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
54410b57cec5SDimitry Andric //  Implement the public interfaces to this file...
54420b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
54430b57cec5SDimitry Andric 
54440b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
54450b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
54460b57cec5SDimitry Andric 
54470b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
54480b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
54490b57cec5SDimitry Andric 
54500b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
54510b57cec5SDimitry Andric   // expect of a function called "verify".
54520b57cec5SDimitry Andric   return !V.verify(F);
54530b57cec5SDimitry Andric }
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
54560b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
54570b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
54580b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
54590b57cec5SDimitry Andric 
54600b57cec5SDimitry Andric   bool Broken = false;
54610b57cec5SDimitry Andric   for (const Function &F : M)
54620b57cec5SDimitry Andric     Broken |= !V.verify(F);
54630b57cec5SDimitry Andric 
54640b57cec5SDimitry Andric   Broken |= !V.verify();
54650b57cec5SDimitry Andric   if (BrokenDebugInfo)
54660b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
54670b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
54680b57cec5SDimitry Andric   // expect of a function called "verify".
54690b57cec5SDimitry Andric   return Broken;
54700b57cec5SDimitry Andric }
54710b57cec5SDimitry Andric 
54720b57cec5SDimitry Andric namespace {
54730b57cec5SDimitry Andric 
54740b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
54750b57cec5SDimitry Andric   static char ID;
54760b57cec5SDimitry Andric 
54770b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
54780b57cec5SDimitry Andric   bool FatalErrors = true;
54790b57cec5SDimitry Andric 
54800b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
54810b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
54820b57cec5SDimitry Andric   }
54830b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
54840b57cec5SDimitry Andric       : FunctionPass(ID),
54850b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
54860b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
54870b57cec5SDimitry Andric   }
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
54908bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
54910b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
54920b57cec5SDimitry Andric     return false;
54930b57cec5SDimitry Andric   }
54940b57cec5SDimitry Andric 
54950b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
54960b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
54970b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
54980b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
54990b57cec5SDimitry Andric     }
55000b57cec5SDimitry Andric     return false;
55010b57cec5SDimitry Andric   }
55020b57cec5SDimitry Andric 
55030b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
55040b57cec5SDimitry Andric     bool HasErrors = false;
55050b57cec5SDimitry Andric     for (Function &F : M)
55060b57cec5SDimitry Andric       if (F.isDeclaration())
55070b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
55080b57cec5SDimitry Andric 
55090b57cec5SDimitry Andric     HasErrors |= !V->verify();
55100b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
55110b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
55120b57cec5SDimitry Andric     return false;
55130b57cec5SDimitry Andric   }
55140b57cec5SDimitry Andric 
55150b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
55160b57cec5SDimitry Andric     AU.setPreservesAll();
55170b57cec5SDimitry Andric   }
55180b57cec5SDimitry Andric };
55190b57cec5SDimitry Andric 
55200b57cec5SDimitry Andric } // end anonymous namespace
55210b57cec5SDimitry Andric 
55220b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
55230b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
55240b57cec5SDimitry Andric   if (Diagnostic)
55250b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
55260b57cec5SDimitry Andric }
55270b57cec5SDimitry Andric 
55280b57cec5SDimitry Andric #define AssertTBAA(C, ...)                                                     \
55290b57cec5SDimitry Andric   do {                                                                         \
55300b57cec5SDimitry Andric     if (!(C)) {                                                                \
55310b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
55320b57cec5SDimitry Andric       return false;                                                            \
55330b57cec5SDimitry Andric     }                                                                          \
55340b57cec5SDimitry Andric   } while (false)
55350b57cec5SDimitry Andric 
55360b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
55370b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
55380b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
55390b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
55400b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
55410b57cec5SDimitry Andric                                  bool IsNewFormat) {
55420b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
55430b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
55440b57cec5SDimitry Andric     return {true, ~0u};
55450b57cec5SDimitry Andric   }
55460b57cec5SDimitry Andric 
55470b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
55480b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
55490b57cec5SDimitry Andric     return Itr->second;
55500b57cec5SDimitry Andric 
55510b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
55520b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
55530b57cec5SDimitry Andric   (void)InsertResult;
55540b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
55550b57cec5SDimitry Andric   return Result;
55560b57cec5SDimitry Andric }
55570b57cec5SDimitry Andric 
55580b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
55590b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
55600b57cec5SDimitry Andric                                      bool IsNewFormat) {
55610b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
55620b57cec5SDimitry Andric 
55630b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
55640b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
55650b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
55660b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
55670b57cec5SDimitry Andric                : InvalidNode;
55680b57cec5SDimitry Andric   }
55690b57cec5SDimitry Andric 
55700b57cec5SDimitry Andric   if (IsNewFormat) {
55710b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
55720b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
55730b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
55740b57cec5SDimitry Andric       return InvalidNode;
55750b57cec5SDimitry Andric     }
55760b57cec5SDimitry Andric   } else {
55770b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
55780b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
55790b57cec5SDimitry Andric                   BaseNode);
55800b57cec5SDimitry Andric       return InvalidNode;
55810b57cec5SDimitry Andric     }
55820b57cec5SDimitry Andric   }
55830b57cec5SDimitry Andric 
55840b57cec5SDimitry Andric   // Check the type size field.
55850b57cec5SDimitry Andric   if (IsNewFormat) {
55860b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
55870b57cec5SDimitry Andric         BaseNode->getOperand(1));
55880b57cec5SDimitry Andric     if (!TypeSizeNode) {
55890b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
55900b57cec5SDimitry Andric       return InvalidNode;
55910b57cec5SDimitry Andric     }
55920b57cec5SDimitry Andric   }
55930b57cec5SDimitry Andric 
55940b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
55950b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
55960b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
55970b57cec5SDimitry Andric                 BaseNode);
55980b57cec5SDimitry Andric     return InvalidNode;
55990b57cec5SDimitry Andric   }
56000b57cec5SDimitry Andric 
56010b57cec5SDimitry Andric   bool Failed = false;
56020b57cec5SDimitry Andric 
56030b57cec5SDimitry Andric   Optional<APInt> PrevOffset;
56040b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
56050b57cec5SDimitry Andric 
56060b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
56070b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
56080b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
56090b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
56100b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
56110b57cec5SDimitry Andric            Idx += NumOpsPerField) {
56120b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
56130b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
56140b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
56150b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
56160b57cec5SDimitry Andric       Failed = true;
56170b57cec5SDimitry Andric       continue;
56180b57cec5SDimitry Andric     }
56190b57cec5SDimitry Andric 
56200b57cec5SDimitry Andric     auto *OffsetEntryCI =
56210b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
56220b57cec5SDimitry Andric     if (!OffsetEntryCI) {
56230b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
56240b57cec5SDimitry Andric       Failed = true;
56250b57cec5SDimitry Andric       continue;
56260b57cec5SDimitry Andric     }
56270b57cec5SDimitry Andric 
56280b57cec5SDimitry Andric     if (BitWidth == ~0u)
56290b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
56300b57cec5SDimitry Andric 
56310b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
56320b57cec5SDimitry Andric       CheckFailed(
56330b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
56340b57cec5SDimitry Andric           BaseNode);
56350b57cec5SDimitry Andric       Failed = true;
56360b57cec5SDimitry Andric       continue;
56370b57cec5SDimitry Andric     }
56380b57cec5SDimitry Andric 
56390b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
56400b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
56410b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
56420b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
56430b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
56440b57cec5SDimitry Andric     bool IsAscending =
56450b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
56460b57cec5SDimitry Andric 
56470b57cec5SDimitry Andric     if (!IsAscending) {
56480b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
56490b57cec5SDimitry Andric       Failed = true;
56500b57cec5SDimitry Andric     }
56510b57cec5SDimitry Andric 
56520b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
56530b57cec5SDimitry Andric 
56540b57cec5SDimitry Andric     if (IsNewFormat) {
56550b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
56560b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
56570b57cec5SDimitry Andric       if (!MemberSizeNode) {
56580b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
56590b57cec5SDimitry Andric         Failed = true;
56600b57cec5SDimitry Andric         continue;
56610b57cec5SDimitry Andric       }
56620b57cec5SDimitry Andric     }
56630b57cec5SDimitry Andric   }
56640b57cec5SDimitry Andric 
56650b57cec5SDimitry Andric   return Failed ? InvalidNode
56660b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
56670b57cec5SDimitry Andric }
56680b57cec5SDimitry Andric 
56690b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
56700b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
56710b57cec5SDimitry Andric }
56720b57cec5SDimitry Andric 
56730b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
56740b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
56750b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
56760b57cec5SDimitry Andric     return false;
56770b57cec5SDimitry Andric 
56780b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
56790b57cec5SDimitry Andric     return false;
56800b57cec5SDimitry Andric 
56810b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
56820b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
56830b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
56840b57cec5SDimitry Andric       return false;
56850b57cec5SDimitry Andric   }
56860b57cec5SDimitry Andric 
56870b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
56880b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
56890b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
56900b57cec5SDimitry Andric }
56910b57cec5SDimitry Andric 
56920b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
56930b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
56940b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
56950b57cec5SDimitry Andric     return ResultIt->second;
56960b57cec5SDimitry Andric 
56970b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
56980b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
56990b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
57000b57cec5SDimitry Andric   (void)InsertResult;
57010b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
57020b57cec5SDimitry Andric 
57030b57cec5SDimitry Andric   return Result;
57040b57cec5SDimitry Andric }
57050b57cec5SDimitry Andric 
57060b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
57070b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
57080b57cec5SDimitry Andric ///
57090b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
57100b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
57110b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
57120b57cec5SDimitry Andric                                                    APInt &Offset,
57130b57cec5SDimitry Andric                                                    bool IsNewFormat) {
57140b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
57150b57cec5SDimitry Andric 
57160b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
57170b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
57180b57cec5SDimitry Andric   // to Assert that.
57190b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
57200b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
57210b57cec5SDimitry Andric 
57220b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
57230b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
57240b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
57250b57cec5SDimitry Andric            Idx += NumOpsPerField) {
57260b57cec5SDimitry Andric     auto *OffsetEntryCI =
57270b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
57280b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
57290b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
57300b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
57310b57cec5SDimitry Andric                     BaseNode, &Offset);
57320b57cec5SDimitry Andric         return nullptr;
57330b57cec5SDimitry Andric       }
57340b57cec5SDimitry Andric 
57350b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
57360b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
57370b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
57380b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
57390b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
57400b57cec5SDimitry Andric     }
57410b57cec5SDimitry Andric   }
57420b57cec5SDimitry Andric 
57430b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
57440b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
57450b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
57460b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
57470b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
57480b57cec5SDimitry Andric }
57490b57cec5SDimitry Andric 
57500b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
57510b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
57520b57cec5SDimitry Andric     return false;
57530b57cec5SDimitry Andric 
57540b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
57550b57cec5SDimitry Andric   // its first operand.
57560b57cec5SDimitry Andric   MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0));
57570b57cec5SDimitry Andric   if (!Parent)
57580b57cec5SDimitry Andric     return false;
57590b57cec5SDimitry Andric 
57600b57cec5SDimitry Andric   return true;
57610b57cec5SDimitry Andric }
57620b57cec5SDimitry Andric 
57630b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
57640b57cec5SDimitry Andric   AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
57650b57cec5SDimitry Andric                  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
57660b57cec5SDimitry Andric                  isa<AtomicCmpXchgInst>(I),
57670b57cec5SDimitry Andric              "This instruction shall not have a TBAA access tag!", &I);
57680b57cec5SDimitry Andric 
57690b57cec5SDimitry Andric   bool IsStructPathTBAA =
57700b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
57710b57cec5SDimitry Andric 
57720b57cec5SDimitry Andric   AssertTBAA(
57730b57cec5SDimitry Andric       IsStructPathTBAA,
57740b57cec5SDimitry Andric       "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
57750b57cec5SDimitry Andric 
57760b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
57770b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
57780b57cec5SDimitry Andric 
57790b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
57800b57cec5SDimitry Andric 
57810b57cec5SDimitry Andric   if (IsNewFormat) {
57820b57cec5SDimitry Andric     AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
57830b57cec5SDimitry Andric                "Access tag metadata must have either 4 or 5 operands", &I, MD);
57840b57cec5SDimitry Andric   } else {
57850b57cec5SDimitry Andric     AssertTBAA(MD->getNumOperands() < 5,
57860b57cec5SDimitry Andric                "Struct tag metadata must have either 3 or 4 operands", &I, MD);
57870b57cec5SDimitry Andric   }
57880b57cec5SDimitry Andric 
57890b57cec5SDimitry Andric   // Check the access size field.
57900b57cec5SDimitry Andric   if (IsNewFormat) {
57910b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
57920b57cec5SDimitry Andric         MD->getOperand(3));
57930b57cec5SDimitry Andric     AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
57940b57cec5SDimitry Andric   }
57950b57cec5SDimitry Andric 
57960b57cec5SDimitry Andric   // Check the immutability flag.
57970b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
57980b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
57990b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
58000b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
58010b57cec5SDimitry Andric     AssertTBAA(IsImmutableCI,
58020b57cec5SDimitry Andric                "Immutability tag on struct tag metadata must be a constant",
58030b57cec5SDimitry Andric                &I, MD);
58040b57cec5SDimitry Andric     AssertTBAA(
58050b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
58060b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
58070b57cec5SDimitry Andric         &I, MD);
58080b57cec5SDimitry Andric   }
58090b57cec5SDimitry Andric 
58100b57cec5SDimitry Andric   AssertTBAA(BaseNode && AccessType,
58110b57cec5SDimitry Andric              "Malformed struct tag metadata: base and access-type "
58120b57cec5SDimitry Andric              "should be non-null and point to Metadata nodes",
58130b57cec5SDimitry Andric              &I, MD, BaseNode, AccessType);
58140b57cec5SDimitry Andric 
58150b57cec5SDimitry Andric   if (!IsNewFormat) {
58160b57cec5SDimitry Andric     AssertTBAA(isValidScalarTBAANode(AccessType),
58170b57cec5SDimitry Andric                "Access type node must be a valid scalar type", &I, MD,
58180b57cec5SDimitry Andric                AccessType);
58190b57cec5SDimitry Andric   }
58200b57cec5SDimitry Andric 
58210b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
58220b57cec5SDimitry Andric   AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
58230b57cec5SDimitry Andric 
58240b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
58250b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
58260b57cec5SDimitry Andric 
58270b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
58280b57cec5SDimitry Andric 
58290b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
58300b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
58310b57cec5SDimitry Andric                                                IsNewFormat)) {
58320b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
58330b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
58340b57cec5SDimitry Andric       return false;
58350b57cec5SDimitry Andric     }
58360b57cec5SDimitry Andric 
58370b57cec5SDimitry Andric     bool Invalid;
58380b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
58390b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
58400b57cec5SDimitry Andric                                                              IsNewFormat);
58410b57cec5SDimitry Andric 
58420b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
58430b57cec5SDimitry Andric     // errors we wanted to print.
58440b57cec5SDimitry Andric     if (Invalid)
58450b57cec5SDimitry Andric       return false;
58460b57cec5SDimitry Andric 
58470b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
58480b57cec5SDimitry Andric 
58490b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
58500b57cec5SDimitry Andric       AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
58510b57cec5SDimitry Andric                  &I, MD, &Offset);
58520b57cec5SDimitry Andric 
58530b57cec5SDimitry Andric     AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
58540b57cec5SDimitry Andric                    (BaseNodeBitWidth == 0 && Offset == 0) ||
58550b57cec5SDimitry Andric                    (IsNewFormat && BaseNodeBitWidth == ~0u),
58560b57cec5SDimitry Andric                "Access bit-width not the same as description bit-width", &I, MD,
58570b57cec5SDimitry Andric                BaseNodeBitWidth, Offset.getBitWidth());
58580b57cec5SDimitry Andric 
58590b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
58600b57cec5SDimitry Andric       break;
58610b57cec5SDimitry Andric   }
58620b57cec5SDimitry Andric 
58630b57cec5SDimitry Andric   AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
58640b57cec5SDimitry Andric              &I, MD);
58650b57cec5SDimitry Andric   return true;
58660b57cec5SDimitry Andric }
58670b57cec5SDimitry Andric 
58680b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
58690b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
58700b57cec5SDimitry Andric 
58710b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
58720b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
58730b57cec5SDimitry Andric }
58740b57cec5SDimitry Andric 
58750b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
58760b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
58770b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
58780b57cec5SDimitry Andric   Result Res;
58790b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
58800b57cec5SDimitry Andric   return Res;
58810b57cec5SDimitry Andric }
58820b57cec5SDimitry Andric 
58830b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
58840b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
58850b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
58860b57cec5SDimitry Andric }
58870b57cec5SDimitry Andric 
58880b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
58890b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
58900b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
58910b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
58920b57cec5SDimitry Andric 
58930b57cec5SDimitry Andric   return PreservedAnalyses::all();
58940b57cec5SDimitry Andric }
58950b57cec5SDimitry Andric 
58960b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
58970b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
58980b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
58990b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
59000b57cec5SDimitry Andric 
59010b57cec5SDimitry Andric   return PreservedAnalyses::all();
59020b57cec5SDimitry Andric }
5903