xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
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"
890b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
900b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
910b57cec5SDimitry Andric #include "llvm/IR/Module.h"
920b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
930b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
940b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
950b57cec5SDimitry Andric #include "llvm/IR/Type.h"
960b57cec5SDimitry Andric #include "llvm/IR/Use.h"
970b57cec5SDimitry Andric #include "llvm/IR/User.h"
980b57cec5SDimitry Andric #include "llvm/IR/Value.h"
990b57cec5SDimitry Andric #include "llvm/Pass.h"
1000b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1010b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1020b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1030b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
1040b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1050b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
1060b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1070b57cec5SDimitry Andric #include <algorithm>
1080b57cec5SDimitry Andric #include <cassert>
1090b57cec5SDimitry Andric #include <cstdint>
1100b57cec5SDimitry Andric #include <memory>
1110b57cec5SDimitry Andric #include <string>
1120b57cec5SDimitry Andric #include <utility>
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric using namespace llvm;
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric namespace llvm {
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric struct VerifierSupport {
1190b57cec5SDimitry Andric   raw_ostream *OS;
1200b57cec5SDimitry Andric   const Module &M;
1210b57cec5SDimitry Andric   ModuleSlotTracker MST;
122*8bcb0991SDimitry Andric   Triple TT;
1230b57cec5SDimitry Andric   const DataLayout &DL;
1240b57cec5SDimitry Andric   LLVMContext &Context;
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1270b57cec5SDimitry Andric   bool Broken = false;
1280b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1290b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1300b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1310b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
134*8bcb0991SDimitry Andric       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
135*8bcb0991SDimitry Andric         Context(M.getContext()) {}
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric private:
1380b57cec5SDimitry Andric   void Write(const Module *M) {
1390b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1400b57cec5SDimitry Andric   }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   void Write(const Value *V) {
1430b57cec5SDimitry Andric     if (V)
1440b57cec5SDimitry Andric       Write(*V);
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   void Write(const Value &V) {
1480b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1490b57cec5SDimitry Andric       V.print(*OS, MST);
1500b57cec5SDimitry Andric       *OS << '\n';
1510b57cec5SDimitry Andric     } else {
1520b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1530b57cec5SDimitry Andric       *OS << '\n';
1540b57cec5SDimitry Andric     }
1550b57cec5SDimitry Andric   }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   void Write(const Metadata *MD) {
1580b57cec5SDimitry Andric     if (!MD)
1590b57cec5SDimitry Andric       return;
1600b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
1610b57cec5SDimitry Andric     *OS << '\n';
1620b57cec5SDimitry Andric   }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
1650b57cec5SDimitry Andric     Write(MD.get());
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
1690b57cec5SDimitry Andric     if (!NMD)
1700b57cec5SDimitry Andric       return;
1710b57cec5SDimitry Andric     NMD->print(*OS, MST);
1720b57cec5SDimitry Andric     *OS << '\n';
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   void Write(Type *T) {
1760b57cec5SDimitry Andric     if (!T)
1770b57cec5SDimitry Andric       return;
1780b57cec5SDimitry Andric     *OS << ' ' << *T;
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   void Write(const Comdat *C) {
1820b57cec5SDimitry Andric     if (!C)
1830b57cec5SDimitry Andric       return;
1840b57cec5SDimitry Andric     *OS << *C;
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   void Write(const APInt *AI) {
1880b57cec5SDimitry Andric     if (!AI)
1890b57cec5SDimitry Andric       return;
1900b57cec5SDimitry Andric     *OS << *AI << '\n';
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
1960b57cec5SDimitry Andric     for (const T &V : Vs)
1970b57cec5SDimitry Andric       Write(V);
1980b57cec5SDimitry Andric   }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2010b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2020b57cec5SDimitry Andric     Write(V1);
2030b57cec5SDimitry Andric     WriteTs(Vs...);
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric public:
2090b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2100b57cec5SDimitry Andric   ///
2110b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2120b57cec5SDimitry Andric   /// something is not correct.
2130b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2140b57cec5SDimitry Andric     if (OS)
2150b57cec5SDimitry Andric       *OS << Message << '\n';
2160b57cec5SDimitry Andric     Broken = true;
2170b57cec5SDimitry Andric   }
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric   /// A check failed (with values to print).
2200b57cec5SDimitry Andric   ///
2210b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2220b57cec5SDimitry Andric   /// breakpoint on.
2230b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2240b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2250b57cec5SDimitry Andric     CheckFailed(Message);
2260b57cec5SDimitry Andric     if (OS)
2270b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2280b57cec5SDimitry Andric   }
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   /// A debug info check failed.
2310b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
2320b57cec5SDimitry Andric     if (OS)
2330b57cec5SDimitry Andric       *OS << Message << '\n';
2340b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
2350b57cec5SDimitry Andric     BrokenDebugInfo = true;
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
2390b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2400b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
2410b57cec5SDimitry Andric                             const Ts &... Vs) {
2420b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
2430b57cec5SDimitry Andric     if (OS)
2440b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2450b57cec5SDimitry Andric   }
2460b57cec5SDimitry Andric };
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric } // namespace llvm
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric namespace {
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
2530b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   DominatorTree DT;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
2580b57cec5SDimitry Andric   /// instructions we have seen so far.
2590b57cec5SDimitry Andric   ///
2600b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
2610b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
2620b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
2650b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
2680b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
2710b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   /// The result type for a landingpad.
2740b57cec5SDimitry Andric   Type *LandingPadResultTy;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
2770b57cec5SDimitry Andric   /// already.
2780b57cec5SDimitry Andric   bool SawFrameEscape;
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
2810b57cec5SDimitry Andric   bool HasDebugInfo = false;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   /// Whether source was present on the first DIFile encountered in each CU.
2840b57cec5SDimitry Andric   DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
2870b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
2880b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
2910b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
2920b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
2950b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
2980b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3010b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3020b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3030b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3040b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3070b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric public:
3140b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3150b57cec5SDimitry Andric                     const Module &M)
3160b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3170b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3180b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   bool verify(const Function &F) {
3240b57cec5SDimitry Andric     assert(F.getParent() == &M &&
3250b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
3280b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
3290b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
3300b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
3310b57cec5SDimitry Andric     // this code outside of a pass manager.
3320b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
3330b57cec5SDimitry Andric     if (!F.empty())
3340b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
3370b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
3380b57cec5SDimitry Andric         continue;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric       if (OS) {
3410b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
3420b57cec5SDimitry Andric             << "' does not have terminator!\n";
3430b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
3440b57cec5SDimitry Andric         *OS << "\n";
3450b57cec5SDimitry Andric       }
3460b57cec5SDimitry Andric       return false;
3470b57cec5SDimitry Andric     }
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric     Broken = false;
3500b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
3510b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
3520b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
3530b57cec5SDimitry Andric     InstsInThisBlock.clear();
3540b57cec5SDimitry Andric     DebugFnArgs.clear();
3550b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
3560b57cec5SDimitry Andric     SawFrameEscape = false;
3570b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric     return !Broken;
3600b57cec5SDimitry Andric   }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
3630b57cec5SDimitry Andric   bool verify() {
3640b57cec5SDimitry Andric     Broken = false;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
3670b57cec5SDimitry Andric     for (const Function &F : M)
3680b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
3690b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
3720b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
3730b57cec5SDimitry Andric     verifyFrameRecoverIndices();
3740b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
3750b57cec5SDimitry Andric       visitGlobalVariable(GV);
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
3780b57cec5SDimitry Andric       visitGlobalAlias(GA);
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
3810b57cec5SDimitry Andric       visitNamedMDNode(NMD);
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
3840b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     visitModuleFlags(M);
3870b57cec5SDimitry Andric     visitModuleIdents(M);
3880b57cec5SDimitry Andric     visitModuleCommandLines(M);
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     verifyCompileUnits();
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
3930b57cec5SDimitry Andric     DISubprogramAttachments.clear();
3940b57cec5SDimitry Andric     return !Broken;
3950b57cec5SDimitry Andric   }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric private:
3980b57cec5SDimitry Andric   // Verification methods...
3990b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4000b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4010b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
4020b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
4030b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
4040b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
4050b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
4060b57cec5SDimitry Andric   void visitMDNode(const MDNode &MD);
4070b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
4080b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
4090b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
4100b57cec5SDimitry Andric   void visitModuleIdents(const Module &M);
4110b57cec5SDimitry Andric   void visitModuleCommandLines(const Module &M);
4120b57cec5SDimitry Andric   void visitModuleFlags(const Module &M);
4130b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
4140b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
4150b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
4160b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
4170b57cec5SDimitry Andric   void visitFunction(const Function &F);
4180b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
4190b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
4200b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
421*8bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
4240b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
4250b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
4260b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
4270b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
4280b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
4290b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   // InstVisitor overrides...
4340b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
4350b57cec5SDimitry Andric   void visit(Instruction &I);
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
4380b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
4390b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
4400b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
4410b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
4420b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
4430b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
4440b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
4450b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
4460b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
4470b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
4480b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
4490b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
4500b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
4510b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
4520b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
4530b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
4540b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
4550b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
4560b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
4570b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
4580b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
4590b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
4600b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
4610b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
4620b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
4630b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
4640b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
4650b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
4660b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
4670b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
4680b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
4690b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
4700b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
4710b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
4720b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
4730b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
4740b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
4750b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
4760b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
4770b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
4780b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
4790b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
4800b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
4810b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
4820b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
4830b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
4840b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
4850b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
4860b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
4870b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
4880b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
4890b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
4900b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
4910b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
4920b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
4930b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
4940b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
4970b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
4980b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
4990b57cec5SDimitry Andric   bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
5000b57cec5SDimitry Andric                         unsigned ArgNo, std::string &Suffix);
5010b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
5020b57cec5SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
5030b57cec5SDimitry Andric                             const Value *V);
5040b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
5050b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
5060b57cec5SDimitry Andric                            const Value *V, bool IsIntrinsic);
5070b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
5100b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
5110b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
5120b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
5130b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
5160b57cec5SDimitry Andric   template <typename ValueOrMetadata>
5170b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
5180b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
5190b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
5200b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
521*8bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   /// Module-level debug info verification...
5240b57cec5SDimitry Andric   void verifyCompileUnits();
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
5270b57cec5SDimitry Andric   /// declarations share the same calling convention.
5280b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   /// Verify all-or-nothing property of DIFile source attribute within a CU.
5310b57cec5SDimitry Andric   void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
5320b57cec5SDimitry Andric };
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric } // end anonymous namespace
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
5370b57cec5SDimitry Andric #define Assert(C, ...) \
5380b57cec5SDimitry Andric   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
5410b57cec5SDimitry Andric /// an error message.
5420b57cec5SDimitry Andric #define AssertDI(C, ...) \
5430b57cec5SDimitry Andric   do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
5460b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
5470b57cec5SDimitry Andric     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
5480b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
5490b57cec5SDimitry Andric }
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric // Helper to recursively iterate over indirect users. By
5520b57cec5SDimitry Andric // returning false, the callback can ask to stop recursing
5530b57cec5SDimitry Andric // further.
5540b57cec5SDimitry Andric static void forEachUser(const Value *User,
5550b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
5560b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
5570b57cec5SDimitry Andric   if (!Visited.insert(User).second)
5580b57cec5SDimitry Andric     return;
5590b57cec5SDimitry Andric   for (const Value *TheNextUser : User->materialized_users())
5600b57cec5SDimitry Andric     if (Callback(TheNextUser))
5610b57cec5SDimitry Andric       forEachUser(TheNextUser, Visited, Callback);
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
5650b57cec5SDimitry Andric   Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
5660b57cec5SDimitry Andric          "Global is external, but doesn't have external or weak linkage!", &GV);
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   Assert(GV.getAlignment() <= Value::MaximumAlignment,
5690b57cec5SDimitry Andric          "huge alignment values are unsupported", &GV);
5700b57cec5SDimitry Andric   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
5710b57cec5SDimitry Andric          "Only global variables can have appending linkage!", &GV);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
5740b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
5750b57cec5SDimitry Andric     Assert(GVar && GVar->getValueType()->isArrayTy(),
5760b57cec5SDimitry Andric            "Only global arrays can have appending linkage!", GVar);
5770b57cec5SDimitry Andric   }
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
5800b57cec5SDimitry Andric     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
5830b57cec5SDimitry Andric     Assert(!GV.isDSOLocal(),
5840b57cec5SDimitry Andric            "GlobalValue with DLLImport Storage is dso_local!", &GV);
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric     Assert((GV.isDeclaration() && GV.hasExternalLinkage()) ||
5870b57cec5SDimitry Andric                GV.hasAvailableExternallyLinkage(),
5880b57cec5SDimitry Andric            "Global is marked as dllimport, but not external", &GV);
5890b57cec5SDimitry Andric   }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   if (GV.hasLocalLinkage())
5920b57cec5SDimitry Andric     Assert(GV.isDSOLocal(),
5930b57cec5SDimitry Andric            "GlobalValue with private or internal linkage must be dso_local!",
5940b57cec5SDimitry Andric            &GV);
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   if (!GV.hasDefaultVisibility() && !GV.hasExternalWeakLinkage())
5970b57cec5SDimitry Andric     Assert(GV.isDSOLocal(),
5980b57cec5SDimitry Andric            "GlobalValue with non default visibility must be dso_local!", &GV);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
6010b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
6020b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
6030b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
6040b57cec5SDimitry Andric                     I);
6050b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
6060b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
6070b57cec5SDimitry Andric                     I->getParent()->getParent(),
6080b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
6090b57cec5SDimitry Andric       return false;
6100b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
6110b57cec5SDimitry Andric       if (F->getParent() != &M)
6120b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
6130b57cec5SDimitry Andric                     F, F->getParent());
6140b57cec5SDimitry Andric       return false;
6150b57cec5SDimitry Andric     }
6160b57cec5SDimitry Andric     return true;
6170b57cec5SDimitry Andric   });
6180b57cec5SDimitry Andric }
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
6210b57cec5SDimitry Andric   if (GV.hasInitializer()) {
6220b57cec5SDimitry Andric     Assert(GV.getInitializer()->getType() == GV.getValueType(),
6230b57cec5SDimitry Andric            "Global variable initializer type does not match global "
6240b57cec5SDimitry Andric            "variable type!",
6250b57cec5SDimitry Andric            &GV);
6260b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
6270b57cec5SDimitry Andric     // cannot be constant.
6280b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
6290b57cec5SDimitry Andric       Assert(GV.getInitializer()->isNullValue(),
6300b57cec5SDimitry Andric              "'common' global must have a zero initializer!", &GV);
6310b57cec5SDimitry Andric       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
6320b57cec5SDimitry Andric              &GV);
6330b57cec5SDimitry Andric       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
6340b57cec5SDimitry Andric     }
6350b57cec5SDimitry Andric   }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
6380b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
6390b57cec5SDimitry Andric     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
6400b57cec5SDimitry Andric            "invalid linkage for intrinsic global variable", &GV);
6410b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
6420b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
6430b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
6440b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
6450b57cec5SDimitry Andric       PointerType *FuncPtrTy =
6460b57cec5SDimitry Andric           FunctionType::get(Type::getVoidTy(Context), false)->
6470b57cec5SDimitry Andric           getPointerTo(DL.getProgramAddressSpace());
6480b57cec5SDimitry Andric       Assert(STy &&
6490b57cec5SDimitry Andric                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
6500b57cec5SDimitry Andric                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
6510b57cec5SDimitry Andric                  STy->getTypeAtIndex(1) == FuncPtrTy,
6520b57cec5SDimitry Andric              "wrong type for intrinsic global variable", &GV);
6530b57cec5SDimitry Andric       Assert(STy->getNumElements() == 3,
6540b57cec5SDimitry Andric              "the third field of the element type is mandatory, "
6550b57cec5SDimitry Andric              "specify i8* null to migrate from the obsoleted 2-field form");
6560b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
6570b57cec5SDimitry Andric       Assert(ETy->isPointerTy() &&
6580b57cec5SDimitry Andric                  cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
6590b57cec5SDimitry Andric              "wrong type for intrinsic global variable", &GV);
6600b57cec5SDimitry Andric     }
6610b57cec5SDimitry Andric   }
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
6640b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
6650b57cec5SDimitry Andric     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
6660b57cec5SDimitry Andric            "invalid linkage for intrinsic global variable", &GV);
6670b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
6680b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
6690b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
6700b57cec5SDimitry Andric       Assert(PTy, "wrong type for intrinsic global variable", &GV);
6710b57cec5SDimitry Andric       if (GV.hasInitializer()) {
6720b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
6730b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
6740b57cec5SDimitry Andric         Assert(InitArray, "wrong initalizer for intrinsic global variable",
6750b57cec5SDimitry Andric                Init);
6760b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
677*8bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
6780b57cec5SDimitry Andric           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
6790b57cec5SDimitry Andric                      isa<GlobalAlias>(V),
6800b57cec5SDimitry Andric                  "invalid llvm.used member", V);
6810b57cec5SDimitry Andric           Assert(V->hasName(), "members of llvm.used must be named", V);
6820b57cec5SDimitry Andric         }
6830b57cec5SDimitry Andric       }
6840b57cec5SDimitry Andric     }
6850b57cec5SDimitry Andric   }
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   // Visit any debug info attachments.
6880b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
6890b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
6900b57cec5SDimitry Andric   for (auto *MD : MDs) {
6910b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
6920b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
6930b57cec5SDimitry Andric     else
6940b57cec5SDimitry Andric       AssertDI(false, "!dbg attachment of global variable must be a "
6950b57cec5SDimitry Andric                       "DIGlobalVariableExpression");
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
6990b57cec5SDimitry Andric   // the runtime size. If the global is a struct or an array containing
7000b57cec5SDimitry Andric   // scalable vectors, that will be caught by the isValidElementType methods
7010b57cec5SDimitry Andric   // in StructType or ArrayType instead.
7020b57cec5SDimitry Andric   if (auto *VTy = dyn_cast<VectorType>(GV.getValueType()))
7030b57cec5SDimitry Andric     Assert(!VTy->isScalable(), "Globals cannot contain scalable vectors", &GV);
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
7060b57cec5SDimitry Andric     visitGlobalValue(GV);
7070b57cec5SDimitry Andric     return;
7080b57cec5SDimitry Andric   }
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
7110b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   visitGlobalValue(GV);
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
7170b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
7180b57cec5SDimitry Andric   Visited.insert(&GA);
7190b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
7200b57cec5SDimitry Andric }
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
7230b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
7240b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
7250b57cec5SDimitry Andric     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
7260b57cec5SDimitry Andric            &GA);
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
7290b57cec5SDimitry Andric       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric       Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
7320b57cec5SDimitry Andric              &GA);
7330b57cec5SDimitry Andric     } else {
7340b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
7350b57cec5SDimitry Andric       // Do not recurse into global initializers.
7360b57cec5SDimitry Andric       return;
7370b57cec5SDimitry Andric     }
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
7410b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
7440b57cec5SDimitry Andric     Value *V = &*U;
7450b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
7460b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
7470b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
7480b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
7490b57cec5SDimitry Andric   }
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
7530b57cec5SDimitry Andric   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
7540b57cec5SDimitry Andric          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
7550b57cec5SDimitry Andric          "weak_odr, or external linkage!",
7560b57cec5SDimitry Andric          &GA);
7570b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
7580b57cec5SDimitry Andric   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
7590b57cec5SDimitry Andric   Assert(GA.getType() == Aliasee->getType(),
7600b57cec5SDimitry Andric          "Alias and aliasee types should match!", &GA);
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
7630b57cec5SDimitry Andric          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric   visitGlobalValue(GA);
7680b57cec5SDimitry Andric }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
7710b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
7720b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
7730b57cec5SDimitry Andric   if (NMD.getName().startswith("llvm.dbg."))
7740b57cec5SDimitry Andric     AssertDI(NMD.getName() == "llvm.dbg.cu",
7750b57cec5SDimitry Andric              "unrecognized named metadata node in the llvm.dbg namespace",
7760b57cec5SDimitry Andric              &NMD);
7770b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
7780b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
7790b57cec5SDimitry Andric       AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric     if (!MD)
7820b57cec5SDimitry Andric       continue;
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     visitMDNode(*MD);
7850b57cec5SDimitry Andric   }
7860b57cec5SDimitry Andric }
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric void Verifier::visitMDNode(const MDNode &MD) {
7890b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
7900b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
7910b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
7920b57cec5SDimitry Andric     return;
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
7950b57cec5SDimitry Andric   default:
7960b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
7970b57cec5SDimitry Andric   case Metadata::MDTupleKind:
7980b57cec5SDimitry Andric     break;
7990b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
8000b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
8010b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
8020b57cec5SDimitry Andric     break;
8030b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
8040b57cec5SDimitry Andric   }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
8070b57cec5SDimitry Andric     if (!Op)
8080b57cec5SDimitry Andric       continue;
8090b57cec5SDimitry Andric     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
8100b57cec5SDimitry Andric            &MD, Op);
8110b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
8120b57cec5SDimitry Andric       visitMDNode(*N);
8130b57cec5SDimitry Andric       continue;
8140b57cec5SDimitry Andric     }
8150b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
8160b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
8170b57cec5SDimitry Andric       continue;
8180b57cec5SDimitry Andric     }
8190b57cec5SDimitry Andric   }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
8220b57cec5SDimitry Andric   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
8230b57cec5SDimitry Andric   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
8270b57cec5SDimitry Andric   Assert(MD.getValue(), "Expected valid value", &MD);
8280b57cec5SDimitry Andric   Assert(!MD.getValue()->getType()->isMetadataTy(),
8290b57cec5SDimitry Andric          "Unexpected metadata round-trip through values", &MD, MD.getValue());
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
8320b57cec5SDimitry Andric   if (!L)
8330b57cec5SDimitry Andric     return;
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric   Assert(F, "function-local metadata used outside a function", L);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
8380b57cec5SDimitry Andric   // function that we expect.
8390b57cec5SDimitry Andric   Function *ActualF = nullptr;
8400b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
8410b57cec5SDimitry Andric     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
8420b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
8430b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
8440b57cec5SDimitry Andric     ActualF = BB->getParent();
8450b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
8460b57cec5SDimitry Andric     ActualF = A->getParent();
8470b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   Assert(ActualF == F, "function-local metadata used in wrong function", L);
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
8530b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
8540b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
8550b57cec5SDimitry Andric     visitMDNode(*N);
8560b57cec5SDimitry Andric     return;
8570b57cec5SDimitry Andric   }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
8600b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
8610b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
8620b57cec5SDimitry Andric     return;
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
8650b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
8660b57cec5SDimitry Andric }
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
8690b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
8700b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
8730b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
8740b57cec5SDimitry Andric            "location requires a valid scope", &N, N.getRawScope());
8750b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
8760b57cec5SDimitry Andric     AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
8770b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
8780b57cec5SDimitry Andric     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
8790b57cec5SDimitry Andric }
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
8820b57cec5SDimitry Andric   AssertDI(N.getTag(), "invalid tag", &N);
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
8860b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
8870b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
8910b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
8920b57cec5SDimitry Andric   auto Count = N.getCount();
8930b57cec5SDimitry Andric   AssertDI(Count, "Count must either be a signed constant or a DIVariable",
8940b57cec5SDimitry Andric            &N);
8950b57cec5SDimitry Andric   AssertDI(!Count.is<ConstantInt*>() ||
8960b57cec5SDimitry Andric                Count.get<ConstantInt*>()->getSExtValue() >= -1,
8970b57cec5SDimitry Andric            "invalid subrange count", &N);
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
9010b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
9020b57cec5SDimitry Andric }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
9050b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
9060b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_unspecified_type,
9070b57cec5SDimitry Andric            "invalid tag", &N);
9080b57cec5SDimitry Andric   AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
9090b57cec5SDimitry Andric             "has conflicting flags", &N);
9100b57cec5SDimitry Andric }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
9130b57cec5SDimitry Andric   // Common scope checks.
9140b57cec5SDimitry Andric   visitDIScope(N);
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
9170b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_pointer_type ||
9180b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
9190b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_reference_type ||
9200b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
9210b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_const_type ||
9220b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_volatile_type ||
9230b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_restrict_type ||
9240b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_atomic_type ||
9250b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_member ||
9260b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_inheritance ||
9270b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_friend,
9280b57cec5SDimitry Andric            "invalid tag", &N);
9290b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
9300b57cec5SDimitry Andric     AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
9310b57cec5SDimitry Andric              N.getRawExtraData());
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
9350b57cec5SDimitry Andric   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
9360b57cec5SDimitry Andric            N.getRawBaseType());
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
9390b57cec5SDimitry Andric     AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
9400b57cec5SDimitry Andric                  N.getTag() == dwarf::DW_TAG_reference_type ||
9410b57cec5SDimitry Andric                  N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
9420b57cec5SDimitry Andric              "DWARF address space only applies to pointer or reference types",
9430b57cec5SDimitry Andric              &N);
9440b57cec5SDimitry Andric   }
9450b57cec5SDimitry Andric }
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric /// Detect mutually exclusive flags.
9480b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
9490b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
9500b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
9510b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
9520b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
9560b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
9570b57cec5SDimitry Andric   AssertDI(Params, "invalid template params", &N, &RawParams);
9580b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
9590b57cec5SDimitry Andric     AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
9600b57cec5SDimitry Andric              &N, Params, Op);
9610b57cec5SDimitry Andric   }
9620b57cec5SDimitry Andric }
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
9650b57cec5SDimitry Andric   // Common scope checks.
9660b57cec5SDimitry Andric   visitDIScope(N);
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
9690b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_structure_type ||
9700b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_union_type ||
9710b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_enumeration_type ||
9720b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_class_type ||
9730b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_variant_part,
9740b57cec5SDimitry Andric            "invalid tag", &N);
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
9770b57cec5SDimitry Andric   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
9780b57cec5SDimitry Andric            N.getRawBaseType());
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
9810b57cec5SDimitry Andric            "invalid composite elements", &N, N.getRawElements());
9820b57cec5SDimitry Andric   AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
9830b57cec5SDimitry Andric            N.getRawVTableHolder());
9840b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
9850b57cec5SDimitry Andric            "invalid reference flags", &N);
986*8bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
987*8bcb0991SDimitry Andric   AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,
988*8bcb0991SDimitry Andric            "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric   if (N.isVector()) {
9910b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
9920b57cec5SDimitry Andric     AssertDI(Elements.size() == 1 &&
9930b57cec5SDimitry Andric              Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
9940b57cec5SDimitry Andric              "invalid vector, expected one element of type subrange", &N);
9950b57cec5SDimitry Andric   }
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
9980b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_class_type ||
10010b57cec5SDimitry Andric       N.getTag() == dwarf::DW_TAG_union_type) {
10020b57cec5SDimitry Andric     AssertDI(N.getFile() && !N.getFile()->getFilename().empty(),
10030b57cec5SDimitry Andric              "class/union requires a filename", &N, N.getFile());
10040b57cec5SDimitry Andric   }
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
10070b57cec5SDimitry Andric     AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
10080b57cec5SDimitry Andric              "discriminator can only appear on variant part");
10090b57cec5SDimitry Andric   }
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
10130b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
10140b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
10150b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
10160b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
10170b57cec5SDimitry Andric       AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
10180b57cec5SDimitry Andric     }
10190b57cec5SDimitry Andric   }
10200b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
10210b57cec5SDimitry Andric            "invalid reference flags", &N);
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
10250b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
10260b57cec5SDimitry Andric   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
10270b57cec5SDimitry Andric   if (Checksum) {
10280b57cec5SDimitry Andric     AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
10290b57cec5SDimitry Andric              "invalid checksum kind", &N);
10300b57cec5SDimitry Andric     size_t Size;
10310b57cec5SDimitry Andric     switch (Checksum->Kind) {
10320b57cec5SDimitry Andric     case DIFile::CSK_MD5:
10330b57cec5SDimitry Andric       Size = 32;
10340b57cec5SDimitry Andric       break;
10350b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
10360b57cec5SDimitry Andric       Size = 40;
10370b57cec5SDimitry Andric       break;
10380b57cec5SDimitry Andric     }
10390b57cec5SDimitry Andric     AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
10400b57cec5SDimitry Andric     AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
10410b57cec5SDimitry Andric              "invalid checksum", &N);
10420b57cec5SDimitry Andric   }
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
10460b57cec5SDimitry Andric   AssertDI(N.isDistinct(), "compile units must be distinct", &N);
10470b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
10500b57cec5SDimitry Andric   // as those could be empty.
10510b57cec5SDimitry Andric   AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
10520b57cec5SDimitry Andric            N.getRawFile());
10530b57cec5SDimitry Andric   AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
10540b57cec5SDimitry Andric            N.getFile());
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   verifySourceDebugInfo(N, *N.getFile());
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
10590b57cec5SDimitry Andric            "invalid emission kind", &N);
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
10620b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
10630b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
10640b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
10650b57cec5SDimitry Andric       AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
10660b57cec5SDimitry Andric                "invalid enum type", &N, N.getEnumTypes(), Op);
10670b57cec5SDimitry Andric     }
10680b57cec5SDimitry Andric   }
10690b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
10700b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
10710b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
10720b57cec5SDimitry Andric       AssertDI(Op && (isa<DIType>(Op) ||
10730b57cec5SDimitry Andric                       (isa<DISubprogram>(Op) &&
10740b57cec5SDimitry Andric                        !cast<DISubprogram>(Op)->isDefinition())),
10750b57cec5SDimitry Andric                "invalid retained type", &N, Op);
10760b57cec5SDimitry Andric     }
10770b57cec5SDimitry Andric   }
10780b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
10790b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
10800b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
10810b57cec5SDimitry Andric       AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
10820b57cec5SDimitry Andric                "invalid global variable ref", &N, Op);
10830b57cec5SDimitry Andric     }
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
10860b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
10870b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
10880b57cec5SDimitry Andric       AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
10890b57cec5SDimitry Andric                &N, Op);
10900b57cec5SDimitry Andric     }
10910b57cec5SDimitry Andric   }
10920b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
10930b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
10940b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
10950b57cec5SDimitry Andric       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
10960b57cec5SDimitry Andric     }
10970b57cec5SDimitry Andric   }
10980b57cec5SDimitry Andric   CUVisited.insert(&N);
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
11020b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
11030b57cec5SDimitry Andric   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
11040b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
11050b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
11060b57cec5SDimitry Andric   else
11070b57cec5SDimitry Andric     AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
11080b57cec5SDimitry Andric   if (auto *T = N.getRawType())
11090b57cec5SDimitry Andric     AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
11100b57cec5SDimitry Andric   AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
11110b57cec5SDimitry Andric            N.getRawContainingType());
11120b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
11130b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
11140b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
11150b57cec5SDimitry Andric     AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
11160b57cec5SDimitry Andric              "invalid subprogram declaration", &N, S);
11170b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
11180b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
11190b57cec5SDimitry Andric     AssertDI(Node, "invalid retained nodes list", &N, RawNode);
11200b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
11210b57cec5SDimitry Andric       AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
11220b57cec5SDimitry Andric                "invalid retained nodes, expected DILocalVariable or DILabel",
11230b57cec5SDimitry Andric                &N, Node, Op);
11240b57cec5SDimitry Andric     }
11250b57cec5SDimitry Andric   }
11260b57cec5SDimitry Andric   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
11270b57cec5SDimitry Andric            "invalid reference flags", &N);
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
11300b57cec5SDimitry Andric   if (N.isDefinition()) {
11310b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
11320b57cec5SDimitry Andric     AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
11330b57cec5SDimitry Andric     AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
11340b57cec5SDimitry Andric     AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
11350b57cec5SDimitry Andric     if (N.getFile())
11360b57cec5SDimitry Andric       verifySourceDebugInfo(*N.getUnit(), *N.getFile());
11370b57cec5SDimitry Andric   } else {
11380b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
11390b57cec5SDimitry Andric     AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
11400b57cec5SDimitry Andric   }
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
11430b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
11440b57cec5SDimitry Andric     AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
11450b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
11460b57cec5SDimitry Andric       AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
11470b57cec5SDimitry Andric                Op);
11480b57cec5SDimitry Andric   }
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
11510b57cec5SDimitry Andric     AssertDI(N.isDefinition(),
11520b57cec5SDimitry Andric              "DIFlagAllCallsDescribed must be attached to a definition");
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
11560b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
11570b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
11580b57cec5SDimitry Andric            "invalid local scope", &N, N.getRawScope());
11590b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
11600b57cec5SDimitry Andric     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
11640b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   AssertDI(N.getLine() || !N.getColumn(),
11670b57cec5SDimitry Andric            "cannot have column info without line info", &N);
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
11710b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
11720b57cec5SDimitry Andric }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
11750b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
11760b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
11770b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
11780b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
11790b57cec5SDimitry Andric     AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
11800b57cec5SDimitry Andric }
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
11830b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
11840b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
11850b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
11890b57cec5SDimitry Andric   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
11900b57cec5SDimitry Andric                N.getMacinfoType() == dwarf::DW_MACINFO_undef,
11910b57cec5SDimitry Andric            "invalid macinfo type", &N);
11920b57cec5SDimitry Andric   AssertDI(!N.getName().empty(), "anonymous macro", &N);
11930b57cec5SDimitry Andric   if (!N.getValue().empty()) {
11940b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
11950b57cec5SDimitry Andric   }
11960b57cec5SDimitry Andric }
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
11990b57cec5SDimitry Andric   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
12000b57cec5SDimitry Andric            "invalid macinfo type", &N);
12010b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
12020b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
12050b57cec5SDimitry Andric     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
12060b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
12070b57cec5SDimitry Andric       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
12080b57cec5SDimitry Andric     }
12090b57cec5SDimitry Andric   }
12100b57cec5SDimitry Andric }
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
12130b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
12140b57cec5SDimitry Andric   AssertDI(!N.getName().empty(), "anonymous module", &N);
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
12180b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
12190b57cec5SDimitry Andric }
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
12220b57cec5SDimitry Andric   visitDITemplateParameter(N);
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
12250b57cec5SDimitry Andric            &N);
12260b57cec5SDimitry Andric }
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
12290b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
12300b57cec5SDimitry Andric   visitDITemplateParameter(N);
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
12330b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
12340b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
12350b57cec5SDimitry Andric            "invalid tag", &N);
12360b57cec5SDimitry Andric }
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
12390b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
12400b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
12410b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
12420b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
12430b57cec5SDimitry Andric }
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
12460b57cec5SDimitry Andric   // Checks common to all variables.
12470b57cec5SDimitry Andric   visitDIVariable(N);
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
12500b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
12510b57cec5SDimitry Andric   AssertDI(N.getType(), "missing global variable type", &N);
12520b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
12530b57cec5SDimitry Andric     AssertDI(isa<DIDerivedType>(Member),
12540b57cec5SDimitry Andric              "invalid static data member declaration", &N, Member);
12550b57cec5SDimitry Andric   }
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
12590b57cec5SDimitry Andric   // Checks common to all variables.
12600b57cec5SDimitry Andric   visitDIVariable(N);
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
12630b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
12640b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
12650b57cec5SDimitry Andric            "local variable requires a valid scope", &N, N.getRawScope());
12660b57cec5SDimitry Andric   if (auto Ty = N.getType())
12670b57cec5SDimitry Andric     AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
12680b57cec5SDimitry Andric }
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
12710b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
12720b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
12730b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
12740b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
12770b57cec5SDimitry Andric   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
12780b57cec5SDimitry Andric            "label requires a valid scope", &N, N.getRawScope());
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
12820b57cec5SDimitry Andric   AssertDI(N.isValid(), "invalid expression", &N);
12830b57cec5SDimitry Andric }
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
12860b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
12870b57cec5SDimitry Andric   AssertDI(GVE.getVariable(), "missing variable");
12880b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
12890b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
12900b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
12910b57cec5SDimitry Andric     visitDIExpression(*Expr);
12920b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
12930b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
12940b57cec5SDimitry Andric   }
12950b57cec5SDimitry Andric }
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
12980b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
12990b57cec5SDimitry Andric   if (auto *T = N.getRawType())
13000b57cec5SDimitry Andric     AssertDI(isType(T), "invalid type ref", &N, T);
13010b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
13020b57cec5SDimitry Andric     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
13030b57cec5SDimitry Andric }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
13060b57cec5SDimitry Andric   AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
13070b57cec5SDimitry Andric                N.getTag() == dwarf::DW_TAG_imported_declaration,
13080b57cec5SDimitry Andric            "invalid tag", &N);
13090b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
13100b57cec5SDimitry Andric     AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
13110b57cec5SDimitry Andric   AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
13120b57cec5SDimitry Andric            N.getRawEntity());
13130b57cec5SDimitry Andric }
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
1316*8bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
1317*8bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
1318*8bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
13190b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1320*8bcb0991SDimitry Andric       Assert(!GV->hasPrivateLinkage(),
1321*8bcb0991SDimitry Andric              "comdat global value has private linkage", GV);
13220b57cec5SDimitry Andric }
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric void Verifier::visitModuleIdents(const Module &M) {
13250b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
13260b57cec5SDimitry Andric   if (!Idents)
13270b57cec5SDimitry Andric     return;
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
13300b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
13310b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
13320b57cec5SDimitry Andric     Assert(N->getNumOperands() == 1,
13330b57cec5SDimitry Andric            "incorrect number of operands in llvm.ident metadata", N);
13340b57cec5SDimitry Andric     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
13350b57cec5SDimitry Andric            ("invalid value for llvm.ident metadata entry operand"
13360b57cec5SDimitry Andric             "(the operand should be a string)"),
13370b57cec5SDimitry Andric            N->getOperand(0));
13380b57cec5SDimitry Andric   }
13390b57cec5SDimitry Andric }
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric void Verifier::visitModuleCommandLines(const Module &M) {
13420b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
13430b57cec5SDimitry Andric   if (!CommandLines)
13440b57cec5SDimitry Andric     return;
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
13470b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
13480b57cec5SDimitry Andric   // requirement is met.
13490b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
13500b57cec5SDimitry Andric     Assert(N->getNumOperands() == 1,
13510b57cec5SDimitry Andric            "incorrect number of operands in llvm.commandline metadata", N);
13520b57cec5SDimitry Andric     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
13530b57cec5SDimitry Andric            ("invalid value for llvm.commandline metadata entry operand"
13540b57cec5SDimitry Andric             "(the operand should be a string)"),
13550b57cec5SDimitry Andric            N->getOperand(0));
13560b57cec5SDimitry Andric   }
13570b57cec5SDimitry Andric }
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric void Verifier::visitModuleFlags(const Module &M) {
13600b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
13610b57cec5SDimitry Andric   if (!Flags) return;
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
13640b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
13650b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
13660b57cec5SDimitry Andric   for (const MDNode *MDN : Flags->operands())
13670b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
13680b57cec5SDimitry Andric 
13690b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
13700b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
13710b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
13720b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
13750b57cec5SDimitry Andric     if (!Op) {
13760b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
13770b57cec5SDimitry Andric                   Flag);
13780b57cec5SDimitry Andric       continue;
13790b57cec5SDimitry Andric     }
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
13820b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
13830b57cec5SDimitry Andric                    "flag does not have the required value"),
13840b57cec5SDimitry Andric                   Flag);
13850b57cec5SDimitry Andric       continue;
13860b57cec5SDimitry Andric     }
13870b57cec5SDimitry Andric   }
13880b57cec5SDimitry Andric }
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric void
13910b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
13920b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
13930b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
13940b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
13950b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
13960b57cec5SDimitry Andric   Assert(Op->getNumOperands() == 3,
13970b57cec5SDimitry Andric          "incorrect number of operands in module flag", Op);
13980b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
13990b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
14000b57cec5SDimitry Andric     Assert(
14010b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
14020b57cec5SDimitry Andric         "invalid behavior operand in module flag (expected constant integer)",
14030b57cec5SDimitry Andric         Op->getOperand(0));
14040b57cec5SDimitry Andric     Assert(false,
14050b57cec5SDimitry Andric            "invalid behavior operand in module flag (unexpected constant)",
14060b57cec5SDimitry Andric            Op->getOperand(0));
14070b57cec5SDimitry Andric   }
14080b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
14090b57cec5SDimitry Andric   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
14100b57cec5SDimitry Andric          Op->getOperand(1));
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric   // Sanity check the values for behaviors with additional requirements.
14130b57cec5SDimitry Andric   switch (MFB) {
14140b57cec5SDimitry Andric   case Module::Error:
14150b57cec5SDimitry Andric   case Module::Warning:
14160b57cec5SDimitry Andric   case Module::Override:
14170b57cec5SDimitry Andric     // These behavior types accept any value.
14180b57cec5SDimitry Andric     break;
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric   case Module::Max: {
14210b57cec5SDimitry Andric     Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
14220b57cec5SDimitry Andric            "invalid value for 'max' module flag (expected constant integer)",
14230b57cec5SDimitry Andric            Op->getOperand(2));
14240b57cec5SDimitry Andric     break;
14250b57cec5SDimitry Andric   }
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric   case Module::Require: {
14280b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
14290b57cec5SDimitry Andric     // MDString), and a value.
14300b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
14310b57cec5SDimitry Andric     Assert(Value && Value->getNumOperands() == 2,
14320b57cec5SDimitry Andric            "invalid value for 'require' module flag (expected metadata pair)",
14330b57cec5SDimitry Andric            Op->getOperand(2));
14340b57cec5SDimitry Andric     Assert(isa<MDString>(Value->getOperand(0)),
14350b57cec5SDimitry Andric            ("invalid value for 'require' module flag "
14360b57cec5SDimitry Andric             "(first value operand should be a string)"),
14370b57cec5SDimitry Andric            Value->getOperand(0));
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
14400b57cec5SDimitry Andric     // scanned.
14410b57cec5SDimitry Andric     Requirements.push_back(Value);
14420b57cec5SDimitry Andric     break;
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   case Module::Append:
14460b57cec5SDimitry Andric   case Module::AppendUnique: {
14470b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
14480b57cec5SDimitry Andric     Assert(isa<MDNode>(Op->getOperand(2)),
14490b57cec5SDimitry Andric            "invalid value for 'append'-type module flag "
14500b57cec5SDimitry Andric            "(expected a metadata node)",
14510b57cec5SDimitry Andric            Op->getOperand(2));
14520b57cec5SDimitry Andric     break;
14530b57cec5SDimitry Andric   }
14540b57cec5SDimitry Andric   }
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
14570b57cec5SDimitry Andric   if (MFB != Module::Require) {
14580b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
14590b57cec5SDimitry Andric     Assert(Inserted,
14600b57cec5SDimitry Andric            "module flag identifiers must be unique (or of 'require' type)", ID);
14610b57cec5SDimitry Andric   }
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
14640b57cec5SDimitry Andric     ConstantInt *Value
14650b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
14660b57cec5SDimitry Andric     Assert(Value, "wchar_size metadata requires constant integer argument");
14670b57cec5SDimitry Andric   }
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
14700b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
14710b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
14720b57cec5SDimitry Andric     // have been created by a client directly.
14730b57cec5SDimitry Andric     Assert(M.getNamedMetadata("llvm.linker.options"),
14740b57cec5SDimitry Andric            "'Linker Options' named metadata no longer supported");
14750b57cec5SDimitry Andric   }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
14780b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
14790b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
14800b57cec5SDimitry Andric   }
14810b57cec5SDimitry Andric }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
14840b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
14850b57cec5SDimitry Andric     if (!FuncMDO)
14860b57cec5SDimitry Andric       return;
14870b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
14880b57cec5SDimitry Andric     Assert(F && isa<Function>(F->getValue()), "expected a Function or null",
14890b57cec5SDimitry Andric            FuncMDO);
14900b57cec5SDimitry Andric   };
14910b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
14920b57cec5SDimitry Andric   Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
14930b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
14940b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
14950b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
14960b57cec5SDimitry Andric   Assert(Count && Count->getType()->isIntegerTy(),
14970b57cec5SDimitry Andric          "expected an integer constant", Node->getOperand(2));
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric /// Return true if this attribute kind only applies to functions.
15010b57cec5SDimitry Andric static bool isFuncOnlyAttr(Attribute::AttrKind Kind) {
15020b57cec5SDimitry Andric   switch (Kind) {
15030b57cec5SDimitry Andric   case Attribute::NoReturn:
15040b57cec5SDimitry Andric   case Attribute::NoSync:
15050b57cec5SDimitry Andric   case Attribute::WillReturn:
15060b57cec5SDimitry Andric   case Attribute::NoCfCheck:
15070b57cec5SDimitry Andric   case Attribute::NoUnwind:
15080b57cec5SDimitry Andric   case Attribute::NoInline:
15090b57cec5SDimitry Andric   case Attribute::NoFree:
15100b57cec5SDimitry Andric   case Attribute::AlwaysInline:
15110b57cec5SDimitry Andric   case Attribute::OptimizeForSize:
15120b57cec5SDimitry Andric   case Attribute::StackProtect:
15130b57cec5SDimitry Andric   case Attribute::StackProtectReq:
15140b57cec5SDimitry Andric   case Attribute::StackProtectStrong:
15150b57cec5SDimitry Andric   case Attribute::SafeStack:
15160b57cec5SDimitry Andric   case Attribute::ShadowCallStack:
15170b57cec5SDimitry Andric   case Attribute::NoRedZone:
15180b57cec5SDimitry Andric   case Attribute::NoImplicitFloat:
15190b57cec5SDimitry Andric   case Attribute::Naked:
15200b57cec5SDimitry Andric   case Attribute::InlineHint:
15210b57cec5SDimitry Andric   case Attribute::StackAlignment:
15220b57cec5SDimitry Andric   case Attribute::UWTable:
15230b57cec5SDimitry Andric   case Attribute::NonLazyBind:
15240b57cec5SDimitry Andric   case Attribute::ReturnsTwice:
15250b57cec5SDimitry Andric   case Attribute::SanitizeAddress:
15260b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress:
15270b57cec5SDimitry Andric   case Attribute::SanitizeMemTag:
15280b57cec5SDimitry Andric   case Attribute::SanitizeThread:
15290b57cec5SDimitry Andric   case Attribute::SanitizeMemory:
15300b57cec5SDimitry Andric   case Attribute::MinSize:
15310b57cec5SDimitry Andric   case Attribute::NoDuplicate:
15320b57cec5SDimitry Andric   case Attribute::Builtin:
15330b57cec5SDimitry Andric   case Attribute::NoBuiltin:
15340b57cec5SDimitry Andric   case Attribute::Cold:
15350b57cec5SDimitry Andric   case Attribute::OptForFuzzing:
15360b57cec5SDimitry Andric   case Attribute::OptimizeNone:
15370b57cec5SDimitry Andric   case Attribute::JumpTable:
15380b57cec5SDimitry Andric   case Attribute::Convergent:
15390b57cec5SDimitry Andric   case Attribute::ArgMemOnly:
15400b57cec5SDimitry Andric   case Attribute::NoRecurse:
15410b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:
15420b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly:
15430b57cec5SDimitry Andric   case Attribute::AllocSize:
15440b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
15450b57cec5SDimitry Andric   case Attribute::Speculatable:
15460b57cec5SDimitry Andric   case Attribute::StrictFP:
15470b57cec5SDimitry Andric     return true;
15480b57cec5SDimitry Andric   default:
15490b57cec5SDimitry Andric     break;
15500b57cec5SDimitry Andric   }
15510b57cec5SDimitry Andric   return false;
15520b57cec5SDimitry Andric }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric /// Return true if this is a function attribute that can also appear on
15550b57cec5SDimitry Andric /// arguments.
15560b57cec5SDimitry Andric static bool isFuncOrArgAttr(Attribute::AttrKind Kind) {
15570b57cec5SDimitry Andric   return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly ||
15580b57cec5SDimitry Andric          Kind == Attribute::ReadNone;
15590b57cec5SDimitry Andric }
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
15620b57cec5SDimitry Andric                                     const Value *V) {
15630b57cec5SDimitry Andric   for (Attribute A : Attrs) {
15640b57cec5SDimitry Andric     if (A.isStringAttribute())
15650b57cec5SDimitry Andric       continue;
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric     if (isFuncOnlyAttr(A.getKindAsEnum())) {
15680b57cec5SDimitry Andric       if (!IsFunction) {
15690b57cec5SDimitry Andric         CheckFailed("Attribute '" + A.getAsString() +
15700b57cec5SDimitry Andric                         "' only applies to functions!",
15710b57cec5SDimitry Andric                     V);
15720b57cec5SDimitry Andric         return;
15730b57cec5SDimitry Andric       }
15740b57cec5SDimitry Andric     } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) {
15750b57cec5SDimitry Andric       CheckFailed("Attribute '" + A.getAsString() +
15760b57cec5SDimitry Andric                       "' does not apply to functions!",
15770b57cec5SDimitry Andric                   V);
15780b57cec5SDimitry Andric       return;
15790b57cec5SDimitry Andric     }
15800b57cec5SDimitry Andric   }
15810b57cec5SDimitry Andric }
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
15840b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
15850b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
15860b57cec5SDimitry Andric                                     const Value *V) {
15870b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
15880b57cec5SDimitry Andric     return;
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric   verifyAttributeTypes(Attrs, /*IsFunction=*/false, V);
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
15930b57cec5SDimitry Andric     Assert(Attrs.getNumAttributes() == 1,
15940b57cec5SDimitry Andric            "Attribute 'immarg' is incompatible with other attributes", V);
15950b57cec5SDimitry Andric   }
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
15980b57cec5SDimitry Andric   // sret.
15990b57cec5SDimitry Andric   unsigned AttrCount = 0;
16000b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
16010b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
16020b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
16030b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
16040b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
16050b57cec5SDimitry Andric   Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
16060b57cec5SDimitry Andric                          "and 'sret' are incompatible!",
16070b57cec5SDimitry Andric          V);
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
16100b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::ReadOnly)),
16110b57cec5SDimitry Andric          "Attributes "
16120b57cec5SDimitry Andric          "'inalloca and readonly' are incompatible!",
16130b57cec5SDimitry Andric          V);
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
16160b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::Returned)),
16170b57cec5SDimitry Andric          "Attributes "
16180b57cec5SDimitry Andric          "'sret and returned' are incompatible!",
16190b57cec5SDimitry Andric          V);
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
16220b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::SExt)),
16230b57cec5SDimitry Andric          "Attributes "
16240b57cec5SDimitry Andric          "'zeroext and signext' are incompatible!",
16250b57cec5SDimitry Andric          V);
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
16280b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::ReadOnly)),
16290b57cec5SDimitry Andric          "Attributes "
16300b57cec5SDimitry Andric          "'readnone and readonly' are incompatible!",
16310b57cec5SDimitry Andric          V);
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
16340b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::WriteOnly)),
16350b57cec5SDimitry Andric          "Attributes "
16360b57cec5SDimitry Andric          "'readnone and writeonly' are incompatible!",
16370b57cec5SDimitry Andric          V);
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
16400b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::WriteOnly)),
16410b57cec5SDimitry Andric          "Attributes "
16420b57cec5SDimitry Andric          "'readonly and writeonly' are incompatible!",
16430b57cec5SDimitry Andric          V);
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric   Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
16460b57cec5SDimitry Andric            Attrs.hasAttribute(Attribute::AlwaysInline)),
16470b57cec5SDimitry Andric          "Attributes "
16480b57cec5SDimitry Andric          "'noinline and alwaysinline' are incompatible!",
16490b57cec5SDimitry Andric          V);
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
16520b57cec5SDimitry Andric     Assert(Attrs.getByValType() == cast<PointerType>(Ty)->getElementType(),
16530b57cec5SDimitry Andric            "Attribute 'byval' type does not match parameter!", V);
16540b57cec5SDimitry Andric   }
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
16570b57cec5SDimitry Andric   Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs),
16580b57cec5SDimitry Andric          "Wrong types for attribute: " +
16590b57cec5SDimitry Andric              AttributeSet::get(Context, IncompatibleAttrs).getAsString(),
16600b57cec5SDimitry Andric          V);
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
16630b57cec5SDimitry Andric     SmallPtrSet<Type*, 4> Visited;
16640b57cec5SDimitry Andric     if (!PTy->getElementType()->isSized(&Visited)) {
16650b57cec5SDimitry Andric       Assert(!Attrs.hasAttribute(Attribute::ByVal) &&
16660b57cec5SDimitry Andric                  !Attrs.hasAttribute(Attribute::InAlloca),
16670b57cec5SDimitry Andric              "Attributes 'byval' and 'inalloca' do not support unsized types!",
16680b57cec5SDimitry Andric              V);
16690b57cec5SDimitry Andric     }
16700b57cec5SDimitry Andric     if (!isa<PointerType>(PTy->getElementType()))
16710b57cec5SDimitry Andric       Assert(!Attrs.hasAttribute(Attribute::SwiftError),
16720b57cec5SDimitry Andric              "Attribute 'swifterror' only applies to parameters "
16730b57cec5SDimitry Andric              "with pointer to pointer type!",
16740b57cec5SDimitry Andric              V);
16750b57cec5SDimitry Andric   } else {
16760b57cec5SDimitry Andric     Assert(!Attrs.hasAttribute(Attribute::ByVal),
16770b57cec5SDimitry Andric            "Attribute 'byval' only applies to parameters with pointer type!",
16780b57cec5SDimitry Andric            V);
16790b57cec5SDimitry Andric     Assert(!Attrs.hasAttribute(Attribute::SwiftError),
16800b57cec5SDimitry Andric            "Attribute 'swifterror' only applies to parameters "
16810b57cec5SDimitry Andric            "with pointer type!",
16820b57cec5SDimitry Andric            V);
16830b57cec5SDimitry Andric   }
16840b57cec5SDimitry Andric }
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric // Check parameter attributes against a function type.
16870b57cec5SDimitry Andric // The value V is printed in error messages.
16880b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
16890b57cec5SDimitry Andric                                    const Value *V, bool IsIntrinsic) {
16900b57cec5SDimitry Andric   if (Attrs.isEmpty())
16910b57cec5SDimitry Andric     return;
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric   bool SawNest = false;
16940b57cec5SDimitry Andric   bool SawReturned = false;
16950b57cec5SDimitry Andric   bool SawSRet = false;
16960b57cec5SDimitry Andric   bool SawSwiftSelf = false;
16970b57cec5SDimitry Andric   bool SawSwiftError = false;
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric   // Verify return value attributes.
17000b57cec5SDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttributes();
17010b57cec5SDimitry Andric   Assert((!RetAttrs.hasAttribute(Attribute::ByVal) &&
17020b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::Nest) &&
17030b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::StructRet) &&
17040b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::NoCapture) &&
17050b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::Returned) &&
17060b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::InAlloca) &&
17070b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::SwiftSelf) &&
17080b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::SwiftError)),
17090b57cec5SDimitry Andric          "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', "
17100b57cec5SDimitry Andric          "'returned', 'swiftself', and 'swifterror' do not apply to return "
17110b57cec5SDimitry Andric          "values!",
17120b57cec5SDimitry Andric          V);
17130b57cec5SDimitry Andric   Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) &&
17140b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::WriteOnly) &&
17150b57cec5SDimitry Andric           !RetAttrs.hasAttribute(Attribute::ReadNone)),
17160b57cec5SDimitry Andric          "Attribute '" + RetAttrs.getAsString() +
17170b57cec5SDimitry Andric              "' does not apply to function returns",
17180b57cec5SDimitry Andric          V);
17190b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric   // Verify parameter attributes.
17220b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
17230b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
17240b57cec5SDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttributes(i);
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric     if (!IsIntrinsic) {
17270b57cec5SDimitry Andric       Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),
17280b57cec5SDimitry Andric              "immarg attribute only applies to intrinsics",V);
17290b57cec5SDimitry Andric     }
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
17340b57cec5SDimitry Andric       Assert(!SawNest, "More than one parameter has attribute nest!", V);
17350b57cec5SDimitry Andric       SawNest = true;
17360b57cec5SDimitry Andric     }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
17390b57cec5SDimitry Andric       Assert(!SawReturned, "More than one parameter has attribute returned!",
17400b57cec5SDimitry Andric              V);
17410b57cec5SDimitry Andric       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
17420b57cec5SDimitry Andric              "Incompatible argument and return types for 'returned' attribute",
17430b57cec5SDimitry Andric              V);
17440b57cec5SDimitry Andric       SawReturned = true;
17450b57cec5SDimitry Andric     }
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
17480b57cec5SDimitry Andric       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
17490b57cec5SDimitry Andric       Assert(i == 0 || i == 1,
17500b57cec5SDimitry Andric              "Attribute 'sret' is not on first or second parameter!", V);
17510b57cec5SDimitry Andric       SawSRet = true;
17520b57cec5SDimitry Andric     }
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
17550b57cec5SDimitry Andric       Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
17560b57cec5SDimitry Andric       SawSwiftSelf = true;
17570b57cec5SDimitry Andric     }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
17600b57cec5SDimitry Andric       Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
17610b57cec5SDimitry Andric              V);
17620b57cec5SDimitry Andric       SawSwiftError = true;
17630b57cec5SDimitry Andric     }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
17660b57cec5SDimitry Andric       Assert(i == FT->getNumParams() - 1,
17670b57cec5SDimitry Andric              "inalloca isn't on the last parameter!", V);
17680b57cec5SDimitry Andric     }
17690b57cec5SDimitry Andric   }
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   if (!Attrs.hasAttributes(AttributeList::FunctionIndex))
17720b57cec5SDimitry Andric     return;
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V);
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
17770b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::ReadOnly)),
17780b57cec5SDimitry Andric          "Attributes 'readnone and readonly' are incompatible!", V);
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
17810b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::WriteOnly)),
17820b57cec5SDimitry Andric          "Attributes 'readnone and writeonly' are incompatible!", V);
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
17850b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::WriteOnly)),
17860b57cec5SDimitry Andric          "Attributes 'readonly and writeonly' are incompatible!", V);
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
17890b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)),
17900b57cec5SDimitry Andric          "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
17910b57cec5SDimitry Andric          "incompatible!",
17920b57cec5SDimitry Andric          V);
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
17950b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)),
17960b57cec5SDimitry Andric          "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
17990b57cec5SDimitry Andric            Attrs.hasFnAttribute(Attribute::AlwaysInline)),
18000b57cec5SDimitry Andric          "Attributes 'noinline and alwaysinline' are incompatible!", V);
18010b57cec5SDimitry Andric 
18020b57cec5SDimitry Andric   if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) {
18030b57cec5SDimitry Andric     Assert(Attrs.hasFnAttribute(Attribute::NoInline),
18040b57cec5SDimitry Andric            "Attribute 'optnone' requires 'noinline'!", V);
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize),
18070b57cec5SDimitry Andric            "Attributes 'optsize and optnone' are incompatible!", V);
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric     Assert(!Attrs.hasFnAttribute(Attribute::MinSize),
18100b57cec5SDimitry Andric            "Attributes 'minsize and optnone' are incompatible!", V);
18110b57cec5SDimitry Andric   }
18120b57cec5SDimitry Andric 
18130b57cec5SDimitry Andric   if (Attrs.hasFnAttribute(Attribute::JumpTable)) {
18140b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
18150b57cec5SDimitry Andric     Assert(GV->hasGlobalUnnamedAddr(),
18160b57cec5SDimitry Andric            "Attribute 'jumptable' requires 'unnamed_addr'", V);
18170b57cec5SDimitry Andric   }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   if (Attrs.hasFnAttribute(Attribute::AllocSize)) {
18200b57cec5SDimitry Andric     std::pair<unsigned, Optional<unsigned>> Args =
18210b57cec5SDimitry Andric         Attrs.getAllocSizeArgs(AttributeList::FunctionIndex);
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
18240b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
18250b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
18260b57cec5SDimitry Andric         return false;
18270b57cec5SDimitry Andric       }
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
18300b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
18310b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
18320b57cec5SDimitry Andric                     V);
18330b57cec5SDimitry Andric         return false;
18340b57cec5SDimitry Andric       }
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric       return true;
18370b57cec5SDimitry Andric     };
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric     if (!CheckParam("element size", Args.first))
18400b57cec5SDimitry Andric       return;
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric     if (Args.second && !CheckParam("number of elements", *Args.second))
18430b57cec5SDimitry Andric       return;
18440b57cec5SDimitry Andric   }
18450b57cec5SDimitry Andric }
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
18480b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
18490b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
18500b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
18510b57cec5SDimitry Andric       MDNode *MD = Pair.second;
18520b57cec5SDimitry Andric       Assert(MD->getNumOperands() >= 2,
18530b57cec5SDimitry Andric              "!prof annotations should have no less than 2 operands", MD);
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric       // Check first operand.
18560b57cec5SDimitry Andric       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
18570b57cec5SDimitry Andric              MD);
18580b57cec5SDimitry Andric       Assert(isa<MDString>(MD->getOperand(0)),
18590b57cec5SDimitry Andric              "expected string with name of the !prof annotation", MD);
18600b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
18610b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
18620b57cec5SDimitry Andric       Assert(ProfName.equals("function_entry_count") ||
18630b57cec5SDimitry Andric                  ProfName.equals("synthetic_function_entry_count"),
18640b57cec5SDimitry Andric              "first operand should be 'function_entry_count'"
18650b57cec5SDimitry Andric              " or 'synthetic_function_entry_count'",
18660b57cec5SDimitry Andric              MD);
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric       // Check second operand.
18690b57cec5SDimitry Andric       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
18700b57cec5SDimitry Andric              MD);
18710b57cec5SDimitry Andric       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
18720b57cec5SDimitry Andric              "expected integer argument to function_entry_count", MD);
18730b57cec5SDimitry Andric     }
18740b57cec5SDimitry Andric   }
18750b57cec5SDimitry Andric }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
18780b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
18790b57cec5SDimitry Andric     return;
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
18820b57cec5SDimitry Andric   Stack.push_back(EntryC);
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric   while (!Stack.empty()) {
18850b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric     // Check this constant expression.
18880b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
18890b57cec5SDimitry Andric       visitConstantExpr(CE);
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
18920b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
18930b57cec5SDimitry Andric       // that the global value is in the correct module
18940b57cec5SDimitry Andric       Assert(GV->getParent() == &M, "Referencing global in another module!",
18950b57cec5SDimitry Andric              EntryC, &M, GV, GV->getParent());
18960b57cec5SDimitry Andric       continue;
18970b57cec5SDimitry Andric     }
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric     // Visit all sub-expressions.
19000b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
19010b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
19020b57cec5SDimitry Andric       if (!OpC)
19030b57cec5SDimitry Andric         continue;
19040b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
19050b57cec5SDimitry Andric         continue;
19060b57cec5SDimitry Andric       Stack.push_back(OpC);
19070b57cec5SDimitry Andric     }
19080b57cec5SDimitry Andric   }
19090b57cec5SDimitry Andric }
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
19120b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
19130b57cec5SDimitry Andric     Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
19140b57cec5SDimitry Andric                                  CE->getType()),
19150b57cec5SDimitry Andric            "Invalid bitcast", CE);
19160b57cec5SDimitry Andric 
19170b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::IntToPtr ||
19180b57cec5SDimitry Andric       CE->getOpcode() == Instruction::PtrToInt) {
19190b57cec5SDimitry Andric     auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr
19200b57cec5SDimitry Andric                       ? CE->getType()
19210b57cec5SDimitry Andric                       : CE->getOperand(0)->getType();
19220b57cec5SDimitry Andric     StringRef Msg = CE->getOpcode() == Instruction::IntToPtr
19230b57cec5SDimitry Andric                         ? "inttoptr not supported for non-integral pointers"
19240b57cec5SDimitry Andric                         : "ptrtoint not supported for non-integral pointers";
19250b57cec5SDimitry Andric     Assert(
19260b57cec5SDimitry Andric         !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())),
19270b57cec5SDimitry Andric         Msg);
19280b57cec5SDimitry Andric   }
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
19320b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
19330b57cec5SDimitry Andric   // function and return value.
19340b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
19350b57cec5SDimitry Andric }
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
19380b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
19390b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
19400b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
19410b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric   Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
19440b57cec5SDimitry Andric              !Call.onlyAccessesArgMemory(),
19450b57cec5SDimitry Andric          "gc.statepoint must read and write all memory to preserve "
19460b57cec5SDimitry Andric          "reordering restrictions required by safepoint semantics",
19470b57cec5SDimitry Andric          Call);
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric   const int64_t NumPatchBytes =
19500b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
19510b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
19520b57cec5SDimitry Andric   Assert(NumPatchBytes >= 0,
19530b57cec5SDimitry Andric          "gc.statepoint number of patchable bytes must be "
19540b57cec5SDimitry Andric          "positive",
19550b57cec5SDimitry Andric          Call);
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric   const Value *Target = Call.getArgOperand(2);
19580b57cec5SDimitry Andric   auto *PT = dyn_cast<PointerType>(Target->getType());
19590b57cec5SDimitry Andric   Assert(PT && PT->getElementType()->isFunctionTy(),
19600b57cec5SDimitry Andric          "gc.statepoint callee must be of function pointer type", Call, Target);
19610b57cec5SDimitry Andric   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
19640b57cec5SDimitry Andric   Assert(NumCallArgs >= 0,
19650b57cec5SDimitry Andric          "gc.statepoint number of arguments to underlying call "
19660b57cec5SDimitry Andric          "must be positive",
19670b57cec5SDimitry Andric          Call);
19680b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
19690b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
19700b57cec5SDimitry Andric     Assert(NumCallArgs >= NumParams,
19710b57cec5SDimitry Andric            "gc.statepoint mismatch in number of vararg call args", Call);
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric     // TODO: Remove this limitation
19740b57cec5SDimitry Andric     Assert(TargetFuncType->getReturnType()->isVoidTy(),
19750b57cec5SDimitry Andric            "gc.statepoint doesn't support wrapping non-void "
19760b57cec5SDimitry Andric            "vararg functions yet",
19770b57cec5SDimitry Andric            Call);
19780b57cec5SDimitry Andric   } else
19790b57cec5SDimitry Andric     Assert(NumCallArgs == NumParams,
19800b57cec5SDimitry Andric            "gc.statepoint mismatch in number of call args", Call);
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric   const uint64_t Flags
19830b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
19840b57cec5SDimitry Andric   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
19850b57cec5SDimitry Andric          "unknown flag used in gc.statepoint flags argument", Call);
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
19880b57cec5SDimitry Andric   // the type of the wrapped callee.
19890b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
19900b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
19910b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
19920b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
19930b57cec5SDimitry Andric     Assert(ArgType == ParamType,
19940b57cec5SDimitry Andric            "gc.statepoint call argument does not match wrapped "
19950b57cec5SDimitry Andric            "function type",
19960b57cec5SDimitry Andric            Call);
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
19990b57cec5SDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i);
20000b57cec5SDimitry Andric       Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
20010b57cec5SDimitry Andric              "Attribute 'sret' cannot be used for vararg call arguments!",
20020b57cec5SDimitry Andric              Call);
20030b57cec5SDimitry Andric     }
20040b57cec5SDimitry Andric   }
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
20070b57cec5SDimitry Andric 
20080b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
20090b57cec5SDimitry Andric   Assert(isa<ConstantInt>(NumTransitionArgsV),
20100b57cec5SDimitry Andric          "gc.statepoint number of transition arguments "
20110b57cec5SDimitry Andric          "must be constant integer",
20120b57cec5SDimitry Andric          Call);
20130b57cec5SDimitry Andric   const int NumTransitionArgs =
20140b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
20150b57cec5SDimitry Andric   Assert(NumTransitionArgs >= 0,
20160b57cec5SDimitry Andric          "gc.statepoint number of transition arguments must be positive", Call);
20170b57cec5SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
20200b57cec5SDimitry Andric   Assert(isa<ConstantInt>(NumDeoptArgsV),
20210b57cec5SDimitry Andric          "gc.statepoint number of deoptimization arguments "
20220b57cec5SDimitry Andric          "must be constant integer",
20230b57cec5SDimitry Andric          Call);
20240b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
20250b57cec5SDimitry Andric   Assert(NumDeoptArgs >= 0,
20260b57cec5SDimitry Andric          "gc.statepoint number of deoptimization arguments "
20270b57cec5SDimitry Andric          "must be positive",
20280b57cec5SDimitry Andric          Call);
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric   const int ExpectedNumArgs =
20310b57cec5SDimitry Andric       7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
20320b57cec5SDimitry Andric   Assert(ExpectedNumArgs <= (int)Call.arg_size(),
20330b57cec5SDimitry Andric          "gc.statepoint too few arguments according to length fields", Call);
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
20360b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
20370b57cec5SDimitry Andric   // of the same statepoint sequence
20380b57cec5SDimitry Andric   for (const User *U : Call.users()) {
20390b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
20400b57cec5SDimitry Andric     Assert(UserCall, "illegal use of statepoint token", Call, U);
20410b57cec5SDimitry Andric     if (!UserCall)
20420b57cec5SDimitry Andric       continue;
20430b57cec5SDimitry Andric     Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
20440b57cec5SDimitry Andric            "gc.result or gc.relocate are the only value uses "
20450b57cec5SDimitry Andric            "of a gc.statepoint",
20460b57cec5SDimitry Andric            Call, U);
20470b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
20480b57cec5SDimitry Andric       Assert(UserCall->getArgOperand(0) == &Call,
20490b57cec5SDimitry Andric              "gc.result connected to wrong gc.statepoint", Call, UserCall);
20500b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
20510b57cec5SDimitry Andric       Assert(UserCall->getArgOperand(0) == &Call,
20520b57cec5SDimitry Andric              "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
20530b57cec5SDimitry Andric     }
20540b57cec5SDimitry Andric   }
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
20570b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
20580b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
20590b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
20600b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
20610b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
20620b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
20630b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
20640b57cec5SDimitry Andric }
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
20670b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
20680b57cec5SDimitry Andric     Function *F = Counts.first;
20690b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
20700b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
20710b57cec5SDimitry Andric     Assert(MaxRecoveredIndex <= EscapedObjectCount,
20720b57cec5SDimitry Andric            "all indices passed to llvm.localrecover must be less than the "
20730b57cec5SDimitry Andric            "number of arguments passed to llvm.localescape in the parent "
20740b57cec5SDimitry Andric            "function",
20750b57cec5SDimitry Andric            F);
20760b57cec5SDimitry Andric   }
20770b57cec5SDimitry Andric }
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
20800b57cec5SDimitry Andric   BasicBlock *UnwindDest;
20810b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
20820b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
20830b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
20840b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
20850b57cec5SDimitry Andric   else
20860b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
20870b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
20880b57cec5SDimitry Andric }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
20910b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
20920b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
20930b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
20940b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
20950b57cec5SDimitry Andric     if (Visited.count(PredPad))
20960b57cec5SDimitry Andric       continue;
20970b57cec5SDimitry Andric     Active.insert(PredPad);
20980b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
20990b57cec5SDimitry Andric     do {
21000b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
21010b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
21020b57cec5SDimitry Andric         // Found a cycle; report error
21030b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
21040b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
21050b57cec5SDimitry Andric         do {
21060b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
21070b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
21080b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
21090b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
21100b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
21110b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
21120b57cec5SDimitry Andric         Assert(false, "EH pads can't handle each other's exceptions",
21130b57cec5SDimitry Andric                ArrayRef<Instruction *>(CycleNodes));
21140b57cec5SDimitry Andric       }
21150b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
21160b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
21170b57cec5SDimitry Andric         break;
21180b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
21190b57cec5SDimitry Andric       PredPad = SuccPad;
21200b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
21210b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
21220b57cec5SDimitry Andric         break;
21230b57cec5SDimitry Andric       Terminator = TermI->second;
21240b57cec5SDimitry Andric       Active.insert(PredPad);
21250b57cec5SDimitry Andric     } while (true);
21260b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
21270b57cec5SDimitry Andric     // nodes' successors.
21280b57cec5SDimitry Andric     Active.clear();
21290b57cec5SDimitry Andric   }
21300b57cec5SDimitry Andric }
21310b57cec5SDimitry Andric 
21320b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
21330b57cec5SDimitry Andric //
21340b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
21350b57cec5SDimitry Andric   visitGlobalValue(F);
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   // Check function arguments.
21380b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
21390b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric   Assert(&Context == &F.getContext(),
21420b57cec5SDimitry Andric          "Function context does not match Module context!", &F);
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
21450b57cec5SDimitry Andric   Assert(FT->getNumParams() == NumArgs,
21460b57cec5SDimitry Andric          "# formal arguments must match # of arguments for function type!", &F,
21470b57cec5SDimitry Andric          FT);
21480b57cec5SDimitry Andric   Assert(F.getReturnType()->isFirstClassType() ||
21490b57cec5SDimitry Andric              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
21500b57cec5SDimitry Andric          "Functions cannot return aggregate values!", &F);
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
21530b57cec5SDimitry Andric          "Invalid struct return type!", &F);
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
21580b57cec5SDimitry Andric          "Attribute after last parameter!", &F);
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   bool isLLVMdotName = F.getName().size() >= 5 &&
21610b57cec5SDimitry Andric                        F.getName().substr(0, 5) == "llvm.";
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   // Check function attributes.
21640b57cec5SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName);
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
21670b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
21680b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
21690b57cec5SDimitry Andric   Assert(!Attrs.hasFnAttribute(Attribute::Builtin),
21700b57cec5SDimitry Andric          "Attribute 'builtin' can only be applied to a callsite.", &F);
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
21730b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
21740b57cec5SDimitry Andric   // restrictions can be lifted.
21750b57cec5SDimitry Andric   switch (F.getCallingConv()) {
21760b57cec5SDimitry Andric   default:
21770b57cec5SDimitry Andric   case CallingConv::C:
21780b57cec5SDimitry Andric     break;
21790b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
21800b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
21810b57cec5SDimitry Andric     Assert(F.getReturnType()->isVoidTy(),
21820b57cec5SDimitry Andric            "Calling convention requires void return type", &F);
21830b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
21840b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
21850b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
21860b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
21870b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
21880b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
21890b57cec5SDimitry Andric     Assert(!F.hasStructRetAttr(),
21900b57cec5SDimitry Andric            "Calling convention does not allow sret", &F);
21910b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
21920b57cec5SDimitry Andric   case CallingConv::Fast:
21930b57cec5SDimitry Andric   case CallingConv::Cold:
21940b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
21950b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
21960b57cec5SDimitry Andric   case CallingConv::PTX_Device:
21970b57cec5SDimitry Andric     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
21980b57cec5SDimitry Andric                           "perfect forwarding!",
21990b57cec5SDimitry Andric            &F);
22000b57cec5SDimitry Andric     break;
22010b57cec5SDimitry Andric   }
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
22040b57cec5SDimitry Andric   unsigned i = 0;
22050b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
22060b57cec5SDimitry Andric     Assert(Arg.getType() == FT->getParamType(i),
22070b57cec5SDimitry Andric            "Argument value does not match function argument type!", &Arg,
22080b57cec5SDimitry Andric            FT->getParamType(i));
22090b57cec5SDimitry Andric     Assert(Arg.getType()->isFirstClassType(),
22100b57cec5SDimitry Andric            "Function arguments must have first-class types!", &Arg);
22110b57cec5SDimitry Andric     if (!isLLVMdotName) {
22120b57cec5SDimitry Andric       Assert(!Arg.getType()->isMetadataTy(),
22130b57cec5SDimitry Andric              "Function takes metadata but isn't an intrinsic", &Arg, &F);
22140b57cec5SDimitry Andric       Assert(!Arg.getType()->isTokenTy(),
22150b57cec5SDimitry Andric              "Function takes token but isn't an intrinsic", &Arg, &F);
22160b57cec5SDimitry Andric     }
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
22190b57cec5SDimitry Andric     if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
22200b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
22210b57cec5SDimitry Andric     }
22220b57cec5SDimitry Andric     ++i;
22230b57cec5SDimitry Andric   }
22240b57cec5SDimitry Andric 
22250b57cec5SDimitry Andric   if (!isLLVMdotName)
22260b57cec5SDimitry Andric     Assert(!F.getReturnType()->isTokenTy(),
22270b57cec5SDimitry Andric            "Functions returns a token but isn't an intrinsic", &F);
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric   // Get the function metadata attachments.
22300b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
22310b57cec5SDimitry Andric   F.getAllMetadata(MDs);
22320b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
22330b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
22340b57cec5SDimitry Andric 
22350b57cec5SDimitry Andric   // Check validity of the personality function
22360b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
22370b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
22380b57cec5SDimitry Andric     if (Per)
22390b57cec5SDimitry Andric       Assert(Per->getParent() == F.getParent(),
22400b57cec5SDimitry Andric              "Referencing personality function in another module!",
22410b57cec5SDimitry Andric              &F, F.getParent(), Per, Per->getParent());
22420b57cec5SDimitry Andric   }
22430b57cec5SDimitry Andric 
22440b57cec5SDimitry Andric   if (F.isMaterializable()) {
22450b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
22460b57cec5SDimitry Andric     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
22470b57cec5SDimitry Andric            MDs.empty() ? nullptr : MDs.front().second);
22480b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
22490b57cec5SDimitry Andric     for (const auto &I : MDs) {
22500b57cec5SDimitry Andric       // This is used for call site debug information.
22510b57cec5SDimitry Andric       AssertDI(I.first != LLVMContext::MD_dbg ||
22520b57cec5SDimitry Andric                    !cast<DISubprogram>(I.second)->isDistinct(),
22530b57cec5SDimitry Andric                "function declaration may only have a unique !dbg attachment",
22540b57cec5SDimitry Andric                &F);
22550b57cec5SDimitry Andric       Assert(I.first != LLVMContext::MD_prof,
22560b57cec5SDimitry Andric              "function declaration may not have a !prof attachment", &F);
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric       // Verify the metadata itself.
22590b57cec5SDimitry Andric       visitMDNode(*I.second);
22600b57cec5SDimitry Andric     }
22610b57cec5SDimitry Andric     Assert(!F.hasPersonalityFn(),
22620b57cec5SDimitry Andric            "Function declaration shouldn't have a personality routine", &F);
22630b57cec5SDimitry Andric   } else {
22640b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
22650b57cec5SDimitry Andric     // is not legal to define intrinsics.
22660b57cec5SDimitry Andric     Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric     // Check the entry node
22690b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
22700b57cec5SDimitry Andric     Assert(pred_empty(Entry),
22710b57cec5SDimitry Andric            "Entry block to function must not have predecessors!", Entry);
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
22740b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
22750b57cec5SDimitry Andric       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
22760b57cec5SDimitry Andric              "blockaddress may not be used with the entry block!", Entry);
22770b57cec5SDimitry Andric     }
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
22800b57cec5SDimitry Andric     // Visit metadata attachments.
22810b57cec5SDimitry Andric     for (const auto &I : MDs) {
22820b57cec5SDimitry Andric       // Verify that the attachment is legal.
22830b57cec5SDimitry Andric       switch (I.first) {
22840b57cec5SDimitry Andric       default:
22850b57cec5SDimitry Andric         break;
22860b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
22870b57cec5SDimitry Andric         ++NumDebugAttachments;
22880b57cec5SDimitry Andric         AssertDI(NumDebugAttachments == 1,
22890b57cec5SDimitry Andric                  "function must have a single !dbg attachment", &F, I.second);
22900b57cec5SDimitry Andric         AssertDI(isa<DISubprogram>(I.second),
22910b57cec5SDimitry Andric                  "function !dbg attachment must be a subprogram", &F, I.second);
22920b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
22930b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
22940b57cec5SDimitry Andric         AssertDI(!AttachedTo || AttachedTo == &F,
22950b57cec5SDimitry Andric                  "DISubprogram attached to more than one function", SP, &F);
22960b57cec5SDimitry Andric         AttachedTo = &F;
22970b57cec5SDimitry Andric         break;
22980b57cec5SDimitry Andric       }
22990b57cec5SDimitry Andric       case LLVMContext::MD_prof:
23000b57cec5SDimitry Andric         ++NumProfAttachments;
23010b57cec5SDimitry Andric         Assert(NumProfAttachments == 1,
23020b57cec5SDimitry Andric                "function must have a single !prof attachment", &F, I.second);
23030b57cec5SDimitry Andric         break;
23040b57cec5SDimitry Andric       }
23050b57cec5SDimitry Andric 
23060b57cec5SDimitry Andric       // Verify the metadata itself.
23070b57cec5SDimitry Andric       visitMDNode(*I.second);
23080b57cec5SDimitry Andric     }
23090b57cec5SDimitry Andric   }
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
23120b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
23130b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
23140b57cec5SDimitry Andric   // uses.
23150b57cec5SDimitry Andric   if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
23160b57cec5SDimitry Andric     const User *U;
23170b57cec5SDimitry Andric     if (F.hasAddressTaken(&U))
23180b57cec5SDimitry Andric       Assert(false, "Invalid user of intrinsic instruction!", U);
23190b57cec5SDimitry Andric   }
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric   auto *N = F.getSubprogram();
23220b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
23230b57cec5SDimitry Andric   if (!HasDebugInfo)
23240b57cec5SDimitry Andric     return;
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   // Check that all !dbg attachments lead to back to N (or, at least, another
23270b57cec5SDimitry Andric   // subprogram that describes the same function).
23280b57cec5SDimitry Andric   //
23290b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
23300b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
23310b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
23320b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
23330b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
23340b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
23350b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
23360b57cec5SDimitry Andric     if (!DL)
23370b57cec5SDimitry Andric       return;
23380b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
23390b57cec5SDimitry Andric       return;
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
23420b57cec5SDimitry Andric     AssertDI(Parent && isa<DILocalScope>(Parent),
23430b57cec5SDimitry Andric              "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
23440b57cec5SDimitry Andric              Parent);
23450b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
23460b57cec5SDimitry Andric     if (Scope && !Seen.insert(Scope).second)
23470b57cec5SDimitry Andric       return;
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric     DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
23520b57cec5SDimitry Andric     // validation in that case
23530b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
23540b57cec5SDimitry Andric       return;
23550b57cec5SDimitry Andric 
23560b57cec5SDimitry Andric     // FIXME: Once N is canonical, check "SP == &N".
23570b57cec5SDimitry Andric     AssertDI(SP->describes(&F),
23580b57cec5SDimitry Andric              "!dbg attachment points at wrong subprogram for function", N, &F,
23590b57cec5SDimitry Andric              &I, DL, Scope, SP);
23600b57cec5SDimitry Andric   };
23610b57cec5SDimitry Andric   for (auto &BB : F)
23620b57cec5SDimitry Andric     for (auto &I : BB) {
23630b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
23640b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
23650b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
23660b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
23670b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
23680b57cec5SDimitry Andric       if (BrokenDebugInfo)
23690b57cec5SDimitry Andric         return;
23700b57cec5SDimitry Andric     }
23710b57cec5SDimitry Andric }
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
23740b57cec5SDimitry Andric //
23750b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
23760b57cec5SDimitry Andric   InstsInThisBlock.clear();
23770b57cec5SDimitry Andric 
23780b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
23790b57cec5SDimitry Andric   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
23820b57cec5SDimitry Andric   // it.
23830b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
23840b57cec5SDimitry Andric     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
23850b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
23860b57cec5SDimitry Andric     llvm::sort(Preds);
23870b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
23880b57cec5SDimitry Andric       // Ensure that PHI nodes have at least one entry!
23890b57cec5SDimitry Andric       Assert(PN.getNumIncomingValues() != 0,
23900b57cec5SDimitry Andric              "PHI nodes must have at least one entry.  If the block is dead, "
23910b57cec5SDimitry Andric              "the PHI should be removed!",
23920b57cec5SDimitry Andric              &PN);
23930b57cec5SDimitry Andric       Assert(PN.getNumIncomingValues() == Preds.size(),
23940b57cec5SDimitry Andric              "PHINode should have one entry for each predecessor of its "
23950b57cec5SDimitry Andric              "parent basic block!",
23960b57cec5SDimitry Andric              &PN);
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
23990b57cec5SDimitry Andric       Values.clear();
24000b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
24010b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
24020b57cec5SDimitry Andric         Values.push_back(
24030b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
24040b57cec5SDimitry Andric       llvm::sort(Values);
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
24070b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
24080b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
24090b57cec5SDimitry Andric         // all identical.
24100b57cec5SDimitry Andric         //
24110b57cec5SDimitry Andric         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
24120b57cec5SDimitry Andric                    Values[i].second == Values[i - 1].second,
24130b57cec5SDimitry Andric                "PHI node has multiple entries for the same basic block with "
24140b57cec5SDimitry Andric                "different incoming values!",
24150b57cec5SDimitry Andric                &PN, Values[i].first, Values[i].second, Values[i - 1].second);
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
24180b57cec5SDimitry Andric         // matched up.
24190b57cec5SDimitry Andric         Assert(Values[i].first == Preds[i],
24200b57cec5SDimitry Andric                "PHI node entries do not match predecessors!", &PN,
24210b57cec5SDimitry Andric                Values[i].first, Preds[i]);
24220b57cec5SDimitry Andric       }
24230b57cec5SDimitry Andric     }
24240b57cec5SDimitry Andric   }
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
24270b57cec5SDimitry Andric   for (auto &I : BB)
24280b57cec5SDimitry Andric   {
24290b57cec5SDimitry Andric     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
24300b57cec5SDimitry Andric   }
24310b57cec5SDimitry Andric }
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
24340b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
24350b57cec5SDimitry Andric   Assert(&I == I.getParent()->getTerminator(),
24360b57cec5SDimitry Andric          "Terminator found in the middle of a basic block!", I.getParent());
24370b57cec5SDimitry Andric   visitInstruction(I);
24380b57cec5SDimitry Andric }
24390b57cec5SDimitry Andric 
24400b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
24410b57cec5SDimitry Andric   if (BI.isConditional()) {
24420b57cec5SDimitry Andric     Assert(BI.getCondition()->getType()->isIntegerTy(1),
24430b57cec5SDimitry Andric            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
24440b57cec5SDimitry Andric   }
24450b57cec5SDimitry Andric   visitTerminator(BI);
24460b57cec5SDimitry Andric }
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
24490b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
24500b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
24510b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
24520b57cec5SDimitry Andric     Assert(N == 0,
24530b57cec5SDimitry Andric            "Found return instr that returns non-void in Function of void "
24540b57cec5SDimitry Andric            "return type!",
24550b57cec5SDimitry Andric            &RI, F->getReturnType());
24560b57cec5SDimitry Andric   else
24570b57cec5SDimitry Andric     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
24580b57cec5SDimitry Andric            "Function return type does not match operand "
24590b57cec5SDimitry Andric            "type of return inst!",
24600b57cec5SDimitry Andric            &RI, F->getReturnType());
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
24630b57cec5SDimitry Andric   // terminators...
24640b57cec5SDimitry Andric   visitTerminator(RI);
24650b57cec5SDimitry Andric }
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
24680b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
24690b57cec5SDimitry Andric   // have the same type as the switched-on value.
24700b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
24710b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
24720b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
24730b57cec5SDimitry Andric     Assert(Case.getCaseValue()->getType() == SwitchTy,
24740b57cec5SDimitry Andric            "Switch constants must all be same type as switch value!", &SI);
24750b57cec5SDimitry Andric     Assert(Constants.insert(Case.getCaseValue()).second,
24760b57cec5SDimitry Andric            "Duplicate integer as switch case", &SI, Case.getCaseValue());
24770b57cec5SDimitry Andric   }
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric   visitTerminator(SI);
24800b57cec5SDimitry Andric }
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
24830b57cec5SDimitry Andric   Assert(BI.getAddress()->getType()->isPointerTy(),
24840b57cec5SDimitry Andric          "Indirectbr operand must have pointer type!", &BI);
24850b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
24860b57cec5SDimitry Andric     Assert(BI.getDestination(i)->getType()->isLabelTy(),
24870b57cec5SDimitry Andric            "Indirectbr destinations must all have pointer type!", &BI);
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric   visitTerminator(BI);
24900b57cec5SDimitry Andric }
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
24930b57cec5SDimitry Andric   Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
24940b57cec5SDimitry Andric          &CBI);
24950b57cec5SDimitry Andric   Assert(CBI.getType()->isVoidTy(), "Callbr return value is not supported!",
24960b57cec5SDimitry Andric          &CBI);
24970b57cec5SDimitry Andric   for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
24980b57cec5SDimitry Andric     Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
24990b57cec5SDimitry Andric            "Callbr successors must all have pointer type!", &CBI);
25000b57cec5SDimitry Andric   for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
25010b57cec5SDimitry Andric     Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)),
25020b57cec5SDimitry Andric            "Using an unescaped label as a callbr argument!", &CBI);
25030b57cec5SDimitry Andric     if (isa<BasicBlock>(CBI.getOperand(i)))
25040b57cec5SDimitry Andric       for (unsigned j = i + 1; j != e; ++j)
25050b57cec5SDimitry Andric         Assert(CBI.getOperand(i) != CBI.getOperand(j),
25060b57cec5SDimitry Andric                "Duplicate callbr destination!", &CBI);
25070b57cec5SDimitry Andric   }
2508*8bcb0991SDimitry Andric   {
2509*8bcb0991SDimitry Andric     SmallPtrSet<BasicBlock *, 4> ArgBBs;
2510*8bcb0991SDimitry Andric     for (Value *V : CBI.args())
2511*8bcb0991SDimitry Andric       if (auto *BA = dyn_cast<BlockAddress>(V))
2512*8bcb0991SDimitry Andric         ArgBBs.insert(BA->getBasicBlock());
2513*8bcb0991SDimitry Andric     for (BasicBlock *BB : CBI.getIndirectDests())
2514*8bcb0991SDimitry Andric       Assert(ArgBBs.find(BB) != ArgBBs.end(),
2515*8bcb0991SDimitry Andric              "Indirect label missing from arglist.", &CBI);
2516*8bcb0991SDimitry Andric   }
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric   visitTerminator(CBI);
25190b57cec5SDimitry Andric }
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
25220b57cec5SDimitry Andric   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
25230b57cec5SDimitry Andric                                          SI.getOperand(2)),
25240b57cec5SDimitry Andric          "Invalid operands for select instruction!", &SI);
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric   Assert(SI.getTrueValue()->getType() == SI.getType(),
25270b57cec5SDimitry Andric          "Select values must have same type as select instruction!", &SI);
25280b57cec5SDimitry Andric   visitInstruction(SI);
25290b57cec5SDimitry Andric }
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
25320b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
25330b57cec5SDimitry Andric ///
25340b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
25350b57cec5SDimitry Andric   Assert(false, "User-defined operators should not live outside of a pass!", &I);
25360b57cec5SDimitry Andric }
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
25390b57cec5SDimitry Andric   // Get the source and destination types
25400b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
25410b57cec5SDimitry Andric   Type *DestTy = I.getType();
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
25440b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
25450b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
25480b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
25490b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
25500b57cec5SDimitry Andric          "trunc source and destination must both be a vector or neither", &I);
25510b57cec5SDimitry Andric   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric   visitInstruction(I);
25540b57cec5SDimitry Andric }
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
25570b57cec5SDimitry Andric   // Get the source and destination types
25580b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
25590b57cec5SDimitry Andric   Type *DestTy = I.getType();
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
25620b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
25630b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
25640b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
25650b57cec5SDimitry Andric          "zext source and destination must both be a vector or neither", &I);
25660b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
25670b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
25680b57cec5SDimitry Andric 
25690b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   visitInstruction(I);
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
25750b57cec5SDimitry Andric   // Get the source and destination types
25760b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
25770b57cec5SDimitry Andric   Type *DestTy = I.getType();
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
25800b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
25810b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
25840b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
25850b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
25860b57cec5SDimitry Andric          "sext source and destination must both be a vector or neither", &I);
25870b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   visitInstruction(I);
25900b57cec5SDimitry Andric }
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
25930b57cec5SDimitry Andric   // Get the source and destination types
25940b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
25950b57cec5SDimitry Andric   Type *DestTy = I.getType();
25960b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
25970b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
25980b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
26010b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
26020b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
26030b57cec5SDimitry Andric          "fptrunc source and destination must both be a vector or neither", &I);
26040b57cec5SDimitry Andric   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric   visitInstruction(I);
26070b57cec5SDimitry Andric }
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
26100b57cec5SDimitry Andric   // Get the source and destination types
26110b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26120b57cec5SDimitry Andric   Type *DestTy = I.getType();
26130b57cec5SDimitry Andric 
26140b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
26150b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
26160b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
26190b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
26200b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
26210b57cec5SDimitry Andric          "fpext source and destination must both be a vector or neither", &I);
26220b57cec5SDimitry Andric   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric   visitInstruction(I);
26250b57cec5SDimitry Andric }
26260b57cec5SDimitry Andric 
26270b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
26280b57cec5SDimitry Andric   // Get the source and destination types
26290b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26300b57cec5SDimitry Andric   Type *DestTy = I.getType();
26310b57cec5SDimitry Andric 
26320b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
26330b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
26360b57cec5SDimitry Andric          "UIToFP source and dest must both be vector or scalar", &I);
26370b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
26380b57cec5SDimitry Andric          "UIToFP source must be integer or integer vector", &I);
26390b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
26400b57cec5SDimitry Andric          &I);
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   if (SrcVec && DstVec)
26430b57cec5SDimitry Andric     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
26440b57cec5SDimitry Andric                cast<VectorType>(DestTy)->getNumElements(),
26450b57cec5SDimitry Andric            "UIToFP source and dest vector length mismatch", &I);
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric   visitInstruction(I);
26480b57cec5SDimitry Andric }
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
26510b57cec5SDimitry Andric   // Get the source and destination types
26520b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26530b57cec5SDimitry Andric   Type *DestTy = I.getType();
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
26560b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
26590b57cec5SDimitry Andric          "SIToFP source and dest must both be vector or scalar", &I);
26600b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
26610b57cec5SDimitry Andric          "SIToFP source must be integer or integer vector", &I);
26620b57cec5SDimitry Andric   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
26630b57cec5SDimitry Andric          &I);
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric   if (SrcVec && DstVec)
26660b57cec5SDimitry Andric     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
26670b57cec5SDimitry Andric                cast<VectorType>(DestTy)->getNumElements(),
26680b57cec5SDimitry Andric            "SIToFP source and dest vector length mismatch", &I);
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric   visitInstruction(I);
26710b57cec5SDimitry Andric }
26720b57cec5SDimitry Andric 
26730b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
26740b57cec5SDimitry Andric   // Get the source and destination types
26750b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
26760b57cec5SDimitry Andric   Type *DestTy = I.getType();
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
26790b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
26800b57cec5SDimitry Andric 
26810b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
26820b57cec5SDimitry Andric          "FPToUI source and dest must both be vector or scalar", &I);
26830b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
26840b57cec5SDimitry Andric          &I);
26850b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(),
26860b57cec5SDimitry Andric          "FPToUI result must be integer or integer vector", &I);
26870b57cec5SDimitry Andric 
26880b57cec5SDimitry Andric   if (SrcVec && DstVec)
26890b57cec5SDimitry Andric     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
26900b57cec5SDimitry Andric                cast<VectorType>(DestTy)->getNumElements(),
26910b57cec5SDimitry Andric            "FPToUI source and dest vector length mismatch", &I);
26920b57cec5SDimitry Andric 
26930b57cec5SDimitry Andric   visitInstruction(I);
26940b57cec5SDimitry Andric }
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &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 
27010b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
27020b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric   Assert(SrcVec == DstVec,
27050b57cec5SDimitry Andric          "FPToSI source and dest must both be vector or scalar", &I);
27060b57cec5SDimitry Andric   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
27070b57cec5SDimitry Andric          &I);
27080b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(),
27090b57cec5SDimitry Andric          "FPToSI result must be integer or integer vector", &I);
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric   if (SrcVec && DstVec)
27120b57cec5SDimitry Andric     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
27130b57cec5SDimitry Andric                cast<VectorType>(DestTy)->getNumElements(),
27140b57cec5SDimitry Andric            "FPToSI source and dest vector length mismatch", &I);
27150b57cec5SDimitry Andric 
27160b57cec5SDimitry Andric   visitInstruction(I);
27170b57cec5SDimitry Andric }
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
27200b57cec5SDimitry Andric   // Get the source and destination types
27210b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27220b57cec5SDimitry Andric   Type *DestTy = I.getType();
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
27250b57cec5SDimitry Andric 
27260b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType()))
27270b57cec5SDimitry Andric     Assert(!DL.isNonIntegralPointerType(PTy),
27280b57cec5SDimitry Andric            "ptrtoint not supported for non-integral pointers");
27290b57cec5SDimitry Andric 
27300b57cec5SDimitry Andric   Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
27310b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
27320b57cec5SDimitry Andric          &I);
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
2735*8bcb0991SDimitry Andric     VectorType *VSrc = cast<VectorType>(SrcTy);
2736*8bcb0991SDimitry Andric     VectorType *VDest = cast<VectorType>(DestTy);
27370b57cec5SDimitry Andric     Assert(VSrc->getNumElements() == VDest->getNumElements(),
27380b57cec5SDimitry Andric            "PtrToInt Vector width mismatch", &I);
27390b57cec5SDimitry Andric   }
27400b57cec5SDimitry Andric 
27410b57cec5SDimitry Andric   visitInstruction(I);
27420b57cec5SDimitry Andric }
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
27450b57cec5SDimitry Andric   // Get the source and destination types
27460b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27470b57cec5SDimitry Andric   Type *DestTy = I.getType();
27480b57cec5SDimitry Andric 
27490b57cec5SDimitry Andric   Assert(SrcTy->isIntOrIntVectorTy(),
27500b57cec5SDimitry Andric          "IntToPtr source must be an integral", &I);
27510b57cec5SDimitry Andric   Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType()))
27540b57cec5SDimitry Andric     Assert(!DL.isNonIntegralPointerType(PTy),
27550b57cec5SDimitry Andric            "inttoptr not supported for non-integral pointers");
27560b57cec5SDimitry Andric 
27570b57cec5SDimitry Andric   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
27580b57cec5SDimitry Andric          &I);
27590b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
2760*8bcb0991SDimitry Andric     VectorType *VSrc = cast<VectorType>(SrcTy);
2761*8bcb0991SDimitry Andric     VectorType *VDest = cast<VectorType>(DestTy);
27620b57cec5SDimitry Andric     Assert(VSrc->getNumElements() == VDest->getNumElements(),
27630b57cec5SDimitry Andric            "IntToPtr Vector width mismatch", &I);
27640b57cec5SDimitry Andric   }
27650b57cec5SDimitry Andric   visitInstruction(I);
27660b57cec5SDimitry Andric }
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
27690b57cec5SDimitry Andric   Assert(
27700b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
27710b57cec5SDimitry Andric       "Invalid bitcast", &I);
27720b57cec5SDimitry Andric   visitInstruction(I);
27730b57cec5SDimitry Andric }
27740b57cec5SDimitry Andric 
27750b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
27760b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
27770b57cec5SDimitry Andric   Type *DestTy = I.getType();
27780b57cec5SDimitry Andric 
27790b57cec5SDimitry Andric   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
27800b57cec5SDimitry Andric          &I);
27810b57cec5SDimitry Andric   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
27820b57cec5SDimitry Andric          &I);
27830b57cec5SDimitry Andric   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
27840b57cec5SDimitry Andric          "AddrSpaceCast must be between different address spaces", &I);
27850b57cec5SDimitry Andric   if (SrcTy->isVectorTy())
27860b57cec5SDimitry Andric     Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
27870b57cec5SDimitry Andric            "AddrSpaceCast vector pointer number of elements mismatch", &I);
27880b57cec5SDimitry Andric   visitInstruction(I);
27890b57cec5SDimitry Andric }
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
27920b57cec5SDimitry Andric ///
27930b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
27940b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
27950b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
27960b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
27970b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
27980b57cec5SDimitry Andric   Assert(&PN == &PN.getParent()->front() ||
27990b57cec5SDimitry Andric              isa<PHINode>(--BasicBlock::iterator(&PN)),
28000b57cec5SDimitry Andric          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
28010b57cec5SDimitry Andric 
28020b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
28030b57cec5SDimitry Andric   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
28040b57cec5SDimitry Andric 
28050b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
28060b57cec5SDimitry Andric   // result, and that the incoming blocks are really basic blocks.
28070b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
28080b57cec5SDimitry Andric     Assert(PN.getType() == IncValue->getType(),
28090b57cec5SDimitry Andric            "PHI node operands are not the same type as the result!", &PN);
28100b57cec5SDimitry Andric   }
28110b57cec5SDimitry Andric 
28120b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric   visitInstruction(PN);
28150b57cec5SDimitry Andric }
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
28180b57cec5SDimitry Andric   Assert(Call.getCalledValue()->getType()->isPointerTy(),
28190b57cec5SDimitry Andric          "Called function must be a pointer!", Call);
28200b57cec5SDimitry Andric   PointerType *FPTy = cast<PointerType>(Call.getCalledValue()->getType());
28210b57cec5SDimitry Andric 
28220b57cec5SDimitry Andric   Assert(FPTy->getElementType()->isFunctionTy(),
28230b57cec5SDimitry Andric          "Called function is not pointer to function type!", Call);
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric   Assert(FPTy->getElementType() == Call.getFunctionType(),
28260b57cec5SDimitry Andric          "Called function is not the same type as the call!", Call);
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
28310b57cec5SDimitry Andric   if (FTy->isVarArg())
28320b57cec5SDimitry Andric     Assert(Call.arg_size() >= FTy->getNumParams(),
28330b57cec5SDimitry Andric            "Called function requires more parameters than were provided!",
28340b57cec5SDimitry Andric            Call);
28350b57cec5SDimitry Andric   else
28360b57cec5SDimitry Andric     Assert(Call.arg_size() == FTy->getNumParams(),
28370b57cec5SDimitry Andric            "Incorrect number of arguments passed to called function!", Call);
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
28400b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
28410b57cec5SDimitry Andric     Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
28420b57cec5SDimitry Andric            "Call parameter type does not match function signature!",
28430b57cec5SDimitry Andric            Call.getArgOperand(i), FTy->getParamType(i), Call);
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   Assert(verifyAttributeCount(Attrs, Call.arg_size()),
28480b57cec5SDimitry Andric          "Attribute after last parameter!", Call);
28490b57cec5SDimitry Andric 
28500b57cec5SDimitry Andric   bool IsIntrinsic = Call.getCalledFunction() &&
28510b57cec5SDimitry Andric                      Call.getCalledFunction()->getName().startswith("llvm.");
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   Function *Callee
28540b57cec5SDimitry Andric     = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric   if (Attrs.hasAttribute(AttributeList::FunctionIndex, Attribute::Speculatable)) {
28570b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
28580b57cec5SDimitry Andric     // declaration is also speculatable.
28590b57cec5SDimitry Andric     Assert(Callee && Callee->isSpeculatable(),
28600b57cec5SDimitry Andric            "speculatable attribute may not apply to call sites", Call);
28610b57cec5SDimitry Andric   }
28620b57cec5SDimitry Andric 
28630b57cec5SDimitry Andric   // Verify call attributes.
28640b57cec5SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
28670b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
28680b57cec5SDimitry Andric   // inalloca.
28690b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
28700b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
28710b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
28720b57cec5SDimitry Andric       Assert(AI->isUsedWithInAlloca(),
28730b57cec5SDimitry Andric              "inalloca argument for call has mismatched alloca", AI, Call);
28740b57cec5SDimitry Andric   }
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
28770b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
28780b57cec5SDimitry Andric   // well.
28790b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
28800b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
28810b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
28820b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
28830b57cec5SDimitry Andric         Assert(AI->isSwiftError(),
28840b57cec5SDimitry Andric                "swifterror argument for call has mismatched alloca", AI, Call);
28850b57cec5SDimitry Andric         continue;
28860b57cec5SDimitry Andric       }
28870b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
28880b57cec5SDimitry Andric       Assert(ArgI,
28890b57cec5SDimitry Andric              "swifterror argument should come from an alloca or parameter",
28900b57cec5SDimitry Andric              SwiftErrorArg, Call);
28910b57cec5SDimitry Andric       Assert(ArgI->hasSwiftErrorAttr(),
28920b57cec5SDimitry Andric              "swifterror argument for call has mismatched parameter", ArgI,
28930b57cec5SDimitry Andric              Call);
28940b57cec5SDimitry Andric     }
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric     if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) {
28970b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
28980b57cec5SDimitry Andric       // also has the matching immarg.
28990b57cec5SDimitry Andric       Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
29000b57cec5SDimitry Andric              "immarg may not apply only to call sites",
29010b57cec5SDimitry Andric              Call.getArgOperand(i), Call);
29020b57cec5SDimitry Andric     }
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
29050b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
29060b57cec5SDimitry Andric       Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
29070b57cec5SDimitry Andric              "immarg operand has non-immediate parameter", ArgVal, Call);
29080b57cec5SDimitry Andric     }
29090b57cec5SDimitry Andric   }
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric   if (FTy->isVarArg()) {
29120b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
29130b57cec5SDimitry Andric     bool SawNest = false;
29140b57cec5SDimitry Andric     bool SawReturned = false;
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
29170b57cec5SDimitry Andric       if (Attrs.hasParamAttribute(Idx, Attribute::Nest))
29180b57cec5SDimitry Andric         SawNest = true;
29190b57cec5SDimitry Andric       if (Attrs.hasParamAttribute(Idx, Attribute::Returned))
29200b57cec5SDimitry Andric         SawReturned = true;
29210b57cec5SDimitry Andric     }
29220b57cec5SDimitry Andric 
29230b57cec5SDimitry Andric     // Check attributes on the varargs part.
29240b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
29250b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
29260b57cec5SDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx);
29270b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
29300b57cec5SDimitry Andric         Assert(!SawNest, "More than one parameter has attribute nest!", Call);
29310b57cec5SDimitry Andric         SawNest = true;
29320b57cec5SDimitry Andric       }
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
29350b57cec5SDimitry Andric         Assert(!SawReturned, "More than one parameter has attribute returned!",
29360b57cec5SDimitry Andric                Call);
29370b57cec5SDimitry Andric         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
29380b57cec5SDimitry Andric                "Incompatible argument and return types for 'returned' "
29390b57cec5SDimitry Andric                "attribute",
29400b57cec5SDimitry Andric                Call);
29410b57cec5SDimitry Andric         SawReturned = true;
29420b57cec5SDimitry Andric       }
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
29450b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
29460b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
29470b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
29480b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
29490b57cec5SDimitry Andric         Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
29500b57cec5SDimitry Andric                "Attribute 'sret' cannot be used for vararg call arguments!",
29510b57cec5SDimitry Andric                Call);
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
29540b57cec5SDimitry Andric         Assert(Idx == Call.arg_size() - 1,
29550b57cec5SDimitry Andric                "inalloca isn't on the last argument!", Call);
29560b57cec5SDimitry Andric     }
29570b57cec5SDimitry Andric   }
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
29600b57cec5SDimitry Andric   if (!IsIntrinsic) {
29610b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
29620b57cec5SDimitry Andric       Assert(!ParamTy->isMetadataTy(),
29630b57cec5SDimitry Andric              "Function has metadata parameter but isn't an intrinsic", Call);
29640b57cec5SDimitry Andric       Assert(!ParamTy->isTokenTy(),
29650b57cec5SDimitry Andric              "Function has token parameter but isn't an intrinsic", Call);
29660b57cec5SDimitry Andric     }
29670b57cec5SDimitry Andric   }
29680b57cec5SDimitry Andric 
29690b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
29700b57cec5SDimitry Andric   if (!Call.getCalledFunction())
29710b57cec5SDimitry Andric     Assert(!FTy->getReturnType()->isTokenTy(),
29720b57cec5SDimitry Andric            "Return type cannot be token for indirect call!");
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
29750b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
29760b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet" and
29790b57cec5SDimitry Andric   // at most one "gc-transition" operand bundle.
29800b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
29810b57cec5SDimitry Andric        FoundGCTransitionBundle = false;
29820b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
29830b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
29840b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
29850b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
29860b57cec5SDimitry Andric       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
29870b57cec5SDimitry Andric       FoundDeoptBundle = true;
29880b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
29890b57cec5SDimitry Andric       Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
29900b57cec5SDimitry Andric              Call);
29910b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
29920b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
29930b57cec5SDimitry Andric       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
29940b57cec5SDimitry Andric       FoundFuncletBundle = true;
29950b57cec5SDimitry Andric       Assert(BU.Inputs.size() == 1,
29960b57cec5SDimitry Andric              "Expected exactly one funclet bundle operand", Call);
29970b57cec5SDimitry Andric       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
29980b57cec5SDimitry Andric              "Funclet bundle operands should correspond to a FuncletPadInst",
29990b57cec5SDimitry Andric              Call);
30000b57cec5SDimitry Andric     }
30010b57cec5SDimitry Andric   }
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
30040b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
30050b57cec5SDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info.
30060b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
30070b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
30080b57cec5SDimitry Andric     AssertDI(Call.getDebugLoc(),
30090b57cec5SDimitry Andric              "inlinable function call in a function with "
30100b57cec5SDimitry Andric              "debug info must have a !dbg location",
30110b57cec5SDimitry Andric              Call);
30120b57cec5SDimitry Andric 
30130b57cec5SDimitry Andric   visitInstruction(Call);
30140b57cec5SDimitry Andric }
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
30170b57cec5SDimitry Andric /// types with different pointee types and the same address space.
30180b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
30190b57cec5SDimitry Andric   if (L == R)
30200b57cec5SDimitry Andric     return true;
30210b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
30220b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
30230b57cec5SDimitry Andric   if (!PL || !PR)
30240b57cec5SDimitry Andric     return false;
30250b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
30260b57cec5SDimitry Andric }
30270b57cec5SDimitry Andric 
30280b57cec5SDimitry Andric static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) {
30290b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
30300b57cec5SDimitry Andric       Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
30310b57cec5SDimitry Andric       Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf,
30320b57cec5SDimitry Andric       Attribute::SwiftError};
30330b57cec5SDimitry Andric   AttrBuilder Copy;
30340b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
30350b57cec5SDimitry Andric     if (Attrs.hasParamAttribute(I, AK))
30360b57cec5SDimitry Andric       Copy.addAttribute(AK);
30370b57cec5SDimitry Andric   }
30380b57cec5SDimitry Andric   if (Attrs.hasParamAttribute(I, Attribute::Alignment))
30390b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
30400b57cec5SDimitry Andric   return Copy;
30410b57cec5SDimitry Andric }
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
30440b57cec5SDimitry Andric   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
30470b57cec5SDimitry Andric   //   parameters or return types may differ in pointee type, but not
30480b57cec5SDimitry Andric   //   address space.
30490b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
30500b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
30510b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
30520b57cec5SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
30530b57cec5SDimitry Andric     Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
30540b57cec5SDimitry Andric            "cannot guarantee tail call due to mismatched parameter counts",
30550b57cec5SDimitry Andric            &CI);
30560b57cec5SDimitry Andric     for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
30570b57cec5SDimitry Andric       Assert(
30580b57cec5SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
30590b57cec5SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
30600b57cec5SDimitry Andric     }
30610b57cec5SDimitry Andric   }
30620b57cec5SDimitry Andric   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
30630b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched varargs", &CI);
30640b57cec5SDimitry Andric   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
30650b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched return types", &CI);
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
30680b57cec5SDimitry Andric   Assert(F->getCallingConv() == CI.getCallingConv(),
30690b57cec5SDimitry Andric          "cannot guarantee tail call due to mismatched calling conv", &CI);
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
30720b57cec5SDimitry Andric   //   returned, and inalloca, must match.
30730b57cec5SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
30740b57cec5SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
30750b57cec5SDimitry Andric   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
30760b57cec5SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
30770b57cec5SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
30780b57cec5SDimitry Andric     Assert(CallerABIAttrs == CalleeABIAttrs,
30790b57cec5SDimitry Andric            "cannot guarantee tail call due to mismatched ABI impacting "
30800b57cec5SDimitry Andric            "function attributes",
30810b57cec5SDimitry Andric            &CI, CI.getOperand(I));
30820b57cec5SDimitry Andric   }
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
30850b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
30860b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
30870b57cec5SDimitry Andric   //   produced by the call or void.
30880b57cec5SDimitry Andric   Value *RetVal = &CI;
30890b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
30900b57cec5SDimitry Andric 
30910b57cec5SDimitry Andric   // Handle the optional bitcast.
30920b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
30930b57cec5SDimitry Andric     Assert(BI->getOperand(0) == RetVal,
30940b57cec5SDimitry Andric            "bitcast following musttail call must use the call", BI);
30950b57cec5SDimitry Andric     RetVal = BI;
30960b57cec5SDimitry Andric     Next = BI->getNextNode();
30970b57cec5SDimitry Andric   }
30980b57cec5SDimitry Andric 
30990b57cec5SDimitry Andric   // Check the return.
31000b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
31010b57cec5SDimitry Andric   Assert(Ret, "musttail call must precede a ret with an optional bitcast",
31020b57cec5SDimitry Andric          &CI);
31030b57cec5SDimitry Andric   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
31040b57cec5SDimitry Andric          "musttail call result must be returned", Ret);
31050b57cec5SDimitry Andric }
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
31080b57cec5SDimitry Andric   visitCallBase(CI);
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric   if (CI.isMustTailCall())
31110b57cec5SDimitry Andric     verifyMustTailCall(CI);
31120b57cec5SDimitry Andric }
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
31150b57cec5SDimitry Andric   visitCallBase(II);
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
31180b57cec5SDimitry Andric   // exception handling instruction.
31190b57cec5SDimitry Andric   Assert(
31200b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
31210b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
31220b57cec5SDimitry Andric       &II);
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   visitTerminator(II);
31250b57cec5SDimitry Andric }
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
31280b57cec5SDimitry Andric ///
31290b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
31300b57cec5SDimitry Andric   Assert(U.getType() == U.getOperand(0)->getType(),
31310b57cec5SDimitry Andric          "Unary operators must have same type for"
31320b57cec5SDimitry Andric          "operands and result!",
31330b57cec5SDimitry Andric          &U);
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   switch (U.getOpcode()) {
31360b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
31370b57cec5SDimitry Andric   // floating-point operands.
31380b57cec5SDimitry Andric   case Instruction::FNeg:
31390b57cec5SDimitry Andric     Assert(U.getType()->isFPOrFPVectorTy(),
31400b57cec5SDimitry Andric            "FNeg operator only works with float types!", &U);
31410b57cec5SDimitry Andric     break;
31420b57cec5SDimitry Andric   default:
31430b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
31440b57cec5SDimitry Andric   }
31450b57cec5SDimitry Andric 
31460b57cec5SDimitry Andric   visitInstruction(U);
31470b57cec5SDimitry Andric }
31480b57cec5SDimitry Andric 
31490b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
31500b57cec5SDimitry Andric /// of the same type!
31510b57cec5SDimitry Andric ///
31520b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
31530b57cec5SDimitry Andric   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
31540b57cec5SDimitry Andric          "Both operands to a binary operator are not of the same type!", &B);
31550b57cec5SDimitry Andric 
31560b57cec5SDimitry Andric   switch (B.getOpcode()) {
31570b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
31580b57cec5SDimitry Andric   // integral operands.
31590b57cec5SDimitry Andric   case Instruction::Add:
31600b57cec5SDimitry Andric   case Instruction::Sub:
31610b57cec5SDimitry Andric   case Instruction::Mul:
31620b57cec5SDimitry Andric   case Instruction::SDiv:
31630b57cec5SDimitry Andric   case Instruction::UDiv:
31640b57cec5SDimitry Andric   case Instruction::SRem:
31650b57cec5SDimitry Andric   case Instruction::URem:
31660b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
31670b57cec5SDimitry Andric            "Integer arithmetic operators only work with integral types!", &B);
31680b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
31690b57cec5SDimitry Andric            "Integer arithmetic operators must have same type "
31700b57cec5SDimitry Andric            "for operands and result!",
31710b57cec5SDimitry Andric            &B);
31720b57cec5SDimitry Andric     break;
31730b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
31740b57cec5SDimitry Andric   // floating-point operands.
31750b57cec5SDimitry Andric   case Instruction::FAdd:
31760b57cec5SDimitry Andric   case Instruction::FSub:
31770b57cec5SDimitry Andric   case Instruction::FMul:
31780b57cec5SDimitry Andric   case Instruction::FDiv:
31790b57cec5SDimitry Andric   case Instruction::FRem:
31800b57cec5SDimitry Andric     Assert(B.getType()->isFPOrFPVectorTy(),
31810b57cec5SDimitry Andric            "Floating-point arithmetic operators only work with "
31820b57cec5SDimitry Andric            "floating-point types!",
31830b57cec5SDimitry Andric            &B);
31840b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
31850b57cec5SDimitry Andric            "Floating-point arithmetic operators must have same type "
31860b57cec5SDimitry Andric            "for operands and result!",
31870b57cec5SDimitry Andric            &B);
31880b57cec5SDimitry Andric     break;
31890b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
31900b57cec5SDimitry Andric   case Instruction::And:
31910b57cec5SDimitry Andric   case Instruction::Or:
31920b57cec5SDimitry Andric   case Instruction::Xor:
31930b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
31940b57cec5SDimitry Andric            "Logical operators only work with integral types!", &B);
31950b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
31960b57cec5SDimitry Andric            "Logical operators must have same type for operands and result!",
31970b57cec5SDimitry Andric            &B);
31980b57cec5SDimitry Andric     break;
31990b57cec5SDimitry Andric   case Instruction::Shl:
32000b57cec5SDimitry Andric   case Instruction::LShr:
32010b57cec5SDimitry Andric   case Instruction::AShr:
32020b57cec5SDimitry Andric     Assert(B.getType()->isIntOrIntVectorTy(),
32030b57cec5SDimitry Andric            "Shifts only work with integral types!", &B);
32040b57cec5SDimitry Andric     Assert(B.getType() == B.getOperand(0)->getType(),
32050b57cec5SDimitry Andric            "Shift return type must be same as operands!", &B);
32060b57cec5SDimitry Andric     break;
32070b57cec5SDimitry Andric   default:
32080b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
32090b57cec5SDimitry Andric   }
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric   visitInstruction(B);
32120b57cec5SDimitry Andric }
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
32150b57cec5SDimitry Andric   // Check that the operands are the same type
32160b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
32170b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
32180b57cec5SDimitry Andric   Assert(Op0Ty == Op1Ty,
32190b57cec5SDimitry Andric          "Both operands to ICmp instruction are not of the same type!", &IC);
32200b57cec5SDimitry Andric   // Check that the operands are the right type
32210b57cec5SDimitry Andric   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
32220b57cec5SDimitry Andric          "Invalid operand types for ICmp instruction", &IC);
32230b57cec5SDimitry Andric   // Check that the predicate is valid.
32240b57cec5SDimitry Andric   Assert(IC.isIntPredicate(),
32250b57cec5SDimitry Andric          "Invalid predicate in ICmp instruction!", &IC);
32260b57cec5SDimitry Andric 
32270b57cec5SDimitry Andric   visitInstruction(IC);
32280b57cec5SDimitry Andric }
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
32310b57cec5SDimitry Andric   // Check that the operands are the same type
32320b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
32330b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
32340b57cec5SDimitry Andric   Assert(Op0Ty == Op1Ty,
32350b57cec5SDimitry Andric          "Both operands to FCmp instruction are not of the same type!", &FC);
32360b57cec5SDimitry Andric   // Check that the operands are the right type
32370b57cec5SDimitry Andric   Assert(Op0Ty->isFPOrFPVectorTy(),
32380b57cec5SDimitry Andric          "Invalid operand types for FCmp instruction", &FC);
32390b57cec5SDimitry Andric   // Check that the predicate is valid.
32400b57cec5SDimitry Andric   Assert(FC.isFPPredicate(),
32410b57cec5SDimitry Andric          "Invalid predicate in FCmp instruction!", &FC);
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric   visitInstruction(FC);
32440b57cec5SDimitry Andric }
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
32470b57cec5SDimitry Andric   Assert(
32480b57cec5SDimitry Andric       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
32490b57cec5SDimitry Andric       "Invalid extractelement operands!", &EI);
32500b57cec5SDimitry Andric   visitInstruction(EI);
32510b57cec5SDimitry Andric }
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
32540b57cec5SDimitry Andric   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
32550b57cec5SDimitry Andric                                             IE.getOperand(2)),
32560b57cec5SDimitry Andric          "Invalid insertelement operands!", &IE);
32570b57cec5SDimitry Andric   visitInstruction(IE);
32580b57cec5SDimitry Andric }
32590b57cec5SDimitry Andric 
32600b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
32610b57cec5SDimitry Andric   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
32620b57cec5SDimitry Andric                                             SV.getOperand(2)),
32630b57cec5SDimitry Andric          "Invalid shufflevector operands!", &SV);
32640b57cec5SDimitry Andric   visitInstruction(SV);
32650b57cec5SDimitry Andric }
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
32680b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric   Assert(isa<PointerType>(TargetTy),
32710b57cec5SDimitry Andric          "GEP base pointer is not a vector or a vector of pointers", &GEP);
32720b57cec5SDimitry Andric   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
32730b57cec5SDimitry Andric 
32740b57cec5SDimitry Andric   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
32750b57cec5SDimitry Andric   Assert(all_of(
32760b57cec5SDimitry Andric       Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
32770b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
32780b57cec5SDimitry Andric   Type *ElTy =
32790b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
32800b57cec5SDimitry Andric   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric   Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
32830b57cec5SDimitry Andric              GEP.getResultElementType() == ElTy,
32840b57cec5SDimitry Andric          "GEP is not of right type for indices!", &GEP, ElTy);
32850b57cec5SDimitry Andric 
32860b57cec5SDimitry Andric   if (GEP.getType()->isVectorTy()) {
32870b57cec5SDimitry Andric     // Additional checks for vector GEPs.
32880b57cec5SDimitry Andric     unsigned GEPWidth = GEP.getType()->getVectorNumElements();
32890b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
32900b57cec5SDimitry Andric       Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
32910b57cec5SDimitry Andric              "Vector GEP result width doesn't match operand's", &GEP);
32920b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
32930b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
32940b57cec5SDimitry Andric       if (IndexTy->isVectorTy()) {
32950b57cec5SDimitry Andric         unsigned IndexWidth = IndexTy->getVectorNumElements();
32960b57cec5SDimitry Andric         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
32970b57cec5SDimitry Andric       }
32980b57cec5SDimitry Andric       Assert(IndexTy->isIntOrIntVectorTy(),
32990b57cec5SDimitry Andric              "All GEP indices should be of integer type");
33000b57cec5SDimitry Andric     }
33010b57cec5SDimitry Andric   }
33020b57cec5SDimitry Andric 
33030b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
33040b57cec5SDimitry Andric     Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
33050b57cec5SDimitry Andric            "GEP address space doesn't match type", &GEP);
33060b57cec5SDimitry Andric   }
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric   visitInstruction(GEP);
33090b57cec5SDimitry Andric }
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
33120b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
33130b57cec5SDimitry Andric }
33140b57cec5SDimitry Andric 
33150b57cec5SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
33160b57cec5SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
33170b57cec5SDimitry Andric          "precondition violation");
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
33200b57cec5SDimitry Andric   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
33210b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
33220b57cec5SDimitry Andric   Assert(NumRanges >= 1, "It should have at least one range!", Range);
33230b57cec5SDimitry Andric 
33240b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
33250b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
33260b57cec5SDimitry Andric     ConstantInt *Low =
33270b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
33280b57cec5SDimitry Andric     Assert(Low, "The lower limit must be an integer!", Low);
33290b57cec5SDimitry Andric     ConstantInt *High =
33300b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
33310b57cec5SDimitry Andric     Assert(High, "The upper limit must be an integer!", High);
33320b57cec5SDimitry Andric     Assert(High->getType() == Low->getType() && High->getType() == Ty,
33330b57cec5SDimitry Andric            "Range types must match instruction type!", &I);
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric     APInt HighV = High->getValue();
33360b57cec5SDimitry Andric     APInt LowV = Low->getValue();
33370b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
33380b57cec5SDimitry Andric     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
33390b57cec5SDimitry Andric            "Range must not be empty!", Range);
33400b57cec5SDimitry Andric     if (i != 0) {
33410b57cec5SDimitry Andric       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
33420b57cec5SDimitry Andric              "Intervals are overlapping", Range);
33430b57cec5SDimitry Andric       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
33440b57cec5SDimitry Andric              Range);
33450b57cec5SDimitry Andric       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
33460b57cec5SDimitry Andric              Range);
33470b57cec5SDimitry Andric     }
33480b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
33490b57cec5SDimitry Andric   }
33500b57cec5SDimitry Andric   if (NumRanges > 2) {
33510b57cec5SDimitry Andric     APInt FirstLow =
33520b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
33530b57cec5SDimitry Andric     APInt FirstHigh =
33540b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
33550b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
33560b57cec5SDimitry Andric     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
33570b57cec5SDimitry Andric            "Intervals are overlapping", Range);
33580b57cec5SDimitry Andric     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
33590b57cec5SDimitry Andric            Range);
33600b57cec5SDimitry Andric   }
33610b57cec5SDimitry Andric }
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
33640b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
33650b57cec5SDimitry Andric   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
33660b57cec5SDimitry Andric   Assert(!(Size & (Size - 1)),
33670b57cec5SDimitry Andric          "atomic memory access' operand must have a power-of-two size", Ty, I);
33680b57cec5SDimitry Andric }
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
33710b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
33720b57cec5SDimitry Andric   Assert(PTy, "Load operand must be a pointer.", &LI);
33730b57cec5SDimitry Andric   Type *ElTy = LI.getType();
33740b57cec5SDimitry Andric   Assert(LI.getAlignment() <= Value::MaximumAlignment,
33750b57cec5SDimitry Andric          "huge alignment values are unsupported", &LI);
33760b57cec5SDimitry Andric   Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
33770b57cec5SDimitry Andric   if (LI.isAtomic()) {
33780b57cec5SDimitry Andric     Assert(LI.getOrdering() != AtomicOrdering::Release &&
33790b57cec5SDimitry Andric                LI.getOrdering() != AtomicOrdering::AcquireRelease,
33800b57cec5SDimitry Andric            "Load cannot have Release ordering", &LI);
33810b57cec5SDimitry Andric     Assert(LI.getAlignment() != 0,
33820b57cec5SDimitry Andric            "Atomic load must specify explicit alignment", &LI);
33830b57cec5SDimitry Andric     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
33840b57cec5SDimitry Andric            "atomic load operand must have integer, pointer, or floating point "
33850b57cec5SDimitry Andric            "type!",
33860b57cec5SDimitry Andric            ElTy, &LI);
33870b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
33880b57cec5SDimitry Andric   } else {
33890b57cec5SDimitry Andric     Assert(LI.getSyncScopeID() == SyncScope::System,
33900b57cec5SDimitry Andric            "Non-atomic load cannot have SynchronizationScope specified", &LI);
33910b57cec5SDimitry Andric   }
33920b57cec5SDimitry Andric 
33930b57cec5SDimitry Andric   visitInstruction(LI);
33940b57cec5SDimitry Andric }
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
33970b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
33980b57cec5SDimitry Andric   Assert(PTy, "Store operand must be a pointer.", &SI);
33990b57cec5SDimitry Andric   Type *ElTy = PTy->getElementType();
34000b57cec5SDimitry Andric   Assert(ElTy == SI.getOperand(0)->getType(),
34010b57cec5SDimitry Andric          "Stored value type does not match pointer operand type!", &SI, ElTy);
34020b57cec5SDimitry Andric   Assert(SI.getAlignment() <= Value::MaximumAlignment,
34030b57cec5SDimitry Andric          "huge alignment values are unsupported", &SI);
34040b57cec5SDimitry Andric   Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
34050b57cec5SDimitry Andric   if (SI.isAtomic()) {
34060b57cec5SDimitry Andric     Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
34070b57cec5SDimitry Andric                SI.getOrdering() != AtomicOrdering::AcquireRelease,
34080b57cec5SDimitry Andric            "Store cannot have Acquire ordering", &SI);
34090b57cec5SDimitry Andric     Assert(SI.getAlignment() != 0,
34100b57cec5SDimitry Andric            "Atomic store must specify explicit alignment", &SI);
34110b57cec5SDimitry Andric     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
34120b57cec5SDimitry Andric            "atomic store operand must have integer, pointer, or floating point "
34130b57cec5SDimitry Andric            "type!",
34140b57cec5SDimitry Andric            ElTy, &SI);
34150b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
34160b57cec5SDimitry Andric   } else {
34170b57cec5SDimitry Andric     Assert(SI.getSyncScopeID() == SyncScope::System,
34180b57cec5SDimitry Andric            "Non-atomic store cannot have SynchronizationScope specified", &SI);
34190b57cec5SDimitry Andric   }
34200b57cec5SDimitry Andric   visitInstruction(SI);
34210b57cec5SDimitry Andric }
34220b57cec5SDimitry Andric 
34230b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
34240b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
34250b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
34260b57cec5SDimitry Andric   unsigned Idx = 0;
34270b57cec5SDimitry Andric   for (auto I = Call.arg_begin(), E = Call.arg_end(); I != E; ++I, ++Idx) {
34280b57cec5SDimitry Andric     if (*I == SwiftErrorVal) {
34290b57cec5SDimitry Andric       Assert(Call.paramHasAttr(Idx, Attribute::SwiftError),
34300b57cec5SDimitry Andric              "swifterror value when used in a callsite should be marked "
34310b57cec5SDimitry Andric              "with swifterror attribute",
34320b57cec5SDimitry Andric              SwiftErrorVal, Call);
34330b57cec5SDimitry Andric     }
34340b57cec5SDimitry Andric   }
34350b57cec5SDimitry Andric }
34360b57cec5SDimitry Andric 
34370b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
34380b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
34390b57cec5SDimitry Andric   // a swifterror argument.
34400b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
34410b57cec5SDimitry Andric     Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
34420b57cec5SDimitry Andric            isa<InvokeInst>(U),
34430b57cec5SDimitry Andric            "swifterror value can only be loaded and stored from, or "
34440b57cec5SDimitry Andric            "as a swifterror argument!",
34450b57cec5SDimitry Andric            SwiftErrorVal, U);
34460b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
34470b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
34480b57cec5SDimitry Andric       Assert(StoreI->getOperand(1) == SwiftErrorVal,
34490b57cec5SDimitry Andric              "swifterror value should be the second operand when used "
34500b57cec5SDimitry Andric              "by stores", SwiftErrorVal, U);
34510b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
34520b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
34530b57cec5SDimitry Andric   }
34540b57cec5SDimitry Andric }
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
34570b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
34580b57cec5SDimitry Andric   PointerType *PTy = AI.getType();
34590b57cec5SDimitry Andric   // TODO: Relax this restriction?
34600b57cec5SDimitry Andric   Assert(PTy->getAddressSpace() == DL.getAllocaAddrSpace(),
34610b57cec5SDimitry Andric          "Allocation instruction pointer not in the stack address space!",
34620b57cec5SDimitry Andric          &AI);
34630b57cec5SDimitry Andric   Assert(AI.getAllocatedType()->isSized(&Visited),
34640b57cec5SDimitry Andric          "Cannot allocate unsized type", &AI);
34650b57cec5SDimitry Andric   Assert(AI.getArraySize()->getType()->isIntegerTy(),
34660b57cec5SDimitry Andric          "Alloca array size must have integer type", &AI);
34670b57cec5SDimitry Andric   Assert(AI.getAlignment() <= Value::MaximumAlignment,
34680b57cec5SDimitry Andric          "huge alignment values are unsupported", &AI);
34690b57cec5SDimitry Andric 
34700b57cec5SDimitry Andric   if (AI.isSwiftError()) {
34710b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
34720b57cec5SDimitry Andric   }
34730b57cec5SDimitry Andric 
34740b57cec5SDimitry Andric   visitInstruction(AI);
34750b57cec5SDimitry Andric }
34760b57cec5SDimitry Andric 
34770b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   // FIXME: more conditions???
34800b57cec5SDimitry Andric   Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic,
34810b57cec5SDimitry Andric          "cmpxchg instructions must be atomic.", &CXI);
34820b57cec5SDimitry Andric   Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic,
34830b57cec5SDimitry Andric          "cmpxchg instructions must be atomic.", &CXI);
34840b57cec5SDimitry Andric   Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered,
34850b57cec5SDimitry Andric          "cmpxchg instructions cannot be unordered.", &CXI);
34860b57cec5SDimitry Andric   Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered,
34870b57cec5SDimitry Andric          "cmpxchg instructions cannot be unordered.", &CXI);
34880b57cec5SDimitry Andric   Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()),
34890b57cec5SDimitry Andric          "cmpxchg instructions failure argument shall be no stronger than the "
34900b57cec5SDimitry Andric          "success argument",
34910b57cec5SDimitry Andric          &CXI);
34920b57cec5SDimitry Andric   Assert(CXI.getFailureOrdering() != AtomicOrdering::Release &&
34930b57cec5SDimitry Andric              CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease,
34940b57cec5SDimitry Andric          "cmpxchg failure ordering cannot include release semantics", &CXI);
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
34970b57cec5SDimitry Andric   Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
34980b57cec5SDimitry Andric   Type *ElTy = PTy->getElementType();
34990b57cec5SDimitry Andric   Assert(ElTy->isIntOrPtrTy(),
35000b57cec5SDimitry Andric          "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
35010b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
35020b57cec5SDimitry Andric   Assert(ElTy == CXI.getOperand(1)->getType(),
35030b57cec5SDimitry Andric          "Expected value type does not match pointer operand type!", &CXI,
35040b57cec5SDimitry Andric          ElTy);
35050b57cec5SDimitry Andric   Assert(ElTy == CXI.getOperand(2)->getType(),
35060b57cec5SDimitry Andric          "Stored value type does not match pointer operand type!", &CXI, ElTy);
35070b57cec5SDimitry Andric   visitInstruction(CXI);
35080b57cec5SDimitry Andric }
35090b57cec5SDimitry Andric 
35100b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
35110b57cec5SDimitry Andric   Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic,
35120b57cec5SDimitry Andric          "atomicrmw instructions must be atomic.", &RMWI);
35130b57cec5SDimitry Andric   Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
35140b57cec5SDimitry Andric          "atomicrmw instructions cannot be unordered.", &RMWI);
35150b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
35160b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
35170b57cec5SDimitry Andric   Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
35180b57cec5SDimitry Andric   Type *ElTy = PTy->getElementType();
35190b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
35200b57cec5SDimitry Andric     Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
35210b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
35220b57cec5SDimitry Andric            " operand must have integer or floating point type!",
35230b57cec5SDimitry Andric            &RMWI, ElTy);
35240b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
35250b57cec5SDimitry Andric     Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
35260b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
35270b57cec5SDimitry Andric            " operand must have floating point type!",
35280b57cec5SDimitry Andric            &RMWI, ElTy);
35290b57cec5SDimitry Andric   } else {
35300b57cec5SDimitry Andric     Assert(ElTy->isIntegerTy(), "atomicrmw " +
35310b57cec5SDimitry Andric            AtomicRMWInst::getOperationName(Op) +
35320b57cec5SDimitry Andric            " operand must have integer type!",
35330b57cec5SDimitry Andric            &RMWI, ElTy);
35340b57cec5SDimitry Andric   }
35350b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
35360b57cec5SDimitry Andric   Assert(ElTy == RMWI.getOperand(1)->getType(),
35370b57cec5SDimitry Andric          "Argument value type does not match pointer operand type!", &RMWI,
35380b57cec5SDimitry Andric          ElTy);
35390b57cec5SDimitry Andric   Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
35400b57cec5SDimitry Andric          "Invalid binary operation!", &RMWI);
35410b57cec5SDimitry Andric   visitInstruction(RMWI);
35420b57cec5SDimitry Andric }
35430b57cec5SDimitry Andric 
35440b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
35450b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
35460b57cec5SDimitry Andric   Assert(Ordering == AtomicOrdering::Acquire ||
35470b57cec5SDimitry Andric              Ordering == AtomicOrdering::Release ||
35480b57cec5SDimitry Andric              Ordering == AtomicOrdering::AcquireRelease ||
35490b57cec5SDimitry Andric              Ordering == AtomicOrdering::SequentiallyConsistent,
35500b57cec5SDimitry Andric          "fence instructions may only have acquire, release, acq_rel, or "
35510b57cec5SDimitry Andric          "seq_cst ordering.",
35520b57cec5SDimitry Andric          &FI);
35530b57cec5SDimitry Andric   visitInstruction(FI);
35540b57cec5SDimitry Andric }
35550b57cec5SDimitry Andric 
35560b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
35570b57cec5SDimitry Andric   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
35580b57cec5SDimitry Andric                                           EVI.getIndices()) == EVI.getType(),
35590b57cec5SDimitry Andric          "Invalid ExtractValueInst operands!", &EVI);
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric   visitInstruction(EVI);
35620b57cec5SDimitry Andric }
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
35650b57cec5SDimitry Andric   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
35660b57cec5SDimitry Andric                                           IVI.getIndices()) ==
35670b57cec5SDimitry Andric              IVI.getOperand(1)->getType(),
35680b57cec5SDimitry Andric          "Invalid InsertValueInst operands!", &IVI);
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   visitInstruction(IVI);
35710b57cec5SDimitry Andric }
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
35740b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
35750b57cec5SDimitry Andric     return FPI->getParentPad();
35760b57cec5SDimitry Andric 
35770b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
35780b57cec5SDimitry Andric }
35790b57cec5SDimitry Andric 
35800b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
35810b57cec5SDimitry Andric   assert(I.isEHPad());
35820b57cec5SDimitry Andric 
35830b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
35840b57cec5SDimitry Andric   Function *F = BB->getParent();
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
35890b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
35900b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
35910b57cec5SDimitry Andric     // invoke.
35920b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
35930b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
35940b57cec5SDimitry Andric       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
35950b57cec5SDimitry Andric              "Block containing LandingPadInst must be jumped to "
35960b57cec5SDimitry Andric              "only by the unwind edge of an invoke.",
35970b57cec5SDimitry Andric              LPI);
35980b57cec5SDimitry Andric     }
35990b57cec5SDimitry Andric     return;
36000b57cec5SDimitry Andric   }
36010b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
36020b57cec5SDimitry Andric     if (!pred_empty(BB))
36030b57cec5SDimitry Andric       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
36040b57cec5SDimitry Andric              "Block containg CatchPadInst must be jumped to "
36050b57cec5SDimitry Andric              "only by its catchswitch.",
36060b57cec5SDimitry Andric              CPI);
36070b57cec5SDimitry Andric     Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
36080b57cec5SDimitry Andric            "Catchswitch cannot unwind to one of its catchpads",
36090b57cec5SDimitry Andric            CPI->getCatchSwitch(), CPI);
36100b57cec5SDimitry Andric     return;
36110b57cec5SDimitry Andric   }
36120b57cec5SDimitry Andric 
36130b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
36140b57cec5SDimitry Andric   // pad relationship.
36150b57cec5SDimitry Andric   Instruction *ToPad = &I;
36160b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
36170b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
36180b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
36190b57cec5SDimitry Andric     Value *FromPad;
36200b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
36210b57cec5SDimitry Andric       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
36220b57cec5SDimitry Andric              "EH pad must be jumped to via an unwind edge", ToPad, II);
36230b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
36240b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
36250b57cec5SDimitry Andric       else
36260b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
36270b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
36280b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
36290b57cec5SDimitry Andric       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
36300b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
36310b57cec5SDimitry Andric       FromPad = CSI;
36320b57cec5SDimitry Andric     } else {
36330b57cec5SDimitry Andric       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
36340b57cec5SDimitry Andric     }
36350b57cec5SDimitry Andric 
36360b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
36370b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
36380b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
36390b57cec5SDimitry Andric       Assert(FromPad != ToPad,
36400b57cec5SDimitry Andric              "EH pad cannot handle exceptions raised within it", FromPad, TI);
36410b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
36420b57cec5SDimitry Andric         // This is a legal unwind edge.
36430b57cec5SDimitry Andric         break;
36440b57cec5SDimitry Andric       }
36450b57cec5SDimitry Andric       Assert(!isa<ConstantTokenNone>(FromPad),
36460b57cec5SDimitry Andric              "A single unwind edge may only enter one EH pad", TI);
36470b57cec5SDimitry Andric       Assert(Seen.insert(FromPad).second,
36480b57cec5SDimitry Andric              "EH pad jumps through a cycle of pads", FromPad);
36490b57cec5SDimitry Andric     }
36500b57cec5SDimitry Andric   }
36510b57cec5SDimitry Andric }
36520b57cec5SDimitry Andric 
36530b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
36540b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
36550b57cec5SDimitry Andric   // isn't a cleanup.
36560b57cec5SDimitry Andric   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
36570b57cec5SDimitry Andric          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
36580b57cec5SDimitry Andric 
36590b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric   if (!LandingPadResultTy)
36620b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
36630b57cec5SDimitry Andric   else
36640b57cec5SDimitry Andric     Assert(LandingPadResultTy == LPI.getType(),
36650b57cec5SDimitry Andric            "The landingpad instruction should have a consistent result type "
36660b57cec5SDimitry Andric            "inside a function.",
36670b57cec5SDimitry Andric            &LPI);
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
36700b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
36710b57cec5SDimitry Andric          "LandingPadInst needs to be in a function with a personality.", &LPI);
36720b57cec5SDimitry Andric 
36730b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
36740b57cec5SDimitry Andric   // block.
36750b57cec5SDimitry Andric   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
36760b57cec5SDimitry Andric          "LandingPadInst not the first non-PHI instruction in the block.",
36770b57cec5SDimitry Andric          &LPI);
36780b57cec5SDimitry Andric 
36790b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
36800b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
36810b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
36820b57cec5SDimitry Andric       Assert(isa<PointerType>(Clause->getType()),
36830b57cec5SDimitry Andric              "Catch operand does not have pointer type!", &LPI);
36840b57cec5SDimitry Andric     } else {
36850b57cec5SDimitry Andric       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
36860b57cec5SDimitry Andric       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
36870b57cec5SDimitry Andric              "Filter operand is not an array of constants!", &LPI);
36880b57cec5SDimitry Andric     }
36890b57cec5SDimitry Andric   }
36900b57cec5SDimitry Andric 
36910b57cec5SDimitry Andric   visitInstruction(LPI);
36920b57cec5SDimitry Andric }
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
36950b57cec5SDimitry Andric   Assert(RI.getFunction()->hasPersonalityFn(),
36960b57cec5SDimitry Andric          "ResumeInst needs to be in a function with a personality.", &RI);
36970b57cec5SDimitry Andric 
36980b57cec5SDimitry Andric   if (!LandingPadResultTy)
36990b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
37000b57cec5SDimitry Andric   else
37010b57cec5SDimitry Andric     Assert(LandingPadResultTy == RI.getValue()->getType(),
37020b57cec5SDimitry Andric            "The resume instruction should have a consistent result type "
37030b57cec5SDimitry Andric            "inside a function.",
37040b57cec5SDimitry Andric            &RI);
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric   visitTerminator(RI);
37070b57cec5SDimitry Andric }
37080b57cec5SDimitry Andric 
37090b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
37100b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
37110b57cec5SDimitry Andric 
37120b57cec5SDimitry Andric   Function *F = BB->getParent();
37130b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
37140b57cec5SDimitry Andric          "CatchPadInst needs to be in a function with a personality.", &CPI);
37150b57cec5SDimitry Andric 
37160b57cec5SDimitry Andric   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
37170b57cec5SDimitry Andric          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
37180b57cec5SDimitry Andric          CPI.getParentPad());
37190b57cec5SDimitry Andric 
37200b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
37210b57cec5SDimitry Andric   // block.
37220b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CPI,
37230b57cec5SDimitry Andric          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
37240b57cec5SDimitry Andric 
37250b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
37260b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
37270b57cec5SDimitry Andric }
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
37300b57cec5SDimitry Andric   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
37310b57cec5SDimitry Andric          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
37320b57cec5SDimitry Andric          CatchReturn.getOperand(0));
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric   visitTerminator(CatchReturn);
37350b57cec5SDimitry Andric }
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
37380b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric   Function *F = BB->getParent();
37410b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
37420b57cec5SDimitry Andric          "CleanupPadInst needs to be in a function with a personality.", &CPI);
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
37450b57cec5SDimitry Andric   // block.
37460b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CPI,
37470b57cec5SDimitry Andric          "CleanupPadInst not the first non-PHI instruction in the block.",
37480b57cec5SDimitry Andric          &CPI);
37490b57cec5SDimitry Andric 
37500b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
37510b57cec5SDimitry Andric   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
37520b57cec5SDimitry Andric          "CleanupPadInst has an invalid parent.", &CPI);
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
37550b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
37560b57cec5SDimitry Andric }
37570b57cec5SDimitry Andric 
37580b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
37590b57cec5SDimitry Andric   User *FirstUser = nullptr;
37600b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
37610b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
37620b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric   while (!Worklist.empty()) {
37650b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
37660b57cec5SDimitry Andric     Assert(Seen.insert(CurrentPad).second,
37670b57cec5SDimitry Andric            "FuncletPadInst must not be nested within itself", CurrentPad);
37680b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
37690b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
37700b57cec5SDimitry Andric       BasicBlock *UnwindDest;
37710b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
37720b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
37730b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
37740b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
37750b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
37760b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
37770b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
37780b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
37790b57cec5SDimitry Andric           continue;
37800b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
37810b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
37820b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
37830b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
37840b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
37850b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
37860b57cec5SDimitry Andric         // such calls to be annotated nounwind.
37870b57cec5SDimitry Andric         continue;
37880b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
37890b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
37900b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
37910b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
37920b57cec5SDimitry Andric         Worklist.push_back(CPI);
37930b57cec5SDimitry Andric         continue;
37940b57cec5SDimitry Andric       } else {
37950b57cec5SDimitry Andric         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
37960b57cec5SDimitry Andric         continue;
37970b57cec5SDimitry Andric       }
37980b57cec5SDimitry Andric 
37990b57cec5SDimitry Andric       Value *UnwindPad;
38000b57cec5SDimitry Andric       bool ExitsFPI;
38010b57cec5SDimitry Andric       if (UnwindDest) {
38020b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
38030b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
38040b57cec5SDimitry Andric           continue;
38050b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
38060b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
38070b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
38080b57cec5SDimitry Andric           continue;
38090b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
38100b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
38110b57cec5SDimitry Andric         // of them are exited so we can stop searching their
38120b57cec5SDimitry Andric         // children.
38130b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
38140b57cec5SDimitry Andric         ExitsFPI = false;
38150b57cec5SDimitry Andric         do {
38160b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
38170b57cec5SDimitry Andric             ExitsFPI = true;
38180b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
38190b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
38200b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
38210b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
38220b57cec5SDimitry Andric             break;
38230b57cec5SDimitry Andric           }
38240b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
38250b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
38260b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
38270b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
38280b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
38290b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
38300b57cec5SDimitry Andric             break;
38310b57cec5SDimitry Andric           }
38320b57cec5SDimitry Andric           ExitedPad = ExitedParent;
38330b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
38340b57cec5SDimitry Andric       } else {
38350b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
38360b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
38370b57cec5SDimitry Andric         ExitsFPI = true;
38380b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
38390b57cec5SDimitry Andric       }
38400b57cec5SDimitry Andric 
38410b57cec5SDimitry Andric       if (ExitsFPI) {
38420b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
38430b57cec5SDimitry Andric         // such edges.
38440b57cec5SDimitry Andric         if (FirstUser) {
38450b57cec5SDimitry Andric           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
38460b57cec5SDimitry Andric                                               "pad must have the same unwind "
38470b57cec5SDimitry Andric                                               "dest",
38480b57cec5SDimitry Andric                  &FPI, U, FirstUser);
38490b57cec5SDimitry Andric         } else {
38500b57cec5SDimitry Andric           FirstUser = U;
38510b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
38520b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
38530b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
38540b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
38550b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
38560b57cec5SDimitry Andric         }
38570b57cec5SDimitry Andric       }
38580b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
38590b57cec5SDimitry Andric       // soon as we know where they unwind to.
38600b57cec5SDimitry Andric       if (CurrentPad != &FPI)
38610b57cec5SDimitry Andric         break;
38620b57cec5SDimitry Andric     }
38630b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
38640b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
38650b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
38660b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
38670b57cec5SDimitry Andric         // all direct uses of FPI.
38680b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
38690b57cec5SDimitry Andric         continue;
38700b57cec5SDimitry Andric       }
38710b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
38720b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
38730b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
38740b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
38750b57cec5SDimitry Andric       // UnresolvedAncestorPad.
38760b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
38770b57cec5SDimitry Andric       while (!Worklist.empty()) {
38780b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
38790b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
38800b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
38810b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
38820b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
38830b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
38840b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
38850b57cec5SDimitry Andric             break;
38860b57cec5SDimitry Andric           }
38870b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
38880b57cec5SDimitry Andric         }
38890b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
38900b57cec5SDimitry Andric         // then the uncle is not yet resolved.
38910b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
38920b57cec5SDimitry Andric           break;
38930b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
38940b57cec5SDimitry Andric         Worklist.pop_back();
38950b57cec5SDimitry Andric       }
38960b57cec5SDimitry Andric     }
38970b57cec5SDimitry Andric   }
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric   if (FirstUnwindPad) {
39000b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
39010b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
39020b57cec5SDimitry Andric       Value *SwitchUnwindPad;
39030b57cec5SDimitry Andric       if (SwitchUnwindDest)
39040b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
39050b57cec5SDimitry Andric       else
39060b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
39070b57cec5SDimitry Andric       Assert(SwitchUnwindPad == FirstUnwindPad,
39080b57cec5SDimitry Andric              "Unwind edges out of a catch must have the same unwind dest as "
39090b57cec5SDimitry Andric              "the parent catchswitch",
39100b57cec5SDimitry Andric              &FPI, FirstUser, CatchSwitch);
39110b57cec5SDimitry Andric     }
39120b57cec5SDimitry Andric   }
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   visitInstruction(FPI);
39150b57cec5SDimitry Andric }
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
39180b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
39190b57cec5SDimitry Andric 
39200b57cec5SDimitry Andric   Function *F = BB->getParent();
39210b57cec5SDimitry Andric   Assert(F->hasPersonalityFn(),
39220b57cec5SDimitry Andric          "CatchSwitchInst needs to be in a function with a personality.",
39230b57cec5SDimitry Andric          &CatchSwitch);
39240b57cec5SDimitry Andric 
39250b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
39260b57cec5SDimitry Andric   // block.
39270b57cec5SDimitry Andric   Assert(BB->getFirstNonPHI() == &CatchSwitch,
39280b57cec5SDimitry Andric          "CatchSwitchInst not the first non-PHI instruction in the block.",
39290b57cec5SDimitry Andric          &CatchSwitch);
39300b57cec5SDimitry Andric 
39310b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
39320b57cec5SDimitry Andric   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
39330b57cec5SDimitry Andric          "CatchSwitchInst has an invalid parent.", ParentPad);
39340b57cec5SDimitry Andric 
39350b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
39360b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
39370b57cec5SDimitry Andric     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
39380b57cec5SDimitry Andric            "CatchSwitchInst must unwind to an EH block which is not a "
39390b57cec5SDimitry Andric            "landingpad.",
39400b57cec5SDimitry Andric            &CatchSwitch);
39410b57cec5SDimitry Andric 
39420b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
39430b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
39440b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
39450b57cec5SDimitry Andric   }
39460b57cec5SDimitry Andric 
39470b57cec5SDimitry Andric   Assert(CatchSwitch.getNumHandlers() != 0,
39480b57cec5SDimitry Andric          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
39510b57cec5SDimitry Andric     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
39520b57cec5SDimitry Andric            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
39530b57cec5SDimitry Andric   }
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
39560b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
39570b57cec5SDimitry Andric }
39580b57cec5SDimitry Andric 
39590b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
39600b57cec5SDimitry Andric   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
39610b57cec5SDimitry Andric          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
39620b57cec5SDimitry Andric          CRI.getOperand(0));
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
39650b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
39660b57cec5SDimitry Andric     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
39670b57cec5SDimitry Andric            "CleanupReturnInst must unwind to an EH block which is not a "
39680b57cec5SDimitry Andric            "landingpad.",
39690b57cec5SDimitry Andric            &CRI);
39700b57cec5SDimitry Andric   }
39710b57cec5SDimitry Andric 
39720b57cec5SDimitry Andric   visitTerminator(CRI);
39730b57cec5SDimitry Andric }
39740b57cec5SDimitry Andric 
39750b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
39760b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
39770b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
39780b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
39790b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
39800b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
39810b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
39820b57cec5SDimitry Andric       return;
39830b57cec5SDimitry Andric   }
39840b57cec5SDimitry Andric 
39850b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
39860b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
39870b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
39880b57cec5SDimitry Andric   //
39890b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
39900b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
39910b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
39920b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
39930b57cec5SDimitry Andric     return;
39940b57cec5SDimitry Andric 
39950b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
39960b57cec5SDimitry Andric   Assert(DT.dominates(Op, U),
39970b57cec5SDimitry Andric          "Instruction does not dominate all uses!", Op, &I);
39980b57cec5SDimitry Andric }
39990b57cec5SDimitry Andric 
40000b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
40010b57cec5SDimitry Andric   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
40020b57cec5SDimitry Andric          "apply only to pointer types", &I);
4003*8bcb0991SDimitry Andric   Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
40040b57cec5SDimitry Andric          "dereferenceable, dereferenceable_or_null apply only to load"
4005*8bcb0991SDimitry Andric          " and inttoptr instructions, use attributes for calls or invokes", &I);
40060b57cec5SDimitry Andric   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
40070b57cec5SDimitry Andric          "take one operand!", &I);
40080b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
40090b57cec5SDimitry Andric   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
40100b57cec5SDimitry Andric          "dereferenceable_or_null metadata value must be an i64!", &I);
40110b57cec5SDimitry Andric }
40120b57cec5SDimitry Andric 
4013*8bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4014*8bcb0991SDimitry Andric   Assert(MD->getNumOperands() >= 2,
4015*8bcb0991SDimitry Andric          "!prof annotations should have no less than 2 operands", MD);
4016*8bcb0991SDimitry Andric 
4017*8bcb0991SDimitry Andric   // Check first operand.
4018*8bcb0991SDimitry Andric   Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
4019*8bcb0991SDimitry Andric   Assert(isa<MDString>(MD->getOperand(0)),
4020*8bcb0991SDimitry Andric          "expected string with name of the !prof annotation", MD);
4021*8bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
4022*8bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
4023*8bcb0991SDimitry Andric 
4024*8bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
4025*8bcb0991SDimitry Andric   if (ProfName.equals("branch_weights")) {
4026*8bcb0991SDimitry Andric     unsigned ExpectedNumOperands = 0;
4027*8bcb0991SDimitry Andric     if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4028*8bcb0991SDimitry Andric       ExpectedNumOperands = BI->getNumSuccessors();
4029*8bcb0991SDimitry Andric     else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4030*8bcb0991SDimitry Andric       ExpectedNumOperands = SI->getNumSuccessors();
4031*8bcb0991SDimitry Andric     else if (isa<CallInst>(&I) || isa<InvokeInst>(&I))
4032*8bcb0991SDimitry Andric       ExpectedNumOperands = 1;
4033*8bcb0991SDimitry Andric     else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4034*8bcb0991SDimitry Andric       ExpectedNumOperands = IBI->getNumDestinations();
4035*8bcb0991SDimitry Andric     else if (isa<SelectInst>(&I))
4036*8bcb0991SDimitry Andric       ExpectedNumOperands = 2;
4037*8bcb0991SDimitry Andric     else
4038*8bcb0991SDimitry Andric       CheckFailed("!prof branch_weights are not allowed for this instruction",
4039*8bcb0991SDimitry Andric                   MD);
4040*8bcb0991SDimitry Andric 
4041*8bcb0991SDimitry Andric     Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
4042*8bcb0991SDimitry Andric            "Wrong number of operands", MD);
4043*8bcb0991SDimitry Andric     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4044*8bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
4045*8bcb0991SDimitry Andric       Assert(MDO, "second operand should not be null", MD);
4046*8bcb0991SDimitry Andric       Assert(mdconst::dyn_extract<ConstantInt>(MDO),
4047*8bcb0991SDimitry Andric              "!prof brunch_weights operand is not a const int");
4048*8bcb0991SDimitry Andric     }
4049*8bcb0991SDimitry Andric   }
4050*8bcb0991SDimitry Andric }
4051*8bcb0991SDimitry Andric 
40520b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
40530b57cec5SDimitry Andric ///
40540b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
40550b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
40560b57cec5SDimitry Andric   Assert(BB, "Instruction not embedded in basic block!", &I);
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
40590b57cec5SDimitry Andric     for (User *U : I.users()) {
40600b57cec5SDimitry Andric       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
40610b57cec5SDimitry Andric              "Only PHI nodes may reference their own value!", &I);
40620b57cec5SDimitry Andric     }
40630b57cec5SDimitry Andric   }
40640b57cec5SDimitry Andric 
40650b57cec5SDimitry Andric   // Check that void typed values don't have names
40660b57cec5SDimitry Andric   Assert(!I.getType()->isVoidTy() || !I.hasName(),
40670b57cec5SDimitry Andric          "Instruction has a name, but provides a void value!", &I);
40680b57cec5SDimitry Andric 
40690b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
40700b57cec5SDimitry Andric   // value type.
40710b57cec5SDimitry Andric   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
40720b57cec5SDimitry Andric          "Instruction returns a non-scalar type!", &I);
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
40750b57cec5SDimitry Andric   // checked against the callee type.
40760b57cec5SDimitry Andric   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
40770b57cec5SDimitry Andric          "Invalid use of metadata!", &I);
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
40800b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
40810b57cec5SDimitry Andric   // instruction, it is an error!
40820b57cec5SDimitry Andric   for (Use &U : I.uses()) {
40830b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
40840b57cec5SDimitry Andric       Assert(Used->getParent() != nullptr,
40850b57cec5SDimitry Andric              "Instruction referencing"
40860b57cec5SDimitry Andric              " instruction not embedded in a basic block!",
40870b57cec5SDimitry Andric              &I, Used);
40880b57cec5SDimitry Andric     else {
40890b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
40900b57cec5SDimitry Andric       return;
40910b57cec5SDimitry Andric     }
40920b57cec5SDimitry Andric   }
40930b57cec5SDimitry Andric 
40940b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
40950b57cec5SDimitry Andric   // call.
40960b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
40990b57cec5SDimitry Andric     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
41000b57cec5SDimitry Andric 
41010b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
41020b57cec5SDimitry Andric     // instructions.
41030b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
41040b57cec5SDimitry Andric       Assert(false, "Instruction operands must be first-class values!", &I);
41050b57cec5SDimitry Andric     }
41060b57cec5SDimitry Andric 
41070b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
41080b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
41090b57cec5SDimitry Andric       // taken.
41100b57cec5SDimitry Andric       Assert(!F->isIntrinsic() ||
41110b57cec5SDimitry Andric                  (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)),
41120b57cec5SDimitry Andric              "Cannot take the address of an intrinsic!", &I);
41130b57cec5SDimitry Andric       Assert(
41140b57cec5SDimitry Andric           !F->isIntrinsic() || isa<CallInst>(I) ||
41150b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::donothing ||
41160b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::coro_resume ||
41170b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::coro_destroy ||
41180b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
41190b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
41200b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
41210b57cec5SDimitry Andric               F->getIntrinsicID() == Intrinsic::wasm_rethrow_in_catch,
41220b57cec5SDimitry Andric           "Cannot invoke an intrinsic other than donothing, patchpoint, "
41230b57cec5SDimitry Andric           "statepoint, coro_resume or coro_destroy",
41240b57cec5SDimitry Andric           &I);
41250b57cec5SDimitry Andric       Assert(F->getParent() == &M, "Referencing function in another module!",
41260b57cec5SDimitry Andric              &I, &M, F, F->getParent());
41270b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
41280b57cec5SDimitry Andric       Assert(OpBB->getParent() == BB->getParent(),
41290b57cec5SDimitry Andric              "Referring to a basic block in another function!", &I);
41300b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
41310b57cec5SDimitry Andric       Assert(OpArg->getParent() == BB->getParent(),
41320b57cec5SDimitry Andric              "Referring to an argument in another function!", &I);
41330b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
41340b57cec5SDimitry Andric       Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
41350b57cec5SDimitry Andric              &M, GV, GV->getParent());
41360b57cec5SDimitry Andric     } else if (isa<Instruction>(I.getOperand(i))) {
41370b57cec5SDimitry Andric       verifyDominatesUse(I, i);
41380b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
41390b57cec5SDimitry Andric       Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
41400b57cec5SDimitry Andric              "Cannot take the address of an inline asm!", &I);
41410b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
41420b57cec5SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy() ||
41430b57cec5SDimitry Andric           !DL.getNonIntegralAddressSpaces().empty()) {
41440b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
41450b57cec5SDimitry Andric         // illegal bitcast.  If the datalayout string specifies non-integral
41460b57cec5SDimitry Andric         // address spaces then we also need to check for illegal ptrtoint and
41470b57cec5SDimitry Andric         // inttoptr expressions.
41480b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
41490b57cec5SDimitry Andric       }
41500b57cec5SDimitry Andric     }
41510b57cec5SDimitry Andric   }
41520b57cec5SDimitry Andric 
41530b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
41540b57cec5SDimitry Andric     Assert(I.getType()->isFPOrFPVectorTy(),
41550b57cec5SDimitry Andric            "fpmath requires a floating point result!", &I);
41560b57cec5SDimitry Andric     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
41570b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
41580b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
41590b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
41600b57cec5SDimitry Andric       Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
41610b57cec5SDimitry Andric              "fpmath accuracy must have float type", &I);
41620b57cec5SDimitry Andric       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
41630b57cec5SDimitry Andric              "fpmath accuracy not a positive number!", &I);
41640b57cec5SDimitry Andric     } else {
41650b57cec5SDimitry Andric       Assert(false, "invalid fpmath accuracy!", &I);
41660b57cec5SDimitry Andric     }
41670b57cec5SDimitry Andric   }
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
41700b57cec5SDimitry Andric     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
41710b57cec5SDimitry Andric            "Ranges are only for loads, calls and invokes!", &I);
41720b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
41730b57cec5SDimitry Andric   }
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric   if (I.getMetadata(LLVMContext::MD_nonnull)) {
41760b57cec5SDimitry Andric     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
41770b57cec5SDimitry Andric            &I);
41780b57cec5SDimitry Andric     Assert(isa<LoadInst>(I),
41790b57cec5SDimitry Andric            "nonnull applies only to load instructions, use attributes"
41800b57cec5SDimitry Andric            " for calls or invokes",
41810b57cec5SDimitry Andric            &I);
41820b57cec5SDimitry Andric   }
41830b57cec5SDimitry Andric 
41840b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
41850b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
41860b57cec5SDimitry Andric 
41870b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
41880b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
41890b57cec5SDimitry Andric 
41900b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
41910b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
41920b57cec5SDimitry Andric 
41930b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
41940b57cec5SDimitry Andric     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
41950b57cec5SDimitry Andric            &I);
41960b57cec5SDimitry Andric     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
41970b57cec5SDimitry Andric            "use attributes for calls or invokes", &I);
41980b57cec5SDimitry Andric     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
41990b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
42000b57cec5SDimitry Andric     Assert(CI && CI->getType()->isIntegerTy(64),
42010b57cec5SDimitry Andric            "align metadata value must be an i64!", &I);
42020b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
42030b57cec5SDimitry Andric     Assert(isPowerOf2_64(Align),
42040b57cec5SDimitry Andric            "align metadata value must be a power of 2!", &I);
42050b57cec5SDimitry Andric     Assert(Align <= Value::MaximumAlignment,
42060b57cec5SDimitry Andric            "alignment is larger that implementation defined limit", &I);
42070b57cec5SDimitry Andric   }
42080b57cec5SDimitry Andric 
4209*8bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
4210*8bcb0991SDimitry Andric     visitProfMetadata(I, MD);
4211*8bcb0991SDimitry Andric 
42120b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
42130b57cec5SDimitry Andric     AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
42140b57cec5SDimitry Andric     visitMDNode(*N);
42150b57cec5SDimitry Andric   }
42160b57cec5SDimitry Andric 
4217*8bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
42180b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
4219*8bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
4220*8bcb0991SDimitry Andric   }
42210b57cec5SDimitry Andric 
42220b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
42230b57cec5SDimitry Andric }
42240b57cec5SDimitry Andric 
42250b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
42260b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
42270b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
42280b57cec5SDimitry Andric   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
42290b57cec5SDimitry Andric          IF);
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
42320b57cec5SDimitry Andric   // describe.
42330b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
42340b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
42350b57cec5SDimitry Andric 
42360b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
42370b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
42380b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
42390b57cec5SDimitry Andric 
42400b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
42410b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
42420b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
42430b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
42440b57cec5SDimitry Andric   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
42450b57cec5SDimitry Andric          "Intrinsic has incorrect return type!", IF);
42460b57cec5SDimitry Andric   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
42470b57cec5SDimitry Andric          "Intrinsic has incorrect argument type!", IF);
42480b57cec5SDimitry Andric 
42490b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
42500b57cec5SDimitry Andric   if (IsVarArg)
42510b57cec5SDimitry Andric     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
42520b57cec5SDimitry Andric            "Intrinsic was not defined with variable arguments!", IF);
42530b57cec5SDimitry Andric   else
42540b57cec5SDimitry Andric     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
42550b57cec5SDimitry Andric            "Callsite was not defined with variable arguments!", IF);
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
42580b57cec5SDimitry Andric   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
42590b57cec5SDimitry Andric 
42600b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
42610b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
42620b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
42630b57cec5SDimitry Andric   // the name.
42640b57cec5SDimitry Andric   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
42650b57cec5SDimitry Andric   Assert(ExpectedName == IF->getName(),
42660b57cec5SDimitry Andric          "Intrinsic name not mangled correctly for type arguments! "
42670b57cec5SDimitry Andric          "Should be: " +
42680b57cec5SDimitry Andric              ExpectedName,
42690b57cec5SDimitry Andric          IF);
42700b57cec5SDimitry Andric 
42710b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
42720b57cec5SDimitry Andric   // or are local to *this* function.
42730b57cec5SDimitry Andric   for (Value *V : Call.args())
42740b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
42750b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
42760b57cec5SDimitry Andric 
42770b57cec5SDimitry Andric   switch (ID) {
42780b57cec5SDimitry Andric   default:
42790b57cec5SDimitry Andric     break;
42800b57cec5SDimitry Andric   case Intrinsic::coro_id: {
42810b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
42820b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
42830b57cec5SDimitry Andric       break;
42840b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
42850b57cec5SDimitry Andric     Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
42860b57cec5SDimitry Andric       "info argument of llvm.coro.begin must refer to an initialized "
42870b57cec5SDimitry Andric       "constant");
42880b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
42890b57cec5SDimitry Andric     Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
42900b57cec5SDimitry Andric       "info argument of llvm.coro.begin must refer to either a struct or "
42910b57cec5SDimitry Andric       "an array");
42920b57cec5SDimitry Andric     break;
42930b57cec5SDimitry Andric   }
42940b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fadd:
42950b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fsub:
42960b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fmul:
42970b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fdiv:
42980b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_frem:
42990b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fma:
4300*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
4301*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui:
43020b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
43030b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext:
43040b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_sqrt:
43050b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_pow:
43060b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_powi:
43070b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_sin:
43080b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_cos:
43090b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_exp:
43100b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_exp2:
43110b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_log:
43120b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_log10:
43130b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_log2:
4314*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
4315*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint:
43160b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_rint:
43170b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_nearbyint:
43180b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_maxnum:
43190b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_minnum:
43200b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_ceil:
43210b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_floor:
4322*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
4323*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround:
43240b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_round:
43250b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_trunc:
43260b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
43270b57cec5SDimitry Andric     break;
43280b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
43290b57cec5SDimitry Andric     Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
43300b57cec5SDimitry Andric            "invalid llvm.dbg.declare intrinsic call 1", Call);
43310b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
43320b57cec5SDimitry Andric     break;
43330b57cec5SDimitry Andric   case Intrinsic::dbg_addr: // llvm.dbg.addr
43340b57cec5SDimitry Andric     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
43350b57cec5SDimitry Andric     break;
43360b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
43370b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
43380b57cec5SDimitry Andric     break;
43390b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
43400b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
43410b57cec5SDimitry Andric     break;
43420b57cec5SDimitry Andric   case Intrinsic::memcpy:
43430b57cec5SDimitry Andric   case Intrinsic::memmove:
43440b57cec5SDimitry Andric   case Intrinsic::memset: {
43450b57cec5SDimitry Andric     const auto *MI = cast<MemIntrinsic>(&Call);
43460b57cec5SDimitry Andric     auto IsValidAlignment = [&](unsigned Alignment) -> bool {
43470b57cec5SDimitry Andric       return Alignment == 0 || isPowerOf2_32(Alignment);
43480b57cec5SDimitry Andric     };
43490b57cec5SDimitry Andric     Assert(IsValidAlignment(MI->getDestAlignment()),
43500b57cec5SDimitry Andric            "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
43510b57cec5SDimitry Andric            Call);
43520b57cec5SDimitry Andric     if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
43530b57cec5SDimitry Andric       Assert(IsValidAlignment(MTI->getSourceAlignment()),
43540b57cec5SDimitry Andric              "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
43550b57cec5SDimitry Andric              Call);
43560b57cec5SDimitry Andric     }
43570b57cec5SDimitry Andric 
43580b57cec5SDimitry Andric     break;
43590b57cec5SDimitry Andric   }
43600b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
43610b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
43620b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
43630b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
43660b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
43670b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
43680b57cec5SDimitry Andric     Assert(ElementSizeVal.isPowerOf2(),
43690b57cec5SDimitry Andric            "element size of the element-wise atomic memory intrinsic "
43700b57cec5SDimitry Andric            "must be a power of 2",
43710b57cec5SDimitry Andric            Call);
43720b57cec5SDimitry Andric 
43730b57cec5SDimitry Andric     if (auto *LengthCI = dyn_cast<ConstantInt>(AMI->getLength())) {
43740b57cec5SDimitry Andric       uint64_t Length = LengthCI->getZExtValue();
43750b57cec5SDimitry Andric       uint64_t ElementSize = AMI->getElementSizeInBytes();
43760b57cec5SDimitry Andric       Assert((Length % ElementSize) == 0,
43770b57cec5SDimitry Andric              "constant length must be a multiple of the element size in the "
43780b57cec5SDimitry Andric              "element-wise atomic memory intrinsic",
43790b57cec5SDimitry Andric              Call);
43800b57cec5SDimitry Andric     }
43810b57cec5SDimitry Andric 
43820b57cec5SDimitry Andric     auto IsValidAlignment = [&](uint64_t Alignment) {
43830b57cec5SDimitry Andric       return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
43840b57cec5SDimitry Andric     };
43850b57cec5SDimitry Andric     uint64_t DstAlignment = AMI->getDestAlignment();
43860b57cec5SDimitry Andric     Assert(IsValidAlignment(DstAlignment),
43870b57cec5SDimitry Andric            "incorrect alignment of the destination argument", Call);
43880b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
43890b57cec5SDimitry Andric       uint64_t SrcAlignment = AMT->getSourceAlignment();
43900b57cec5SDimitry Andric       Assert(IsValidAlignment(SrcAlignment),
43910b57cec5SDimitry Andric              "incorrect alignment of the source argument", Call);
43920b57cec5SDimitry Andric     }
43930b57cec5SDimitry Andric     break;
43940b57cec5SDimitry Andric   }
43950b57cec5SDimitry Andric   case Intrinsic::gcroot:
43960b57cec5SDimitry Andric   case Intrinsic::gcwrite:
43970b57cec5SDimitry Andric   case Intrinsic::gcread:
43980b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
43990b57cec5SDimitry Andric       AllocaInst *AI =
44000b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
44010b57cec5SDimitry Andric       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
44020b57cec5SDimitry Andric       Assert(isa<Constant>(Call.getArgOperand(1)),
44030b57cec5SDimitry Andric              "llvm.gcroot parameter #2 must be a constant.", Call);
44040b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
44050b57cec5SDimitry Andric         Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
44060b57cec5SDimitry Andric                "llvm.gcroot parameter #1 must either be a pointer alloca, "
44070b57cec5SDimitry Andric                "or argument #2 must be a non-null constant.",
44080b57cec5SDimitry Andric                Call);
44090b57cec5SDimitry Andric       }
44100b57cec5SDimitry Andric     }
44110b57cec5SDimitry Andric 
44120b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
44130b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
44140b57cec5SDimitry Andric     break;
44150b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
44160b57cec5SDimitry Andric     Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
44170b57cec5SDimitry Andric            "llvm.init_trampoline parameter #2 must resolve to a function.",
44180b57cec5SDimitry Andric            Call);
44190b57cec5SDimitry Andric     break;
44200b57cec5SDimitry Andric   case Intrinsic::prefetch:
44210b57cec5SDimitry Andric     Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
44220b57cec5SDimitry Andric            cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
44230b57cec5SDimitry Andric            "invalid arguments to llvm.prefetch", Call);
44240b57cec5SDimitry Andric     break;
44250b57cec5SDimitry Andric   case Intrinsic::stackprotector:
44260b57cec5SDimitry Andric     Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
44270b57cec5SDimitry Andric            "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
44280b57cec5SDimitry Andric     break;
44290b57cec5SDimitry Andric   case Intrinsic::localescape: {
44300b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
44310b57cec5SDimitry Andric     Assert(BB == &BB->getParent()->front(),
44320b57cec5SDimitry Andric            "llvm.localescape used outside of entry block", Call);
44330b57cec5SDimitry Andric     Assert(!SawFrameEscape,
44340b57cec5SDimitry Andric            "multiple calls to llvm.localescape in one function", Call);
44350b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
44360b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
44370b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
44380b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
44390b57cec5SDimitry Andric       Assert(AI && AI->isStaticAlloca(),
44400b57cec5SDimitry Andric              "llvm.localescape only accepts static allocas", Call);
44410b57cec5SDimitry Andric     }
44420b57cec5SDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands();
44430b57cec5SDimitry Andric     SawFrameEscape = true;
44440b57cec5SDimitry Andric     break;
44450b57cec5SDimitry Andric   }
44460b57cec5SDimitry Andric   case Intrinsic::localrecover: {
44470b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
44480b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
44490b57cec5SDimitry Andric     Assert(Fn && !Fn->isDeclaration(),
44500b57cec5SDimitry Andric            "llvm.localrecover first "
44510b57cec5SDimitry Andric            "argument must be function defined in this module",
44520b57cec5SDimitry Andric            Call);
44530b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
44540b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
44550b57cec5SDimitry Andric     Entry.second = unsigned(
44560b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
44570b57cec5SDimitry Andric     break;
44580b57cec5SDimitry Andric   }
44590b57cec5SDimitry Andric 
44600b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
44610b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
44620b57cec5SDimitry Andric       Assert(!CI->isInlineAsm(),
44630b57cec5SDimitry Andric              "gc.statepoint support for inline assembly unimplemented", CI);
44640b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
44650b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric     verifyStatepoint(Call);
44680b57cec5SDimitry Andric     break;
44690b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
44700b57cec5SDimitry Andric     Assert(Call.getParent()->getParent()->hasGC(),
44710b57cec5SDimitry Andric            "Enclosing function does not use GC.", Call);
44720b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
44730b57cec5SDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
44740b57cec5SDimitry Andric     const Function *StatepointFn =
44750b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
44760b57cec5SDimitry Andric     Assert(StatepointFn && StatepointFn->isDeclaration() &&
44770b57cec5SDimitry Andric                StatepointFn->getIntrinsicID() ==
44780b57cec5SDimitry Andric                    Intrinsic::experimental_gc_statepoint,
44790b57cec5SDimitry Andric            "gc.result operand #1 must be from a statepoint", Call,
44800b57cec5SDimitry Andric            Call.getArgOperand(0));
44810b57cec5SDimitry Andric 
44820b57cec5SDimitry Andric     // Assert that result type matches wrapped callee.
44830b57cec5SDimitry Andric     const Value *Target = StatepointCall->getArgOperand(2);
44840b57cec5SDimitry Andric     auto *PT = cast<PointerType>(Target->getType());
44850b57cec5SDimitry Andric     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
44860b57cec5SDimitry Andric     Assert(Call.getType() == TargetFuncType->getReturnType(),
44870b57cec5SDimitry Andric            "gc.result result type does not match wrapped callee", Call);
44880b57cec5SDimitry Andric     break;
44890b57cec5SDimitry Andric   }
44900b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
44910b57cec5SDimitry Andric     Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call);
44920b57cec5SDimitry Andric 
44930b57cec5SDimitry Andric     Assert(isa<PointerType>(Call.getType()->getScalarType()),
44940b57cec5SDimitry Andric            "gc.relocate must return a pointer or a vector of pointers", Call);
44950b57cec5SDimitry Andric 
44960b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
44970b57cec5SDimitry Andric 
44980b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
44990b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
45000b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
45030b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
45040b57cec5SDimitry Andric 
45050b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
45060b57cec5SDimitry Andric       // statepoint terminator
45070b57cec5SDimitry Andric       Assert(InvokeBB, "safepoints should have unique landingpads",
45080b57cec5SDimitry Andric              LandingPad->getParent());
45090b57cec5SDimitry Andric       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
45100b57cec5SDimitry Andric              InvokeBB);
45110b57cec5SDimitry Andric       Assert(isStatepoint(InvokeBB->getTerminator()),
45120b57cec5SDimitry Andric              "gc relocate should be linked to a statepoint", InvokeBB);
45130b57cec5SDimitry Andric     } else {
45140b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
45150b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
45160b57cec5SDimitry Andric       // relocates of a call statepoint.
45170b57cec5SDimitry Andric       auto Token = Call.getArgOperand(0);
45180b57cec5SDimitry Andric       Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
45190b57cec5SDimitry Andric              "gc relocate is incorrectly tied to the statepoint", Call, Token);
45200b57cec5SDimitry Andric     }
45210b57cec5SDimitry Andric 
45220b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
45230b57cec5SDimitry Andric     const CallBase &StatepointCall =
45240b57cec5SDimitry Andric         *cast<CallBase>(cast<GCRelocateInst>(Call).getStatepoint());
45250b57cec5SDimitry Andric 
45260b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
45270b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
45280b57cec5SDimitry Andric     Assert(isa<ConstantInt>(Base),
45290b57cec5SDimitry Andric            "gc.relocate operand #2 must be integer offset", Call);
45300b57cec5SDimitry Andric 
45310b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
45320b57cec5SDimitry Andric     Assert(isa<ConstantInt>(Derived),
45330b57cec5SDimitry Andric            "gc.relocate operand #3 must be integer offset", Call);
45340b57cec5SDimitry Andric 
45350b57cec5SDimitry Andric     const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
45360b57cec5SDimitry Andric     const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
45370b57cec5SDimitry Andric     // Check the bounds
45380b57cec5SDimitry Andric     Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCall.arg_size(),
45390b57cec5SDimitry Andric            "gc.relocate: statepoint base index out of bounds", Call);
45400b57cec5SDimitry Andric     Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCall.arg_size(),
45410b57cec5SDimitry Andric            "gc.relocate: statepoint derived index out of bounds", Call);
45420b57cec5SDimitry Andric 
45430b57cec5SDimitry Andric     // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
45440b57cec5SDimitry Andric     // section of the statepoint's argument.
45450b57cec5SDimitry Andric     Assert(StatepointCall.arg_size() > 0,
45460b57cec5SDimitry Andric            "gc.statepoint: insufficient arguments");
45470b57cec5SDimitry Andric     Assert(isa<ConstantInt>(StatepointCall.getArgOperand(3)),
45480b57cec5SDimitry Andric            "gc.statement: number of call arguments must be constant integer");
45490b57cec5SDimitry Andric     const unsigned NumCallArgs =
45500b57cec5SDimitry Andric         cast<ConstantInt>(StatepointCall.getArgOperand(3))->getZExtValue();
45510b57cec5SDimitry Andric     Assert(StatepointCall.arg_size() > NumCallArgs + 5,
45520b57cec5SDimitry Andric            "gc.statepoint: mismatch in number of call arguments");
45530b57cec5SDimitry Andric     Assert(isa<ConstantInt>(StatepointCall.getArgOperand(NumCallArgs + 5)),
45540b57cec5SDimitry Andric            "gc.statepoint: number of transition arguments must be "
45550b57cec5SDimitry Andric            "a constant integer");
45560b57cec5SDimitry Andric     const int NumTransitionArgs =
45570b57cec5SDimitry Andric         cast<ConstantInt>(StatepointCall.getArgOperand(NumCallArgs + 5))
45580b57cec5SDimitry Andric             ->getZExtValue();
45590b57cec5SDimitry Andric     const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
45600b57cec5SDimitry Andric     Assert(isa<ConstantInt>(StatepointCall.getArgOperand(DeoptArgsStart)),
45610b57cec5SDimitry Andric            "gc.statepoint: number of deoptimization arguments must be "
45620b57cec5SDimitry Andric            "a constant integer");
45630b57cec5SDimitry Andric     const int NumDeoptArgs =
45640b57cec5SDimitry Andric         cast<ConstantInt>(StatepointCall.getArgOperand(DeoptArgsStart))
45650b57cec5SDimitry Andric             ->getZExtValue();
45660b57cec5SDimitry Andric     const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
45670b57cec5SDimitry Andric     const int GCParamArgsEnd = StatepointCall.arg_size();
45680b57cec5SDimitry Andric     Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
45690b57cec5SDimitry Andric            "gc.relocate: statepoint base index doesn't fall within the "
45700b57cec5SDimitry Andric            "'gc parameters' section of the statepoint call",
45710b57cec5SDimitry Andric            Call);
45720b57cec5SDimitry Andric     Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
45730b57cec5SDimitry Andric            "gc.relocate: statepoint derived index doesn't fall within the "
45740b57cec5SDimitry Andric            "'gc parameters' section of the statepoint call",
45750b57cec5SDimitry Andric            Call);
45760b57cec5SDimitry Andric 
45770b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
45780b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
45790b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
45800b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
45810b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
45820b57cec5SDimitry Andric     Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
45830b57cec5SDimitry Andric            "gc.relocate: relocated value must be a gc pointer", Call);
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric     auto ResultType = Call.getType();
45860b57cec5SDimitry Andric     auto DerivedType = Relocate.getDerivedPtr()->getType();
45870b57cec5SDimitry Andric     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
45880b57cec5SDimitry Andric            "gc.relocate: vector relocates to vector and pointer to pointer",
45890b57cec5SDimitry Andric            Call);
45900b57cec5SDimitry Andric     Assert(
45910b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
45920b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
45930b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
45940b57cec5SDimitry Andric         Call);
45950b57cec5SDimitry Andric     break;
45960b57cec5SDimitry Andric   }
45970b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
45980b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
45990b57cec5SDimitry Andric     Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
46000b57cec5SDimitry Andric            "eh.exceptionpointer argument must be a catchpad", Call);
46010b57cec5SDimitry Andric     break;
46020b57cec5SDimitry Andric   }
46030b57cec5SDimitry Andric   case Intrinsic::masked_load: {
46040b57cec5SDimitry Andric     Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
46050b57cec5SDimitry Andric            Call);
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(0);
46080b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
46090b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
46100b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
46110b57cec5SDimitry Andric     Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
46120b57cec5SDimitry Andric            Call);
46130b57cec5SDimitry Andric     Assert(Alignment->getValue().isPowerOf2(),
46140b57cec5SDimitry Andric            "masked_load: alignment must be a power of 2", Call);
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric     // DataTy is the overloaded type
46170b57cec5SDimitry Andric     Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
46180b57cec5SDimitry Andric     Assert(DataTy == Call.getType(),
46190b57cec5SDimitry Andric            "masked_load: return must match pointer type", Call);
46200b57cec5SDimitry Andric     Assert(PassThru->getType() == DataTy,
46210b57cec5SDimitry Andric            "masked_load: pass through and data type must match", Call);
46220b57cec5SDimitry Andric     Assert(Mask->getType()->getVectorNumElements() ==
46230b57cec5SDimitry Andric                DataTy->getVectorNumElements(),
46240b57cec5SDimitry Andric            "masked_load: vector mask must be same length as data", Call);
46250b57cec5SDimitry Andric     break;
46260b57cec5SDimitry Andric   }
46270b57cec5SDimitry Andric   case Intrinsic::masked_store: {
46280b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
46290b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(1);
46300b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
46310b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
46320b57cec5SDimitry Andric     Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
46330b57cec5SDimitry Andric            Call);
46340b57cec5SDimitry Andric     Assert(Alignment->getValue().isPowerOf2(),
46350b57cec5SDimitry Andric            "masked_store: alignment must be a power of 2", Call);
46360b57cec5SDimitry Andric 
46370b57cec5SDimitry Andric     // DataTy is the overloaded type
46380b57cec5SDimitry Andric     Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
46390b57cec5SDimitry Andric     Assert(DataTy == Val->getType(),
46400b57cec5SDimitry Andric            "masked_store: storee must match pointer type", Call);
46410b57cec5SDimitry Andric     Assert(Mask->getType()->getVectorNumElements() ==
46420b57cec5SDimitry Andric                DataTy->getVectorNumElements(),
46430b57cec5SDimitry Andric            "masked_store: vector mask must be same length as data", Call);
46440b57cec5SDimitry Andric     break;
46450b57cec5SDimitry Andric   }
46460b57cec5SDimitry Andric 
46470b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
46480b57cec5SDimitry Andric     Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
46490b57cec5SDimitry Andric     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
46500b57cec5SDimitry Andric            "experimental_guard must have exactly one "
46510b57cec5SDimitry Andric            "\"deopt\" operand bundle");
46520b57cec5SDimitry Andric     break;
46530b57cec5SDimitry Andric   }
46540b57cec5SDimitry Andric 
46550b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
46560b57cec5SDimitry Andric     Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
46570b57cec5SDimitry Andric            Call);
46580b57cec5SDimitry Andric     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
46590b57cec5SDimitry Andric            "experimental_deoptimize must have exactly one "
46600b57cec5SDimitry Andric            "\"deopt\" operand bundle");
46610b57cec5SDimitry Andric     Assert(Call.getType() == Call.getFunction()->getReturnType(),
46620b57cec5SDimitry Andric            "experimental_deoptimize return type must match caller return type");
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
46650b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
46660b57cec5SDimitry Andric       Assert(RI,
46670b57cec5SDimitry Andric              "calls to experimental_deoptimize must be followed by a return");
46680b57cec5SDimitry Andric 
46690b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
46700b57cec5SDimitry Andric         Assert(RI->getReturnValue() == &Call,
46710b57cec5SDimitry Andric                "calls to experimental_deoptimize must be followed by a return "
46720b57cec5SDimitry Andric                "of the value computed by experimental_deoptimize");
46730b57cec5SDimitry Andric     }
46740b57cec5SDimitry Andric 
46750b57cec5SDimitry Andric     break;
46760b57cec5SDimitry Andric   }
46770b57cec5SDimitry Andric   case Intrinsic::sadd_sat:
46780b57cec5SDimitry Andric   case Intrinsic::uadd_sat:
46790b57cec5SDimitry Andric   case Intrinsic::ssub_sat:
46800b57cec5SDimitry Andric   case Intrinsic::usub_sat: {
46810b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
46820b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
46830b57cec5SDimitry Andric     Assert(Op1->getType()->isIntOrIntVectorTy(),
46840b57cec5SDimitry Andric            "first operand of [us][add|sub]_sat must be an int type or vector "
46850b57cec5SDimitry Andric            "of ints");
46860b57cec5SDimitry Andric     Assert(Op2->getType()->isIntOrIntVectorTy(),
46870b57cec5SDimitry Andric            "second operand of [us][add|sub]_sat must be an int type or vector "
46880b57cec5SDimitry Andric            "of ints");
46890b57cec5SDimitry Andric     break;
46900b57cec5SDimitry Andric   }
46910b57cec5SDimitry Andric   case Intrinsic::smul_fix:
46920b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
4693*8bcb0991SDimitry Andric   case Intrinsic::umul_fix:
4694*8bcb0991SDimitry Andric   case Intrinsic::umul_fix_sat: {
46950b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
46960b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
46970b57cec5SDimitry Andric     Assert(Op1->getType()->isIntOrIntVectorTy(),
46980b57cec5SDimitry Andric            "first operand of [us]mul_fix[_sat] must be an int type or vector "
46990b57cec5SDimitry Andric            "of ints");
47000b57cec5SDimitry Andric     Assert(Op2->getType()->isIntOrIntVectorTy(),
47010b57cec5SDimitry Andric            "second operand of [us]mul_fix_[sat] must be an int type or vector "
47020b57cec5SDimitry Andric            "of ints");
47030b57cec5SDimitry Andric 
47040b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
47050b57cec5SDimitry Andric     Assert(Op3->getType()->getBitWidth() <= 32,
47060b57cec5SDimitry Andric            "third argument of [us]mul_fix[_sat] must fit within 32 bits");
47070b57cec5SDimitry Andric 
47080b57cec5SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat) {
47090b57cec5SDimitry Andric       Assert(
47100b57cec5SDimitry Andric           Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
47110b57cec5SDimitry Andric           "the scale of smul_fix[_sat] must be less than the width of the operands");
47120b57cec5SDimitry Andric     } else {
47130b57cec5SDimitry Andric       Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
47140b57cec5SDimitry Andric              "the scale of umul_fix[_sat] must be less than or equal to the width of "
47150b57cec5SDimitry Andric              "the operands");
47160b57cec5SDimitry Andric     }
47170b57cec5SDimitry Andric     break;
47180b57cec5SDimitry Andric   }
47190b57cec5SDimitry Andric   case Intrinsic::lround:
47200b57cec5SDimitry Andric   case Intrinsic::llround:
47210b57cec5SDimitry Andric   case Intrinsic::lrint:
47220b57cec5SDimitry Andric   case Intrinsic::llrint: {
47230b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
47240b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
47250b57cec5SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
47260b57cec5SDimitry Andric            "Intrinsic does not support vectors", &Call);
47270b57cec5SDimitry Andric     break;
47280b57cec5SDimitry Andric   }
47290b57cec5SDimitry Andric   };
47300b57cec5SDimitry Andric }
47310b57cec5SDimitry Andric 
47320b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
47330b57cec5SDimitry Andric ///
47340b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
47350b57cec5SDimitry Andric /// built-in assertions that would typically fire.
47360b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
47370b57cec5SDimitry Andric   if (!LocalScope)
47380b57cec5SDimitry Andric     return nullptr;
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
47410b57cec5SDimitry Andric     return SP;
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
47440b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
47450b57cec5SDimitry Andric 
47460b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
47470b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
47480b57cec5SDimitry Andric   return nullptr;
47490b57cec5SDimitry Andric }
47500b57cec5SDimitry Andric 
47510b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
47520b57cec5SDimitry Andric   unsigned NumOperands = FPI.getNumArgOperands();
47530b57cec5SDimitry Andric   bool HasExceptionMD = false;
47540b57cec5SDimitry Andric   bool HasRoundingMD = false;
47550b57cec5SDimitry Andric   switch (FPI.getIntrinsicID()) {
47560b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_sqrt:
47570b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_sin:
47580b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_cos:
47590b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_exp:
47600b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_exp2:
47610b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_log:
47620b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_log10:
47630b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_log2:
47640b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_rint:
47650b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_nearbyint:
47660b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_ceil:
47670b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_floor:
47680b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_round:
47690b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_trunc:
47700b57cec5SDimitry Andric     Assert((NumOperands == 3), "invalid arguments for constrained FP intrinsic",
47710b57cec5SDimitry Andric            &FPI);
47720b57cec5SDimitry Andric     HasExceptionMD = true;
47730b57cec5SDimitry Andric     HasRoundingMD = true;
47740b57cec5SDimitry Andric     break;
47750b57cec5SDimitry Andric 
4776*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
4777*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
4778*8bcb0991SDimitry Andric     Assert((NumOperands == 3), "invalid arguments for constrained FP intrinsic",
4779*8bcb0991SDimitry Andric            &FPI);
4780*8bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
4781*8bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
4782*8bcb0991SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
4783*8bcb0991SDimitry Andric            "Intrinsic does not support vectors", &FPI);
4784*8bcb0991SDimitry Andric     HasExceptionMD = true;
4785*8bcb0991SDimitry Andric     HasRoundingMD = true;
4786*8bcb0991SDimitry Andric   }
4787*8bcb0991SDimitry Andric     break;
4788*8bcb0991SDimitry Andric 
4789*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
4790*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
4791*8bcb0991SDimitry Andric     Assert((NumOperands == 2), "invalid arguments for constrained FP intrinsic",
4792*8bcb0991SDimitry Andric            &FPI);
4793*8bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
4794*8bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
4795*8bcb0991SDimitry Andric     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
4796*8bcb0991SDimitry Andric            "Intrinsic does not support vectors", &FPI);
4797*8bcb0991SDimitry Andric     HasExceptionMD = true;
4798*8bcb0991SDimitry Andric     break;
4799*8bcb0991SDimitry Andric   }
4800*8bcb0991SDimitry Andric 
48010b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fma:
48020b57cec5SDimitry Andric     Assert((NumOperands == 5), "invalid arguments for constrained FP intrinsic",
48030b57cec5SDimitry Andric            &FPI);
48040b57cec5SDimitry Andric     HasExceptionMD = true;
48050b57cec5SDimitry Andric     HasRoundingMD = true;
48060b57cec5SDimitry Andric     break;
48070b57cec5SDimitry Andric 
48080b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fadd:
48090b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fsub:
48100b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fmul:
48110b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fdiv:
48120b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_frem:
48130b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_pow:
48140b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_powi:
48150b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_maxnum:
48160b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_minnum:
48170b57cec5SDimitry Andric     Assert((NumOperands == 4), "invalid arguments for constrained FP intrinsic",
48180b57cec5SDimitry Andric            &FPI);
48190b57cec5SDimitry Andric     HasExceptionMD = true;
48200b57cec5SDimitry Andric     HasRoundingMD = true;
48210b57cec5SDimitry Andric     break;
48220b57cec5SDimitry Andric 
4823*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
4824*8bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
4825*8bcb0991SDimitry Andric     Assert((NumOperands == 2),
4826*8bcb0991SDimitry Andric            "invalid arguments for constrained FP intrinsic", &FPI);
4827*8bcb0991SDimitry Andric     HasExceptionMD = true;
4828*8bcb0991SDimitry Andric 
4829*8bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
4830*8bcb0991SDimitry Andric     uint64_t NumSrcElem = 0;
4831*8bcb0991SDimitry Andric     Assert(Operand->getType()->isFPOrFPVectorTy(),
4832*8bcb0991SDimitry Andric            "Intrinsic first argument must be floating point", &FPI);
4833*8bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
4834*8bcb0991SDimitry Andric       NumSrcElem = OperandT->getNumElements();
4835*8bcb0991SDimitry Andric     }
4836*8bcb0991SDimitry Andric 
4837*8bcb0991SDimitry Andric     Operand = &FPI;
4838*8bcb0991SDimitry Andric     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
4839*8bcb0991SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
4840*8bcb0991SDimitry Andric     Assert(Operand->getType()->isIntOrIntVectorTy(),
4841*8bcb0991SDimitry Andric            "Intrinsic result must be an integer", &FPI);
4842*8bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
4843*8bcb0991SDimitry Andric       Assert(NumSrcElem == OperandT->getNumElements(),
4844*8bcb0991SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
4845*8bcb0991SDimitry Andric              &FPI);
4846*8bcb0991SDimitry Andric     }
4847*8bcb0991SDimitry Andric   }
4848*8bcb0991SDimitry Andric     break;
4849*8bcb0991SDimitry Andric 
48500b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
48510b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
48520b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
48530b57cec5SDimitry Andric       Assert((NumOperands == 3),
48540b57cec5SDimitry Andric              "invalid arguments for constrained FP intrinsic", &FPI);
48550b57cec5SDimitry Andric       HasRoundingMD = true;
48560b57cec5SDimitry Andric     } else {
48570b57cec5SDimitry Andric       Assert((NumOperands == 2),
48580b57cec5SDimitry Andric              "invalid arguments for constrained FP intrinsic", &FPI);
48590b57cec5SDimitry Andric     }
48600b57cec5SDimitry Andric     HasExceptionMD = true;
48610b57cec5SDimitry Andric 
48620b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
48630b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
48640b57cec5SDimitry Andric     Value *Result = &FPI;
48650b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
48660b57cec5SDimitry Andric     Assert(OperandTy->isFPOrFPVectorTy(),
48670b57cec5SDimitry Andric            "Intrinsic first argument must be FP or FP vector", &FPI);
48680b57cec5SDimitry Andric     Assert(ResultTy->isFPOrFPVectorTy(),
48690b57cec5SDimitry Andric            "Intrinsic result must be FP or FP vector", &FPI);
48700b57cec5SDimitry Andric     Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
48710b57cec5SDimitry Andric            "Intrinsic first argument and result disagree on vector use", &FPI);
48720b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
48730b57cec5SDimitry Andric       auto *OperandVecTy = cast<VectorType>(OperandTy);
48740b57cec5SDimitry Andric       auto *ResultVecTy = cast<VectorType>(ResultTy);
48750b57cec5SDimitry Andric       Assert(OperandVecTy->getNumElements() == ResultVecTy->getNumElements(),
48760b57cec5SDimitry Andric              "Intrinsic first argument and result vector lengths must be equal",
48770b57cec5SDimitry Andric              &FPI);
48780b57cec5SDimitry Andric     }
48790b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
48800b57cec5SDimitry Andric       Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
48810b57cec5SDimitry Andric              "Intrinsic first argument's type must be larger than result type",
48820b57cec5SDimitry Andric              &FPI);
48830b57cec5SDimitry Andric     } else {
48840b57cec5SDimitry Andric       Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
48850b57cec5SDimitry Andric              "Intrinsic first argument's type must be smaller than result type",
48860b57cec5SDimitry Andric              &FPI);
48870b57cec5SDimitry Andric     }
48880b57cec5SDimitry Andric   }
48890b57cec5SDimitry Andric     break;
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric   default:
48920b57cec5SDimitry Andric     llvm_unreachable("Invalid constrained FP intrinsic!");
48930b57cec5SDimitry Andric   }
48940b57cec5SDimitry Andric 
48950b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
48960b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
48970b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
48980b57cec5SDimitry Andric   // argument type check is needed here.
48990b57cec5SDimitry Andric 
49000b57cec5SDimitry Andric   if (HasExceptionMD) {
49010b57cec5SDimitry Andric     Assert(FPI.getExceptionBehavior().hasValue(),
49020b57cec5SDimitry Andric            "invalid exception behavior argument", &FPI);
49030b57cec5SDimitry Andric   }
49040b57cec5SDimitry Andric   if (HasRoundingMD) {
49050b57cec5SDimitry Andric     Assert(FPI.getRoundingMode().hasValue(),
49060b57cec5SDimitry Andric            "invalid rounding mode argument", &FPI);
49070b57cec5SDimitry Andric   }
49080b57cec5SDimitry Andric }
49090b57cec5SDimitry Andric 
49100b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
49110b57cec5SDimitry Andric   auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
49120b57cec5SDimitry Andric   AssertDI(isa<ValueAsMetadata>(MD) ||
49130b57cec5SDimitry Andric              (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
49140b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
49150b57cec5SDimitry Andric   AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
49160b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
49170b57cec5SDimitry Andric          DII.getRawVariable());
49180b57cec5SDimitry Andric   AssertDI(isa<DIExpression>(DII.getRawExpression()),
49190b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
49200b57cec5SDimitry Andric          DII.getRawExpression());
49210b57cec5SDimitry Andric 
49220b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
49230b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
49240b57cec5SDimitry Andric     if (!isa<DILocation>(N))
49250b57cec5SDimitry Andric       return;
49260b57cec5SDimitry Andric 
49270b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
49280b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
49290b57cec5SDimitry Andric 
49300b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
49310b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
49320b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
49330b57cec5SDimitry Andric   AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
49340b57cec5SDimitry Andric            &DII, BB, F);
49350b57cec5SDimitry Andric 
49360b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
49370b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
49380b57cec5SDimitry Andric   if (!VarSP || !LocSP)
49390b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
49400b57cec5SDimitry Andric 
49410b57cec5SDimitry Andric   AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
49420b57cec5SDimitry Andric                                " variable and !dbg attachment",
49430b57cec5SDimitry Andric            &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
49440b57cec5SDimitry Andric            Loc->getScope()->getSubprogram());
49450b57cec5SDimitry Andric 
49460b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
49470b57cec5SDimitry Andric   AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
49480b57cec5SDimitry Andric            Var->getRawType());
49490b57cec5SDimitry Andric   verifyFnArgs(DII);
49500b57cec5SDimitry Andric }
49510b57cec5SDimitry Andric 
49520b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
49530b57cec5SDimitry Andric   AssertDI(isa<DILabel>(DLI.getRawLabel()),
49540b57cec5SDimitry Andric          "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
49550b57cec5SDimitry Andric          DLI.getRawLabel());
49560b57cec5SDimitry Andric 
49570b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
49580b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
49590b57cec5SDimitry Andric     if (!isa<DILocation>(N))
49600b57cec5SDimitry Andric       return;
49610b57cec5SDimitry Andric 
49620b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
49630b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
49640b57cec5SDimitry Andric 
49650b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
49660b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
49670b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
49680b57cec5SDimitry Andric   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
49690b57cec5SDimitry Andric          &DLI, BB, F);
49700b57cec5SDimitry Andric 
49710b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
49720b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
49730b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
49740b57cec5SDimitry Andric     return;
49750b57cec5SDimitry Andric 
49760b57cec5SDimitry Andric   AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
49770b57cec5SDimitry Andric                              " label and !dbg attachment",
49780b57cec5SDimitry Andric            &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
49790b57cec5SDimitry Andric            Loc->getScope()->getSubprogram());
49800b57cec5SDimitry Andric }
49810b57cec5SDimitry Andric 
49820b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
49830b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
49840b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
49850b57cec5SDimitry Andric 
49860b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
49870b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
49880b57cec5SDimitry Andric     return;
49890b57cec5SDimitry Andric 
49900b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
49910b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
49920b57cec5SDimitry Andric   if (!Fragment)
49930b57cec5SDimitry Andric     return;
49940b57cec5SDimitry Andric 
49950b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
49960b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
49970b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
49980b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
49990b57cec5SDimitry Andric   // variable and this check fails.
50000b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
50010b57cec5SDimitry Andric   if (V->isArtificial())
50020b57cec5SDimitry Andric     return;
50030b57cec5SDimitry Andric 
50040b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
50050b57cec5SDimitry Andric }
50060b57cec5SDimitry Andric 
50070b57cec5SDimitry Andric template <typename ValueOrMetadata>
50080b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
50090b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
50100b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
50110b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
50120b57cec5SDimitry Andric   // elsewhere.
50130b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
50140b57cec5SDimitry Andric   if (!VarSize)
50150b57cec5SDimitry Andric     return;
50160b57cec5SDimitry Andric 
50170b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
50180b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
50190b57cec5SDimitry Andric   AssertDI(FragSize + FragOffset <= *VarSize,
50200b57cec5SDimitry Andric          "fragment is larger than or outside of variable", Desc, &V);
50210b57cec5SDimitry Andric   AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
50220b57cec5SDimitry Andric }
50230b57cec5SDimitry Andric 
50240b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
50250b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
50260b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
50270b57cec5SDimitry Andric   // contain inlined debug intrinsics.
50280b57cec5SDimitry Andric   if (!HasDebugInfo)
50290b57cec5SDimitry Andric     return;
50300b57cec5SDimitry Andric 
50310b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
50320b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
50330b57cec5SDimitry Andric     return;
50340b57cec5SDimitry Andric 
50350b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
50360b57cec5SDimitry Andric   AssertDI(Var, "dbg intrinsic without variable");
50370b57cec5SDimitry Andric 
50380b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
50390b57cec5SDimitry Andric   if (!ArgNo)
50400b57cec5SDimitry Andric     return;
50410b57cec5SDimitry Andric 
50420b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
50430b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
50440b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
50450b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
50460b57cec5SDimitry Andric 
50470b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
50480b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
50490b57cec5SDimitry Andric   AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
50500b57cec5SDimitry Andric            Prev, Var);
50510b57cec5SDimitry Andric }
50520b57cec5SDimitry Andric 
5053*8bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
5054*8bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5055*8bcb0991SDimitry Andric 
5056*8bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
5057*8bcb0991SDimitry Andric   if (!E || !E->isValid())
5058*8bcb0991SDimitry Andric     return;
5059*8bcb0991SDimitry Andric 
5060*8bcb0991SDimitry Andric   AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
5061*8bcb0991SDimitry Andric }
5062*8bcb0991SDimitry Andric 
50630b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
50640b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
50650b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
50660b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
50670b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
50680b57cec5SDimitry Andric     return;
50690b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
50700b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
50710b57cec5SDimitry Andric   if (CUs)
50720b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
50730b57cec5SDimitry Andric   for (auto *CU : CUVisited)
50740b57cec5SDimitry Andric     AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
50750b57cec5SDimitry Andric   CUVisited.clear();
50760b57cec5SDimitry Andric }
50770b57cec5SDimitry Andric 
50780b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
50790b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
50800b57cec5SDimitry Andric     return;
50810b57cec5SDimitry Andric 
50820b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
50830b57cec5SDimitry Andric   for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
50840b57cec5SDimitry Andric     Assert(First->getCallingConv() == F->getCallingConv(),
50850b57cec5SDimitry Andric            "All llvm.experimental.deoptimize declarations must have the same "
50860b57cec5SDimitry Andric            "calling convention",
50870b57cec5SDimitry Andric            First, F);
50880b57cec5SDimitry Andric   }
50890b57cec5SDimitry Andric }
50900b57cec5SDimitry Andric 
50910b57cec5SDimitry Andric void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
50920b57cec5SDimitry Andric   bool HasSource = F.getSource().hasValue();
50930b57cec5SDimitry Andric   if (!HasSourceDebugInfo.count(&U))
50940b57cec5SDimitry Andric     HasSourceDebugInfo[&U] = HasSource;
50950b57cec5SDimitry Andric   AssertDI(HasSource == HasSourceDebugInfo[&U],
50960b57cec5SDimitry Andric            "inconsistent use of embedded source");
50970b57cec5SDimitry Andric }
50980b57cec5SDimitry Andric 
50990b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
51000b57cec5SDimitry Andric //  Implement the public interfaces to this file...
51010b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
51020b57cec5SDimitry Andric 
51030b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
51040b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
51050b57cec5SDimitry Andric 
51060b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
51070b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
51080b57cec5SDimitry Andric 
51090b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
51100b57cec5SDimitry Andric   // expect of a function called "verify".
51110b57cec5SDimitry Andric   return !V.verify(F);
51120b57cec5SDimitry Andric }
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
51150b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
51160b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
51170b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
51180b57cec5SDimitry Andric 
51190b57cec5SDimitry Andric   bool Broken = false;
51200b57cec5SDimitry Andric   for (const Function &F : M)
51210b57cec5SDimitry Andric     Broken |= !V.verify(F);
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric   Broken |= !V.verify();
51240b57cec5SDimitry Andric   if (BrokenDebugInfo)
51250b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
51260b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
51270b57cec5SDimitry Andric   // expect of a function called "verify".
51280b57cec5SDimitry Andric   return Broken;
51290b57cec5SDimitry Andric }
51300b57cec5SDimitry Andric 
51310b57cec5SDimitry Andric namespace {
51320b57cec5SDimitry Andric 
51330b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
51340b57cec5SDimitry Andric   static char ID;
51350b57cec5SDimitry Andric 
51360b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
51370b57cec5SDimitry Andric   bool FatalErrors = true;
51380b57cec5SDimitry Andric 
51390b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
51400b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
51410b57cec5SDimitry Andric   }
51420b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
51430b57cec5SDimitry Andric       : FunctionPass(ID),
51440b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
51450b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
51460b57cec5SDimitry Andric   }
51470b57cec5SDimitry Andric 
51480b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
5149*8bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
51500b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
51510b57cec5SDimitry Andric     return false;
51520b57cec5SDimitry Andric   }
51530b57cec5SDimitry Andric 
51540b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
51550b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
51560b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
51570b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
51580b57cec5SDimitry Andric     }
51590b57cec5SDimitry Andric     return false;
51600b57cec5SDimitry Andric   }
51610b57cec5SDimitry Andric 
51620b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
51630b57cec5SDimitry Andric     bool HasErrors = false;
51640b57cec5SDimitry Andric     for (Function &F : M)
51650b57cec5SDimitry Andric       if (F.isDeclaration())
51660b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
51670b57cec5SDimitry Andric 
51680b57cec5SDimitry Andric     HasErrors |= !V->verify();
51690b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
51700b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
51710b57cec5SDimitry Andric     return false;
51720b57cec5SDimitry Andric   }
51730b57cec5SDimitry Andric 
51740b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
51750b57cec5SDimitry Andric     AU.setPreservesAll();
51760b57cec5SDimitry Andric   }
51770b57cec5SDimitry Andric };
51780b57cec5SDimitry Andric 
51790b57cec5SDimitry Andric } // end anonymous namespace
51800b57cec5SDimitry Andric 
51810b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
51820b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
51830b57cec5SDimitry Andric   if (Diagnostic)
51840b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
51850b57cec5SDimitry Andric }
51860b57cec5SDimitry Andric 
51870b57cec5SDimitry Andric #define AssertTBAA(C, ...)                                                     \
51880b57cec5SDimitry Andric   do {                                                                         \
51890b57cec5SDimitry Andric     if (!(C)) {                                                                \
51900b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
51910b57cec5SDimitry Andric       return false;                                                            \
51920b57cec5SDimitry Andric     }                                                                          \
51930b57cec5SDimitry Andric   } while (false)
51940b57cec5SDimitry Andric 
51950b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
51960b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
51970b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
51980b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
51990b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
52000b57cec5SDimitry Andric                                  bool IsNewFormat) {
52010b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
52020b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
52030b57cec5SDimitry Andric     return {true, ~0u};
52040b57cec5SDimitry Andric   }
52050b57cec5SDimitry Andric 
52060b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
52070b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
52080b57cec5SDimitry Andric     return Itr->second;
52090b57cec5SDimitry Andric 
52100b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
52110b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
52120b57cec5SDimitry Andric   (void)InsertResult;
52130b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
52140b57cec5SDimitry Andric   return Result;
52150b57cec5SDimitry Andric }
52160b57cec5SDimitry Andric 
52170b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
52180b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
52190b57cec5SDimitry Andric                                      bool IsNewFormat) {
52200b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
52210b57cec5SDimitry Andric 
52220b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
52230b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
52240b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
52250b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
52260b57cec5SDimitry Andric                : InvalidNode;
52270b57cec5SDimitry Andric   }
52280b57cec5SDimitry Andric 
52290b57cec5SDimitry Andric   if (IsNewFormat) {
52300b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
52310b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
52320b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
52330b57cec5SDimitry Andric       return InvalidNode;
52340b57cec5SDimitry Andric     }
52350b57cec5SDimitry Andric   } else {
52360b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
52370b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
52380b57cec5SDimitry Andric                   BaseNode);
52390b57cec5SDimitry Andric       return InvalidNode;
52400b57cec5SDimitry Andric     }
52410b57cec5SDimitry Andric   }
52420b57cec5SDimitry Andric 
52430b57cec5SDimitry Andric   // Check the type size field.
52440b57cec5SDimitry Andric   if (IsNewFormat) {
52450b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
52460b57cec5SDimitry Andric         BaseNode->getOperand(1));
52470b57cec5SDimitry Andric     if (!TypeSizeNode) {
52480b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
52490b57cec5SDimitry Andric       return InvalidNode;
52500b57cec5SDimitry Andric     }
52510b57cec5SDimitry Andric   }
52520b57cec5SDimitry Andric 
52530b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
52540b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
52550b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
52560b57cec5SDimitry Andric                 BaseNode);
52570b57cec5SDimitry Andric     return InvalidNode;
52580b57cec5SDimitry Andric   }
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric   bool Failed = false;
52610b57cec5SDimitry Andric 
52620b57cec5SDimitry Andric   Optional<APInt> PrevOffset;
52630b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
52640b57cec5SDimitry Andric 
52650b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
52660b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
52670b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
52680b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
52690b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
52700b57cec5SDimitry Andric            Idx += NumOpsPerField) {
52710b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
52720b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
52730b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
52740b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
52750b57cec5SDimitry Andric       Failed = true;
52760b57cec5SDimitry Andric       continue;
52770b57cec5SDimitry Andric     }
52780b57cec5SDimitry Andric 
52790b57cec5SDimitry Andric     auto *OffsetEntryCI =
52800b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
52810b57cec5SDimitry Andric     if (!OffsetEntryCI) {
52820b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
52830b57cec5SDimitry Andric       Failed = true;
52840b57cec5SDimitry Andric       continue;
52850b57cec5SDimitry Andric     }
52860b57cec5SDimitry Andric 
52870b57cec5SDimitry Andric     if (BitWidth == ~0u)
52880b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
52890b57cec5SDimitry Andric 
52900b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
52910b57cec5SDimitry Andric       CheckFailed(
52920b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
52930b57cec5SDimitry Andric           BaseNode);
52940b57cec5SDimitry Andric       Failed = true;
52950b57cec5SDimitry Andric       continue;
52960b57cec5SDimitry Andric     }
52970b57cec5SDimitry Andric 
52980b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
52990b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
53000b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
53010b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
53020b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
53030b57cec5SDimitry Andric     bool IsAscending =
53040b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
53050b57cec5SDimitry Andric 
53060b57cec5SDimitry Andric     if (!IsAscending) {
53070b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
53080b57cec5SDimitry Andric       Failed = true;
53090b57cec5SDimitry Andric     }
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
53120b57cec5SDimitry Andric 
53130b57cec5SDimitry Andric     if (IsNewFormat) {
53140b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
53150b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
53160b57cec5SDimitry Andric       if (!MemberSizeNode) {
53170b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
53180b57cec5SDimitry Andric         Failed = true;
53190b57cec5SDimitry Andric         continue;
53200b57cec5SDimitry Andric       }
53210b57cec5SDimitry Andric     }
53220b57cec5SDimitry Andric   }
53230b57cec5SDimitry Andric 
53240b57cec5SDimitry Andric   return Failed ? InvalidNode
53250b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
53260b57cec5SDimitry Andric }
53270b57cec5SDimitry Andric 
53280b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
53290b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
53300b57cec5SDimitry Andric }
53310b57cec5SDimitry Andric 
53320b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
53330b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
53340b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
53350b57cec5SDimitry Andric     return false;
53360b57cec5SDimitry Andric 
53370b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
53380b57cec5SDimitry Andric     return false;
53390b57cec5SDimitry Andric 
53400b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
53410b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
53420b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
53430b57cec5SDimitry Andric       return false;
53440b57cec5SDimitry Andric   }
53450b57cec5SDimitry Andric 
53460b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
53470b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
53480b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
53490b57cec5SDimitry Andric }
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
53520b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
53530b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
53540b57cec5SDimitry Andric     return ResultIt->second;
53550b57cec5SDimitry Andric 
53560b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
53570b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
53580b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
53590b57cec5SDimitry Andric   (void)InsertResult;
53600b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
53610b57cec5SDimitry Andric 
53620b57cec5SDimitry Andric   return Result;
53630b57cec5SDimitry Andric }
53640b57cec5SDimitry Andric 
53650b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
53660b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
53670b57cec5SDimitry Andric ///
53680b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
53690b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
53700b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
53710b57cec5SDimitry Andric                                                    APInt &Offset,
53720b57cec5SDimitry Andric                                                    bool IsNewFormat) {
53730b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
53740b57cec5SDimitry Andric 
53750b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
53760b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
53770b57cec5SDimitry Andric   // to Assert that.
53780b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
53790b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
53800b57cec5SDimitry Andric 
53810b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
53820b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
53830b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
53840b57cec5SDimitry Andric            Idx += NumOpsPerField) {
53850b57cec5SDimitry Andric     auto *OffsetEntryCI =
53860b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
53870b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
53880b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
53890b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
53900b57cec5SDimitry Andric                     BaseNode, &Offset);
53910b57cec5SDimitry Andric         return nullptr;
53920b57cec5SDimitry Andric       }
53930b57cec5SDimitry Andric 
53940b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
53950b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
53960b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
53970b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
53980b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
53990b57cec5SDimitry Andric     }
54000b57cec5SDimitry Andric   }
54010b57cec5SDimitry Andric 
54020b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
54030b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
54040b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
54050b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
54060b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
54070b57cec5SDimitry Andric }
54080b57cec5SDimitry Andric 
54090b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
54100b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
54110b57cec5SDimitry Andric     return false;
54120b57cec5SDimitry Andric 
54130b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
54140b57cec5SDimitry Andric   // its first operand.
54150b57cec5SDimitry Andric   MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0));
54160b57cec5SDimitry Andric   if (!Parent)
54170b57cec5SDimitry Andric     return false;
54180b57cec5SDimitry Andric 
54190b57cec5SDimitry Andric   return true;
54200b57cec5SDimitry Andric }
54210b57cec5SDimitry Andric 
54220b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
54230b57cec5SDimitry Andric   AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
54240b57cec5SDimitry Andric                  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
54250b57cec5SDimitry Andric                  isa<AtomicCmpXchgInst>(I),
54260b57cec5SDimitry Andric              "This instruction shall not have a TBAA access tag!", &I);
54270b57cec5SDimitry Andric 
54280b57cec5SDimitry Andric   bool IsStructPathTBAA =
54290b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
54300b57cec5SDimitry Andric 
54310b57cec5SDimitry Andric   AssertTBAA(
54320b57cec5SDimitry Andric       IsStructPathTBAA,
54330b57cec5SDimitry Andric       "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
54340b57cec5SDimitry Andric 
54350b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
54360b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
54370b57cec5SDimitry Andric 
54380b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
54390b57cec5SDimitry Andric 
54400b57cec5SDimitry Andric   if (IsNewFormat) {
54410b57cec5SDimitry Andric     AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
54420b57cec5SDimitry Andric                "Access tag metadata must have either 4 or 5 operands", &I, MD);
54430b57cec5SDimitry Andric   } else {
54440b57cec5SDimitry Andric     AssertTBAA(MD->getNumOperands() < 5,
54450b57cec5SDimitry Andric                "Struct tag metadata must have either 3 or 4 operands", &I, MD);
54460b57cec5SDimitry Andric   }
54470b57cec5SDimitry Andric 
54480b57cec5SDimitry Andric   // Check the access size field.
54490b57cec5SDimitry Andric   if (IsNewFormat) {
54500b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
54510b57cec5SDimitry Andric         MD->getOperand(3));
54520b57cec5SDimitry Andric     AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
54530b57cec5SDimitry Andric   }
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric   // Check the immutability flag.
54560b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
54570b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
54580b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
54590b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
54600b57cec5SDimitry Andric     AssertTBAA(IsImmutableCI,
54610b57cec5SDimitry Andric                "Immutability tag on struct tag metadata must be a constant",
54620b57cec5SDimitry Andric                &I, MD);
54630b57cec5SDimitry Andric     AssertTBAA(
54640b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
54650b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
54660b57cec5SDimitry Andric         &I, MD);
54670b57cec5SDimitry Andric   }
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric   AssertTBAA(BaseNode && AccessType,
54700b57cec5SDimitry Andric              "Malformed struct tag metadata: base and access-type "
54710b57cec5SDimitry Andric              "should be non-null and point to Metadata nodes",
54720b57cec5SDimitry Andric              &I, MD, BaseNode, AccessType);
54730b57cec5SDimitry Andric 
54740b57cec5SDimitry Andric   if (!IsNewFormat) {
54750b57cec5SDimitry Andric     AssertTBAA(isValidScalarTBAANode(AccessType),
54760b57cec5SDimitry Andric                "Access type node must be a valid scalar type", &I, MD,
54770b57cec5SDimitry Andric                AccessType);
54780b57cec5SDimitry Andric   }
54790b57cec5SDimitry Andric 
54800b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
54810b57cec5SDimitry Andric   AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
54820b57cec5SDimitry Andric 
54830b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
54840b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
54870b57cec5SDimitry Andric 
54880b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
54890b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
54900b57cec5SDimitry Andric                                                IsNewFormat)) {
54910b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
54920b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
54930b57cec5SDimitry Andric       return false;
54940b57cec5SDimitry Andric     }
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric     bool Invalid;
54970b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
54980b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
54990b57cec5SDimitry Andric                                                              IsNewFormat);
55000b57cec5SDimitry Andric 
55010b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
55020b57cec5SDimitry Andric     // errors we wanted to print.
55030b57cec5SDimitry Andric     if (Invalid)
55040b57cec5SDimitry Andric       return false;
55050b57cec5SDimitry Andric 
55060b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
55070b57cec5SDimitry Andric 
55080b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
55090b57cec5SDimitry Andric       AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
55100b57cec5SDimitry Andric                  &I, MD, &Offset);
55110b57cec5SDimitry Andric 
55120b57cec5SDimitry Andric     AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
55130b57cec5SDimitry Andric                    (BaseNodeBitWidth == 0 && Offset == 0) ||
55140b57cec5SDimitry Andric                    (IsNewFormat && BaseNodeBitWidth == ~0u),
55150b57cec5SDimitry Andric                "Access bit-width not the same as description bit-width", &I, MD,
55160b57cec5SDimitry Andric                BaseNodeBitWidth, Offset.getBitWidth());
55170b57cec5SDimitry Andric 
55180b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
55190b57cec5SDimitry Andric       break;
55200b57cec5SDimitry Andric   }
55210b57cec5SDimitry Andric 
55220b57cec5SDimitry Andric   AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
55230b57cec5SDimitry Andric              &I, MD);
55240b57cec5SDimitry Andric   return true;
55250b57cec5SDimitry Andric }
55260b57cec5SDimitry Andric 
55270b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
55280b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
55290b57cec5SDimitry Andric 
55300b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
55310b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
55320b57cec5SDimitry Andric }
55330b57cec5SDimitry Andric 
55340b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
55350b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
55360b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
55370b57cec5SDimitry Andric   Result Res;
55380b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
55390b57cec5SDimitry Andric   return Res;
55400b57cec5SDimitry Andric }
55410b57cec5SDimitry Andric 
55420b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
55430b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
55440b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
55450b57cec5SDimitry Andric }
55460b57cec5SDimitry Andric 
55470b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
55480b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
55490b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
55500b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
55510b57cec5SDimitry Andric 
55520b57cec5SDimitry Andric   return PreservedAnalyses::all();
55530b57cec5SDimitry Andric }
55540b57cec5SDimitry Andric 
55550b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
55560b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
55570b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
55580b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
55590b57cec5SDimitry Andric 
55600b57cec5SDimitry Andric   return PreservedAnalyses::all();
55610b57cec5SDimitry Andric }
5562