blob: 037506a389caa0f676291445dd39be617edeeee9 [file] [log] [blame]
Nick Lewyckyd489edf2012-02-25 07:20:06 +00001//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3e6e3e62002-03-29 19:06:18 +000010// This file defines the function verifier interface, that can be used for some
Chris Lattner2f7c9632001-06-06 20:29:01 +000011// sanity checking of input to the system.
12//
Misha Brukman1c9de462004-06-24 21:47:35 +000013// Note that this does not provide full `Java style' security and verifications,
14// instead it just tries to ensure that code is well-formed.
Chris Lattner2f7c9632001-06-06 20:29:01 +000015//
Misha Brukman1c9de462004-06-24 21:47:35 +000016// * Both of a binary operator's parameters are of the same type
Chris Lattnerd46bb6e2002-04-24 19:12:21 +000017// * Verify that the indices of mem access instructions match other operands
Misha Brukman1c9de462004-06-24 21:47:35 +000018// * Verify that arithmetic and other things are only performed on first-class
Chris Lattner8e72d6f2002-08-02 17:37:08 +000019// types. Verify that shifts & logicals only happen on integrals f.e.
Misha Brukman1c9de462004-06-24 21:47:35 +000020// * All of the constants in a switch statement are of the correct type
Chris Lattner8e72d6f2002-08-02 17:37:08 +000021// * The code is in valid SSA form
Misha Brukman1c9de462004-06-24 21:47:35 +000022// * It should be illegal to put a label into any other type (like a structure)
Chris Lattner2f7c9632001-06-06 20:29:01 +000023// or to return one. [except constant arrays!]
Nick Lewyckyf88c84f2008-03-28 06:46:51 +000024// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
Chris Lattnerd02f08d2002-02-20 17:55:43 +000025// * PHI nodes must have an entry for each predecessor, with no extras.
Chris Lattner069a7952002-06-25 15:56:27 +000026// * PHI nodes must be the first thing in a basic block, all grouped together
Chris Lattner4cd9df82002-10-06 21:00:31 +000027// * PHI nodes must have at least one entry
Chris Lattner069a7952002-06-25 15:56:27 +000028// * All basic blocks should only end with terminator insts, not contain them
Chris Lattner3e6e3e62002-03-29 19:06:18 +000029// * The entry node to a function must not have predecessors
Misha Brukmanfa100532003-10-10 17:54:14 +000030// * All Instructions must be embedded into a basic block
Misha Brukman1c9de462004-06-24 21:47:35 +000031// * Functions cannot take a void-typed parameter
Chris Lattneraf95e582002-04-13 22:48:46 +000032// * Verify that a function's argument list agrees with it's declared type.
Chris Lattnerfbf5be52002-03-15 20:25:09 +000033// * It is illegal to specify a name for a void value.
Misha Brukmanfa100532003-10-10 17:54:14 +000034// * It is illegal to have a internal global value with no initializer
Chris Lattner486302a2002-04-12 18:20:49 +000035// * It is illegal to have a ret instruction that returns a value that does not
36// agree with the function return value type.
Chris Lattner338a4622002-05-08 19:49:50 +000037// * Function call argument types match the function prototype
Bill Wendlingfae14752011-08-12 20:24:12 +000038// * A landing pad is defined by a landingpad instruction, and can be jumped to
39// only by the unwind edge of an invoke instruction.
40// * A landingpad instruction must be the first non-PHI instruction in the
41// block.
Vedant Kumar029c3512015-10-21 20:33:31 +000042// * Landingpad instructions must be in a function with a personality function.
Chris Lattnerd46bb6e2002-04-24 19:12:21 +000043// * All other things that are tested by asserts spread about the code...
Chris Lattner2f7c9632001-06-06 20:29:01 +000044//
45//===----------------------------------------------------------------------===//
46
Chandler Carruth5ad5f152014-01-13 09:26:24 +000047#include "llvm/IR/Verifier.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000048#include "llvm/ADT/APFloat.h"
49#include "llvm/ADT/APInt.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/DenseMap.h"
52#include "llvm/ADT/ilist.h"
Joseph Tremoulet8ea80862016-01-10 04:31:05 +000053#include "llvm/ADT/MapVector.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000054#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000057#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/ADT/SmallVector.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000059#include "llvm/ADT/StringMap.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Twine.h"
62#include "llvm/IR/Argument.h"
63#include "llvm/IR/Attributes.h"
64#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000065#include "llvm/IR/CFG.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000066#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000067#include "llvm/IR/CallingConv.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000068#include "llvm/IR/Comdat.h"
69#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000070#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000071#include "llvm/IR/Constants.h"
Matt Arsenault24b49c42013-07-31 17:49:08 +000072#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000073#include "llvm/IR/DebugInfo.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000074#include "llvm/IR/DebugInfoMetadata.h"
75#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000076#include "llvm/IR/DerivedTypes.h"
Adrian Prantle3656182016-05-09 19:57:29 +000077#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000078#include "llvm/IR/Dominators.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000079#include "llvm/IR/Function.h"
80#include "llvm/IR/GlobalAlias.h"
81#include "llvm/IR/GlobalValue.h"
82#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000083#include "llvm/IR/InlineAsm.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000084#include "llvm/IR/InstrTypes.h"
85#include "llvm/IR/Instruction.h"
86#include "llvm/IR/Instructions.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000087#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000088#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000089#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000090#include "llvm/IR/LLVMContext.h"
91#include "llvm/IR/Metadata.h"
92#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +000093#include "llvm/IR/ModuleSlotTracker.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000094#include "llvm/IR/PassManager.h"
Philip Reames38303a32014-12-03 19:53:15 +000095#include "llvm/IR/Statepoint.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000096#include "llvm/IR/Type.h"
97#include "llvm/IR/Use.h"
98#include "llvm/IR/User.h"
99#include "llvm/IR/Value.h"
Chris Lattner8a923e72008-03-12 17:45:29 +0000100#include "llvm/Pass.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000101#include "llvm/Support/AtomicOrdering.h"
102#include "llvm/Support/Casting.h"
Manman Ren74c61b92013-07-19 00:31:03 +0000103#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000104#include "llvm/Support/Debug.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000105#include "llvm/Support/Dwarf.h"
Torok Edwin6dd27302009-07-08 18:01:40 +0000106#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000107#include "llvm/Support/MathExtras.h"
Chris Lattner24025262009-02-28 21:05:51 +0000108#include "llvm/Support/raw_ostream.h"
Chris Lattnerd02f08d2002-02-20 17:55:43 +0000109#include <algorithm>
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000110#include <cassert>
111#include <cstdint>
112#include <memory>
113#include <string>
114#include <utility>
115
Chris Lattner189d19f2003-11-21 20:23:48 +0000116using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +0000117
Duncan P. N. Exon Smith0633fd72015-03-17 17:28:41 +0000118static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
Manman Ren74c61b92013-07-19 00:31:03 +0000119
Dan Gohmand78c4002008-05-13 00:00:25 +0000120namespace {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000121
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000122struct VerifierSupport {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000123 raw_ostream *OS;
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000124 const Module &M;
125 ModuleSlotTracker MST;
126 const DataLayout &DL;
127 LLVMContext &Context;
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000128
Duncan P. N. Exon Smith9c3ff192016-04-20 15:55:24 +0000129 /// Track the brokenness of the module while recursively visiting.
130 bool Broken = false;
Adrian Prantl541a9c52016-05-06 19:26:47 +0000131 /// Broken debug info can be "recovered" from by stripping the debug info.
132 bool BrokenDebugInfo = false;
133 /// Whether to treat broken debug info as an error.
134 bool TreatBrokenDebugInfoAsError = true;
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000135
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000136 explicit VerifierSupport(raw_ostream *OS, const Module &M)
137 : OS(OS), M(M), MST(&M), DL(M.getDataLayout()), Context(M.getContext()) {}
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000138
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000139private:
Keno Fischera6c4ce42015-12-01 19:06:36 +0000140 void Write(const Module *M) {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000141 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
Keno Fischera6c4ce42015-12-01 19:06:36 +0000142 }
143
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000144 void Write(const Value *V) {
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000145 if (!V)
146 return;
147 if (isa<Instruction>(V)) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000148 V->print(*OS, MST);
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +0000149 *OS << '\n';
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000150 } else {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000151 V->printAsOperand(*OS, true, MST);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000152 *OS << '\n';
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000153 }
154 }
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000155
Philip Reames9818dd72015-06-26 22:04:34 +0000156 void Write(ImmutableCallSite CS) {
157 Write(CS.getInstruction());
Philip Reamesa3c6f002015-06-26 21:39:44 +0000158 }
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000159
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000160 void Write(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000161 if (!MD)
162 return;
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000163 MD->print(*OS, MST, &M);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000164 *OS << '\n';
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000165 }
166
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +0000167 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
168 Write(MD.get());
169 }
170
Duncan P. N. Exon Smithf238c782015-03-24 17:18:03 +0000171 void Write(const NamedMDNode *NMD) {
172 if (!NMD)
173 return;
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000174 NMD->print(*OS, MST);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000175 *OS << '\n';
Duncan P. N. Exon Smithf238c782015-03-24 17:18:03 +0000176 }
177
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000178 void Write(Type *T) {
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000179 if (!T)
180 return;
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000181 *OS << ' ' << *T;
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000182 }
183
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000184 void Write(const Comdat *C) {
David Majnemerdad0a642014-06-27 18:19:56 +0000185 if (!C)
186 return;
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000187 *OS << *C;
David Majnemerdad0a642014-06-27 18:19:56 +0000188 }
189
Sanjoy Das3336f682016-12-11 20:07:15 +0000190 void Write(const APInt *AI) {
191 if (!AI)
192 return;
193 *OS << *AI << '\n';
194 }
195
196 void Write(const unsigned i) { *OS << i << '\n'; }
197
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000198 template <typename T> void Write(ArrayRef<T> Vs) {
199 for (const T &V : Vs)
200 Write(V);
201 }
202
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000203 template <typename T1, typename... Ts>
204 void WriteTs(const T1 &V1, const Ts &... Vs) {
205 Write(V1);
206 WriteTs(Vs...);
207 }
208
209 template <typename... Ts> void WriteTs() {}
210
211public:
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000212 /// \brief A check failed, so printout out the condition and the message.
213 ///
214 /// This provides a nice place to put a breakpoint if you want to see why
215 /// something is not correct.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000216 void CheckFailed(const Twine &Message) {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000217 if (OS)
218 *OS << Message << '\n';
Duncan P. N. Exon Smith6a607c02015-03-31 02:37:13 +0000219 Broken = true;
David Majnemerdad0a642014-06-27 18:19:56 +0000220 }
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000221
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000222 /// \brief A check failed (with values to print).
223 ///
224 /// This calls the Message-only version so that the above is easier to set a
225 /// breakpoint on.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000226 template <typename T1, typename... Ts>
227 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
228 CheckFailed(Message);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000229 if (OS)
230 WriteTs(V1, Vs...);
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000231 }
Adrian Prantl541a9c52016-05-06 19:26:47 +0000232
233 /// A debug info check failed.
234 void DebugInfoCheckFailed(const Twine &Message) {
235 if (OS)
236 *OS << Message << '\n';
237 Broken |= TreatBrokenDebugInfoAsError;
238 BrokenDebugInfo = true;
239 }
240
241 /// A debug info check failed (with values to print).
242 template <typename T1, typename... Ts>
243 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
244 const Ts &... Vs) {
245 DebugInfoCheckFailed(Message);
246 if (OS)
247 WriteTs(V1, Vs...);
248 }
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000249};
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000250
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000251class Verifier : public InstVisitor<Verifier>, VerifierSupport {
252 friend class InstVisitor<Verifier>;
253
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000254 DominatorTree DT;
Chris Lattnerc9e79d02004-09-29 20:07:45 +0000255
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000256 /// \brief When verifying a basic block, keep track of all of the
257 /// instructions we have seen so far.
258 ///
259 /// This allows us to do efficient dominance checks for the case when an
260 /// instruction has an operand that is an instruction in the same block.
261 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
Bill Wendlingfae14752011-08-12 20:24:12 +0000262
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000263 /// \brief Keep track of the metadata nodes that have been checked already.
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000264 SmallPtrSet<const Metadata *, 32> MDNodes;
Manman Ren9974c882013-07-23 00:22:51 +0000265
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000266 /// Track all DICompileUnits visited.
267 SmallPtrSet<const Metadata *, 2> CUVisited;
268
David Majnemer654e1302015-07-31 17:58:14 +0000269 /// \brief The result type for a landingpad.
270 Type *LandingPadResultTy;
271
Reid Kleckner60381792015-07-07 22:25:32 +0000272 /// \brief Whether we've seen a call to @llvm.localescape in this function
Reid Klecknere9b89312015-01-13 00:48:10 +0000273 /// already.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000274 bool SawFrameEscape;
275
Reid Kleckner60381792015-07-07 22:25:32 +0000276 /// Stores the count of how many objects were passed to llvm.localescape for a
277 /// given function and the largest index passed to llvm.localrecover.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000278 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
Reid Klecknere9b89312015-01-13 00:48:10 +0000279
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000280 // Maps catchswitches and cleanuppads that unwind to siblings to the
281 // terminators that indicate the unwind, used to detect cycles therein.
282 MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo;
283
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000284 /// Cache of constants visited in search of ConstantExprs.
285 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
286
Sanjoy Dase0aa4142016-05-12 01:17:38 +0000287 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
288 SmallVector<const Function *, 4> DeoptimizeDeclarations;
289
Ivan Krasin3b1c2602016-01-20 08:41:22 +0000290 // Verify that this GlobalValue is only used in this module.
291 // This map is used to avoid visiting uses twice. We can arrive at a user
292 // twice, if they have multiple operands. In particular for very large
293 // constant expressions, we can arrive at a particular user many times.
294 SmallPtrSet<const Value *, 32> GlobalValueVisited;
295
Sanjoy Das3336f682016-12-11 20:07:15 +0000296 /// Cache of TBAA base nodes that have already been visited. This cachce maps
297 /// a node that has been visited to a pair (IsInvalid, BitWidth) where
298 ///
299 /// \c IsInvalid is true iff the node is invalid.
300 /// \c BitWidth, if non-zero, is the bitwidth of the integer used to denoting
301 /// the offset of the access. If zero, only a zero offset is allowed.
302 ///
303 /// \c BitWidth has no meaning if \c IsInvalid is true.
304 typedef std::pair<bool, unsigned> TBAABaseNodeSummary;
305 DenseMap<MDNode *, TBAABaseNodeSummary> TBAABaseNodes;
306
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000307 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +0000308
Chandler Carruth043949d2014-01-19 02:22:18 +0000309public:
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000310 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
311 const Module &M)
312 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
Adrian Prantl541a9c52016-05-06 19:26:47 +0000313 SawFrameEscape(false) {
314 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
315 }
316
317 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
Chris Lattner0e851da2002-04-18 20:37:37 +0000318
Chandler Carruth043949d2014-01-19 02:22:18 +0000319 bool verify(const Function &F) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000320 assert(F.getParent() == &M &&
321 "An instance of this class only works with a specific module!");
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000322
323 // First ensure the function is well-enough formed to compute dominance
Peter Collingbourne71bb7942016-06-06 22:32:52 +0000324 // information, and directly compute a dominance tree. We don't rely on the
325 // pass manager to provide this as it isolates us from a potentially
326 // out-of-date dominator tree and makes it significantly more complex to run
327 // this code outside of a pass manager.
328 // FIXME: It's really gross that we have to cast away constness here.
329 if (!F.empty())
330 DT.recalculate(const_cast<Function &>(F));
331
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000332 for (const BasicBlock &BB : F) {
Duncan P. N. Exon Smith8ec8da42016-04-20 18:27:18 +0000333 if (!BB.empty() && BB.back().isTerminator())
334 continue;
335
336 if (OS) {
337 *OS << "Basic Block in function '" << F.getName()
338 << "' does not have terminator!\n";
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000339 BB.printAsOperand(*OS, true, MST);
Duncan P. N. Exon Smith8ec8da42016-04-20 18:27:18 +0000340 *OS << "\n";
Chandler Carruth76777602014-01-17 10:56:02 +0000341 }
Duncan P. N. Exon Smith8ec8da42016-04-20 18:27:18 +0000342 return false;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000343 }
Chandler Carruth76777602014-01-17 10:56:02 +0000344
Chandler Carruth043949d2014-01-19 02:22:18 +0000345 Broken = false;
346 // FIXME: We strip const here because the inst visitor strips const.
347 visit(const_cast<Function &>(F));
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000348 verifySiblingFuncletUnwinds();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000349 InstsInThisBlock.clear();
David Majnemer654e1302015-07-31 17:58:14 +0000350 LandingPadResultTy = nullptr;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000351 SawFrameEscape = false;
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000352 SiblingFuncletInfo.clear();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000353
Chandler Carruth043949d2014-01-19 02:22:18 +0000354 return !Broken;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000355 }
356
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000357 /// Verify the module that this instance of \c Verifier was initialized with.
358 bool verify() {
Chandler Carruth043949d2014-01-19 02:22:18 +0000359 Broken = false;
360
Peter Collingbournebb738172016-06-06 23:21:27 +0000361 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
362 for (const Function &F : M)
363 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
364 DeoptimizeDeclarations.push_back(&F);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000365
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000366 // Now that we've visited every function, verify that we never asked to
367 // recover a frame index that wasn't escaped.
368 verifyFrameRecoverIndices();
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000369 for (const GlobalVariable &GV : M.globals())
370 visitGlobalVariable(GV);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000371
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000372 for (const GlobalAlias &GA : M.aliases())
373 visitGlobalAlias(GA);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000374
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000375 for (const NamedMDNode &NMD : M.named_metadata())
376 visitNamedMDNode(NMD);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000377
David Majnemerdad0a642014-06-27 18:19:56 +0000378 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
379 visitComdat(SMEC.getValue());
380
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000381 visitModuleFlags(M);
382 visitModuleIdents(M);
383
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000384 verifyCompileUnits();
385
Sanjoy Dase0aa4142016-05-12 01:17:38 +0000386 verifyDeoptimizeCallingConvs();
387
Chandler Carruth043949d2014-01-19 02:22:18 +0000388 return !Broken;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000389 }
Chris Lattner9713b842002-04-28 16:04:26 +0000390
Chandler Carruth043949d2014-01-19 02:22:18 +0000391private:
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000392 // Verification methods...
Chandler Carruth043949d2014-01-19 02:22:18 +0000393 void visitGlobalValue(const GlobalValue &GV);
394 void visitGlobalVariable(const GlobalVariable &GV);
395 void visitGlobalAlias(const GlobalAlias &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000396 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
Craig Topper71b7b682014-08-21 05:55:13 +0000397 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
Rafael Espindola64c1e182014-06-03 02:41:57 +0000398 const GlobalAlias &A, const Constant &C);
Chandler Carruth043949d2014-01-19 02:22:18 +0000399 void visitNamedMDNode(const NamedMDNode &NMD);
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000400 void visitMDNode(const MDNode &MD);
401 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
402 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
David Majnemerdad0a642014-06-27 18:19:56 +0000403 void visitComdat(const Comdat &C);
Chandler Carruth043949d2014-01-19 02:22:18 +0000404 void visitModuleIdents(const Module &M);
405 void visitModuleFlags(const Module &M);
406 void visitModuleFlag(const MDNode *Op,
407 DenseMap<const MDString *, const MDNode *> &SeenIDs,
408 SmallVectorImpl<const MDNode *> &Requirements);
409 void visitFunction(const Function &F);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000410 void visitBasicBlock(BasicBlock &BB);
Sanjoy Das26f28a22016-11-09 19:36:39 +0000411 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
412 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
Sanjoy Das2582e692016-11-08 20:46:01 +0000413 void visitTBAAMetadata(Instruction &I, MDNode *MD);
Philip Reamesbf9676f2014-10-20 23:52:07 +0000414
Sanjoy Das3336f682016-12-11 20:07:15 +0000415 /// \name Helper functions used by \c visitTBAAMetadata.
416 /// @{
417 MDNode *getFieldNodeFromTBAABaseNode(Instruction &I, MDNode *BaseNode,
418 APInt &Offset);
419 TBAABaseNodeSummary verifyTBAABaseNode(Instruction &I, MDNode *BaseNode);
420 TBAABaseNodeSummary verifyTBAABaseNodeImpl(Instruction &I, MDNode *BaseNode);
421 /// @}
422
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +0000423 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +0000424#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
425#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000426 void visitDIScope(const DIScope &N);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000427 void visitDIVariable(const DIVariable &N);
428 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
429 void visitDITemplateParameter(const DITemplateParameter &N);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000430
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000431 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
432
Chandler Carruth043949d2014-01-19 02:22:18 +0000433 // InstVisitor overrides...
434 using InstVisitor<Verifier>::visit;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000435 void visit(Instruction &I);
436
437 void visitTruncInst(TruncInst &I);
438 void visitZExtInst(ZExtInst &I);
439 void visitSExtInst(SExtInst &I);
440 void visitFPTruncInst(FPTruncInst &I);
441 void visitFPExtInst(FPExtInst &I);
442 void visitFPToUIInst(FPToUIInst &I);
443 void visitFPToSIInst(FPToSIInst &I);
444 void visitUIToFPInst(UIToFPInst &I);
445 void visitSIToFPInst(SIToFPInst &I);
446 void visitIntToPtrInst(IntToPtrInst &I);
447 void visitPtrToIntInst(PtrToIntInst &I);
448 void visitBitCastInst(BitCastInst &I);
449 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
450 void visitPHINode(PHINode &PN);
451 void visitBinaryOperator(BinaryOperator &B);
452 void visitICmpInst(ICmpInst &IC);
453 void visitFCmpInst(FCmpInst &FC);
454 void visitExtractElementInst(ExtractElementInst &EI);
455 void visitInsertElementInst(InsertElementInst &EI);
456 void visitShuffleVectorInst(ShuffleVectorInst &EI);
457 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
458 void visitCallInst(CallInst &CI);
459 void visitInvokeInst(InvokeInst &II);
460 void visitGetElementPtrInst(GetElementPtrInst &GEP);
461 void visitLoadInst(LoadInst &LI);
462 void visitStoreInst(StoreInst &SI);
463 void verifyDominatesUse(Instruction &I, unsigned i);
464 void visitInstruction(Instruction &I);
465 void visitTerminatorInst(TerminatorInst &I);
466 void visitBranchInst(BranchInst &BI);
467 void visitReturnInst(ReturnInst &RI);
468 void visitSwitchInst(SwitchInst &SI);
469 void visitIndirectBrInst(IndirectBrInst &BI);
470 void visitSelectInst(SelectInst &SI);
471 void visitUserOp1(Instruction &I);
472 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
Philip Reames007561a2015-06-26 22:21:52 +0000473 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +0000474 template <class DbgIntrinsicTy>
475 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000476 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
477 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
478 void visitFenceInst(FenceInst &FI);
479 void visitAllocaInst(AllocaInst &AI);
480 void visitExtractValueInst(ExtractValueInst &EVI);
481 void visitInsertValueInst(InsertValueInst &IVI);
David Majnemer85a549d2015-08-11 02:48:30 +0000482 void visitEHPadPredecessors(Instruction &I);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000483 void visitLandingPadInst(LandingPadInst &LPI);
David Majnemerba6665d2016-08-01 18:06:34 +0000484 void visitResumeInst(ResumeInst &RI);
David Majnemer654e1302015-07-31 17:58:14 +0000485 void visitCatchPadInst(CatchPadInst &CPI);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000486 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
David Majnemer654e1302015-07-31 17:58:14 +0000487 void visitCleanupPadInst(CleanupPadInst &CPI);
Joseph Tremoulet81e81962016-01-10 04:30:02 +0000488 void visitFuncletPadInst(FuncletPadInst &FPI);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000489 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
David Majnemer654e1302015-07-31 17:58:14 +0000490 void visitCleanupReturnInst(CleanupReturnInst &CRI);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000491
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000492 void verifyCallSite(CallSite CS);
Manman Ren9bfd0d02016-04-01 21:41:15 +0000493 void verifySwiftErrorCallSite(CallSite CS, const Value *SwiftErrorVal);
494 void verifySwiftErrorValue(const Value *SwiftErrorVal);
Reid Kleckner5772b772014-04-24 20:14:34 +0000495 void verifyMustTailCall(CallInst &CI);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000496 bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000497 unsigned ArgNo, std::string &Suffix);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000498 bool verifyAttributeCount(AttributeSet Attrs, unsigned Params);
499 void verifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000500 const Value *V);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000501 void verifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000502 bool isReturnValue, const Value *V);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000503 void verifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000504 const Value *V);
Benjamin Kramer7ab4fe32016-06-12 17:46:23 +0000505 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000506
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000507 void visitConstantExprsRecursively(const Constant *EntryC);
508 void visitConstantExpr(const ConstantExpr *CE);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000509 void verifyStatepoint(ImmutableCallSite CS);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000510 void verifyFrameRecoverIndices();
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000511 void verifySiblingFuncletUnwinds();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000512
Adrian Prantl941fa752016-12-05 18:04:47 +0000513 void verifyFragmentExpression(const DbgInfoIntrinsic &I);
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000514
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000515 /// Module-level debug info verification...
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000516 void verifyCompileUnits();
Sanjoy Dase0aa4142016-05-12 01:17:38 +0000517
518 /// Module-level verification that all @llvm.experimental.deoptimize
519 /// declarations share the same calling convention.
520 void verifyDeoptimizeCallingConvs();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000521};
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000522
523} // end anonymous namespace
Chris Lattner189d19f2003-11-21 20:23:48 +0000524
Adrian Prantl541a9c52016-05-06 19:26:47 +0000525/// We know that cond should be true, if not print an error message.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000526#define Assert(C, ...) \
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000527 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
Chris Lattner2f7c9632001-06-06 20:29:01 +0000528
Adrian Prantl541a9c52016-05-06 19:26:47 +0000529/// We know that a debug info condition should be true, if not print
530/// an error message.
531#define AssertDI(C, ...) \
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000532 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
Adrian Prantl541a9c52016-05-06 19:26:47 +0000533
Chris Lattnere5a22c02008-08-28 04:02:44 +0000534void Verifier::visit(Instruction &I) {
535 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000536 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
Chris Lattnere5a22c02008-08-28 04:02:44 +0000537 InstVisitor<Verifier>::visit(I);
538}
539
Keno Fischer60f82a22016-01-14 22:20:56 +0000540// Helper to recursively iterate over indirect users. By
541// returning false, the callback can ask to stop recursing
542// further.
543static void forEachUser(const Value *User,
544 SmallPtrSet<const Value *, 32> &Visited,
545 llvm::function_ref<bool(const Value *)> Callback) {
546 if (!Visited.insert(User).second)
547 return;
Rafael Espindola257a3532016-01-15 19:00:20 +0000548 for (const Value *TheNextUser : User->materialized_users())
Keno Fischer60f82a22016-01-14 22:20:56 +0000549 if (Callback(TheNextUser))
550 forEachUser(TheNextUser, Visited, Callback);
551}
Chris Lattnere5a22c02008-08-28 04:02:44 +0000552
Chandler Carruth043949d2014-01-19 02:22:18 +0000553void Verifier::visitGlobalValue(const GlobalValue &GV) {
Rafael Espindola4787ba32016-05-11 13:51:39 +0000554 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000555 "Global is external, but doesn't have external or weak linkage!", &GV);
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000556
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000557 Assert(GV.getAlignment() <= Value::MaximumAlignment,
558 "huge alignment values are unsupported", &GV);
559 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
560 "Only global variables can have appending linkage!", &GV);
Chris Lattner3ac483b2003-04-16 20:42:40 +0000561
562 if (GV.hasAppendingLinkage()) {
Chandler Carruth043949d2014-01-19 02:22:18 +0000563 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
David Blaikie60310f22015-05-08 00:42:26 +0000564 Assert(GVar && GVar->getValueType()->isArrayTy(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000565 "Only global arrays can have appending linkage!", GVar);
Chris Lattner3ac483b2003-04-16 20:42:40 +0000566 }
Peter Collingbourne46eb0f52015-07-05 20:52:40 +0000567
568 if (GV.isDeclarationForLinker())
569 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
Keno Fischer60f82a22016-01-14 22:20:56 +0000570
Ivan Krasin3b1c2602016-01-20 08:41:22 +0000571 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
Keno Fischer60f82a22016-01-14 22:20:56 +0000572 if (const Instruction *I = dyn_cast<Instruction>(V)) {
573 if (!I->getParent() || !I->getParent()->getParent())
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000574 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
575 I);
576 else if (I->getParent()->getParent()->getParent() != &M)
577 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
578 I->getParent()->getParent(),
Keno Fischer60f82a22016-01-14 22:20:56 +0000579 I->getParent()->getParent()->getParent());
580 return false;
581 } else if (const Function *F = dyn_cast<Function>(V)) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000582 if (F->getParent() != &M)
583 CheckFailed("Global is used by function in a different module", &GV, &M,
584 F, F->getParent());
Keno Fischer60f82a22016-01-14 22:20:56 +0000585 return false;
586 }
587 return true;
588 });
Chris Lattner3ac483b2003-04-16 20:42:40 +0000589}
590
Chandler Carruth043949d2014-01-19 02:22:18 +0000591void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
Chris Lattnerd79f3d52007-09-19 17:14:45 +0000592 if (GV.hasInitializer()) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000593 Assert(GV.getInitializer()->getType() == GV.getValueType(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000594 "Global variable initializer type does not match global "
595 "variable type!",
596 &GV);
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000597
Chris Lattner0aff0b22009-08-05 05:41:44 +0000598 // If the global has common linkage, it must have a zero initializer and
599 // cannot be constant.
600 if (GV.hasCommonLinkage()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000601 Assert(GV.getInitializer()->isNullValue(),
602 "'common' global must have a zero initializer!", &GV);
603 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
604 &GV);
605 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
Chris Lattner0aff0b22009-08-05 05:41:44 +0000606 }
Chris Lattnerd79f3d52007-09-19 17:14:45 +0000607 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000608
Nick Lewycky466d0c12011-04-08 07:30:21 +0000609 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
610 GV.getName() == "llvm.global_dtors")) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000611 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
612 "invalid linkage for intrinsic global variable", &GV);
Nick Lewycky466d0c12011-04-08 07:30:21 +0000613 // Don't worry about emitting an error for it not being an array,
614 // visitGlobalValue will complain on appending non-array.
David Blaikie60310f22015-05-08 00:42:26 +0000615 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
Chris Lattner229907c2011-07-18 04:54:35 +0000616 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
617 PointerType *FuncPtrTy =
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000618 FunctionType::get(Type::getVoidTy(Context), false)->getPointerTo();
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000619 // FIXME: Reject the 2-field form in LLVM 4.0.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000620 Assert(STy &&
621 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
622 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
623 STy->getTypeAtIndex(1) == FuncPtrTy,
624 "wrong type for intrinsic global variable", &GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000625 if (STy->getNumElements() == 3) {
626 Type *ETy = STy->getTypeAtIndex(2);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000627 Assert(ETy->isPointerTy() &&
628 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
629 "wrong type for intrinsic global variable", &GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000630 }
Nick Lewycky466d0c12011-04-08 07:30:21 +0000631 }
632 }
633
Rafael Espindola8bd2c222013-04-22 15:16:51 +0000634 if (GV.hasName() && (GV.getName() == "llvm.used" ||
Rafael Espindola9aadcc42013-07-19 18:44:51 +0000635 GV.getName() == "llvm.compiler.used")) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000636 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
637 "invalid linkage for intrinsic global variable", &GV);
David Blaikie0c28fd72015-05-20 21:46:30 +0000638 Type *GVType = GV.getValueType();
Rafael Espindola74f2e462013-04-22 14:58:02 +0000639 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
640 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000641 Assert(PTy, "wrong type for intrinsic global variable", &GV);
Rafael Espindola74f2e462013-04-22 14:58:02 +0000642 if (GV.hasInitializer()) {
Chandler Carruth043949d2014-01-19 02:22:18 +0000643 const Constant *Init = GV.getInitializer();
644 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000645 Assert(InitArray, "wrong initalizer for intrinsic global variable",
646 Init);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000647 for (Value *Op : InitArray->operands()) {
648 Value *V = Op->stripPointerCastsNoFollowAliases();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000649 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
650 isa<GlobalAlias>(V),
651 "invalid llvm.used member", V);
652 Assert(V->hasName(), "members of llvm.used must be named", V);
Rafael Espindola74f2e462013-04-22 14:58:02 +0000653 }
654 }
655 }
656 }
657
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000658 Assert(!GV.hasDLLImportStorageClass() ||
659 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
660 GV.hasAvailableExternallyLinkage(),
661 "Global is marked as dllimport, but not external", &GV);
Nico Rieck7157bb72014-01-14 15:22:47 +0000662
Matt Arsenault24b49c42013-07-31 17:49:08 +0000663 if (!GV.hasInitializer()) {
664 visitGlobalValue(GV);
665 return;
666 }
667
668 // Walk any aggregate initializers looking for bitcasts between address spaces
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000669 visitConstantExprsRecursively(GV.getInitializer());
Matt Arsenault24b49c42013-07-31 17:49:08 +0000670
Chris Lattnere3400652004-12-15 20:23:49 +0000671 visitGlobalValue(GV);
672}
673
Rafael Espindola64c1e182014-06-03 02:41:57 +0000674void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
675 SmallPtrSet<const GlobalAlias*, 4> Visited;
676 Visited.insert(&GA);
677 visitAliaseeSubExpr(Visited, GA, C);
678}
679
Craig Topper71b7b682014-08-21 05:55:13 +0000680void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
Rafael Espindola64c1e182014-06-03 02:41:57 +0000681 const GlobalAlias &GA, const Constant &C) {
682 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
Rafael Espindola89345772015-11-26 19:22:59 +0000683 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
684 &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000685
686 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000687 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000688
Sanjoy Das5ce32722016-04-08 00:48:30 +0000689 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000690 &GA);
Bob Wilson2f7cc012014-06-12 01:46:54 +0000691 } else {
692 // Only continue verifying subexpressions of GlobalAliases.
693 // Do not recurse into global initializers.
694 return;
Rafael Espindola64c1e182014-06-03 02:41:57 +0000695 }
696 }
697
698 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000699 visitConstantExprsRecursively(CE);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000700
701 for (const Use &U : C.operands()) {
702 Value *V = &*U;
703 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
704 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
705 else if (const auto *C2 = dyn_cast<Constant>(V))
706 visitAliaseeSubExpr(Visited, GA, *C2);
707 }
708}
709
Chandler Carruth043949d2014-01-19 02:22:18 +0000710void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000711 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
712 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
713 "weak_odr, or external linkage!",
714 &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000715 const Constant *Aliasee = GA.getAliasee();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000716 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
717 Assert(GA.getType() == Aliasee->getType(),
718 "Alias and aliasee types should match!", &GA);
Anton Korobeynikova50eed42008-05-08 23:11:06 +0000719
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000720 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
721 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
Matt Arsenault828b5652013-07-20 17:46:05 +0000722
Rafael Espindola64c1e182014-06-03 02:41:57 +0000723 visitAliaseeSubExpr(GA, *Aliasee);
Anton Korobeynikov25b2e822008-03-22 08:36:14 +0000724
Anton Korobeynikova97b6942007-04-25 14:27:10 +0000725 visitGlobalValue(GA);
726}
727
Chandler Carruth043949d2014-01-19 02:22:18 +0000728void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
Adrian Prantlb3510af2016-10-05 22:15:37 +0000729 // There used to be various other llvm.dbg.* nodes, but we don't support
730 // upgrading them and we want to reserve the namespace for future uses.
731 if (NMD.getName().startswith("llvm.dbg."))
732 AssertDI(NMD.getName() == "llvm.dbg.cu",
733 "unrecognized named metadata node in the llvm.dbg namespace",
734 &NMD);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000735 for (const MDNode *MD : NMD.operands()) {
Adrian Prantlb3510af2016-10-05 22:15:37 +0000736 if (NMD.getName() == "llvm.dbg.cu")
Adrian Prantl541a9c52016-05-06 19:26:47 +0000737 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
Duncan P. N. Exon Smithf238c782015-03-24 17:18:03 +0000738
Duncan P. N. Exon Smithd23ddbd2015-03-31 02:27:32 +0000739 if (!MD)
740 continue;
741
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000742 visitMDNode(*MD);
Duncan Sands76d62172010-04-29 16:10:30 +0000743 }
744}
745
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000746void Verifier::visitMDNode(const MDNode &MD) {
Duncan Sands76d62172010-04-29 16:10:30 +0000747 // Only visit each node once. Metadata can be mutually recursive, so this
748 // avoids infinite recursion here, as well as being an optimization.
David Blaikie70573dc2014-11-19 07:49:26 +0000749 if (!MDNodes.insert(&MD).second)
Duncan Sands76d62172010-04-29 16:10:30 +0000750 return;
751
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +0000752 switch (MD.getMetadataID()) {
753 default:
754 llvm_unreachable("Invalid MDNode subclass");
755 case Metadata::MDTupleKind:
756 break;
757#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
758 case Metadata::CLASS##Kind: \
759 visit##CLASS(cast<CLASS>(MD)); \
760 break;
761#include "llvm/IR/Metadata.def"
762 }
763
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000764 for (const Metadata *Op : MD.operands()) {
Duncan Sands76d62172010-04-29 16:10:30 +0000765 if (!Op)
766 continue;
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000767 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
768 &MD, Op);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000769 if (auto *N = dyn_cast<MDNode>(Op)) {
770 visitMDNode(*N);
Duncan Sands76d62172010-04-29 16:10:30 +0000771 continue;
772 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000773 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
774 visitValueAsMetadata(*V, nullptr);
775 continue;
776 }
Duncan Sands76d62172010-04-29 16:10:30 +0000777 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000778
779 // Check these last, so we diagnose problems in operands first.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000780 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
781 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000782}
783
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000784void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000785 Assert(MD.getValue(), "Expected valid value", &MD);
786 Assert(!MD.getValue()->getType()->isMetadataTy(),
787 "Unexpected metadata round-trip through values", &MD, MD.getValue());
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000788
789 auto *L = dyn_cast<LocalAsMetadata>(&MD);
790 if (!L)
791 return;
792
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000793 Assert(F, "function-local metadata used outside a function", L);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000794
795 // If this was an instruction, bb, or argument, verify that it is in the
796 // function that we expect.
797 Function *ActualF = nullptr;
798 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000799 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000800 ActualF = I->getParent()->getParent();
801 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
802 ActualF = BB->getParent();
803 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
804 ActualF = A->getParent();
805 assert(ActualF && "Unimplemented function local metadata case!");
806
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000807 Assert(ActualF == F, "function-local metadata used in wrong function", L);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000808}
809
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000810void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000811 Metadata *MD = MDV.getMetadata();
812 if (auto *N = dyn_cast<MDNode>(MD)) {
813 visitMDNode(*N);
814 return;
815 }
816
817 // Only visit each node once. Metadata can be mutually recursive, so this
818 // avoids infinite recursion here, as well as being an optimization.
819 if (!MDNodes.insert(MD).second)
820 return;
821
822 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
823 visitValueAsMetadata(*V, F);
Duncan Sands76d62172010-04-29 16:10:30 +0000824}
825
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000826static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
827static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
828static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +0000829
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +0000830template <class Ty>
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000831static bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +0000832 for (Metadata *MD : N.operands()) {
833 if (MD) {
834 if (!isa<Ty>(MD))
835 return false;
836 } else {
837 if (!AllowNull)
838 return false;
839 }
840 }
841 return true;
842}
843
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000844template <class Ty> static bool isValidMetadataArray(const MDTuple &N) {
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +0000845 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
846}
847
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000848template <class Ty> static bool isValidMetadataNullArray(const MDTuple &N) {
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +0000849 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
850}
851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000852void Verifier::visitDILocation(const DILocation &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000853 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
854 "location requires a valid scope", &N, N.getRawScope());
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +0000855 if (auto *IA = N.getRawInlinedAt())
Adrian Prantl541a9c52016-05-06 19:26:47 +0000856 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
Duncan P. N. Exon Smith692bdb92015-02-10 01:32:56 +0000857}
858
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000859void Verifier::visitGenericDINode(const GenericDINode &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000860 AssertDI(N.getTag(), "invalid tag", &N);
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +0000861}
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000862
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000863void Verifier::visitDIScope(const DIScope &N) {
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000864 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +0000865 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000866}
867
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000868void Verifier::visitDISubrange(const DISubrange &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000869 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
870 AssertDI(N.getCount() >= -1, "invalid subrange count", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000871}
872
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000873void Verifier::visitDIEnumerator(const DIEnumerator &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000874 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000875}
876
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000877void Verifier::visitDIBasicType(const DIBasicType &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000878 AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
879 N.getTag() == dwarf::DW_TAG_unspecified_type,
880 "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000881}
882
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000883void Verifier::visitDIDerivedType(const DIDerivedType &N) {
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000884 // Common scope checks.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000885 visitDIScope(N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000886
Adrian Prantl541a9c52016-05-06 19:26:47 +0000887 AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
888 N.getTag() == dwarf::DW_TAG_pointer_type ||
889 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
890 N.getTag() == dwarf::DW_TAG_reference_type ||
891 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
892 N.getTag() == dwarf::DW_TAG_const_type ||
893 N.getTag() == dwarf::DW_TAG_volatile_type ||
894 N.getTag() == dwarf::DW_TAG_restrict_type ||
Victor Leschuke1156c22016-10-31 19:09:38 +0000895 N.getTag() == dwarf::DW_TAG_atomic_type ||
Adrian Prantl541a9c52016-05-06 19:26:47 +0000896 N.getTag() == dwarf::DW_TAG_member ||
897 N.getTag() == dwarf::DW_TAG_inheritance ||
898 N.getTag() == dwarf::DW_TAG_friend,
899 "invalid tag", &N);
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000900 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000901 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
902 N.getRawExtraData());
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000903 }
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000904
Adrian Prantl541a9c52016-05-06 19:26:47 +0000905 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
906 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
907 N.getRawBaseType());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000908}
909
Duncan P. N. Exon Smith85866b2a2015-03-31 01:28:58 +0000910static bool hasConflictingReferenceFlags(unsigned Flags) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000911 return (Flags & DINode::FlagLValueReference) &&
912 (Flags & DINode::FlagRValueReference);
Duncan P. N. Exon Smith85866b2a2015-03-31 01:28:58 +0000913}
914
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000915void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
916 auto *Params = dyn_cast<MDTuple>(&RawParams);
Adrian Prantl541a9c52016-05-06 19:26:47 +0000917 AssertDI(Params, "invalid template params", &N, &RawParams);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000918 for (Metadata *Op : Params->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000919 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
920 &N, Params, Op);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000921 }
922}
923
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000924void Verifier::visitDICompositeType(const DICompositeType &N) {
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000925 // Common scope checks.
926 visitDIScope(N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000927
Adrian Prantl541a9c52016-05-06 19:26:47 +0000928 AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
929 N.getTag() == dwarf::DW_TAG_structure_type ||
930 N.getTag() == dwarf::DW_TAG_union_type ||
931 N.getTag() == dwarf::DW_TAG_enumeration_type ||
932 N.getTag() == dwarf::DW_TAG_class_type,
933 "invalid tag", &N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000934
Adrian Prantl541a9c52016-05-06 19:26:47 +0000935 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
936 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
937 N.getRawBaseType());
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000938
Adrian Prantl541a9c52016-05-06 19:26:47 +0000939 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
940 "invalid composite elements", &N, N.getRawElements());
941 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
942 N.getRawVTableHolder());
943 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
944 "invalid reference flags", &N);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000945 if (auto *Params = N.getRawTemplateParams())
946 visitTemplateParams(N, *Params);
Duncan P. N. Exon Smithdbfc0102015-07-24 19:57:19 +0000947
948 if (N.getTag() == dwarf::DW_TAG_class_type ||
949 N.getTag() == dwarf::DW_TAG_union_type) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000950 AssertDI(N.getFile() && !N.getFile()->getFilename().empty(),
951 "class/union requires a filename", &N, N.getFile());
Duncan P. N. Exon Smithdbfc0102015-07-24 19:57:19 +0000952 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000953}
954
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000955void Verifier::visitDISubroutineType(const DISubroutineType &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000956 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
Duncan P. N. Exon Smitha8b3a1f2015-03-28 02:43:53 +0000957 if (auto *Types = N.getRawTypeArray()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000958 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
Duncan P. N. Exon Smitha8b3a1f2015-03-28 02:43:53 +0000959 for (Metadata *Ty : N.getTypeArray()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000960 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
Duncan P. N. Exon Smitha8b3a1f2015-03-28 02:43:53 +0000961 }
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000962 }
Adrian Prantl541a9c52016-05-06 19:26:47 +0000963 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
964 "invalid reference flags", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000965}
966
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000967void Verifier::visitDIFile(const DIFile &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000968 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000969}
970
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000971void Verifier::visitDICompileUnit(const DICompileUnit &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000972 AssertDI(N.isDistinct(), "compile units must be distinct", &N);
973 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000974
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000975 // Don't bother verifying the compilation directory or producer string
976 // as those could be empty.
Adrian Prantl541a9c52016-05-06 19:26:47 +0000977 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
978 N.getRawFile());
979 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
980 N.getFile());
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000981
Adrian Prantl541a9c52016-05-06 19:26:47 +0000982 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
983 "invalid emission kind", &N);
Adrian Prantlb939a252016-03-31 23:56:58 +0000984
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000985 if (auto *Array = N.getRawEnumTypes()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000986 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000987 for (Metadata *Op : N.getEnumTypes()->operands()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000988 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
Adrian Prantl541a9c52016-05-06 19:26:47 +0000989 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
990 "invalid enum type", &N, N.getEnumTypes(), Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000991 }
992 }
993 if (auto *Array = N.getRawRetainedTypes()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000994 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000995 for (Metadata *Op : N.getRetainedTypes()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000996 AssertDI(Op && (isa<DIType>(Op) ||
997 (isa<DISubprogram>(Op) &&
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000998 !cast<DISubprogram>(Op)->isDefinition())),
Adrian Prantl541a9c52016-05-06 19:26:47 +0000999 "invalid retained type", &N, Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001000 }
1001 }
1002 if (auto *Array = N.getRawGlobalVariables()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001003 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001004 for (Metadata *Op : N.getGlobalVariables()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001005 AssertDI(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref",
1006 &N, Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001007 }
1008 }
1009 if (auto *Array = N.getRawImportedEntities()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001010 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001011 for (Metadata *Op : N.getImportedEntities()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001012 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1013 &N, Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001014 }
1015 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00001016 if (auto *Array = N.getRawMacros()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001017 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001018 for (Metadata *Op : N.getMacros()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001019 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001020 }
1021 }
Adrian Prantlfaebbb02016-03-28 21:06:26 +00001022 CUVisited.insert(&N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001023}
1024
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001025void Verifier::visitDISubprogram(const DISubprogram &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001026 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1027 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
Davide Italiano5f1c87b2016-04-06 18:46:39 +00001028 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001029 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001030 if (auto *T = N.getRawType())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001031 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1032 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1033 N.getRawContainingType());
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +00001034 if (auto *Params = N.getRawTemplateParams())
1035 visitTemplateParams(N, *Params);
Adrian Prantl75819ae2016-04-15 15:57:41 +00001036 if (auto *S = N.getRawDeclaration())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001037 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1038 "invalid subprogram declaration", &N, S);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +00001039 if (auto *RawVars = N.getRawVariables()) {
1040 auto *Vars = dyn_cast<MDTuple>(RawVars);
Adrian Prantl541a9c52016-05-06 19:26:47 +00001041 AssertDI(Vars, "invalid variable list", &N, RawVars);
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001042 for (Metadata *Op : Vars->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001043 AssertDI(Op && isa<DILocalVariable>(Op), "invalid local variable", &N,
1044 Vars, Op);
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001045 }
1046 }
Adrian Prantl541a9c52016-05-06 19:26:47 +00001047 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1048 "invalid reference flags", &N);
Duncan P. N. Exon Smith3ee34e12015-03-31 02:09:55 +00001049
Adrian Prantl75819ae2016-04-15 15:57:41 +00001050 auto *Unit = N.getRawUnit();
1051 if (N.isDefinition()) {
1052 // Subprogram definitions (not part of the type hierarchy).
Adrian Prantl541a9c52016-05-06 19:26:47 +00001053 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1054 AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
1055 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
Adrian Prantl75819ae2016-04-15 15:57:41 +00001056 } else {
1057 // Subprogram declarations (part of the type hierarchy).
Adrian Prantl541a9c52016-05-06 19:26:47 +00001058 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
Adrian Prantl75819ae2016-04-15 15:57:41 +00001059 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001060}
1061
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001062void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001063 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1064 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1065 "invalid local scope", &N, N.getRawScope());
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001066}
1067
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001068void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1069 visitDILexicalBlockBase(N);
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001070
Adrian Prantl541a9c52016-05-06 19:26:47 +00001071 AssertDI(N.getLine() || !N.getColumn(),
1072 "cannot have column info without line info", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001073}
1074
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001075void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1076 visitDILexicalBlockBase(N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001077}
1078
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001079void Verifier::visitDINamespace(const DINamespace &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001080 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001081 if (auto *S = N.getRawScope())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001082 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001083}
1084
Amjad Abouda9bcf162015-12-10 12:56:35 +00001085void Verifier::visitDIMacro(const DIMacro &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001086 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1087 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1088 "invalid macinfo type", &N);
1089 AssertDI(!N.getName().empty(), "anonymous macro", &N);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00001090 if (!N.getValue().empty()) {
1091 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1092 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00001093}
1094
1095void Verifier::visitDIMacroFile(const DIMacroFile &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001096 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1097 "invalid macinfo type", &N);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001098 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001099 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001100
1101 if (auto *Array = N.getRawElements()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001102 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001103 for (Metadata *Op : N.getElements()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001104 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001105 }
1106 }
1107}
1108
Adrian Prantlab1243f2015-06-29 23:03:47 +00001109void Verifier::visitDIModule(const DIModule &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001110 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1111 AssertDI(!N.getName().empty(), "anonymous module", &N);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001112}
1113
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001114void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001115 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001116}
1117
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001118void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1119 visitDITemplateParameter(N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001120
Adrian Prantl541a9c52016-05-06 19:26:47 +00001121 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1122 &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001123}
1124
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001125void Verifier::visitDITemplateValueParameter(
1126 const DITemplateValueParameter &N) {
1127 visitDITemplateParameter(N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001128
Adrian Prantl541a9c52016-05-06 19:26:47 +00001129 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1130 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1131 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1132 "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001133}
1134
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001135void Verifier::visitDIVariable(const DIVariable &N) {
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001136 if (auto *S = N.getRawScope())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001137 AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1138 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001139 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001140 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001141}
1142
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001143void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001144 // Checks common to all variables.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001145 visitDIVariable(N);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001146
Adrian Prantl541a9c52016-05-06 19:26:47 +00001147 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1148 AssertDI(!N.getName().empty(), "missing global variable name", &N);
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001149 if (auto *V = N.getRawExpr())
1150 AssertDI(isa<DIExpression>(V), "invalid expression location", &N, V);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001151 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001152 AssertDI(isa<DIDerivedType>(Member),
1153 "invalid static data member declaration", &N, Member);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001154 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001155}
1156
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001157void Verifier::visitDILocalVariable(const DILocalVariable &N) {
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001158 // Checks common to all variables.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001159 visitDIVariable(N);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001160
Adrian Prantl541a9c52016-05-06 19:26:47 +00001161 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1162 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1163 "local variable requires a valid scope", &N, N.getRawScope());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001164}
1165
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001166void Verifier::visitDIExpression(const DIExpression &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001167 AssertDI(N.isValid(), "invalid expression", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001168}
1169
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001170void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001171 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001172 if (auto *T = N.getRawType())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001173 AssertDI(isType(T), "invalid type ref", &N, T);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001174 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001175 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001176}
1177
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001178void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001179 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1180 N.getTag() == dwarf::DW_TAG_imported_declaration,
1181 "invalid tag", &N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001182 if (auto *S = N.getRawScope())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001183 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1184 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1185 N.getRawEntity());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001186}
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +00001187
David Majnemerdad0a642014-06-27 18:19:56 +00001188void Verifier::visitComdat(const Comdat &C) {
David Majnemerebc74112014-07-13 04:56:11 +00001189 // The Module is invalid if the GlobalValue has private linkage. Entities
1190 // with private linkage don't have entries in the symbol table.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001191 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001192 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1193 GV);
David Majnemerdad0a642014-06-27 18:19:56 +00001194}
1195
Chandler Carruth043949d2014-01-19 02:22:18 +00001196void Verifier::visitModuleIdents(const Module &M) {
Rafael Espindola0018a592013-10-16 01:49:05 +00001197 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1198 if (!Idents)
1199 return;
1200
1201 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1202 // Scan each llvm.ident entry and make sure that this requirement is met.
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001203 for (const MDNode *N : Idents->operands()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001204 Assert(N->getNumOperands() == 1,
1205 "incorrect number of operands in llvm.ident metadata", N);
1206 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1207 ("invalid value for llvm.ident metadata entry operand"
1208 "(the operand should be a string)"),
1209 N->getOperand(0));
Rafael Espindola0018a592013-10-16 01:49:05 +00001210 }
1211}
1212
Chandler Carruth043949d2014-01-19 02:22:18 +00001213void Verifier::visitModuleFlags(const Module &M) {
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001214 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1215 if (!Flags) return;
1216
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001217 // Scan each flag, and track the flags and requirements.
Chandler Carruth043949d2014-01-19 02:22:18 +00001218 DenseMap<const MDString*, const MDNode*> SeenIDs;
1219 SmallVector<const MDNode*, 16> Requirements;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001220 for (const MDNode *MDN : Flags->operands())
1221 visitModuleFlag(MDN, SeenIDs, Requirements);
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001222
1223 // Validate that the requirements in the module are valid.
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001224 for (const MDNode *Requirement : Requirements) {
Chandler Carruth043949d2014-01-19 02:22:18 +00001225 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001226 const Metadata *ReqValue = Requirement->getOperand(1);
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001227
Chandler Carruth043949d2014-01-19 02:22:18 +00001228 const MDNode *Op = SeenIDs.lookup(Flag);
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001229 if (!Op) {
1230 CheckFailed("invalid requirement on flag, flag is not present in module",
1231 Flag);
1232 continue;
1233 }
1234
1235 if (Op->getOperand(2) != ReqValue) {
1236 CheckFailed(("invalid requirement on flag, "
1237 "flag does not have the required value"),
1238 Flag);
1239 continue;
1240 }
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001241 }
1242}
1243
Chandler Carruth043949d2014-01-19 02:22:18 +00001244void
1245Verifier::visitModuleFlag(const MDNode *Op,
1246 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1247 SmallVectorImpl<const MDNode *> &Requirements) {
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001248 // Each module flag should have three arguments, the merge behavior (a
1249 // constant int), the flag ID (an MDString), and the value.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001250 Assert(Op->getNumOperands() == 3,
1251 "incorrect number of operands in module flag", Op);
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001252 Module::ModFlagBehavior MFB;
1253 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001254 Assert(
David Majnemerd7677e72015-02-11 09:13:06 +00001255 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001256 "invalid behavior operand in module flag (expected constant integer)",
1257 Op->getOperand(0));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001258 Assert(false,
1259 "invalid behavior operand in module flag (unexpected constant)",
1260 Op->getOperand(0));
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001261 }
David Majnemer04b4ed32015-02-16 08:14:22 +00001262 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001263 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1264 Op->getOperand(1));
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001265
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001266 // Sanity check the values for behaviors with additional requirements.
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001267 switch (MFB) {
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001268 case Module::Error:
1269 case Module::Warning:
1270 case Module::Override:
1271 // These behavior types accept any value.
1272 break;
1273
1274 case Module::Require: {
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001275 // The value should itself be an MDNode with two operands, a flag ID (an
1276 // MDString), and a value.
1277 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001278 Assert(Value && Value->getNumOperands() == 2,
1279 "invalid value for 'require' module flag (expected metadata pair)",
1280 Op->getOperand(2));
1281 Assert(isa<MDString>(Value->getOperand(0)),
1282 ("invalid value for 'require' module flag "
1283 "(first value operand should be a string)"),
1284 Value->getOperand(0));
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001285
1286 // Append it to the list of requirements, to check once all module flags are
1287 // scanned.
1288 Requirements.push_back(Value);
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001289 break;
1290 }
1291
1292 case Module::Append:
1293 case Module::AppendUnique: {
1294 // These behavior types require the operand be an MDNode.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001295 Assert(isa<MDNode>(Op->getOperand(2)),
1296 "invalid value for 'append'-type module flag "
1297 "(expected a metadata node)",
1298 Op->getOperand(2));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001299 break;
1300 }
1301 }
1302
1303 // Unless this is a "requires" flag, check the ID is unique.
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001304 if (MFB != Module::Require) {
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001305 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001306 Assert(Inserted,
1307 "module flag identifiers must be unique (or of 'require' type)", ID);
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001308 }
1309}
1310
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001311void Verifier::verifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001312 bool isFunction, const Value *V) {
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001313 unsigned Slot = ~0U;
1314 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1315 if (Attrs.getSlotIndex(I) == Idx) {
1316 Slot = I;
1317 break;
1318 }
1319
1320 assert(Slot != ~0U && "Attribute set inconsistency!");
1321
1322 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1323 I != E; ++I) {
1324 if (I->isStringAttribute())
1325 continue;
1326
1327 if (I->getKindAsEnum() == Attribute::NoReturn ||
1328 I->getKindAsEnum() == Attribute::NoUnwind ||
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001329 I->getKindAsEnum() == Attribute::NoInline ||
1330 I->getKindAsEnum() == Attribute::AlwaysInline ||
1331 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1332 I->getKindAsEnum() == Attribute::StackProtect ||
1333 I->getKindAsEnum() == Attribute::StackProtectReq ||
1334 I->getKindAsEnum() == Attribute::StackProtectStrong ||
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001335 I->getKindAsEnum() == Attribute::SafeStack ||
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001336 I->getKindAsEnum() == Attribute::NoRedZone ||
1337 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1338 I->getKindAsEnum() == Attribute::Naked ||
1339 I->getKindAsEnum() == Attribute::InlineHint ||
1340 I->getKindAsEnum() == Attribute::StackAlignment ||
1341 I->getKindAsEnum() == Attribute::UWTable ||
1342 I->getKindAsEnum() == Attribute::NonLazyBind ||
1343 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1344 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1345 I->getKindAsEnum() == Attribute::SanitizeThread ||
1346 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1347 I->getKindAsEnum() == Attribute::MinSize ||
1348 I->getKindAsEnum() == Attribute::NoDuplicate ||
Michael Gottesman41748d72013-06-27 00:25:01 +00001349 I->getKindAsEnum() == Attribute::Builtin ||
Diego Novilloc6399532013-05-24 12:26:52 +00001350 I->getKindAsEnum() == Attribute::NoBuiltin ||
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001351 I->getKindAsEnum() == Attribute::Cold ||
Tom Roeder44cb65f2014-06-05 19:29:43 +00001352 I->getKindAsEnum() == Attribute::OptimizeNone ||
Owen Anderson85fa7d52015-05-26 23:48:40 +00001353 I->getKindAsEnum() == Attribute::JumpTable ||
Igor Laevsky39d662f2015-07-11 10:30:36 +00001354 I->getKindAsEnum() == Attribute::Convergent ||
James Molloye6f87ca2015-11-06 10:32:53 +00001355 I->getKindAsEnum() == Attribute::ArgMemOnly ||
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001356 I->getKindAsEnum() == Attribute::NoRecurse ||
1357 I->getKindAsEnum() == Attribute::InaccessibleMemOnly ||
George Burgess IV278199f2016-04-12 01:05:35 +00001358 I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly ||
1359 I->getKindAsEnum() == Attribute::AllocSize) {
Tobias Grossereffd02c2013-07-02 03:28:10 +00001360 if (!isFunction) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001361 CheckFailed("Attribute '" + I->getAsString() +
1362 "' only applies to functions!", V);
1363 return;
1364 }
1365 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001366 I->getKindAsEnum() == Attribute::WriteOnly ||
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001367 I->getKindAsEnum() == Attribute::ReadNone) {
1368 if (Idx == 0) {
1369 CheckFailed("Attribute '" + I->getAsString() +
1370 "' does not apply to function returns");
1371 return;
Tobias Grossereffd02c2013-07-02 03:28:10 +00001372 }
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001373 } else if (isFunction) {
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001374 CheckFailed("Attribute '" + I->getAsString() +
1375 "' does not apply to functions!", V);
1376 return;
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001377 }
1378 }
1379}
1380
Duncan Sandsc3a79922009-06-11 08:11:03 +00001381// VerifyParameterAttrs - Check the given attributes for an argument or return
Duncan Sands0009c442008-01-12 16:42:01 +00001382// value of the specified type. The value V is printed in error messages.
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001383void Verifier::verifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
Duncan Sandsc3a79922009-06-11 08:11:03 +00001384 bool isReturnValue, const Value *V) {
Bill Wendlinge1835972013-01-21 23:03:18 +00001385 if (!Attrs.hasAttributes(Idx))
Duncan Sands0009c442008-01-12 16:42:01 +00001386 return;
1387
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001388 verifyAttributeTypes(Attrs, Idx, false, V);
Duncan Sandsc3a79922009-06-11 08:11:03 +00001389
Bill Wendling908126a2012-10-09 09:51:10 +00001390 if (isReturnValue)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001391 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1392 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1393 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1394 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1395 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
Manman Renf46262e2016-03-29 17:37:21 +00001396 !Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
Manman Ren9bfd0d02016-04-01 21:41:15 +00001397 !Attrs.hasAttribute(Idx, Attribute::SwiftSelf) &&
1398 !Attrs.hasAttribute(Idx, Attribute::SwiftError),
Manman Renf46262e2016-03-29 17:37:21 +00001399 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', "
Manman Ren9bfd0d02016-04-01 21:41:15 +00001400 "'returned', 'swiftself', and 'swifterror' do not apply to return "
Manman Renf46262e2016-03-29 17:37:21 +00001401 "values!",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001402 V);
Duncan Sandsc3a79922009-06-11 08:11:03 +00001403
Reid Klecknera534a382013-12-19 02:14:12 +00001404 // Check for mutually incompatible attributes. Only inreg is compatible with
1405 // sret.
1406 unsigned AttrCount = 0;
1407 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1408 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1409 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1410 Attrs.hasAttribute(Idx, Attribute::InReg);
1411 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001412 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1413 "and 'sret' are incompatible!",
1414 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001415
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001416 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1417 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1418 "Attributes "
1419 "'inalloca and readonly' are incompatible!",
1420 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001421
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001422 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1423 Attrs.hasAttribute(Idx, Attribute::Returned)),
1424 "Attributes "
1425 "'sret and returned' are incompatible!",
1426 V);
Stephen Lin6c70dc72013-04-23 16:31:56 +00001427
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001428 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1429 Attrs.hasAttribute(Idx, Attribute::SExt)),
1430 "Attributes "
1431 "'zeroext and signext' are incompatible!",
1432 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001433
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001434 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1435 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1436 "Attributes "
1437 "'readnone and readonly' are incompatible!",
1438 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001439
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001440 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1441 Attrs.hasAttribute(Idx, Attribute::WriteOnly)),
1442 "Attributes "
1443 "'readnone and writeonly' are incompatible!",
1444 V);
1445
1446 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadOnly) &&
1447 Attrs.hasAttribute(Idx, Attribute::WriteOnly)),
1448 "Attributes "
1449 "'readonly and writeonly' are incompatible!",
1450 V);
1451
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001452 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1453 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1454 "Attributes "
1455 "'noinline and alwaysinline' are incompatible!",
1456 V);
Duncan Sands0009c442008-01-12 16:42:01 +00001457
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001458 Assert(
1459 !AttrBuilder(Attrs, Idx).overlaps(AttributeFuncs::typeIncompatible(Ty)),
1460 "Wrong types for attribute: " +
1461 AttributeSet::get(Context, Idx, AttributeFuncs::typeIncompatible(Ty))
1462 .getAsString(Idx),
1463 V);
Dan Gohman6d618722008-08-27 14:48:06 +00001464
Reid Klecknera534a382013-12-19 02:14:12 +00001465 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
Craig Toppere3dcce92015-08-01 22:20:21 +00001466 SmallPtrSet<Type*, 4> Visited;
Owen Anderson08f46e12015-03-13 06:41:26 +00001467 if (!PTy->getElementType()->isSized(&Visited)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001468 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1469 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1470 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1471 V);
Reid Klecknera534a382013-12-19 02:14:12 +00001472 }
Manman Ren9bfd0d02016-04-01 21:41:15 +00001473 if (!isa<PointerType>(PTy->getElementType()))
1474 Assert(!Attrs.hasAttribute(Idx, Attribute::SwiftError),
1475 "Attribute 'swifterror' only applies to parameters "
1476 "with pointer to pointer type!",
1477 V);
Reid Klecknera534a382013-12-19 02:14:12 +00001478 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001479 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1480 "Attribute 'byval' only applies to parameters with pointer type!",
1481 V);
Manman Ren9bfd0d02016-04-01 21:41:15 +00001482 Assert(!Attrs.hasAttribute(Idx, Attribute::SwiftError),
1483 "Attribute 'swifterror' only applies to parameters "
1484 "with pointer type!",
1485 V);
Reid Klecknera534a382013-12-19 02:14:12 +00001486 }
Duncan Sands0009c442008-01-12 16:42:01 +00001487}
1488
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001489// Check parameter attributes against a function type.
Duncan Sands8c582282007-12-21 19:19:01 +00001490// The value V is printed in error messages.
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001491void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
Duncan Sands0009c442008-01-12 16:42:01 +00001492 const Value *V) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001493 if (Attrs.isEmpty())
Duncan Sands8c582282007-12-21 19:19:01 +00001494 return;
1495
Duncan Sands8c582282007-12-21 19:19:01 +00001496 bool SawNest = false;
Stephen Linb8bd2322013-04-20 05:14:40 +00001497 bool SawReturned = false;
Reid Kleckner79418562014-05-09 22:32:13 +00001498 bool SawSRet = false;
Manman Renf46262e2016-03-29 17:37:21 +00001499 bool SawSwiftSelf = false;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001500 bool SawSwiftError = false;
Duncan Sands8c582282007-12-21 19:19:01 +00001501
Chris Lattner8a923e72008-03-12 17:45:29 +00001502 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001503 unsigned Idx = Attrs.getSlotIndex(i);
Duncan Sands8c582282007-12-21 19:19:01 +00001504
Chris Lattner229907c2011-07-18 04:54:35 +00001505 Type *Ty;
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001506 if (Idx == 0)
Chris Lattner8a923e72008-03-12 17:45:29 +00001507 Ty = FT->getReturnType();
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001508 else if (Idx-1 < FT->getNumParams())
1509 Ty = FT->getParamType(Idx-1);
Chris Lattner8a923e72008-03-12 17:45:29 +00001510 else
Duncan Sandsc3a79922009-06-11 08:11:03 +00001511 break; // VarArgs attributes, verified elsewhere.
1512
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001513 verifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
Duncan Sands8c582282007-12-21 19:19:01 +00001514
Stephen Linb8bd2322013-04-20 05:14:40 +00001515 if (Idx == 0)
1516 continue;
1517
1518 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001519 Assert(!SawNest, "More than one parameter has attribute nest!", V);
Duncan Sands8c582282007-12-21 19:19:01 +00001520 SawNest = true;
1521 }
1522
Stephen Linb8bd2322013-04-20 05:14:40 +00001523 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001524 Assert(!SawReturned, "More than one parameter has attribute returned!",
1525 V);
1526 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1527 "Incompatible "
1528 "argument and return types for 'returned' attribute",
1529 V);
Stephen Linb8bd2322013-04-20 05:14:40 +00001530 SawReturned = true;
1531 }
1532
Reid Kleckner79418562014-05-09 22:32:13 +00001533 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001534 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1535 Assert(Idx == 1 || Idx == 2,
1536 "Attribute 'sret' is not on first or second parameter!", V);
Reid Kleckner79418562014-05-09 22:32:13 +00001537 SawSRet = true;
1538 }
Reid Kleckner60d3a832014-01-16 22:59:24 +00001539
Manman Renf46262e2016-03-29 17:37:21 +00001540 if (Attrs.hasAttribute(Idx, Attribute::SwiftSelf)) {
1541 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
1542 SawSwiftSelf = true;
1543 }
1544
Manman Ren9bfd0d02016-04-01 21:41:15 +00001545 if (Attrs.hasAttribute(Idx, Attribute::SwiftError)) {
1546 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
1547 V);
1548 SawSwiftError = true;
1549 }
1550
Reid Kleckner60d3a832014-01-16 22:59:24 +00001551 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001552 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1553 V);
Reid Kleckner60d3a832014-01-16 22:59:24 +00001554 }
Duncan Sands8c582282007-12-21 19:19:01 +00001555 }
Devang Patel9cc98122008-10-01 23:41:25 +00001556
Bill Wendling77543892013-01-18 21:11:39 +00001557 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1558 return;
1559
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001560 verifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
Bill Wendling9864a652012-10-09 20:11:19 +00001561
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001562 Assert(
1563 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1564 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1565 "Attributes 'readnone and readonly' are incompatible!", V);
Bill Wendling9864a652012-10-09 20:11:19 +00001566
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001567 Assert(
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001568 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001569 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::WriteOnly)),
1570 "Attributes 'readnone and writeonly' are incompatible!", V);
1571
1572 Assert(
1573 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly) &&
1574 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::WriteOnly)),
1575 "Attributes 'readonly and writeonly' are incompatible!", V);
1576
1577 Assert(
1578 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001579 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1580 Attribute::InaccessibleMemOrArgMemOnly)),
1581 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V);
1582
1583 Assert(
1584 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1585 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1586 Attribute::InaccessibleMemOnly)),
1587 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
1588
1589 Assert(
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001590 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1591 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1592 Attribute::AlwaysInline)),
1593 "Attributes 'noinline and alwaysinline' are incompatible!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001594
1595 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1596 Attribute::OptimizeNone)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001597 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1598 "Attribute 'optnone' requires 'noinline'!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001599
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001600 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1601 Attribute::OptimizeForSize),
1602 "Attributes 'optsize and optnone' are incompatible!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001603
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001604 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1605 "Attributes 'minsize and optnone' are incompatible!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001606 }
Tom Roeder44cb65f2014-06-05 19:29:43 +00001607
1608 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1609 Attribute::JumpTable)) {
1610 const GlobalValue *GV = cast<GlobalValue>(V);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001611 Assert(GV->hasGlobalUnnamedAddr(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001612 "Attribute 'jumptable' requires 'unnamed_addr'", V);
Tom Roeder44cb65f2014-06-05 19:29:43 +00001613 }
George Burgess IV278199f2016-04-12 01:05:35 +00001614
1615 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::AllocSize)) {
1616 std::pair<unsigned, Optional<unsigned>> Args =
1617 Attrs.getAllocSizeArgs(AttributeSet::FunctionIndex);
1618
1619 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
1620 if (ParamNo >= FT->getNumParams()) {
1621 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
1622 return false;
1623 }
1624
1625 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
1626 CheckFailed("'allocsize' " + Name +
1627 " argument must refer to an integer parameter",
1628 V);
1629 return false;
1630 }
1631
1632 return true;
1633 };
1634
1635 if (!CheckParam("element size", Args.first))
1636 return;
1637
1638 if (Args.second && !CheckParam("number of elements", *Args.second))
1639 return;
1640 }
Duncan Sands8c582282007-12-21 19:19:01 +00001641}
1642
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001643void Verifier::verifyFunctionMetadata(
Benjamin Kramer7ab4fe32016-06-12 17:46:23 +00001644 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001645 for (const auto &Pair : MDs) {
1646 if (Pair.first == LLVMContext::MD_prof) {
1647 MDNode *MD = Pair.second;
Diego Novillo2567f3d2015-05-13 15:13:45 +00001648 Assert(MD->getNumOperands() == 2,
1649 "!prof annotations should have exactly 2 operands", MD);
1650
1651 // Check first operand.
1652 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1653 MD);
1654 Assert(isa<MDString>(MD->getOperand(0)),
1655 "expected string with name of the !prof annotation", MD);
1656 MDString *MDS = cast<MDString>(MD->getOperand(0));
1657 StringRef ProfName = MDS->getString();
1658 Assert(ProfName.equals("function_entry_count"),
1659 "first operand should be 'function_entry_count'", MD);
1660
1661 // Check second operand.
1662 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1663 MD);
1664 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1665 "expected integer argument to function_entry_count", MD);
1666 }
1667 }
1668}
1669
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00001670void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
1671 if (!ConstantExprVisited.insert(EntryC).second)
1672 return;
1673
1674 SmallVector<const Constant *, 16> Stack;
1675 Stack.push_back(EntryC);
1676
1677 while (!Stack.empty()) {
1678 const Constant *C = Stack.pop_back_val();
1679
1680 // Check this constant expression.
1681 if (const auto *CE = dyn_cast<ConstantExpr>(C))
1682 visitConstantExpr(CE);
1683
Keno Fischerf6d17b92016-01-14 22:42:02 +00001684 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
1685 // Global Values get visited separately, but we do need to make sure
1686 // that the global value is in the correct module
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001687 Assert(GV->getParent() == &M, "Referencing global in another module!",
1688 EntryC, &M, GV, GV->getParent());
Keno Fischerf6d17b92016-01-14 22:42:02 +00001689 continue;
1690 }
1691
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00001692 // Visit all sub-expressions.
1693 for (const Use &U : C->operands()) {
1694 const auto *OpC = dyn_cast<Constant>(U);
1695 if (!OpC)
1696 continue;
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00001697 if (!ConstantExprVisited.insert(OpC).second)
1698 continue;
1699 Stack.push_back(OpC);
1700 }
1701 }
1702}
1703
1704void Verifier::visitConstantExpr(const ConstantExpr *CE) {
Sanjoy Dase1129ee2016-08-02 02:55:57 +00001705 if (CE->getOpcode() == Instruction::BitCast)
1706 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1707 CE->getType()),
1708 "Invalid bitcast", CE);
Rafael Espindolaa4a94f12014-12-16 19:29:29 +00001709
Sanjoy Dase1129ee2016-08-02 02:55:57 +00001710 if (CE->getOpcode() == Instruction::IntToPtr ||
1711 CE->getOpcode() == Instruction::PtrToInt) {
1712 auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr
1713 ? CE->getType()
1714 : CE->getOperand(0)->getType();
1715 StringRef Msg = CE->getOpcode() == Instruction::IntToPtr
1716 ? "inttoptr not supported for non-integral pointers"
1717 : "ptrtoint not supported for non-integral pointers";
1718 Assert(
1719 !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())),
1720 Msg);
1721 }
Matt Arsenault24b49c42013-07-31 17:49:08 +00001722}
1723
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001724bool Verifier::verifyAttributeCount(AttributeSet Attrs, unsigned Params) {
Bill Wendling0aed1132013-01-30 06:54:41 +00001725 if (Attrs.getNumSlots() == 0)
Devang Patel82fed672008-09-23 22:35:17 +00001726 return true;
Nick Lewycky3fc89802009-09-07 20:44:51 +00001727
Devang Patel82fed672008-09-23 22:35:17 +00001728 unsigned LastSlot = Attrs.getNumSlots() - 1;
Bill Wendling25e65a62013-01-25 21:30:53 +00001729 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
Devang Patel82fed672008-09-23 22:35:17 +00001730 if (LastIndex <= Params
Bill Wendling25e65a62013-01-25 21:30:53 +00001731 || (LastIndex == AttributeSet::FunctionIndex
1732 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
Devang Patel82fed672008-09-23 22:35:17 +00001733 return true;
Matt Arsenaultc4c92262013-07-20 17:46:00 +00001734
Devang Patel82fed672008-09-23 22:35:17 +00001735 return false;
1736}
Nick Lewycky3fc89802009-09-07 20:44:51 +00001737
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001738/// Verify that statepoint intrinsic is well formed.
1739void Verifier::verifyStatepoint(ImmutableCallSite CS) {
Philip Reames0285c742015-02-03 23:18:47 +00001740 assert(CS.getCalledFunction() &&
1741 CS.getCalledFunction()->getIntrinsicID() ==
1742 Intrinsic::experimental_gc_statepoint);
Philip Reames1ffa9372015-01-30 23:28:05 +00001743
Philip Reames0285c742015-02-03 23:18:47 +00001744 const Instruction &CI = *CS.getInstruction();
1745
Igor Laevsky39d662f2015-07-11 10:30:36 +00001746 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1747 !CS.onlyAccessesArgMemory(),
1748 "gc.statepoint must read and write all memory to preserve "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001749 "reordering restrictions required by safepoint semantics",
1750 &CI);
1751
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001752 const Value *IDV = CS.getArgument(0);
1753 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1754 &CI);
1755
1756 const Value *NumPatchBytesV = CS.getArgument(1);
1757 Assert(isa<ConstantInt>(NumPatchBytesV),
1758 "gc.statepoint number of patchable bytes must be a constant integer",
1759 &CI);
Sanjoy Das9af34eb2015-05-13 20:11:59 +00001760 const int64_t NumPatchBytes =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001761 cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1762 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1763 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1764 "positive",
1765 &CI);
1766
1767 const Value *Target = CS.getArgument(2);
Craig Toppere3dcce92015-08-01 22:20:21 +00001768 auto *PT = dyn_cast<PointerType>(Target->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001769 Assert(PT && PT->getElementType()->isFunctionTy(),
1770 "gc.statepoint callee must be of function pointer type", &CI, Target);
Quentin Colombet3e93ebe2015-05-09 00:02:06 +00001771 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
Philip Reames1ffa9372015-01-30 23:28:05 +00001772
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001773 const Value *NumCallArgsV = CS.getArgument(3);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001774 Assert(isa<ConstantInt>(NumCallArgsV),
1775 "gc.statepoint number of arguments to underlying call "
1776 "must be constant integer",
1777 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001778 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001779 Assert(NumCallArgs >= 0,
1780 "gc.statepoint number of arguments to underlying call "
1781 "must be positive",
1782 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001783 const int NumParams = (int)TargetFuncType->getNumParams();
1784 if (TargetFuncType->isVarArg()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001785 Assert(NumCallArgs >= NumParams,
1786 "gc.statepoint mismatch in number of vararg call args", &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001787
1788 // TODO: Remove this limitation
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001789 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1790 "gc.statepoint doesn't support wrapping non-void "
1791 "vararg functions yet",
1792 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001793 } else
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001794 Assert(NumCallArgs == NumParams,
1795 "gc.statepoint mismatch in number of call args", &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001796
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001797 const Value *FlagsV = CS.getArgument(4);
Pat Gavlincc0431d2015-05-08 18:07:42 +00001798 Assert(isa<ConstantInt>(FlagsV),
1799 "gc.statepoint flags must be constant integer", &CI);
1800 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1801 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1802 "unknown flag used in gc.statepoint flags argument", &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001803
1804 // Verify that the types of the call parameter arguments match
1805 // the type of the wrapped callee.
1806 for (int i = 0; i < NumParams; i++) {
1807 Type *ParamType = TargetFuncType->getParamType(i);
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001808 Type *ArgType = CS.getArgument(5 + i)->getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001809 Assert(ArgType == ParamType,
1810 "gc.statepoint call argument does not match wrapped "
1811 "function type",
1812 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001813 }
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001814
1815 const int EndCallArgsInx = 4 + NumCallArgs;
Pat Gavlincc0431d2015-05-08 18:07:42 +00001816
1817 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1818 Assert(isa<ConstantInt>(NumTransitionArgsV),
1819 "gc.statepoint number of transition arguments "
1820 "must be constant integer",
1821 &CI);
1822 const int NumTransitionArgs =
1823 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1824 Assert(NumTransitionArgs >= 0,
1825 "gc.statepoint number of transition arguments must be positive", &CI);
1826 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1827
1828 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001829 Assert(isa<ConstantInt>(NumDeoptArgsV),
1830 "gc.statepoint number of deoptimization arguments "
1831 "must be constant integer",
1832 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001833 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001834 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1835 "must be positive",
1836 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001837
Pat Gavlincc0431d2015-05-08 18:07:42 +00001838 const int ExpectedNumArgs =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001839 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
Pat Gavlincc0431d2015-05-08 18:07:42 +00001840 Assert(ExpectedNumArgs <= (int)CS.arg_size(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001841 "gc.statepoint too few arguments according to length fields", &CI);
1842
Philip Reames1ffa9372015-01-30 23:28:05 +00001843 // Check that the only uses of this gc.statepoint are gc.result or
1844 // gc.relocate calls which are tied to this statepoint and thus part
1845 // of the same statepoint sequence
Philip Reames0285c742015-02-03 23:18:47 +00001846 for (const User *U : CI.users()) {
Philip Reames1ffa9372015-01-30 23:28:05 +00001847 const CallInst *Call = dyn_cast<const CallInst>(U);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001848 Assert(Call, "illegal use of statepoint token", &CI, U);
Philip Reames1ffa9372015-01-30 23:28:05 +00001849 if (!Call) continue;
Philip Reames92d1f0c2016-04-12 18:05:10 +00001850 Assert(isa<GCRelocateInst>(Call) || isa<GCResultInst>(Call),
Sanjoy Das25fb5bd2016-08-11 00:56:46 +00001851 "gc.result or gc.relocate are the only value uses "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001852 "of a gc.statepoint",
1853 &CI, U);
Philip Reames92d1f0c2016-04-12 18:05:10 +00001854 if (isa<GCResultInst>(Call)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001855 Assert(Call->getArgOperand(0) == &CI,
1856 "gc.result connected to wrong gc.statepoint", &CI, Call);
Manuel Jacob83eefa62016-01-05 04:03:00 +00001857 } else if (isa<GCRelocateInst>(Call)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001858 Assert(Call->getArgOperand(0) == &CI,
1859 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
Philip Reames1ffa9372015-01-30 23:28:05 +00001860 }
1861 }
1862
1863 // Note: It is legal for a single derived pointer to be listed multiple
1864 // times. It's non-optimal, but it is legal. It can also happen after
1865 // insertion if we strip a bitcast away.
1866 // Note: It is really tempting to check that each base is relocated and
1867 // that a derived pointer is never reused as a base pointer. This turns
1868 // out to be problematic since optimizations run after safepoint insertion
1869 // can recognize equality properties that the insertion logic doesn't know
1870 // about. See example statepoint.ll in the verifier subdirectory
1871}
1872
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001873void Verifier::verifyFrameRecoverIndices() {
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001874 for (auto &Counts : FrameEscapeInfo) {
1875 Function *F = Counts.first;
1876 unsigned EscapedObjectCount = Counts.second.first;
1877 unsigned MaxRecoveredIndex = Counts.second.second;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001878 Assert(MaxRecoveredIndex <= EscapedObjectCount,
Reid Kleckner60381792015-07-07 22:25:32 +00001879 "all indices passed to llvm.localrecover must be less than the "
1880 "number of arguments passed ot llvm.localescape in the parent "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001881 "function",
1882 F);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001883 }
1884}
1885
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00001886static Instruction *getSuccPad(TerminatorInst *Terminator) {
1887 BasicBlock *UnwindDest;
1888 if (auto *II = dyn_cast<InvokeInst>(Terminator))
1889 UnwindDest = II->getUnwindDest();
1890 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
1891 UnwindDest = CSI->getUnwindDest();
1892 else
1893 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
1894 return UnwindDest->getFirstNonPHI();
1895}
1896
1897void Verifier::verifySiblingFuncletUnwinds() {
1898 SmallPtrSet<Instruction *, 8> Visited;
1899 SmallPtrSet<Instruction *, 8> Active;
1900 for (const auto &Pair : SiblingFuncletInfo) {
1901 Instruction *PredPad = Pair.first;
1902 if (Visited.count(PredPad))
1903 continue;
1904 Active.insert(PredPad);
1905 TerminatorInst *Terminator = Pair.second;
1906 do {
1907 Instruction *SuccPad = getSuccPad(Terminator);
1908 if (Active.count(SuccPad)) {
1909 // Found a cycle; report error
1910 Instruction *CyclePad = SuccPad;
1911 SmallVector<Instruction *, 8> CycleNodes;
1912 do {
1913 CycleNodes.push_back(CyclePad);
1914 TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad];
1915 if (CycleTerminator != CyclePad)
1916 CycleNodes.push_back(CycleTerminator);
1917 CyclePad = getSuccPad(CycleTerminator);
1918 } while (CyclePad != SuccPad);
1919 Assert(false, "EH pads can't handle each other's exceptions",
1920 ArrayRef<Instruction *>(CycleNodes));
1921 }
1922 // Don't re-walk a node we've already checked
1923 if (!Visited.insert(SuccPad).second)
1924 break;
1925 // Walk to this successor if it has a map entry.
1926 PredPad = SuccPad;
1927 auto TermI = SiblingFuncletInfo.find(PredPad);
1928 if (TermI == SiblingFuncletInfo.end())
1929 break;
1930 Terminator = TermI->second;
1931 Active.insert(PredPad);
1932 } while (true);
1933 // Each node only has one successor, so we've walked all the active
1934 // nodes' successors.
1935 Active.clear();
1936 }
1937}
1938
Chris Lattner0e851da2002-04-18 20:37:37 +00001939// visitFunction - Verify that a function is ok.
Chris Lattnerd02f08d2002-02-20 17:55:43 +00001940//
Chandler Carruth043949d2014-01-19 02:22:18 +00001941void Verifier::visitFunction(const Function &F) {
Peter Collingbournebb738172016-06-06 23:21:27 +00001942 visitGlobalValue(F);
1943
Chris Lattner2ad5aa82005-05-08 22:27:09 +00001944 // Check function arguments.
Chris Lattner229907c2011-07-18 04:54:35 +00001945 FunctionType *FT = F.getFunctionType();
Chris Lattner45ffa212007-08-18 06:13:19 +00001946 unsigned NumArgs = F.arg_size();
Chris Lattneraf95e582002-04-13 22:48:46 +00001947
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001948 Assert(&Context == &F.getContext(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001949 "Function context does not match Module context!", &F);
Nick Lewycky62f864d2010-02-15 21:52:04 +00001950
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001951 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1952 Assert(FT->getNumParams() == NumArgs,
1953 "# formal arguments must match # of arguments for function type!", &F,
1954 FT);
1955 Assert(F.getReturnType()->isFirstClassType() ||
1956 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1957 "Functions cannot return aggregate values!", &F);
Chris Lattneraf95e582002-04-13 22:48:46 +00001958
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001959 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1960 "Invalid struct return type!", &F);
Devang Patel9d9178592008-03-03 21:46:28 +00001961
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001962 AttributeSet Attrs = F.getAttributes();
Duncan Sandsb99f44a2008-01-11 22:36:48 +00001963
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001964 Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001965 "Attribute after last parameter!", &F);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00001966
Duncan Sands8c582282007-12-21 19:19:01 +00001967 // Check function attributes.
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001968 verifyFunctionAttrs(FT, Attrs, &F);
Duncan Sands07c90662007-07-27 15:09:54 +00001969
Michael Gottesman41748d72013-06-27 00:25:01 +00001970 // On function declarations/definitions, we do not support the builtin
1971 // attribute. We do not check this in VerifyFunctionAttrs since that is
1972 // checking for Attributes that can/can not ever be on functions.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001973 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1974 "Attribute 'builtin' can only be applied to a callsite.", &F);
Michael Gottesman41748d72013-06-27 00:25:01 +00001975
Chris Lattneref13ee32006-05-19 21:25:17 +00001976 // Check that this function meets the restrictions on this calling convention.
Reid Kleckner329d4a22014-08-29 21:25:28 +00001977 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1978 // restrictions can be lifted.
Chris Lattneref13ee32006-05-19 21:25:17 +00001979 switch (F.getCallingConv()) {
1980 default:
Chris Lattneref13ee32006-05-19 21:25:17 +00001981 case CallingConv::C:
1982 break;
Chris Lattneref13ee32006-05-19 21:25:17 +00001983 case CallingConv::Fast:
1984 case CallingConv::Cold:
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001985 case CallingConv::Intel_OCL_BI:
Che-Liang Chiou29947902010-09-25 07:46:17 +00001986 case CallingConv::PTX_Kernel:
1987 case CallingConv::PTX_Device:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001988 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1989 "perfect forwarding!",
1990 &F);
Chris Lattneref13ee32006-05-19 21:25:17 +00001991 break;
1992 }
Nick Lewycky3fc89802009-09-07 20:44:51 +00001993
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001994 bool isLLVMdotName = F.getName().size() >= 5 &&
1995 F.getName().substr(0, 5) == "llvm.";
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001996
Chris Lattneraf95e582002-04-13 22:48:46 +00001997 // Check that the argument values match the function type for this function...
Chris Lattner149376d2002-10-13 20:57:00 +00001998 unsigned i = 0;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001999 for (const Argument &Arg : F.args()) {
2000 Assert(Arg.getType() == FT->getParamType(i),
2001 "Argument value does not match function argument type!", &Arg,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002002 FT->getParamType(i));
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002003 Assert(Arg.getType()->isFirstClassType(),
2004 "Function arguments must have first-class types!", &Arg);
David Majnemerb611e3f2015-08-14 05:09:07 +00002005 if (!isLLVMdotName) {
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002006 Assert(!Arg.getType()->isMetadataTy(),
2007 "Function takes metadata but isn't an intrinsic", &Arg, &F);
2008 Assert(!Arg.getType()->isTokenTy(),
2009 "Function takes token but isn't an intrinsic", &Arg, &F);
David Majnemerb611e3f2015-08-14 05:09:07 +00002010 }
Manman Ren9bfd0d02016-04-01 21:41:15 +00002011
2012 // Check that swifterror argument is only used by loads and stores.
2013 if (Attrs.hasAttribute(i+1, Attribute::SwiftError)) {
2014 verifySwiftErrorValue(&Arg);
2015 }
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002016 ++i;
Dan Gohman4051bf42008-08-27 14:44:57 +00002017 }
Chris Lattneraf95e582002-04-13 22:48:46 +00002018
David Majnemerb611e3f2015-08-14 05:09:07 +00002019 if (!isLLVMdotName)
2020 Assert(!F.getReturnType()->isTokenTy(),
2021 "Functions returns a token but isn't an intrinsic", &F);
2022
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002023 // Get the function metadata attachments.
2024 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2025 F.getAllMetadata(MDs);
2026 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002027 verifyFunctionMetadata(MDs);
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002028
Keno Fischer2ac0c272015-11-16 05:13:30 +00002029 // Check validity of the personality function
2030 if (F.hasPersonalityFn()) {
2031 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2032 if (Per)
2033 Assert(Per->getParent() == F.getParent(),
Keno Fischera6c4ce42015-12-01 19:06:36 +00002034 "Referencing personality function in another module!",
2035 &F, F.getParent(), Per, Per->getParent());
Keno Fischer2ac0c272015-11-16 05:13:30 +00002036 }
2037
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002038 if (F.isMaterializable()) {
2039 // Function has a body somewhere we can't see.
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002040 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2041 MDs.empty() ? nullptr : MDs.front().second);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002042 } else if (F.isDeclaration()) {
Peter Collingbourne21521892016-06-21 23:42:48 +00002043 for (const auto &I : MDs) {
2044 AssertDI(I.first != LLVMContext::MD_dbg,
2045 "function declaration may not have a !dbg attachment", &F);
2046 Assert(I.first != LLVMContext::MD_prof,
2047 "function declaration may not have a !prof attachment", &F);
2048
2049 // Verify the metadata itself.
2050 visitMDNode(*I.second);
2051 }
David Majnemer7fddecc2015-06-17 20:52:32 +00002052 Assert(!F.hasPersonalityFn(),
2053 "Function declaration shouldn't have a personality routine", &F);
Chris Lattnerd79f3d52007-09-19 17:14:45 +00002054 } else {
Chris Lattnercb813312006-12-13 04:45:46 +00002055 // Verify that this function (which has a body) is not named "llvm.*". It
2056 // is not legal to define intrinsics.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002057 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002058
Chris Lattner149376d2002-10-13 20:57:00 +00002059 // Check the entry node
Chandler Carruth043949d2014-01-19 02:22:18 +00002060 const BasicBlock *Entry = &F.getEntryBlock();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002061 Assert(pred_empty(Entry),
2062 "Entry block to function must not have predecessors!", Entry);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002063
Chris Lattner27471742009-11-01 04:08:01 +00002064 // The address of the entry block cannot be taken, unless it is dead.
2065 if (Entry->hasAddressTaken()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002066 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
2067 "blockaddress may not be used with the entry block!", Entry);
Chris Lattner27471742009-11-01 04:08:01 +00002068 }
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002069
Peter Collingbourne6dbee002016-06-14 23:13:15 +00002070 unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002071 // Visit metadata attachments.
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002072 for (const auto &I : MDs) {
2073 // Verify that the attachment is legal.
2074 switch (I.first) {
2075 default:
2076 break;
2077 case LLVMContext::MD_dbg:
Peter Collingbourne382d81c2016-06-01 01:17:57 +00002078 ++NumDebugAttachments;
2079 AssertDI(NumDebugAttachments == 1,
2080 "function must have a single !dbg attachment", &F, I.second);
Adrian Prantl541a9c52016-05-06 19:26:47 +00002081 AssertDI(isa<DISubprogram>(I.second),
2082 "function !dbg attachment must be a subprogram", &F, I.second);
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002083 break;
Peter Collingbourne6dbee002016-06-14 23:13:15 +00002084 case LLVMContext::MD_prof:
2085 ++NumProfAttachments;
2086 Assert(NumProfAttachments == 1,
2087 "function must have a single !prof attachment", &F, I.second);
2088 break;
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002089 }
2090
2091 // Verify the metadata itself.
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002092 visitMDNode(*I.second);
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002093 }
Chris Lattner149376d2002-10-13 20:57:00 +00002094 }
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002095
Chris Lattner7730dcc2009-09-11 17:05:29 +00002096 // If this function is actually an intrinsic, verify that it is only used in
2097 // direct call/invokes, never having its "address taken".
Rafael Espindola257a3532016-01-15 19:00:20 +00002098 // Only do this if the module is materialized, otherwise we don't have all the
2099 // uses.
2100 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00002101 const User *U;
2102 if (F.hasAddressTaken(&U))
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00002103 Assert(false, "Invalid user of intrinsic instruction!", U);
Chris Lattner7730dcc2009-09-11 17:05:29 +00002104 }
Nico Rieck7157bb72014-01-14 15:22:47 +00002105
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002106 Assert(!F.hasDLLImportStorageClass() ||
2107 (F.isDeclaration() && F.hasExternalLinkage()) ||
2108 F.hasAvailableExternallyLinkage(),
2109 "Function is marked as dllimport, but not external.", &F);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002110
2111 auto *N = F.getSubprogram();
2112 if (!N)
2113 return;
2114
Adrian Prantl75819ae2016-04-15 15:57:41 +00002115 visitDISubprogram(*N);
2116
Peter Collingbourned4bff302015-11-05 22:03:56 +00002117 // Check that all !dbg attachments lead to back to N (or, at least, another
2118 // subprogram that describes the same function).
2119 //
2120 // FIXME: Check this incrementally while visiting !dbg attachments.
2121 // FIXME: Only check when N is the canonical subprogram for F.
2122 SmallPtrSet<const MDNode *, 32> Seen;
2123 for (auto &BB : F)
2124 for (auto &I : BB) {
2125 // Be careful about using DILocation here since we might be dealing with
2126 // broken code (this is the Verifier after all).
2127 DILocation *DL =
2128 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
2129 if (!DL)
2130 continue;
2131 if (!Seen.insert(DL).second)
2132 continue;
2133
2134 DILocalScope *Scope = DL->getInlinedAtScope();
2135 if (Scope && !Seen.insert(Scope).second)
2136 continue;
2137
2138 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
Keno Fischer0ef8ccf2015-12-06 23:05:38 +00002139
2140 // Scope and SP could be the same MDNode and we don't want to skip
2141 // validation in that case
2142 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002143 continue;
2144
2145 // FIXME: Once N is canonical, check "SP == &N".
Adrian Prantla2ef0472016-09-14 17:30:37 +00002146 AssertDI(SP->describes(&F),
2147 "!dbg attachment points at wrong subprogram for function", N, &F,
2148 &I, DL, Scope, SP);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002149 }
Chris Lattnerd02f08d2002-02-20 17:55:43 +00002150}
2151
Chris Lattner0e851da2002-04-18 20:37:37 +00002152// verifyBasicBlock - Verify that a basic block is well formed...
2153//
Chris Lattner069a7952002-06-25 15:56:27 +00002154void Verifier::visitBasicBlock(BasicBlock &BB) {
Chris Lattnerc9e79d02004-09-29 20:07:45 +00002155 InstsInThisBlock.clear();
2156
Alkis Evlogimenosbe526cf2004-12-04 02:30:42 +00002157 // Ensure that basic blocks have terminators!
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002158 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
Alkis Evlogimenosbe526cf2004-12-04 02:30:42 +00002159
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002160 // Check constraints that this basic block imposes on all of the PHI nodes in
2161 // it.
2162 if (isa<PHINode>(BB.front())) {
Chris Lattner59a8d2c2007-02-10 08:33:11 +00002163 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
2164 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002165 std::sort(Preds.begin(), Preds.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002166 PHINode *PN;
Chris Lattner307e1df2004-06-05 17:44:48 +00002167 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002168 // Ensure that PHI nodes have at least one entry!
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002169 Assert(PN->getNumIncomingValues() != 0,
2170 "PHI nodes must have at least one entry. If the block is dead, "
2171 "the PHI should be removed!",
2172 PN);
2173 Assert(PN->getNumIncomingValues() == Preds.size(),
2174 "PHINode should have one entry for each predecessor of its "
2175 "parent basic block!",
2176 PN);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002177
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002178 // Get and sort all incoming values in the PHI node...
Chris Lattner59a8d2c2007-02-10 08:33:11 +00002179 Values.clear();
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002180 Values.reserve(PN->getNumIncomingValues());
2181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2182 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
2183 PN->getIncomingValue(i)));
2184 std::sort(Values.begin(), Values.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002185
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002186 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2187 // Check to make sure that if there is more than one entry for a
2188 // particular basic block in this PHI node, that the incoming values are
2189 // all identical.
2190 //
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002191 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
2192 Values[i].second == Values[i - 1].second,
2193 "PHI node has multiple entries for the same basic block with "
2194 "different incoming values!",
2195 PN, Values[i].first, Values[i].second, Values[i - 1].second);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002196
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002197 // Check to make sure that the predecessors and PHI node entries are
2198 // matched up.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002199 Assert(Values[i].first == Preds[i],
2200 "PHI node entries do not match predecessors!", PN,
2201 Values[i].first, Preds[i]);
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002202 }
2203 }
2204 }
Adrian Prantl940257f2014-11-21 00:39:43 +00002205
2206 // Check that all instructions have their parent pointers set up correctly.
Zachary Turner8325a5c2014-11-21 01:19:09 +00002207 for (auto &I : BB)
2208 {
Adrian Prantl940257f2014-11-21 00:39:43 +00002209 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
Zachary Turner8325a5c2014-11-21 01:19:09 +00002210 }
Chris Lattner069a7952002-06-25 15:56:27 +00002211}
Chris Lattnerfbf5be52002-03-15 20:25:09 +00002212
Chris Lattner069a7952002-06-25 15:56:27 +00002213void Verifier::visitTerminatorInst(TerminatorInst &I) {
2214 // Ensure that terminators only exist at the end of the basic block.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002215 Assert(&I == I.getParent()->getTerminator(),
2216 "Terminator found in the middle of a basic block!", I.getParent());
Chris Lattner7af3ee92002-07-18 00:13:42 +00002217 visitInstruction(I);
Chris Lattner069a7952002-06-25 15:56:27 +00002218}
2219
Nick Lewycky1d9a8152010-02-15 22:09:09 +00002220void Verifier::visitBranchInst(BranchInst &BI) {
2221 if (BI.isConditional()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002222 Assert(BI.getCondition()->getType()->isIntegerTy(1),
2223 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
Nick Lewycky1d9a8152010-02-15 22:09:09 +00002224 }
2225 visitTerminatorInst(BI);
2226}
2227
Chris Lattner069a7952002-06-25 15:56:27 +00002228void Verifier::visitReturnInst(ReturnInst &RI) {
2229 Function *F = RI.getParent()->getParent();
Devang Patel59643e52008-02-23 00:35:18 +00002230 unsigned N = RI.getNumOperands();
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002231 if (F->getReturnType()->isVoidTy())
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002232 Assert(N == 0,
2233 "Found return instr that returns non-void in Function of void "
2234 "return type!",
2235 &RI, F->getReturnType());
Jay Foad11522092011-04-04 07:44:02 +00002236 else
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002237 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2238 "Function return type does not match operand "
2239 "type of return inst!",
2240 &RI, F->getReturnType());
Nick Lewycky3fc89802009-09-07 20:44:51 +00002241
Misha Brukman7eb05a12003-08-18 14:43:39 +00002242 // Check to make sure that the return value has necessary properties for
Chris Lattner069a7952002-06-25 15:56:27 +00002243 // terminators...
2244 visitTerminatorInst(RI);
Chris Lattnerd02f08d2002-02-20 17:55:43 +00002245}
2246
Chris Lattnerab5aa142004-05-21 16:47:21 +00002247void Verifier::visitSwitchInst(SwitchInst &SI) {
2248 // Check to make sure that all of the constants in the switch instruction
2249 // have the same type as the switched-on value.
Chris Lattner229907c2011-07-18 04:54:35 +00002250 Type *SwitchTy = SI.getCondition()->getType();
Bob Wilsone4077362013-09-09 19:14:35 +00002251 SmallPtrSet<ConstantInt*, 32> Constants;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002252 for (auto &Case : SI.cases()) {
2253 Assert(Case.getCaseValue()->getType() == SwitchTy,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002254 "Switch constants must all be same type as switch value!", &SI);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002255 Assert(Constants.insert(Case.getCaseValue()).second,
2256 "Duplicate integer as switch case", &SI, Case.getCaseValue());
Stepan Dyatkovskiye89dafd2012-05-21 10:44:40 +00002257 }
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002258
Chris Lattnerab5aa142004-05-21 16:47:21 +00002259 visitTerminatorInst(SI);
2260}
2261
Dan Gohmand0a1e3d2010-08-02 23:08:33 +00002262void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002263 Assert(BI.getAddress()->getType()->isPointerTy(),
2264 "Indirectbr operand must have pointer type!", &BI);
Dan Gohmand0a1e3d2010-08-02 23:08:33 +00002265 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002266 Assert(BI.getDestination(i)->getType()->isLabelTy(),
2267 "Indirectbr destinations must all have pointer type!", &BI);
Dan Gohmand0a1e3d2010-08-02 23:08:33 +00002268
2269 visitTerminatorInst(BI);
2270}
2271
Chris Lattner75648e72004-03-12 05:54:31 +00002272void Verifier::visitSelectInst(SelectInst &SI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002273 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2274 SI.getOperand(2)),
2275 "Invalid operands for select instruction!", &SI);
Chris Lattner88107952008-12-29 00:12:50 +00002276
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002277 Assert(SI.getTrueValue()->getType() == SI.getType(),
2278 "Select values must have same type as select instruction!", &SI);
Chris Lattnercde15fb2004-09-29 21:19:28 +00002279 visitInstruction(SI);
Chris Lattner75648e72004-03-12 05:54:31 +00002280}
2281
Misha Brukmanc566ca362004-03-02 00:22:19 +00002282/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2283/// a pass, if any exist, it's an error.
2284///
Chris Lattner903a25d2002-11-21 16:54:22 +00002285void Verifier::visitUserOp1(Instruction &I) {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00002286 Assert(false, "User-defined operators should not live outside of a pass!", &I);
Chris Lattner903a25d2002-11-21 16:54:22 +00002287}
Chris Lattner0e851da2002-04-18 20:37:37 +00002288
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002289void Verifier::visitTruncInst(TruncInst &I) {
2290 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002291 Type *SrcTy = I.getOperand(0)->getType();
2292 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002293
2294 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002295 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2296 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002297
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002298 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2299 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2300 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2301 "trunc source and destination must both be a vector or neither", &I);
2302 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002303
2304 visitInstruction(I);
2305}
2306
2307void Verifier::visitZExtInst(ZExtInst &I) {
2308 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002309 Type *SrcTy = I.getOperand(0)->getType();
2310 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002311
2312 // Get the size of the types in bits, we'll need this later
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002313 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2314 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2315 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2316 "zext source and destination must both be a vector or neither", &I);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002317 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2318 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002319
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002320 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002321
2322 visitInstruction(I);
2323}
2324
2325void Verifier::visitSExtInst(SExtInst &I) {
2326 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002327 Type *SrcTy = I.getOperand(0)->getType();
2328 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002329
2330 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002331 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2332 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002333
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002334 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2335 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2336 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2337 "sext source and destination must both be a vector or neither", &I);
2338 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002339
2340 visitInstruction(I);
2341}
2342
2343void Verifier::visitFPTruncInst(FPTruncInst &I) {
2344 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002345 Type *SrcTy = I.getOperand(0)->getType();
2346 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002347 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002348 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2349 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002350
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002351 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2352 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2353 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2354 "fptrunc source and destination must both be a vector or neither", &I);
2355 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002356
2357 visitInstruction(I);
2358}
2359
2360void Verifier::visitFPExtInst(FPExtInst &I) {
2361 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002362 Type *SrcTy = I.getOperand(0)->getType();
2363 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002364
2365 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002366 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2367 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002368
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002369 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2370 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2371 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2372 "fpext source and destination must both be a vector or neither", &I);
2373 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002374
2375 visitInstruction(I);
2376}
2377
2378void Verifier::visitUIToFPInst(UIToFPInst &I) {
2379 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002380 Type *SrcTy = I.getOperand(0)->getType();
2381 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002382
Duncan Sands19d0b472010-02-16 11:11:14 +00002383 bool SrcVec = SrcTy->isVectorTy();
2384 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002385
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002386 Assert(SrcVec == DstVec,
2387 "UIToFP source and dest must both be vector or scalar", &I);
2388 Assert(SrcTy->isIntOrIntVectorTy(),
2389 "UIToFP source must be integer or integer vector", &I);
2390 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2391 &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002392
2393 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002394 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2395 cast<VectorType>(DestTy)->getNumElements(),
2396 "UIToFP source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002397
2398 visitInstruction(I);
2399}
2400
2401void Verifier::visitSIToFPInst(SIToFPInst &I) {
2402 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002403 Type *SrcTy = I.getOperand(0)->getType();
2404 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002405
Duncan Sands19d0b472010-02-16 11:11:14 +00002406 bool SrcVec = SrcTy->isVectorTy();
2407 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002408
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002409 Assert(SrcVec == DstVec,
2410 "SIToFP source and dest must both be vector or scalar", &I);
2411 Assert(SrcTy->isIntOrIntVectorTy(),
2412 "SIToFP source must be integer or integer vector", &I);
2413 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2414 &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002415
2416 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002417 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2418 cast<VectorType>(DestTy)->getNumElements(),
2419 "SIToFP source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002420
2421 visitInstruction(I);
2422}
2423
2424void Verifier::visitFPToUIInst(FPToUIInst &I) {
2425 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002426 Type *SrcTy = I.getOperand(0)->getType();
2427 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002428
Duncan Sands19d0b472010-02-16 11:11:14 +00002429 bool SrcVec = SrcTy->isVectorTy();
2430 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002431
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002432 Assert(SrcVec == DstVec,
2433 "FPToUI source and dest must both be vector or scalar", &I);
2434 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2435 &I);
2436 Assert(DestTy->isIntOrIntVectorTy(),
2437 "FPToUI result must be integer or integer vector", &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002438
2439 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002440 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2441 cast<VectorType>(DestTy)->getNumElements(),
2442 "FPToUI source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002443
2444 visitInstruction(I);
2445}
2446
2447void Verifier::visitFPToSIInst(FPToSIInst &I) {
2448 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002449 Type *SrcTy = I.getOperand(0)->getType();
2450 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002451
Duncan Sands19d0b472010-02-16 11:11:14 +00002452 bool SrcVec = SrcTy->isVectorTy();
2453 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002454
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002455 Assert(SrcVec == DstVec,
2456 "FPToSI source and dest must both be vector or scalar", &I);
2457 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2458 &I);
2459 Assert(DestTy->isIntOrIntVectorTy(),
2460 "FPToSI result must be integer or integer vector", &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002461
2462 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002463 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2464 cast<VectorType>(DestTy)->getNumElements(),
2465 "FPToSI source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002466
2467 visitInstruction(I);
2468}
2469
2470void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2471 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002472 Type *SrcTy = I.getOperand(0)->getType();
2473 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002474
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002475 Assert(SrcTy->getScalarType()->isPointerTy(),
2476 "PtrToInt source must be pointer", &I);
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002477
2478 if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType()))
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00002479 Assert(!DL.isNonIntegralPointerType(PTy),
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002480 "ptrtoint not supported for non-integral pointers");
2481
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002482 Assert(DestTy->getScalarType()->isIntegerTy(),
2483 "PtrToInt result must be integral", &I);
2484 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2485 &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002486
2487 if (SrcTy->isVectorTy()) {
2488 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2489 VectorType *VDest = dyn_cast<VectorType>(DestTy);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002490 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2491 "PtrToInt Vector width mismatch", &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002492 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002493
2494 visitInstruction(I);
2495}
2496
2497void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2498 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002499 Type *SrcTy = I.getOperand(0)->getType();
2500 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002501
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002502 Assert(SrcTy->getScalarType()->isIntegerTy(),
2503 "IntToPtr source must be an integral", &I);
2504 Assert(DestTy->getScalarType()->isPointerTy(),
2505 "IntToPtr result must be a pointer", &I);
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002506
2507 if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType()))
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00002508 Assert(!DL.isNonIntegralPointerType(PTy),
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002509 "inttoptr not supported for non-integral pointers");
2510
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002511 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2512 &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002513 if (SrcTy->isVectorTy()) {
2514 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2515 VectorType *VDest = dyn_cast<VectorType>(DestTy);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002516 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2517 "IntToPtr Vector width mismatch", &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002518 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002519 visitInstruction(I);
2520}
2521
2522void Verifier::visitBitCastInst(BitCastInst &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002523 Assert(
Rafael Espindolaa4a94f12014-12-16 19:29:29 +00002524 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2525 "Invalid bitcast", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002526 visitInstruction(I);
2527}
2528
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002529void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2530 Type *SrcTy = I.getOperand(0)->getType();
2531 Type *DestTy = I.getType();
2532
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002533 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2534 &I);
2535 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2536 &I);
2537 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2538 "AddrSpaceCast must be between different address spaces", &I);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002539 if (SrcTy->isVectorTy())
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002540 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2541 "AddrSpaceCast vector pointer number of elements mismatch", &I);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002542 visitInstruction(I);
2543}
2544
Misha Brukmanc566ca362004-03-02 00:22:19 +00002545/// visitPHINode - Ensure that a PHI node is well formed.
2546///
Chris Lattner069a7952002-06-25 15:56:27 +00002547void Verifier::visitPHINode(PHINode &PN) {
2548 // Ensure that the PHI nodes are all grouped together at the top of the block.
2549 // This can be tested by checking whether the instruction before this is
Misha Brukmanfa100532003-10-10 17:54:14 +00002550 // either nonexistent (because this is begin()) or is a PHI node. If not,
Chris Lattner069a7952002-06-25 15:56:27 +00002551 // then there is some other instruction before a PHI.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002552 Assert(&PN == &PN.getParent()->front() ||
2553 isa<PHINode>(--BasicBlock::iterator(&PN)),
2554 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
Chris Lattner069a7952002-06-25 15:56:27 +00002555
David Majnemerb611e3f2015-08-14 05:09:07 +00002556 // Check that a PHI doesn't yield a Token.
2557 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2558
Nick Lewyckyb2b04672009-09-08 01:23:52 +00002559 // Check that all of the values of the PHI node have the same type as the
2560 // result, and that the incoming blocks are really basic blocks.
Pete Cooper833f34d2015-05-12 20:05:31 +00002561 for (Value *IncValue : PN.incoming_values()) {
2562 Assert(PN.getType() == IncValue->getType(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002563 "PHI node operands are not the same type as the result!", &PN);
Nick Lewyckyb2b04672009-09-08 01:23:52 +00002564 }
Chris Lattner3b93c912003-11-12 07:13:37 +00002565
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002566 // All other PHI node constraints are checked in the visitBasicBlock method.
Chris Lattner0e851da2002-04-18 20:37:37 +00002567
2568 visitInstruction(PN);
2569}
2570
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002571void Verifier::verifyCallSite(CallSite CS) {
Duncan Sands8c582282007-12-21 19:19:01 +00002572 Instruction *I = CS.getInstruction();
2573
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002574 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2575 "Called function must be a pointer!", I);
Chris Lattner229907c2011-07-18 04:54:35 +00002576 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattner338a4622002-05-08 19:49:50 +00002577
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002578 Assert(FPTy->getElementType()->isFunctionTy(),
2579 "Called function is not pointer to function type!", I);
David Blaikie348de692015-04-23 21:36:23 +00002580
2581 Assert(FPTy->getElementType() == CS.getFunctionType(),
2582 "Called function is not the same type as the call!", I);
2583
2584 FunctionType *FTy = CS.getFunctionType();
Chris Lattner338a4622002-05-08 19:49:50 +00002585
2586 // Verify that the correct number of arguments are being passed
2587 if (FTy->isVarArg())
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002588 Assert(CS.arg_size() >= FTy->getNumParams(),
2589 "Called function requires more parameters than were provided!", I);
Chris Lattner338a4622002-05-08 19:49:50 +00002590 else
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002591 Assert(CS.arg_size() == FTy->getNumParams(),
2592 "Incorrect number of arguments passed to called function!", I);
Chris Lattner338a4622002-05-08 19:49:50 +00002593
Chris Lattner609de002010-05-10 20:58:42 +00002594 // Verify that all arguments to the call match the function type.
Chris Lattner338a4622002-05-08 19:49:50 +00002595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002596 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2597 "Call parameter type does not match function signature!",
2598 CS.getArgument(i), FTy->getParamType(i), I);
Duncan Sands8c582282007-12-21 19:19:01 +00002599
Bill Wendlinge3a60a92013-04-18 20:15:25 +00002600 AttributeSet Attrs = CS.getAttributes();
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002601
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002602 Assert(verifyAttributeCount(Attrs, CS.arg_size()),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002603 "Attribute after last parameter!", I);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002604
Duncan Sands8c582282007-12-21 19:19:01 +00002605 // Verify call attributes.
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002606 verifyFunctionAttrs(FTy, Attrs, I);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002607
David Majnemer91db08b2014-04-30 17:22:00 +00002608 // Conservatively check the inalloca argument.
2609 // We have a bug if we can find that there is an underlying alloca without
2610 // inalloca.
2611 if (CS.hasInAllocaArgument()) {
2612 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2613 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002614 Assert(AI->isUsedWithInAlloca(),
2615 "inalloca argument for call has mismatched alloca", AI, I);
David Majnemer91db08b2014-04-30 17:22:00 +00002616 }
2617
Manman Ren9bfd0d02016-04-01 21:41:15 +00002618 // For each argument of the callsite, if it has the swifterror argument,
Arnold Schwaighofer6c57f4f2016-09-10 19:42:53 +00002619 // make sure the underlying alloca/parameter it comes from has a swifterror as
2620 // well.
Manman Ren9bfd0d02016-04-01 21:41:15 +00002621 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2622 if (CS.paramHasAttr(i+1, Attribute::SwiftError)) {
2623 Value *SwiftErrorArg = CS.getArgument(i);
Arnold Schwaighofer6c57f4f2016-09-10 19:42:53 +00002624 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
Manman Ren9bfd0d02016-04-01 21:41:15 +00002625 Assert(AI->isSwiftError(),
2626 "swifterror argument for call has mismatched alloca", AI, I);
Arnold Schwaighofer6c57f4f2016-09-10 19:42:53 +00002627 continue;
2628 }
2629 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
2630 Assert(ArgI, "swifterror argument should come from an alloca or parameter", SwiftErrorArg, I);
2631 Assert(ArgI->hasSwiftErrorAttr(),
2632 "swifterror argument for call has mismatched parameter", ArgI, I);
Manman Ren9bfd0d02016-04-01 21:41:15 +00002633 }
2634
Stephen Linb8bd2322013-04-20 05:14:40 +00002635 if (FTy->isVarArg()) {
2636 // FIXME? is 'nest' even legal here?
2637 bool SawNest = false;
2638 bool SawReturned = false;
2639
2640 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2641 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2642 SawNest = true;
2643 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2644 SawReturned = true;
2645 }
2646
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002647 // Check attributes on the varargs part.
2648 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002649 Type *Ty = CS.getArgument(Idx-1)->getType();
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002650 verifyParameterAttrs(Attrs, Idx, Ty, false, I);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002651
Stephen Linb8bd2322013-04-20 05:14:40 +00002652 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002653 Assert(!SawNest, "More than one parameter has attribute nest!", I);
Stephen Linb8bd2322013-04-20 05:14:40 +00002654 SawNest = true;
2655 }
2656
2657 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002658 Assert(!SawReturned, "More than one parameter has attribute returned!",
2659 I);
2660 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2661 "Incompatible argument and return types for 'returned' "
2662 "attribute",
2663 I);
Stephen Linb8bd2322013-04-20 05:14:40 +00002664 SawReturned = true;
2665 }
Duncan Sands0009c442008-01-12 16:42:01 +00002666
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002667 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2668 "Attribute 'sret' cannot be used for vararg call arguments!", I);
Reid Kleckner60d3a832014-01-16 22:59:24 +00002669
2670 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002671 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002672 }
Stephen Linb8bd2322013-04-20 05:14:40 +00002673 }
Duncan Sands8c582282007-12-21 19:19:01 +00002674
Nick Lewyckyadbc2842009-05-30 05:06:04 +00002675 // Verify that there's no metadata unless it's a direct call to an intrinsic.
Craig Topperc6207612014-04-09 06:08:46 +00002676 if (CS.getCalledFunction() == nullptr ||
Chris Lattner609de002010-05-10 20:58:42 +00002677 !CS.getCalledFunction()->getName().startswith("llvm.")) {
David Majnemerb611e3f2015-08-14 05:09:07 +00002678 for (Type *ParamTy : FTy->params()) {
2679 Assert(!ParamTy->isMetadataTy(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002680 "Function has metadata parameter but isn't an intrinsic", I);
David Majnemerb611e3f2015-08-14 05:09:07 +00002681 Assert(!ParamTy->isTokenTy(),
2682 "Function has token parameter but isn't an intrinsic", I);
2683 }
Nick Lewyckyadbc2842009-05-30 05:06:04 +00002684 }
2685
David Majnemerb611e3f2015-08-14 05:09:07 +00002686 // Verify that indirect calls don't return tokens.
2687 if (CS.getCalledFunction() == nullptr)
2688 Assert(!FTy->getReturnType()->isTokenTy(),
2689 "Return type cannot be token for indirect call!");
2690
Philip Reamesa3c6f002015-06-26 21:39:44 +00002691 if (Function *F = CS.getCalledFunction())
2692 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
Philip Reames007561a2015-06-26 22:21:52 +00002693 visitIntrinsicCallSite(ID, CS);
Philip Reamesa3c6f002015-06-26 21:39:44 +00002694
Sanjoy Dasa34ce952016-01-20 19:50:25 +00002695 // Verify that a callsite has at most one "deopt", at most one "funclet" and
2696 // at most one "gc-transition" operand bundle.
2697 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
2698 FoundGCTransitionBundle = false;
Sanjoy Dascdafd842015-11-11 21:38:02 +00002699 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
David Majnemer3bb88c02015-12-15 21:27:27 +00002700 OperandBundleUse BU = CS.getOperandBundleAt(i);
2701 uint32_t Tag = BU.getTagID();
2702 if (Tag == LLVMContext::OB_deopt) {
Sanjoy Dascdafd842015-11-11 21:38:02 +00002703 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2704 FoundDeoptBundle = true;
Sanjoy Dasa34ce952016-01-20 19:50:25 +00002705 } else if (Tag == LLVMContext::OB_gc_transition) {
2706 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
2707 I);
2708 FoundGCTransitionBundle = true;
2709 } else if (Tag == LLVMContext::OB_funclet) {
David Majnemer3bb88c02015-12-15 21:27:27 +00002710 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I);
2711 FoundFuncletBundle = true;
2712 Assert(BU.Inputs.size() == 1,
2713 "Expected exactly one funclet bundle operand", I);
2714 Assert(isa<FuncletPadInst>(BU.Inputs.front()),
2715 "Funclet bundle operands should correspond to a FuncletPadInst",
2716 I);
2717 }
Sanjoy Dascdafd842015-11-11 21:38:02 +00002718 }
2719
Adrian Prantl93035c82016-04-24 22:23:13 +00002720 // Verify that each inlinable callsite of a debug-info-bearing function in a
2721 // debug-info-bearing function has a debug location attached to it. Failure to
2722 // do so causes assertion failures when the inliner sets up inline scope info.
2723 if (I->getFunction()->getSubprogram() && CS.getCalledFunction() &&
2724 CS.getCalledFunction()->getSubprogram())
2725 Assert(I->getDebugLoc(), "inlinable function call in a function with debug "
2726 "info must have a !dbg location",
2727 I);
2728
Duncan Sands8c582282007-12-21 19:19:01 +00002729 visitInstruction(*I);
2730}
2731
Reid Kleckner5772b772014-04-24 20:14:34 +00002732/// Two types are "congruent" if they are identical, or if they are both pointer
2733/// types with different pointee types and the same address space.
2734static bool isTypeCongruent(Type *L, Type *R) {
2735 if (L == R)
2736 return true;
2737 PointerType *PL = dyn_cast<PointerType>(L);
2738 PointerType *PR = dyn_cast<PointerType>(R);
2739 if (!PL || !PR)
2740 return false;
2741 return PL->getAddressSpace() == PR->getAddressSpace();
2742}
2743
Reid Klecknerd20c9702014-05-15 23:58:57 +00002744static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2745 static const Attribute::AttrKind ABIAttrs[] = {
2746 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
Manman Ren9bfd0d02016-04-01 21:41:15 +00002747 Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf,
2748 Attribute::SwiftError};
Reid Klecknerd20c9702014-05-15 23:58:57 +00002749 AttrBuilder Copy;
2750 for (auto AK : ABIAttrs) {
2751 if (Attrs.hasAttribute(I + 1, AK))
2752 Copy.addAttribute(AK);
2753 }
2754 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2755 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2756 return Copy;
2757}
2758
Reid Kleckner5772b772014-04-24 20:14:34 +00002759void Verifier::verifyMustTailCall(CallInst &CI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002760 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002761
2762 // - The caller and callee prototypes must match. Pointer types of
2763 // parameters or return types may differ in pointee type, but not
2764 // address space.
2765 Function *F = CI.getParent()->getParent();
David Blaikie5bacf372015-04-24 21:16:07 +00002766 FunctionType *CallerTy = F->getFunctionType();
2767 FunctionType *CalleeTy = CI.getFunctionType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002768 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2769 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2770 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2771 "cannot guarantee tail call due to mismatched varargs", &CI);
2772 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2773 "cannot guarantee tail call due to mismatched return types", &CI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002774 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002775 Assert(
Reid Kleckner5772b772014-04-24 20:14:34 +00002776 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2777 "cannot guarantee tail call due to mismatched parameter types", &CI);
2778 }
2779
2780 // - The calling conventions of the caller and callee must match.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002781 Assert(F->getCallingConv() == CI.getCallingConv(),
2782 "cannot guarantee tail call due to mismatched calling conv", &CI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002783
2784 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2785 // returned, and inalloca, must match.
Reid Kleckner5772b772014-04-24 20:14:34 +00002786 AttributeSet CallerAttrs = F->getAttributes();
2787 AttributeSet CalleeAttrs = CI.getAttributes();
2788 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
Reid Klecknerd20c9702014-05-15 23:58:57 +00002789 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2790 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002791 Assert(CallerABIAttrs == CalleeABIAttrs,
2792 "cannot guarantee tail call due to mismatched ABI impacting "
2793 "function attributes",
2794 &CI, CI.getOperand(I));
Reid Kleckner5772b772014-04-24 20:14:34 +00002795 }
2796
2797 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2798 // or a pointer bitcast followed by a ret instruction.
2799 // - The ret instruction must return the (possibly bitcasted) value
2800 // produced by the call or void.
2801 Value *RetVal = &CI;
2802 Instruction *Next = CI.getNextNode();
2803
2804 // Handle the optional bitcast.
2805 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002806 Assert(BI->getOperand(0) == RetVal,
2807 "bitcast following musttail call must use the call", BI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002808 RetVal = BI;
2809 Next = BI->getNextNode();
2810 }
2811
2812 // Check the return.
2813 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002814 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2815 &CI);
2816 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2817 "musttail call result must be returned", Ret);
Reid Kleckner5772b772014-04-24 20:14:34 +00002818}
2819
Duncan Sands8c582282007-12-21 19:19:01 +00002820void Verifier::visitCallInst(CallInst &CI) {
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002821 verifyCallSite(&CI);
Chris Lattner7af3ee92002-07-18 00:13:42 +00002822
Reid Kleckner5772b772014-04-24 20:14:34 +00002823 if (CI.isMustTailCall())
2824 verifyMustTailCall(CI);
Duncan Sands8c582282007-12-21 19:19:01 +00002825}
2826
2827void Verifier::visitInvokeInst(InvokeInst &II) {
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002828 verifyCallSite(&II);
Bill Wendlingf4bbc042011-09-21 22:57:02 +00002829
David Majnemer654e1302015-07-31 17:58:14 +00002830 // Verify that the first non-PHI instruction of the unwind destination is an
2831 // exception handling instruction.
2832 Assert(
2833 II.getUnwindDest()->isEHPad(),
2834 "The unwind destination does not have an exception handling instruction!",
2835 &II);
Bill Wendlingf4bbc042011-09-21 22:57:02 +00002836
Dan Gohman9c6e1882010-08-02 23:09:14 +00002837 visitTerminatorInst(II);
Chris Lattner21ea83b2002-04-18 22:11:52 +00002838}
Chris Lattner0e851da2002-04-18 20:37:37 +00002839
Misha Brukmanc566ca362004-03-02 00:22:19 +00002840/// visitBinaryOperator - Check that both arguments to the binary operator are
2841/// of the same type!
2842///
Chris Lattner069a7952002-06-25 15:56:27 +00002843void Verifier::visitBinaryOperator(BinaryOperator &B) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002844 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2845 "Both operands to a binary operator are not of the same type!", &B);
Chris Lattner0e851da2002-04-18 20:37:37 +00002846
Reid Spencer2341c222007-02-02 02:16:23 +00002847 switch (B.getOpcode()) {
Dan Gohman5208dd82009-06-05 16:10:00 +00002848 // Check that integer arithmetic operators are only used with
2849 // integral operands.
2850 case Instruction::Add:
2851 case Instruction::Sub:
2852 case Instruction::Mul:
2853 case Instruction::SDiv:
2854 case Instruction::UDiv:
2855 case Instruction::SRem:
2856 case Instruction::URem:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002857 Assert(B.getType()->isIntOrIntVectorTy(),
2858 "Integer arithmetic operators only work with integral types!", &B);
2859 Assert(B.getType() == B.getOperand(0)->getType(),
2860 "Integer arithmetic operators must have same type "
2861 "for operands and result!",
2862 &B);
Dan Gohman5208dd82009-06-05 16:10:00 +00002863 break;
2864 // Check that floating-point arithmetic operators are only used with
2865 // floating-point operands.
2866 case Instruction::FAdd:
2867 case Instruction::FSub:
2868 case Instruction::FMul:
2869 case Instruction::FDiv:
2870 case Instruction::FRem:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002871 Assert(B.getType()->isFPOrFPVectorTy(),
2872 "Floating-point arithmetic operators only work with "
2873 "floating-point types!",
2874 &B);
2875 Assert(B.getType() == B.getOperand(0)->getType(),
2876 "Floating-point arithmetic operators must have same type "
2877 "for operands and result!",
2878 &B);
Dan Gohman5208dd82009-06-05 16:10:00 +00002879 break;
Chris Lattner1f419252002-09-09 20:26:04 +00002880 // Check that logical operators are only used with integral operands.
Reid Spencer2341c222007-02-02 02:16:23 +00002881 case Instruction::And:
2882 case Instruction::Or:
2883 case Instruction::Xor:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002884 Assert(B.getType()->isIntOrIntVectorTy(),
2885 "Logical operators only work with integral types!", &B);
2886 Assert(B.getType() == B.getOperand(0)->getType(),
2887 "Logical operators must have same type for operands and result!",
2888 &B);
Reid Spencer2341c222007-02-02 02:16:23 +00002889 break;
2890 case Instruction::Shl:
2891 case Instruction::LShr:
2892 case Instruction::AShr:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002893 Assert(B.getType()->isIntOrIntVectorTy(),
2894 "Shifts only work with integral types!", &B);
2895 Assert(B.getType() == B.getOperand(0)->getType(),
2896 "Shift return type must be same as operands!", &B);
Reid Spencer2341c222007-02-02 02:16:23 +00002897 break;
Dan Gohman5208dd82009-06-05 16:10:00 +00002898 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00002899 llvm_unreachable("Unknown BinaryOperator opcode!");
Chris Lattner1f419252002-09-09 20:26:04 +00002900 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002901
Chris Lattner0e851da2002-04-18 20:37:37 +00002902 visitInstruction(B);
2903}
2904
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002905void Verifier::visitICmpInst(ICmpInst &IC) {
Reid Spencerd9436b62006-11-20 01:22:35 +00002906 // Check that the operands are the same type
Chris Lattner229907c2011-07-18 04:54:35 +00002907 Type *Op0Ty = IC.getOperand(0)->getType();
2908 Type *Op1Ty = IC.getOperand(1)->getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002909 Assert(Op0Ty == Op1Ty,
2910 "Both operands to ICmp instruction are not of the same type!", &IC);
Reid Spencerd9436b62006-11-20 01:22:35 +00002911 // Check that the operands are the right type
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002912 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2913 "Invalid operand types for ICmp instruction", &IC);
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002914 // Check that the predicate is valid.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002915 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2916 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2917 "Invalid predicate in ICmp instruction!", &IC);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00002918
Reid Spencerd9436b62006-11-20 01:22:35 +00002919 visitInstruction(IC);
2920}
2921
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002922void Verifier::visitFCmpInst(FCmpInst &FC) {
Reid Spencerd9436b62006-11-20 01:22:35 +00002923 // Check that the operands are the same type
Chris Lattner229907c2011-07-18 04:54:35 +00002924 Type *Op0Ty = FC.getOperand(0)->getType();
2925 Type *Op1Ty = FC.getOperand(1)->getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002926 Assert(Op0Ty == Op1Ty,
2927 "Both operands to FCmp instruction are not of the same type!", &FC);
Reid Spencerd9436b62006-11-20 01:22:35 +00002928 // Check that the operands are the right type
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002929 Assert(Op0Ty->isFPOrFPVectorTy(),
2930 "Invalid operand types for FCmp instruction", &FC);
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002931 // Check that the predicate is valid.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002932 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2933 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2934 "Invalid predicate in FCmp instruction!", &FC);
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002935
Reid Spencerd9436b62006-11-20 01:22:35 +00002936 visitInstruction(FC);
2937}
2938
Robert Bocchino23004482006-01-10 19:05:34 +00002939void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002940 Assert(
2941 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2942 "Invalid extractelement operands!", &EI);
Robert Bocchino23004482006-01-10 19:05:34 +00002943 visitInstruction(EI);
2944}
2945
Robert Bocchinoca27f032006-01-17 20:07:22 +00002946void Verifier::visitInsertElementInst(InsertElementInst &IE) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002947 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2948 IE.getOperand(2)),
2949 "Invalid insertelement operands!", &IE);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002950 visitInstruction(IE);
2951}
2952
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002953void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002954 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2955 SV.getOperand(2)),
2956 "Invalid shufflevector operands!", &SV);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002957 visitInstruction(SV);
2958}
2959
Chris Lattner069a7952002-06-25 15:56:27 +00002960void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Duncan Sandsa71ae962012-02-03 17:28:51 +00002961 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
Nadav Rotem3924cb02011-12-05 06:29:09 +00002962
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002963 Assert(isa<PointerType>(TargetTy),
2964 "GEP base pointer is not a vector or a vector of pointers", &GEP);
David Blaikiecc2cd582015-04-17 22:32:17 +00002965 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
Chris Lattner84d82c72007-02-10 08:30:29 +00002966 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
Chris Lattner229907c2011-07-18 04:54:35 +00002967 Type *ElTy =
David Blaikied288fb82015-03-30 21:41:43 +00002968 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002969 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002970
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002971 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
David Blaikied0a24822015-04-17 22:32:20 +00002972 GEP.getResultElementType() == ElTy,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002973 "GEP is not of right type for indices!", &GEP, ElTy);
Duncan Sandse6beec62012-11-13 12:59:33 +00002974
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002975 if (GEP.getType()->isVectorTy()) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002976 // Additional checks for vector GEPs.
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002977 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2978 if (GEP.getPointerOperandType()->isVectorTy())
2979 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2980 "Vector GEP result width doesn't match operand's", &GEP);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002981 for (Value *Idx : Idxs) {
2982 Type *IndexTy = Idx->getType();
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002983 if (IndexTy->isVectorTy()) {
2984 unsigned IndexWidth = IndexTy->getVectorNumElements();
2985 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2986 }
2987 Assert(IndexTy->getScalarType()->isIntegerTy(),
2988 "All GEP indices should be of integer type");
Duncan Sandse6beec62012-11-13 12:59:33 +00002989 }
Nadav Rotem3924cb02011-12-05 06:29:09 +00002990 }
Chris Lattnerd46bb6e2002-04-24 19:12:21 +00002991 visitInstruction(GEP);
2992}
2993
Rafael Espindolae3c5f3e2012-05-31 16:04:26 +00002994static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2995 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2996}
2997
Sanjoy Das26f28a22016-11-09 19:36:39 +00002998void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
2999 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
Philip Reamesbf9676f2014-10-20 23:52:07 +00003000 "precondition violation");
3001
3002 unsigned NumOperands = Range->getNumOperands();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003003 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003004 unsigned NumRanges = NumOperands / 2;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003005 Assert(NumRanges >= 1, "It should have at least one range!", Range);
3006
Philip Reamesbf9676f2014-10-20 23:52:07 +00003007 ConstantRange LastRange(1); // Dummy initial value
3008 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003009 ConstantInt *Low =
3010 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003011 Assert(Low, "The lower limit must be an integer!", Low);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003012 ConstantInt *High =
3013 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003014 Assert(High, "The upper limit must be an integer!", High);
3015 Assert(High->getType() == Low->getType() && High->getType() == Ty,
3016 "Range types must match instruction type!", &I);
3017
Philip Reamesbf9676f2014-10-20 23:52:07 +00003018 APInt HighV = High->getValue();
3019 APInt LowV = Low->getValue();
3020 ConstantRange CurRange(LowV, HighV);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003021 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3022 "Range must not be empty!", Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003023 if (i != 0) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003024 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
3025 "Intervals are overlapping", Range);
3026 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3027 Range);
3028 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3029 Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003030 }
3031 LastRange = ConstantRange(LowV, HighV);
3032 }
3033 if (NumRanges > 2) {
3034 APInt FirstLow =
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003035 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
Philip Reamesbf9676f2014-10-20 23:52:07 +00003036 APInt FirstHigh =
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003037 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
Philip Reamesbf9676f2014-10-20 23:52:07 +00003038 ConstantRange FirstRange(FirstLow, FirstHigh);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003039 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
3040 "Intervals are overlapping", Range);
3041 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3042 Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003043 }
3044}
3045
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003046void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3047 unsigned Size = DL.getTypeSizeInBits(Ty);
JF Bastiend1fb5852015-12-17 22:09:19 +00003048 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3049 Assert(!(Size & (Size - 1)),
3050 "atomic memory access' operand must have a power-of-two size", Ty, I);
3051}
3052
Chris Lattner069a7952002-06-25 15:56:27 +00003053void Verifier::visitLoadInst(LoadInst &LI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003054 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003055 Assert(PTy, "Load operand must be a pointer.", &LI);
David Blaikie15d9a4c2015-04-06 20:59:48 +00003056 Type *ElTy = LI.getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003057 Assert(LI.getAlignment() <= Value::MaximumAlignment,
3058 "huge alignment values are unsupported", &LI);
Sanjoy Dasc2cf6ef2016-06-01 16:13:10 +00003059 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
Eli Friedman59b66882011-08-09 23:02:53 +00003060 if (LI.isAtomic()) {
JF Bastien800f87a2016-04-06 21:19:33 +00003061 Assert(LI.getOrdering() != AtomicOrdering::Release &&
3062 LI.getOrdering() != AtomicOrdering::AcquireRelease,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003063 "Load cannot have Release ordering", &LI);
3064 Assert(LI.getAlignment() != 0,
3065 "Atomic load must specify explicit alignment", &LI);
JF Bastiend1fb5852015-12-17 22:09:19 +00003066 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
3067 ElTy->isFloatingPointTy(),
3068 "atomic load operand must have integer, pointer, or floating point "
3069 "type!",
3070 ElTy, &LI);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003071 checkAtomicMemAccessSize(ElTy, &LI);
Eli Friedman59b66882011-08-09 23:02:53 +00003072 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003073 Assert(LI.getSynchScope() == CrossThread,
3074 "Non-atomic load cannot have SynchronizationScope specified", &LI);
Eli Friedman59b66882011-08-09 23:02:53 +00003075 }
Rafael Espindolaef9f5502012-03-24 00:14:51 +00003076
Chris Lattnerd46bb6e2002-04-24 19:12:21 +00003077 visitInstruction(LI);
3078}
3079
Chris Lattner069a7952002-06-25 15:56:27 +00003080void Verifier::visitStoreInst(StoreInst &SI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003081 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003082 Assert(PTy, "Store operand must be a pointer.", &SI);
Chris Lattner229907c2011-07-18 04:54:35 +00003083 Type *ElTy = PTy->getElementType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003084 Assert(ElTy == SI.getOperand(0)->getType(),
3085 "Stored value type does not match pointer operand type!", &SI, ElTy);
3086 Assert(SI.getAlignment() <= Value::MaximumAlignment,
3087 "huge alignment values are unsupported", &SI);
Sanjoy Dasc2cf6ef2016-06-01 16:13:10 +00003088 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
Eli Friedman59b66882011-08-09 23:02:53 +00003089 if (SI.isAtomic()) {
JF Bastien800f87a2016-04-06 21:19:33 +00003090 Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
3091 SI.getOrdering() != AtomicOrdering::AcquireRelease,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003092 "Store cannot have Acquire ordering", &SI);
3093 Assert(SI.getAlignment() != 0,
3094 "Atomic store must specify explicit alignment", &SI);
JF Bastiend1fb5852015-12-17 22:09:19 +00003095 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
3096 ElTy->isFloatingPointTy(),
3097 "atomic store operand must have integer, pointer, or floating point "
3098 "type!",
3099 ElTy, &SI);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003100 checkAtomicMemAccessSize(ElTy, &SI);
Eli Friedman59b66882011-08-09 23:02:53 +00003101 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003102 Assert(SI.getSynchScope() == CrossThread,
3103 "Non-atomic store cannot have SynchronizationScope specified", &SI);
Eli Friedman59b66882011-08-09 23:02:53 +00003104 }
Chris Lattnerd46bb6e2002-04-24 19:12:21 +00003105 visitInstruction(SI);
3106}
3107
Manman Ren9bfd0d02016-04-01 21:41:15 +00003108/// Check that SwiftErrorVal is used as a swifterror argument in CS.
3109void Verifier::verifySwiftErrorCallSite(CallSite CS,
3110 const Value *SwiftErrorVal) {
3111 unsigned Idx = 0;
3112 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3113 I != E; ++I, ++Idx) {
3114 if (*I == SwiftErrorVal) {
3115 Assert(CS.paramHasAttr(Idx+1, Attribute::SwiftError),
3116 "swifterror value when used in a callsite should be marked "
3117 "with swifterror attribute",
3118 SwiftErrorVal, CS);
3119 }
3120 }
3121}
3122
3123void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3124 // Check that swifterror value is only used by loads, stores, or as
3125 // a swifterror argument.
3126 for (const User *U : SwiftErrorVal->users()) {
3127 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3128 isa<InvokeInst>(U),
3129 "swifterror value can only be loaded and stored from, or "
3130 "as a swifterror argument!",
3131 SwiftErrorVal, U);
3132 // If it is used by a store, check it is the second operand.
3133 if (auto StoreI = dyn_cast<StoreInst>(U))
3134 Assert(StoreI->getOperand(1) == SwiftErrorVal,
3135 "swifterror value should be the second operand when used "
3136 "by stores", SwiftErrorVal, U);
3137 if (auto CallI = dyn_cast<CallInst>(U))
3138 verifySwiftErrorCallSite(const_cast<CallInst*>(CallI), SwiftErrorVal);
3139 if (auto II = dyn_cast<InvokeInst>(U))
3140 verifySwiftErrorCallSite(const_cast<InvokeInst*>(II), SwiftErrorVal);
3141 }
3142}
3143
Victor Hernandez8acf2952009-10-23 21:09:37 +00003144void Verifier::visitAllocaInst(AllocaInst &AI) {
Craig Toppere3dcce92015-08-01 22:20:21 +00003145 SmallPtrSet<Type*, 4> Visited;
Chris Lattner229907c2011-07-18 04:54:35 +00003146 PointerType *PTy = AI.getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003147 Assert(PTy->getAddressSpace() == 0,
3148 "Allocation instruction pointer not in the generic address space!",
3149 &AI);
David Blaikie5bacf372015-04-24 21:16:07 +00003150 Assert(AI.getAllocatedType()->isSized(&Visited),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003151 "Cannot allocate unsized type", &AI);
3152 Assert(AI.getArraySize()->getType()->isIntegerTy(),
3153 "Alloca array size must have integer type", &AI);
3154 Assert(AI.getAlignment() <= Value::MaximumAlignment,
3155 "huge alignment values are unsupported", &AI);
Reid Klecknera534a382013-12-19 02:14:12 +00003156
Manman Ren9bfd0d02016-04-01 21:41:15 +00003157 if (AI.isSwiftError()) {
3158 verifySwiftErrorValue(&AI);
3159 }
3160
Christopher Lamb55c6d4f2007-12-17 01:00:21 +00003161 visitInstruction(AI);
3162}
3163
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003164void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
Tim Northovere94a5182014-03-11 10:48:52 +00003165
3166 // FIXME: more conditions???
JF Bastien800f87a2016-04-06 21:19:33 +00003167 Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003168 "cmpxchg instructions must be atomic.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003169 Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003170 "cmpxchg instructions must be atomic.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003171 Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003172 "cmpxchg instructions cannot be unordered.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003173 Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003174 "cmpxchg instructions cannot be unordered.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003175 Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()),
3176 "cmpxchg instructions failure argument shall be no stronger than the "
3177 "success argument",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003178 &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003179 Assert(CXI.getFailureOrdering() != AtomicOrdering::Release &&
3180 CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003181 "cmpxchg failure ordering cannot include release semantics", &CXI);
Tim Northovere94a5182014-03-11 10:48:52 +00003182
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003183 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003184 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003185 Type *ElTy = PTy->getElementType();
Philip Reames1960cfd2016-02-19 00:06:41 +00003186 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy(),
3187 "cmpxchg operand must have integer or pointer type",
3188 ElTy, &CXI);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003189 checkAtomicMemAccessSize(ElTy, &CXI);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003190 Assert(ElTy == CXI.getOperand(1)->getType(),
3191 "Expected value type does not match pointer operand type!", &CXI,
3192 ElTy);
3193 Assert(ElTy == CXI.getOperand(2)->getType(),
3194 "Stored value type does not match pointer operand type!", &CXI, ElTy);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003195 visitInstruction(CXI);
3196}
3197
3198void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
JF Bastien800f87a2016-04-06 21:19:33 +00003199 Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003200 "atomicrmw instructions must be atomic.", &RMWI);
JF Bastien800f87a2016-04-06 21:19:33 +00003201 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003202 "atomicrmw instructions cannot be unordered.", &RMWI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003203 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003204 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003205 Type *ElTy = PTy->getElementType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003206 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
3207 &RMWI, ElTy);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003208 checkAtomicMemAccessSize(ElTy, &RMWI);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003209 Assert(ElTy == RMWI.getOperand(1)->getType(),
3210 "Argument value type does not match pointer operand type!", &RMWI,
3211 ElTy);
3212 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
3213 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
3214 "Invalid binary operation!", &RMWI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003215 visitInstruction(RMWI);
3216}
3217
Eli Friedmanfee02c62011-07-25 23:16:38 +00003218void Verifier::visitFenceInst(FenceInst &FI) {
3219 const AtomicOrdering Ordering = FI.getOrdering();
JF Bastien800f87a2016-04-06 21:19:33 +00003220 Assert(Ordering == AtomicOrdering::Acquire ||
3221 Ordering == AtomicOrdering::Release ||
3222 Ordering == AtomicOrdering::AcquireRelease ||
3223 Ordering == AtomicOrdering::SequentiallyConsistent,
3224 "fence instructions may only have acquire, release, acq_rel, or "
3225 "seq_cst ordering.",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003226 &FI);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003227 visitInstruction(FI);
3228}
3229
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003230void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003231 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
3232 EVI.getIndices()) == EVI.getType(),
3233 "Invalid ExtractValueInst operands!", &EVI);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00003234
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003235 visitInstruction(EVI);
Devang Patel295711f2008-02-19 22:15:16 +00003236}
3237
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003238void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003239 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
3240 IVI.getIndices()) ==
3241 IVI.getOperand(1)->getType(),
3242 "Invalid InsertValueInst operands!", &IVI);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00003243
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003244 visitInstruction(IVI);
3245}
Chris Lattner0e851da2002-04-18 20:37:37 +00003246
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003247static Value *getParentPad(Value *EHPad) {
3248 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3249 return FPI->getParentPad();
3250
3251 return cast<CatchSwitchInst>(EHPad)->getParentPad();
3252}
3253
David Majnemer85a549d2015-08-11 02:48:30 +00003254void Verifier::visitEHPadPredecessors(Instruction &I) {
3255 assert(I.isEHPad());
Bill Wendlingfae14752011-08-12 20:24:12 +00003256
David Majnemer85a549d2015-08-11 02:48:30 +00003257 BasicBlock *BB = I.getParent();
3258 Function *F = BB->getParent();
3259
3260 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
3261
3262 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3263 // The landingpad instruction defines its parent as a landing pad block. The
3264 // landing pad block may be branched to only by the unwind edge of an
3265 // invoke.
3266 for (BasicBlock *PredBB : predecessors(BB)) {
3267 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3268 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
3269 "Block containing LandingPadInst must be jumped to "
3270 "only by the unwind edge of an invoke.",
3271 LPI);
3272 }
3273 return;
3274 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003275 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3276 if (!pred_empty(BB))
3277 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3278 "Block containg CatchPadInst must be jumped to "
3279 "only by its catchswitch.",
3280 CPI);
Joseph Tremouleta9a05cb2016-01-10 04:32:03 +00003281 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3282 "Catchswitch cannot unwind to one of its catchpads",
3283 CPI->getCatchSwitch(), CPI);
David Majnemer8a1c45d2015-12-12 05:38:55 +00003284 return;
3285 }
David Majnemer85a549d2015-08-11 02:48:30 +00003286
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003287 // Verify that each pred has a legal terminator with a legal to/from EH
3288 // pad relationship.
3289 Instruction *ToPad = &I;
3290 Value *ToPadParent = getParentPad(ToPad);
David Majnemer85a549d2015-08-11 02:48:30 +00003291 for (BasicBlock *PredBB : predecessors(BB)) {
3292 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003293 Value *FromPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003294 if (auto *II = dyn_cast<InvokeInst>(TI)) {
David Majnemer85a549d2015-08-11 02:48:30 +00003295 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003296 "EH pad must be jumped to via an unwind edge", ToPad, II);
3297 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3298 FromPad = Bundle->Inputs[0];
3299 else
3300 FromPad = ConstantTokenNone::get(II->getContext());
3301 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
David Majnemer45ebda42016-03-01 18:59:50 +00003302 FromPad = CRI->getOperand(0);
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003303 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3304 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3305 FromPad = CSI;
3306 } else {
3307 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3308 }
3309
3310 // The edge may exit from zero or more nested pads.
David Majnemerf08579f2016-03-01 01:19:05 +00003311 SmallSet<Value *, 8> Seen;
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003312 for (;; FromPad = getParentPad(FromPad)) {
3313 Assert(FromPad != ToPad,
3314 "EH pad cannot handle exceptions raised within it", FromPad, TI);
3315 if (FromPad == ToPadParent) {
3316 // This is a legal unwind edge.
3317 break;
3318 }
3319 Assert(!isa<ConstantTokenNone>(FromPad),
3320 "A single unwind edge may only enter one EH pad", TI);
David Majnemerf08579f2016-03-01 01:19:05 +00003321 Assert(Seen.insert(FromPad).second,
3322 "EH pad jumps through a cycle of pads", FromPad);
David Majnemer8a1c45d2015-12-12 05:38:55 +00003323 }
David Majnemer85a549d2015-08-11 02:48:30 +00003324 }
3325}
3326
3327void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
Bill Wendlingfae14752011-08-12 20:24:12 +00003328 // The landingpad instruction is ill-formed if it doesn't have any clauses and
3329 // isn't a cleanup.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003330 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3331 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
Bill Wendlingfae14752011-08-12 20:24:12 +00003332
David Majnemer85a549d2015-08-11 02:48:30 +00003333 visitEHPadPredecessors(LPI);
Bill Wendlingfae14752011-08-12 20:24:12 +00003334
David Majnemer654e1302015-07-31 17:58:14 +00003335 if (!LandingPadResultTy)
3336 LandingPadResultTy = LPI.getType();
3337 else
3338 Assert(LandingPadResultTy == LPI.getType(),
3339 "The landingpad instruction should have a consistent result type "
3340 "inside a function.",
3341 &LPI);
3342
David Majnemer7fddecc2015-06-17 20:52:32 +00003343 Function *F = LPI.getParent()->getParent();
3344 Assert(F->hasPersonalityFn(),
3345 "LandingPadInst needs to be in a function with a personality.", &LPI);
3346
Bill Wendlingfae14752011-08-12 20:24:12 +00003347 // The landingpad instruction must be the first non-PHI instruction in the
3348 // block.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003349 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
3350 "LandingPadInst not the first non-PHI instruction in the block.",
3351 &LPI);
Bill Wendlingfae14752011-08-12 20:24:12 +00003352
Duncan Sands86de1a62011-09-27 16:43:19 +00003353 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00003354 Constant *Clause = LPI.getClause(i);
Duncan Sands68ba8132011-09-27 19:34:22 +00003355 if (LPI.isCatch(i)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003356 Assert(isa<PointerType>(Clause->getType()),
3357 "Catch operand does not have pointer type!", &LPI);
Duncan Sands68ba8132011-09-27 19:34:22 +00003358 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003359 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
3360 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3361 "Filter operand is not an array of constants!", &LPI);
Duncan Sands68ba8132011-09-27 19:34:22 +00003362 }
Duncan Sands86de1a62011-09-27 16:43:19 +00003363 }
3364
Bill Wendlingfae14752011-08-12 20:24:12 +00003365 visitInstruction(LPI);
3366}
3367
David Majnemerba6665d2016-08-01 18:06:34 +00003368void Verifier::visitResumeInst(ResumeInst &RI) {
3369 Assert(RI.getFunction()->hasPersonalityFn(),
3370 "ResumeInst needs to be in a function with a personality.", &RI);
3371
3372 if (!LandingPadResultTy)
3373 LandingPadResultTy = RI.getValue()->getType();
3374 else
3375 Assert(LandingPadResultTy == RI.getValue()->getType(),
3376 "The resume instruction should have a consistent result type "
3377 "inside a function.",
3378 &RI);
3379
3380 visitTerminatorInst(RI);
3381}
3382
David Majnemer654e1302015-07-31 17:58:14 +00003383void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
David Majnemer85a549d2015-08-11 02:48:30 +00003384 BasicBlock *BB = CPI.getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003385
David Majnemer654e1302015-07-31 17:58:14 +00003386 Function *F = BB->getParent();
3387 Assert(F->hasPersonalityFn(),
3388 "CatchPadInst needs to be in a function with a personality.", &CPI);
3389
David Majnemer8a1c45d2015-12-12 05:38:55 +00003390 Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
3391 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3392 CPI.getParentPad());
3393
David Majnemer654e1302015-07-31 17:58:14 +00003394 // The catchpad instruction must be the first non-PHI instruction in the
3395 // block.
3396 Assert(BB->getFirstNonPHI() == &CPI,
David Majnemer8a1c45d2015-12-12 05:38:55 +00003397 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
David Majnemer654e1302015-07-31 17:58:14 +00003398
David Majnemerfe2f7f32016-02-29 22:56:36 +00003399 visitEHPadPredecessors(CPI);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003400 visitFuncletPadInst(CPI);
David Majnemer654e1302015-07-31 17:58:14 +00003401}
3402
David Majnemer8a1c45d2015-12-12 05:38:55 +00003403void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
3404 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
3405 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3406 CatchReturn.getOperand(0));
David Majnemer654e1302015-07-31 17:58:14 +00003407
David Majnemer8a1c45d2015-12-12 05:38:55 +00003408 visitTerminatorInst(CatchReturn);
David Majnemer654e1302015-07-31 17:58:14 +00003409}
3410
3411void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3412 BasicBlock *BB = CPI.getParent();
3413
David Majnemer654e1302015-07-31 17:58:14 +00003414 Function *F = BB->getParent();
3415 Assert(F->hasPersonalityFn(),
3416 "CleanupPadInst needs to be in a function with a personality.", &CPI);
3417
3418 // The cleanuppad instruction must be the first non-PHI instruction in the
3419 // block.
3420 Assert(BB->getFirstNonPHI() == &CPI,
3421 "CleanupPadInst not the first non-PHI instruction in the block.",
3422 &CPI);
3423
David Majnemer8a1c45d2015-12-12 05:38:55 +00003424 auto *ParentPad = CPI.getParentPad();
Joseph Tremoulet06125e52016-01-02 15:24:24 +00003425 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003426 "CleanupPadInst has an invalid parent.", &CPI);
3427
David Majnemerfe2f7f32016-02-29 22:56:36 +00003428 visitEHPadPredecessors(CPI);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003429 visitFuncletPadInst(CPI);
3430}
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003431
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003432void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
3433 User *FirstUser = nullptr;
3434 Value *FirstUnwindPad = nullptr;
3435 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
David Majnemerf08579f2016-03-01 01:19:05 +00003436 SmallSet<FuncletPadInst *, 8> Seen;
David Majnemerfe2f7f32016-02-29 22:56:36 +00003437
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003438 while (!Worklist.empty()) {
3439 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
David Majnemerfe2f7f32016-02-29 22:56:36 +00003440 Assert(Seen.insert(CurrentPad).second,
3441 "FuncletPadInst must not be nested within itself", CurrentPad);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003442 Value *UnresolvedAncestorPad = nullptr;
3443 for (User *U : CurrentPad->users()) {
3444 BasicBlock *UnwindDest;
3445 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
3446 UnwindDest = CRI->getUnwindDest();
3447 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
3448 // We allow catchswitch unwind to caller to nest
3449 // within an outer pad that unwinds somewhere else,
3450 // because catchswitch doesn't have a nounwind variant.
3451 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
3452 if (CSI->unwindsToCaller())
3453 continue;
3454 UnwindDest = CSI->getUnwindDest();
3455 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
3456 UnwindDest = II->getUnwindDest();
3457 } else if (isa<CallInst>(U)) {
3458 // Calls which don't unwind may be found inside funclet
3459 // pads that unwind somewhere else. We don't *require*
3460 // such calls to be annotated nounwind.
3461 continue;
3462 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
3463 // The unwind dest for a cleanup can only be found by
3464 // recursive search. Add it to the worklist, and we'll
3465 // search for its first use that determines where it unwinds.
3466 Worklist.push_back(CPI);
3467 continue;
3468 } else {
3469 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
3470 continue;
3471 }
3472
3473 Value *UnwindPad;
3474 bool ExitsFPI;
3475 if (UnwindDest) {
3476 UnwindPad = UnwindDest->getFirstNonPHI();
David Majnemerfe2f7f32016-02-29 22:56:36 +00003477 if (!cast<Instruction>(UnwindPad)->isEHPad())
3478 continue;
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003479 Value *UnwindParent = getParentPad(UnwindPad);
3480 // Ignore unwind edges that don't exit CurrentPad.
3481 if (UnwindParent == CurrentPad)
3482 continue;
3483 // Determine whether the original funclet pad is exited,
3484 // and if we are scanning nested pads determine how many
3485 // of them are exited so we can stop searching their
3486 // children.
3487 Value *ExitedPad = CurrentPad;
3488 ExitsFPI = false;
3489 do {
3490 if (ExitedPad == &FPI) {
3491 ExitsFPI = true;
3492 // Now we can resolve any ancestors of CurrentPad up to
3493 // FPI, but not including FPI since we need to make sure
3494 // to check all direct users of FPI for consistency.
3495 UnresolvedAncestorPad = &FPI;
3496 break;
3497 }
3498 Value *ExitedParent = getParentPad(ExitedPad);
3499 if (ExitedParent == UnwindParent) {
3500 // ExitedPad is the ancestor-most pad which this unwind
3501 // edge exits, so we can resolve up to it, meaning that
3502 // ExitedParent is the first ancestor still unresolved.
3503 UnresolvedAncestorPad = ExitedParent;
3504 break;
3505 }
3506 ExitedPad = ExitedParent;
3507 } while (!isa<ConstantTokenNone>(ExitedPad));
3508 } else {
3509 // Unwinding to caller exits all pads.
3510 UnwindPad = ConstantTokenNone::get(FPI.getContext());
3511 ExitsFPI = true;
3512 UnresolvedAncestorPad = &FPI;
3513 }
3514
3515 if (ExitsFPI) {
3516 // This unwind edge exits FPI. Make sure it agrees with other
3517 // such edges.
3518 if (FirstUser) {
3519 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
3520 "pad must have the same unwind "
3521 "dest",
3522 &FPI, U, FirstUser);
3523 } else {
3524 FirstUser = U;
3525 FirstUnwindPad = UnwindPad;
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00003526 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
3527 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
3528 getParentPad(UnwindPad) == getParentPad(&FPI))
3529 SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003530 }
3531 }
3532 // Make sure we visit all uses of FPI, but for nested pads stop as
3533 // soon as we know where they unwind to.
3534 if (CurrentPad != &FPI)
3535 break;
3536 }
3537 if (UnresolvedAncestorPad) {
3538 if (CurrentPad == UnresolvedAncestorPad) {
3539 // When CurrentPad is FPI itself, we don't mark it as resolved even if
3540 // we've found an unwind edge that exits it, because we need to verify
3541 // all direct uses of FPI.
3542 assert(CurrentPad == &FPI);
3543 continue;
3544 }
3545 // Pop off the worklist any nested pads that we've found an unwind
3546 // destination for. The pads on the worklist are the uncles,
3547 // great-uncles, etc. of CurrentPad. We've found an unwind destination
3548 // for all ancestors of CurrentPad up to but not including
3549 // UnresolvedAncestorPad.
3550 Value *ResolvedPad = CurrentPad;
3551 while (!Worklist.empty()) {
3552 Value *UnclePad = Worklist.back();
3553 Value *AncestorPad = getParentPad(UnclePad);
3554 // Walk ResolvedPad up the ancestor list until we either find the
3555 // uncle's parent or the last resolved ancestor.
3556 while (ResolvedPad != AncestorPad) {
3557 Value *ResolvedParent = getParentPad(ResolvedPad);
3558 if (ResolvedParent == UnresolvedAncestorPad) {
3559 break;
3560 }
3561 ResolvedPad = ResolvedParent;
3562 }
3563 // If the resolved ancestor search didn't find the uncle's parent,
3564 // then the uncle is not yet resolved.
3565 if (ResolvedPad != AncestorPad)
3566 break;
3567 // This uncle is resolved, so pop it from the worklist.
3568 Worklist.pop_back();
3569 }
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003570 }
3571 }
3572
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003573 if (FirstUnwindPad) {
3574 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
3575 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
3576 Value *SwitchUnwindPad;
3577 if (SwitchUnwindDest)
3578 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
3579 else
3580 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
3581 Assert(SwitchUnwindPad == FirstUnwindPad,
3582 "Unwind edges out of a catch must have the same unwind dest as "
3583 "the parent catchswitch",
3584 &FPI, FirstUser, CatchSwitch);
3585 }
3586 }
3587
3588 visitInstruction(FPI);
David Majnemer654e1302015-07-31 17:58:14 +00003589}
3590
David Majnemer8a1c45d2015-12-12 05:38:55 +00003591void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003592 BasicBlock *BB = CatchSwitch.getParent();
3593
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003594 Function *F = BB->getParent();
3595 Assert(F->hasPersonalityFn(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003596 "CatchSwitchInst needs to be in a function with a personality.",
3597 &CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003598
David Majnemer8a1c45d2015-12-12 05:38:55 +00003599 // The catchswitch instruction must be the first non-PHI instruction in the
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003600 // block.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003601 Assert(BB->getFirstNonPHI() == &CatchSwitch,
3602 "CatchSwitchInst not the first non-PHI instruction in the block.",
3603 &CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003604
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00003605 auto *ParentPad = CatchSwitch.getParentPad();
3606 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3607 "CatchSwitchInst has an invalid parent.", ParentPad);
3608
David Majnemer8a1c45d2015-12-12 05:38:55 +00003609 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003610 Instruction *I = UnwindDest->getFirstNonPHI();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003611 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3612 "CatchSwitchInst must unwind to an EH block which is not a "
3613 "landingpad.",
3614 &CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003615
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00003616 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
3617 if (getParentPad(I) == ParentPad)
3618 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
3619 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003620
Joseph Tremoulet131a4622016-01-02 15:25:25 +00003621 Assert(CatchSwitch.getNumHandlers() != 0,
3622 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3623
Joseph Tremouletd425dd12016-01-02 15:50:34 +00003624 for (BasicBlock *Handler : CatchSwitch.handlers()) {
Joseph Tremoulet131a4622016-01-02 15:25:25 +00003625 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3626 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
Joseph Tremouletd425dd12016-01-02 15:50:34 +00003627 }
Joseph Tremoulet131a4622016-01-02 15:25:25 +00003628
David Majnemerfe2f7f32016-02-29 22:56:36 +00003629 visitEHPadPredecessors(CatchSwitch);
David Majnemer8a1c45d2015-12-12 05:38:55 +00003630 visitTerminatorInst(CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003631}
3632
David Majnemer654e1302015-07-31 17:58:14 +00003633void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003634 Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
3635 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
3636 CRI.getOperand(0));
3637
David Majnemer654e1302015-07-31 17:58:14 +00003638 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3639 Instruction *I = UnwindDest->getFirstNonPHI();
3640 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3641 "CleanupReturnInst must unwind to an EH block which is not a "
3642 "landingpad.",
3643 &CRI);
3644 }
3645
3646 visitTerminatorInst(CRI);
3647}
3648
Rafael Espindola654320a2012-02-26 02:23:37 +00003649void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3650 Instruction *Op = cast<Instruction>(I.getOperand(i));
Rafael Espindola9a167352012-08-17 18:21:28 +00003651 // If the we have an invalid invoke, don't try to compute the dominance.
3652 // We already reject it in the invoke specific checks and the dominance
3653 // computation doesn't handle multiple edges.
3654 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3655 if (II->getNormalDest() == II->getUnwindDest())
3656 return;
3657 }
Rafael Espindola654320a2012-02-26 02:23:37 +00003658
Michael Kruseff379b62016-03-26 23:32:57 +00003659 // Quick check whether the def has already been encountered in the same block.
3660 // PHI nodes are not checked to prevent accepting preceeding PHIs, because PHI
3661 // uses are defined to happen on the incoming edge, not at the instruction.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +00003662 //
3663 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
3664 // wrapping an SSA value, assert that we've already encountered it. See
3665 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
Michael Kruseff379b62016-03-26 23:32:57 +00003666 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
3667 return;
3668
Rafael Espindola103c2cf2012-06-01 21:56:26 +00003669 const Use &U = I.getOperandUse(i);
Michael Kruseff379b62016-03-26 23:32:57 +00003670 Assert(DT.dominates(Op, U),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003671 "Instruction does not dominate all uses!", Op, &I);
Rafael Espindola654320a2012-02-26 02:23:37 +00003672}
3673
Artur Pilipenkocca80022015-10-09 17:41:29 +00003674void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3675 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3676 "apply only to pointer types", &I);
3677 Assert(isa<LoadInst>(I),
3678 "dereferenceable, dereferenceable_or_null apply only to load"
3679 " instructions, use attributes for calls or invokes", &I);
3680 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3681 "take one operand!", &I);
3682 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3683 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3684 "dereferenceable_or_null metadata value must be an i64!", &I);
3685}
3686
Sanjoy Das3336f682016-12-11 20:07:15 +00003687/// Verify that \p BaseNode can be used as the "base type" in the struct-path
3688/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
3689/// struct-type node describing an aggregate data structure (like a struct).
3690Verifier::TBAABaseNodeSummary Verifier::verifyTBAABaseNode(Instruction &I,
3691 MDNode *BaseNode) {
3692 if (BaseNode->getNumOperands() < 2) {
3693 CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
3694 return {true, ~0u};
3695 }
3696
3697 auto Itr = TBAABaseNodes.find(BaseNode);
3698 if (Itr != TBAABaseNodes.end())
3699 return Itr->second;
3700
3701 auto Result = verifyTBAABaseNodeImpl(I, BaseNode);
3702 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
3703 (void)InsertResult;
3704 assert(InsertResult.second && "We just checked!");
3705 return Result;
3706}
3707
3708Verifier::TBAABaseNodeSummary
3709Verifier::verifyTBAABaseNodeImpl(Instruction &I, MDNode *BaseNode) {
3710 const Verifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
3711
3712 if (BaseNode->getNumOperands() == 2) {
3713 // This is a scalar base node.
3714 if (!BaseNode->getOperand(0) || !BaseNode->getOperand(1)) {
3715 CheckFailed("Null operands in scalar type nodes!", &I, BaseNode);
3716 return InvalidNode;
3717 }
3718 if (!isa<MDNode>(BaseNode->getOperand(1))) {
3719 CheckFailed("Invalid parent operand in scalar TBAA node", &I, BaseNode);
3720 return InvalidNode;
3721 }
3722 if (!isa<MDString>(BaseNode->getOperand(0))) {
3723 CheckFailed("Invalid name operand in scalar TBAA node", &I, BaseNode);
3724 return InvalidNode;
3725 }
3726
3727 // Scalar nodes can only be accessed at offset 0.
3728 return {false, 0};
3729 }
3730
3731 if (BaseNode->getNumOperands() % 2 != 1) {
3732 CheckFailed("Struct tag nodes must have an odd number of operands!",
3733 BaseNode);
3734 return InvalidNode;
3735 }
3736
3737 bool Failed = false;
3738
3739 Optional<APInt> PrevOffset;
3740 unsigned BitWidth = ~0u;
3741
3742 // We've already checked that BaseNode is not a degenerate root node with one
3743 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
3744 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) {
3745 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
3746 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
3747 if (!isa<MDNode>(FieldTy)) {
3748 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
3749 Failed = true;
3750 continue;
3751 }
3752
3753 auto *OffsetEntryCI =
3754 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
3755 if (!OffsetEntryCI) {
3756 CheckFailed("Offset entries must be constants!", &I, BaseNode);
3757 Failed = true;
3758 continue;
3759 }
3760
3761 if (BitWidth == ~0u)
3762 BitWidth = OffsetEntryCI->getBitWidth();
3763
3764 if (OffsetEntryCI->getBitWidth() != BitWidth) {
3765 CheckFailed(
3766 "Bitwidth between the offsets and struct type entries must match", &I,
3767 BaseNode);
3768 Failed = true;
3769 continue;
3770 }
3771
3772 // NB! As far as I can tell, we generate a non-strictly increasing offset
3773 // sequence only from structs that have zero size bit fields. When
3774 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
3775 // pick the field lexically the latest in struct type metadata node. This
3776 // mirrors the actual behavior of the alias analysis implementation.
3777 bool IsAscending =
3778 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
3779
3780 if (!IsAscending) {
3781 CheckFailed("Offsets must be increasing!", &I, BaseNode);
3782 Failed = true;
3783 }
3784
3785 PrevOffset = OffsetEntryCI->getValue();
3786 }
3787
3788 return Failed ? InvalidNode : Verifier::TBAABaseNodeSummary(false, BitWidth);
3789}
3790
3791static bool IsRootTBAANode(const MDNode *MD) {
3792 return MD->getNumOperands() < 2;
3793}
3794
3795static bool IsScalarTBAANodeImpl(const MDNode *MD,
3796 SmallPtrSetImpl<const MDNode *> &Visited) {
3797 if (MD->getNumOperands() == 2)
3798 return true;
3799
3800 if (MD->getNumOperands() != 3)
3801 return false;
3802
3803 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
3804 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
3805 return false;
3806
3807 auto *Parent = dyn_cast<MDNode>(MD->getOperand(1));
3808 return Visited.insert(Parent).second &&
3809 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
3810}
3811
3812static bool IsScalarTBAANode(const MDNode *MD) {
3813 SmallPtrSet<const MDNode *, 4> Visited;
3814 return IsScalarTBAANodeImpl(MD, Visited);
3815}
3816
3817/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
3818/// Offset in place to be the offset within the field node returned.
3819///
3820/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
3821MDNode *Verifier::getFieldNodeFromTBAABaseNode(Instruction &I, MDNode *BaseNode,
3822 APInt &Offset) {
3823 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
3824
3825 // Scalar nodes have only one possible "field" -- their parent in the access
3826 // hierarchy. Offset must be zero at this point, but our caller is supposed
3827 // to Assert that.
3828 if (BaseNode->getNumOperands() == 2)
3829 return cast<MDNode>(BaseNode->getOperand(1));
3830
3831 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) {
3832 auto *OffsetEntryCI =
3833 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
3834 if (OffsetEntryCI->getValue().ugt(Offset)) {
3835 if (Idx == 1) {
3836 CheckFailed("Could not find TBAA parent in struct type node", &I,
3837 BaseNode, &Offset);
3838 return nullptr;
3839 }
3840
3841 auto *PrevOffsetEntryCI =
3842 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx - 1));
3843 Offset -= PrevOffsetEntryCI->getValue();
3844 return cast<MDNode>(BaseNode->getOperand(Idx - 2));
3845 }
3846 }
3847
3848 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
3849 BaseNode->getOperand(BaseNode->getNumOperands() - 1));
3850
3851 Offset -= LastOffsetEntryCI->getValue();
3852 return cast<MDNode>(BaseNode->getOperand(BaseNode->getNumOperands() - 2));
3853}
3854
Sanjoy Das2582e692016-11-08 20:46:01 +00003855void Verifier::visitTBAAMetadata(Instruction &I, MDNode *MD) {
3856 bool IsStructPathTBAA =
3857 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
3858
3859 Assert(IsStructPathTBAA,
3860 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
3861 &I);
Sanjoy Das3336f682016-12-11 20:07:15 +00003862
3863 Assert(MD->getNumOperands() < 5,
3864 "Struct tag metadata must have either 3 or 4 operands", &I, MD);
3865
3866 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
3867 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
3868
3869 if (MD->getNumOperands() == 4) {
3870 auto *IsImmutableCI =
3871 mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(3));
3872 Assert(IsImmutableCI,
3873 "Immutability tag on struct tag metadata must be a constant", &I,
3874 MD);
3875 Assert(IsImmutableCI->isZero() || IsImmutableCI->isOne(),
3876 "Immutability part of the struct tag metadata must be either 0 or 1",
3877 &I, MD);
3878 }
3879
3880 Assert(BaseNode && AccessType,
3881 "Malformed struct tag metadata: base and access-type "
3882 "should be non-null and point to Metadata nodes",
3883 &I, MD, BaseNode, AccessType);
3884
3885 Assert(IsScalarTBAANode(AccessType), "Access type node must be scalar", &I,
3886 MD, AccessType);
3887
3888 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
3889 Assert(OffsetCI, "Offset must be constant integer", &I, MD);
3890
3891 APInt Offset = OffsetCI->getValue();
3892 bool SeenAccessTypeInPath = false;
3893
3894 SmallPtrSet<MDNode *, 4> StructPath;
3895
3896 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
3897 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset)) {
3898 if (!StructPath.insert(BaseNode).second) {
3899 CheckFailed("Cycle detected in struct path", &I, MD);
3900 return;
3901 }
3902
3903 bool Invalid;
3904 unsigned BaseNodeBitWidth;
3905 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode);
3906
3907 // If the base node is invalid in itself, then we've already printed all the
3908 // errors we wanted to print.
3909 if (Invalid)
3910 return;
3911
3912 SeenAccessTypeInPath |= BaseNode == AccessType;
3913
3914 if (IsScalarTBAANode(BaseNode) || BaseNode == AccessType)
3915 Assert(Offset == 0, "Offset not zero at the point of scalar access", &I,
3916 MD, &Offset);
3917
3918 Assert(BaseNodeBitWidth == Offset.getBitWidth() ||
3919 (BaseNodeBitWidth == 0 && Offset == 0),
3920 "Access bit-width not the same as description bit-width", &I, MD,
3921 BaseNodeBitWidth, Offset.getBitWidth());
3922 }
3923
3924 Assert(SeenAccessTypeInPath, "Did not see access type in access path!", &I,
3925 MD);
Sanjoy Das2582e692016-11-08 20:46:01 +00003926}
3927
Misha Brukmanc566ca362004-03-02 00:22:19 +00003928/// verifyInstruction - Verify that an instruction is well formed.
3929///
Chris Lattner069a7952002-06-25 15:56:27 +00003930void Verifier::visitInstruction(Instruction &I) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003931 BasicBlock *BB = I.getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003932 Assert(BB, "Instruction not embedded in basic block!", &I);
Chris Lattner0e851da2002-04-18 20:37:37 +00003933
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003934 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
Ahmed Charles821b6662014-03-09 04:57:09 +00003935 for (User *U : I.users()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003936 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3937 "Only PHI nodes may reference their own value!", &I);
Ahmed Charles821b6662014-03-09 04:57:09 +00003938 }
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003939 }
Nick Lewycky3fc89802009-09-07 20:44:51 +00003940
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003941 // Check that void typed values don't have names
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003942 Assert(!I.getType()->isVoidTy() || !I.hasName(),
3943 "Instruction has a name, but provides a void value!", &I);
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003944
Chris Lattner5f126b72004-03-29 00:29:36 +00003945 // Check that the return value of the instruction is either void or a legal
3946 // value type.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003947 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3948 "Instruction returns a non-scalar type!", &I);
Chris Lattner5f126b72004-03-29 00:29:36 +00003949
Nick Lewycky93e06a52009-09-27 23:27:42 +00003950 // Check that the instruction doesn't produce metadata. Calls are already
3951 // checked against the callee type.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003952 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3953 "Invalid use of metadata!", &I);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00003954
Chris Lattner0e851da2002-04-18 20:37:37 +00003955 // Check that all uses of the instruction, if they are instructions
3956 // themselves, actually have parent basic blocks. If the use is not an
3957 // instruction, it is an error!
Chandler Carruthcdf47882014-03-09 03:16:01 +00003958 for (Use &U : I.uses()) {
3959 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003960 Assert(Used->getParent() != nullptr,
3961 "Instruction referencing"
3962 " instruction not embedded in a basic block!",
3963 &I, Used);
Nick Lewycky984161a2009-09-08 02:02:39 +00003964 else {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003965 CheckFailed("Use of instruction is not an instruction!", U);
Nick Lewycky984161a2009-09-08 02:02:39 +00003966 return;
3967 }
Chris Lattner0e851da2002-04-18 20:37:37 +00003968 }
3969
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003970 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003971 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
Chris Lattnerb7e1ef52006-07-11 20:29:49 +00003972
3973 // Check to make sure that only first-class-values are operands to
3974 // instructions.
Devang Patel1f00b532008-02-21 01:54:02 +00003975 if (!I.getOperand(i)->getType()->isFirstClassType()) {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00003976 Assert(false, "Instruction operands must be first-class values!", &I);
Devang Patel1f00b532008-02-21 01:54:02 +00003977 }
Nick Lewyckyadbc2842009-05-30 05:06:04 +00003978
Chris Lattner9ece94b2004-03-14 03:23:54 +00003979 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
Chris Lattnerb7e1ef52006-07-11 20:29:49 +00003980 // Check to make sure that the "address of" an intrinsic function is never
3981 // taken.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003982 Assert(
Justin Lebar9cbc3012016-07-28 23:58:15 +00003983 !F->isIntrinsic() ||
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003984 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3985 "Cannot take the address of an intrinsic!", &I);
3986 Assert(
3987 !F->isIntrinsic() || isa<CallInst>(I) ||
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00003988 F->getIntrinsicID() == Intrinsic::donothing ||
David Majnemerf93082e2016-08-04 20:30:07 +00003989 F->getIntrinsicID() == Intrinsic::coro_resume ||
3990 F->getIntrinsicID() == Intrinsic::coro_destroy ||
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00003991 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
Igor Laevsky9570ff92015-02-19 11:28:47 +00003992 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3993 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
David Majnemerf93082e2016-08-04 20:30:07 +00003994 "Cannot invoke an intrinsic other than donothing, patchpoint, "
3995 "statepoint, coro_resume or coro_destroy",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003996 &I);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003997 Assert(F->getParent() == &M, "Referencing function in another module!",
3998 &I, &M, F, F->getParent());
Chris Lattner9ece94b2004-03-14 03:23:54 +00003999 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004000 Assert(OpBB->getParent() == BB->getParent(),
4001 "Referring to a basic block in another function!", &I);
Chris Lattner9ece94b2004-03-14 03:23:54 +00004002 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004003 Assert(OpArg->getParent() == BB->getParent(),
4004 "Referring to an argument in another function!", &I);
Chris Lattner4ff04522007-04-20 21:48:08 +00004005 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004006 Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
4007 &M, GV, GV->getParent());
Rafael Espindola654320a2012-02-26 02:23:37 +00004008 } else if (isa<Instruction>(I.getOperand(i))) {
4009 verifyDominatesUse(I, i);
Chris Lattner41eb5cd2006-01-26 00:08:45 +00004010 } else if (isa<InlineAsm>(I.getOperand(i))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004011 Assert((i + 1 == e && isa<CallInst>(I)) ||
4012 (i + 3 == e && isa<InvokeInst>(I)),
4013 "Cannot take the address of an inline asm!", &I);
Matt Arsenault24b49c42013-07-31 17:49:08 +00004014 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
Sanjoy Dase1129ee2016-08-02 02:55:57 +00004015 if (CE->getType()->isPtrOrPtrVectorTy() ||
4016 !DL.getNonIntegralAddressSpaces().empty()) {
Matt Arsenault24b49c42013-07-31 17:49:08 +00004017 // If we have a ConstantExpr pointer, we need to see if it came from an
Sanjoy Dase1129ee2016-08-02 02:55:57 +00004018 // illegal bitcast. If the datalayout string specifies non-integral
4019 // address spaces then we also need to check for illegal ptrtoint and
4020 // inttoptr expressions.
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00004021 visitConstantExprsRecursively(CE);
Matt Arsenault24b49c42013-07-31 17:49:08 +00004022 }
Chris Lattnerdf9779c2003-10-05 17:44:18 +00004023 }
4024 }
Rafael Espindolaef9f5502012-03-24 00:14:51 +00004025
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00004026 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004027 Assert(I.getType()->isFPOrFPVectorTy(),
4028 "fpmath requires a floating point result!", &I);
4029 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004030 if (ConstantFP *CFP0 =
4031 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00004032 const APFloat &Accuracy = CFP0->getValueAPF();
Matt Arsenault82f41512016-06-27 19:43:15 +00004033 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle,
4034 "fpmath accuracy must have float type", &I);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004035 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
4036 "fpmath accuracy not a positive number!", &I);
Duncan Sands05f4df82012-04-16 16:28:59 +00004037 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004038 Assert(false, "invalid fpmath accuracy!", &I);
Duncan Sands05f4df82012-04-16 16:28:59 +00004039 }
Duncan Sandsaf06b262012-04-10 08:22:43 +00004040 }
4041
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00004042 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004043 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
4044 "Ranges are only for loads, calls and invokes!", &I);
Philip Reamesbf9676f2014-10-20 23:52:07 +00004045 visitRangeMetadata(I, Range, I.getType());
4046 }
Rafael Espindolaef9f5502012-03-24 00:14:51 +00004047
Philip Reames0ca58b32014-10-21 20:56:29 +00004048 if (I.getMetadata(LLVMContext::MD_nonnull)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004049 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
4050 &I);
4051 Assert(isa<LoadInst>(I),
4052 "nonnull applies only to load instructions, use attributes"
4053 " for calls or invokes",
4054 &I);
Philip Reames0ca58b32014-10-21 20:56:29 +00004055 }
4056
Artur Pilipenkocca80022015-10-09 17:41:29 +00004057 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
4058 visitDereferenceableMetadata(I, MD);
4059
4060 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
4061 visitDereferenceableMetadata(I, MD);
4062
Sanjoy Das3336f682016-12-11 20:07:15 +00004063 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa)) {
4064 Assert(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
4065 isa<VAArgInst>(I),
4066 "TBAA is only for loads, stores and calls!", &I);
4067 visitTBAAMetadata(I, TBAA);
4068 }
Sanjoy Das2582e692016-11-08 20:46:01 +00004069
Artur Pilipenkocca80022015-10-09 17:41:29 +00004070 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
4071 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
4072 &I);
4073 Assert(isa<LoadInst>(I), "align applies only to load instructions, "
4074 "use attributes for calls or invokes", &I);
4075 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
4076 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4077 Assert(CI && CI->getType()->isIntegerTy(64),
4078 "align metadata value must be an i64!", &I);
4079 uint64_t Align = CI->getZExtValue();
4080 Assert(isPowerOf2_64(Align),
4081 "align metadata value must be a power of 2!", &I);
4082 Assert(Align <= Value::MaximumAlignment,
4083 "alignment is larger that implementation defined limit", &I);
4084 }
4085
Duncan P. N. Exon Smitha3bdc322015-03-20 19:26:58 +00004086 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00004087 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
Duncan P. N. Exon Smithfc25da12015-03-24 17:32:19 +00004088 visitMDNode(*N);
Duncan P. N. Exon Smitha3bdc322015-03-20 19:26:58 +00004089 }
4090
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00004091 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
Adrian Prantl941fa752016-12-05 18:04:47 +00004092 verifyFragmentExpression(*DII);
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00004093
Chris Lattnerc9e79d02004-09-29 20:07:45 +00004094 InstsInThisBlock.insert(&I);
Chris Lattnerbb346d02003-05-08 03:47:33 +00004095}
4096
Philip Reames007561a2015-06-26 22:21:52 +00004097/// Allow intrinsics to be verified in different ways.
4098void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
Philip Reames9818dd72015-06-26 22:04:34 +00004099 Function *IF = CS.getCalledFunction();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004100 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
4101 IF);
Nick Lewycky3fc89802009-09-07 20:44:51 +00004102
Chris Lattner144b6192012-05-27 19:37:05 +00004103 // Verify that the intrinsic prototype lines up with what the .td files
4104 // describe.
4105 FunctionType *IFTy = IF->getFunctionType();
Andrew Tricka2efd992013-10-31 17:18:11 +00004106 bool IsVarArg = IFTy->isVarArg();
Matt Arsenaultc4c92262013-07-20 17:46:00 +00004107
Chris Lattner144b6192012-05-27 19:37:05 +00004108 SmallVector<Intrinsic::IITDescriptor, 8> Table;
4109 getIntrinsicInfoTableEntries(ID, Table);
4110 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
Nick Lewycky3fc89802009-09-07 20:44:51 +00004111
Chris Lattner144b6192012-05-27 19:37:05 +00004112 SmallVector<Type *, 4> ArgTys;
Artur Pilipenkobc552272016-06-22 14:56:33 +00004113 Assert(!Intrinsic::matchIntrinsicType(IFTy->getReturnType(),
4114 TableRef, ArgTys),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004115 "Intrinsic has incorrect return type!", IF);
Chris Lattner144b6192012-05-27 19:37:05 +00004116 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
Artur Pilipenkobc552272016-06-22 14:56:33 +00004117 Assert(!Intrinsic::matchIntrinsicType(IFTy->getParamType(i),
4118 TableRef, ArgTys),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004119 "Intrinsic has incorrect argument type!", IF);
Andrew Tricka2efd992013-10-31 17:18:11 +00004120
4121 // Verify if the intrinsic call matches the vararg property.
4122 if (IsVarArg)
Artur Pilipenkob68b8212016-06-24 14:47:27 +00004123 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004124 "Intrinsic was not defined with variable arguments!", IF);
Andrew Tricka2efd992013-10-31 17:18:11 +00004125 else
Artur Pilipenkob68b8212016-06-24 14:47:27 +00004126 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004127 "Callsite was not defined with variable arguments!", IF);
Andrew Tricka2efd992013-10-31 17:18:11 +00004128
4129 // All descriptors should be absorbed by now.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004130 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
Chris Lattner144b6192012-05-27 19:37:05 +00004131
4132 // Now that we have the intrinsic ID and the actual argument types (and we
4133 // know they are legal for the intrinsic!) get the intrinsic name through the
4134 // usual means. This allows us to verify the mangling of argument types into
4135 // the name.
Justin Bogner28e1cf62014-03-10 21:22:44 +00004136 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004137 Assert(ExpectedName == IF->getName(),
4138 "Intrinsic name not mangled correctly for type arguments! "
4139 "Should be: " +
4140 ExpectedName,
4141 IF);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00004142
Chris Lattner588096e2009-12-28 09:07:21 +00004143 // If the intrinsic takes MDNode arguments, verify that they are either global
4144 // or are local to *this* function.
Philip Reames007561a2015-06-26 22:21:52 +00004145 for (Value *V : CS.args())
4146 if (auto *MD = dyn_cast<MetadataAsValue>(V))
4147 visitMetadataAsValue(*MD, CS.getCaller());
Victor Hernandez0471abd2009-12-18 20:09:14 +00004148
Gordon Henriksena2f3e132007-09-17 20:30:04 +00004149 switch (ID) {
4150 default:
4151 break;
Gor Nishanov0f303ac2016-08-12 05:45:49 +00004152 case Intrinsic::coro_id: {
Gor Nishanovdce9b022016-08-29 14:34:12 +00004153 auto *InfoArg = CS.getArgOperand(3)->stripPointerCasts();
Gor Nishanov31d8c9a2016-08-06 02:16:35 +00004154 if (isa<ConstantPointerNull>(InfoArg))
4155 break;
4156 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4157 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
4158 "info argument of llvm.coro.begin must refer to an initialized "
4159 "constant");
4160 Constant *Init = GV->getInitializer();
4161 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4162 "info argument of llvm.coro.begin must refer to either a struct or "
4163 "an array");
4164 break;
4165 }
Chandler Carruth026cc372011-12-12 04:36:02 +00004166 case Intrinsic::ctlz: // llvm.ctlz
4167 case Intrinsic::cttz: // llvm.cttz
Philip Reames9818dd72015-06-26 22:04:34 +00004168 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004169 "is_zero_undef argument of bit counting intrinsics must be a "
4170 "constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00004171 CS);
Chandler Carruth026cc372011-12-12 04:36:02 +00004172 break;
Duncan P. N. Exon Smith959299e2015-03-15 00:50:57 +00004173 case Intrinsic::dbg_declare: // llvm.dbg.declare
Philip Reames9818dd72015-06-26 22:04:34 +00004174 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
4175 "invalid llvm.dbg.declare intrinsic call 1", CS);
4176 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004177 break;
4178 case Intrinsic::dbg_value: // llvm.dbg.value
Philip Reames9818dd72015-06-26 22:04:34 +00004179 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
Duncan P. N. Exon Smith959299e2015-03-15 00:50:57 +00004180 break;
Chris Lattnerdd708342008-11-21 16:42:48 +00004181 case Intrinsic::memcpy:
4182 case Intrinsic::memmove:
Owen Anderson63fbf102015-03-02 09:35:06 +00004183 case Intrinsic::memset: {
Philip Reames9818dd72015-06-26 22:04:34 +00004184 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004185 Assert(AlignCI,
4186 "alignment argument of memory intrinsics must be a constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00004187 CS);
Owen Anderson63fbf102015-03-02 09:35:06 +00004188 const APInt &AlignVal = AlignCI->getValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004189 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
Philip Reames9818dd72015-06-26 22:04:34 +00004190 "alignment argument of memory intrinsics must be a power of 2", CS);
Pete Cooper67cf9a72015-11-19 05:56:52 +00004191 Assert(isa<ConstantInt>(CS.getArgOperand(4)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004192 "isvolatile argument of memory intrinsics must be a constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00004193 CS);
Chris Lattnerecded9a2008-08-23 05:31:10 +00004194 break;
Owen Anderson63fbf102015-03-02 09:35:06 +00004195 }
Bill Wendling05604e02008-08-23 09:46:46 +00004196 case Intrinsic::gcroot:
4197 case Intrinsic::gcwrite:
Chris Lattner25852062008-08-24 20:46:13 +00004198 case Intrinsic::gcread:
4199 if (ID == Intrinsic::gcroot) {
Gordon Henriksenbf40eee2008-10-25 16:28:35 +00004200 AllocaInst *AI =
Philip Reames9818dd72015-06-26 22:04:34 +00004201 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
4202 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
4203 Assert(isa<Constant>(CS.getArgOperand(1)),
4204 "llvm.gcroot parameter #2 must be a constant.", CS);
David Blaikie96b48192015-05-11 23:09:25 +00004205 if (!AI->getAllocatedType()->isPointerTy()) {
Philip Reames9818dd72015-06-26 22:04:34 +00004206 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004207 "llvm.gcroot parameter #1 must either be a pointer alloca, "
4208 "or argument #2 must be a non-null constant.",
Philip Reames9818dd72015-06-26 22:04:34 +00004209 CS);
Talin2e59f142010-09-30 20:23:47 +00004210 }
Chris Lattner25852062008-08-24 20:46:13 +00004211 }
Nick Lewycky3fc89802009-09-07 20:44:51 +00004212
Philip Reames9818dd72015-06-26 22:04:34 +00004213 Assert(CS.getParent()->getParent()->hasGC(),
4214 "Enclosing function does not use GC.", CS);
Chris Lattner25852062008-08-24 20:46:13 +00004215 break;
Duncan Sandsf72ff0c2007-09-29 16:25:54 +00004216 case Intrinsic::init_trampoline:
Philip Reames9818dd72015-06-26 22:04:34 +00004217 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004218 "llvm.init_trampoline parameter #2 must resolve to a function.",
Philip Reames9818dd72015-06-26 22:04:34 +00004219 CS);
Gordon Henriksen9157c492007-12-25 02:02:10 +00004220 break;
Chris Lattner229f7652008-10-16 06:00:36 +00004221 case Intrinsic::prefetch:
Philip Reames9818dd72015-06-26 22:04:34 +00004222 Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
4223 isa<ConstantInt>(CS.getArgOperand(2)) &&
4224 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
4225 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
4226 "invalid arguments to llvm.prefetch", CS);
Chris Lattner229f7652008-10-16 06:00:36 +00004227 break;
Bill Wendlingd8e312d2008-11-18 23:09:31 +00004228 case Intrinsic::stackprotector:
Philip Reames9818dd72015-06-26 22:04:34 +00004229 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
4230 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
Bill Wendlingd8e312d2008-11-18 23:09:31 +00004231 break;
Nick Lewycky9bc89042009-10-13 07:57:33 +00004232 case Intrinsic::lifetime_start:
4233 case Intrinsic::lifetime_end:
4234 case Intrinsic::invariant_start:
Philip Reames9818dd72015-06-26 22:04:34 +00004235 Assert(isa<ConstantInt>(CS.getArgOperand(0)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004236 "size argument of memory use markers must be a constant integer",
Philip Reames9818dd72015-06-26 22:04:34 +00004237 CS);
Nick Lewycky9bc89042009-10-13 07:57:33 +00004238 break;
4239 case Intrinsic::invariant_end:
Philip Reames9818dd72015-06-26 22:04:34 +00004240 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
4241 "llvm.invariant.end parameter #2 must be a constant integer", CS);
Nick Lewycky9bc89042009-10-13 07:57:33 +00004242 break;
Reid Klecknere9b89312015-01-13 00:48:10 +00004243
Reid Kleckner60381792015-07-07 22:25:32 +00004244 case Intrinsic::localescape: {
Philip Reames9818dd72015-06-26 22:04:34 +00004245 BasicBlock *BB = CS.getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004246 Assert(BB == &BB->getParent()->front(),
Reid Kleckner60381792015-07-07 22:25:32 +00004247 "llvm.localescape used outside of entry block", CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004248 Assert(!SawFrameEscape,
Reid Kleckner60381792015-07-07 22:25:32 +00004249 "multiple calls to llvm.localescape in one function", CS);
Philip Reames9818dd72015-06-26 22:04:34 +00004250 for (Value *Arg : CS.args()) {
Reid Kleckner3567d272015-04-02 21:13:31 +00004251 if (isa<ConstantPointerNull>(Arg))
4252 continue; // Null values are allowed as placeholders.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004253 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004254 Assert(AI && AI->isStaticAlloca(),
Reid Kleckner60381792015-07-07 22:25:32 +00004255 "llvm.localescape only accepts static allocas", CS);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004256 }
Philip Reames9818dd72015-06-26 22:04:34 +00004257 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004258 SawFrameEscape = true;
Reid Klecknere9b89312015-01-13 00:48:10 +00004259 break;
4260 }
Reid Kleckner60381792015-07-07 22:25:32 +00004261 case Intrinsic::localrecover: {
Philip Reames9818dd72015-06-26 22:04:34 +00004262 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
Reid Klecknere9b89312015-01-13 00:48:10 +00004263 Function *Fn = dyn_cast<Function>(FnArg);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004264 Assert(Fn && !Fn->isDeclaration(),
Reid Kleckner60381792015-07-07 22:25:32 +00004265 "llvm.localrecover first "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004266 "argument must be function defined in this module",
Philip Reames9818dd72015-06-26 22:04:34 +00004267 CS);
4268 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
Reid Kleckner60381792015-07-07 22:25:32 +00004269 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00004270 CS);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004271 auto &Entry = FrameEscapeInfo[Fn];
4272 Entry.second = unsigned(
4273 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
Reid Klecknere9b89312015-01-13 00:48:10 +00004274 break;
4275 }
4276
Philip Reames1ffa9372015-01-30 23:28:05 +00004277 case Intrinsic::experimental_gc_statepoint:
Philip Reames9818dd72015-06-26 22:04:34 +00004278 Assert(!CS.isInlineAsm(),
4279 "gc.statepoint support for inline assembly unimplemented", CS);
4280 Assert(CS.getParent()->getParent()->hasGC(),
4281 "Enclosing function does not use GC.", CS);
Philip Reames0285c742015-02-03 23:18:47 +00004282
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004283 verifyStatepoint(CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004284 break;
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +00004285 case Intrinsic::experimental_gc_result: {
Philip Reames9818dd72015-06-26 22:04:34 +00004286 Assert(CS.getParent()->getParent()->hasGC(),
4287 "Enclosing function does not use GC.", CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004288 // Are we tied to a statepoint properly?
Philip Reames9818dd72015-06-26 22:04:34 +00004289 CallSite StatepointCS(CS.getArgOperand(0));
Philip Reames76ebd152015-01-07 22:48:01 +00004290 const Function *StatepointFn =
4291 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004292 Assert(StatepointFn && StatepointFn->isDeclaration() &&
4293 StatepointFn->getIntrinsicID() ==
4294 Intrinsic::experimental_gc_statepoint,
Philip Reames9818dd72015-06-26 22:04:34 +00004295 "gc.result operand #1 must be from a statepoint", CS,
4296 CS.getArgOperand(0));
Philip Reames38303a32014-12-03 19:53:15 +00004297
Philip Reamesb23713a2014-12-03 22:23:24 +00004298 // Assert that result type matches wrapped callee.
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004299 const Value *Target = StatepointCS.getArgument(2);
Craig Toppere3dcce92015-08-01 22:20:21 +00004300 auto *PT = cast<PointerType>(Target->getType());
4301 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
Philip Reames9818dd72015-06-26 22:04:34 +00004302 Assert(CS.getType() == TargetFuncType->getReturnType(),
4303 "gc.result result type does not match wrapped callee", CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004304 break;
4305 }
4306 case Intrinsic::experimental_gc_relocate: {
Philip Reames9818dd72015-06-26 22:04:34 +00004307 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
Igor Laevsky9570ff92015-02-19 11:28:47 +00004308
Philip Reames3e2cf532016-01-07 03:32:11 +00004309 Assert(isa<PointerType>(CS.getType()->getScalarType()),
4310 "gc.relocate must return a pointer or a vector of pointers", CS);
4311
Igor Laevsky9570ff92015-02-19 11:28:47 +00004312 // Check that this relocate is correctly tied to the statepoint
4313
4314 // This is case for relocate on the unwinding path of an invoke statepoint
Chen Lid71999e2015-12-26 07:54:32 +00004315 if (LandingPadInst *LandingPad =
4316 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) {
Igor Laevsky9570ff92015-02-19 11:28:47 +00004317
Sanjoy Das5665c992015-05-11 23:47:27 +00004318 const BasicBlock *InvokeBB =
Chen Lid71999e2015-12-26 07:54:32 +00004319 LandingPad->getParent()->getUniquePredecessor();
Igor Laevsky9570ff92015-02-19 11:28:47 +00004320
4321 // Landingpad relocates should have only one predecessor with invoke
4322 // statepoint terminator
Sanjoy Das5665c992015-05-11 23:47:27 +00004323 Assert(InvokeBB, "safepoints should have unique landingpads",
Chen Lid71999e2015-12-26 07:54:32 +00004324 LandingPad->getParent());
Sanjoy Das5665c992015-05-11 23:47:27 +00004325 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
4326 InvokeBB);
4327 Assert(isStatepoint(InvokeBB->getTerminator()),
4328 "gc relocate should be linked to a statepoint", InvokeBB);
Igor Laevsky9570ff92015-02-19 11:28:47 +00004329 }
4330 else {
4331 // In all other cases relocate should be tied to the statepoint directly.
4332 // This covers relocates on a normal return path of invoke statepoint and
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004333 // relocates of a call statepoint.
Philip Reames9818dd72015-06-26 22:04:34 +00004334 auto Token = CS.getArgOperand(0);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004335 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
Philip Reames9818dd72015-06-26 22:04:34 +00004336 "gc relocate is incorrectly tied to the statepoint", CS, Token);
Igor Laevsky9570ff92015-02-19 11:28:47 +00004337 }
4338
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004339 // Verify rest of the relocate arguments.
Igor Laevsky9570ff92015-02-19 11:28:47 +00004340
Manuel Jacob83eefa62016-01-05 04:03:00 +00004341 ImmutableCallSite StatepointCS(
4342 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint());
Philip Reames337c4bd2014-12-01 21:18:12 +00004343
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004344 // Both the base and derived must be piped through the safepoint.
Philip Reames9818dd72015-06-26 22:04:34 +00004345 Value* Base = CS.getArgOperand(1);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004346 Assert(isa<ConstantInt>(Base),
Philip Reames9818dd72015-06-26 22:04:34 +00004347 "gc.relocate operand #2 must be integer offset", CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004348
Philip Reames9818dd72015-06-26 22:04:34 +00004349 Value* Derived = CS.getArgOperand(2);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004350 Assert(isa<ConstantInt>(Derived),
Philip Reames9818dd72015-06-26 22:04:34 +00004351 "gc.relocate operand #3 must be integer offset", CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004352
4353 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
4354 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
4355 // Check the bounds
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004356 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
Philip Reames9818dd72015-06-26 22:04:34 +00004357 "gc.relocate: statepoint base index out of bounds", CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004358 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
Philip Reames9818dd72015-06-26 22:04:34 +00004359 "gc.relocate: statepoint derived index out of bounds", CS);
Philip Reames76ebd152015-01-07 22:48:01 +00004360
4361 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004362 // section of the statepoint's argument.
Owen Anderson3e7e67b2015-03-10 05:58:21 +00004363 Assert(StatepointCS.arg_size() > 0,
4364 "gc.statepoint: insufficient arguments");
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004365 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
Owen Andersona3c68fd2015-03-11 06:57:30 +00004366 "gc.statement: number of call arguments must be constant integer");
Owen Anderson3e7e67b2015-03-10 05:58:21 +00004367 const unsigned NumCallArgs =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004368 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
4369 Assert(StatepointCS.arg_size() > NumCallArgs + 5,
Owen Anderson3e7e67b2015-03-10 05:58:21 +00004370 "gc.statepoint: mismatch in number of call arguments");
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004371 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
Pat Gavlincc0431d2015-05-08 18:07:42 +00004372 "gc.statepoint: number of transition arguments must be "
4373 "a constant integer");
4374 const int NumTransitionArgs =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004375 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
4376 ->getZExtValue();
4377 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
Pat Gavlincc0431d2015-05-08 18:07:42 +00004378 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
Owen Andersona3c68fd2015-03-11 06:57:30 +00004379 "gc.statepoint: number of deoptimization arguments must be "
4380 "a constant integer");
Philip Reames76ebd152015-01-07 22:48:01 +00004381 const int NumDeoptArgs =
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004382 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))
4383 ->getZExtValue();
Pat Gavlincc0431d2015-05-08 18:07:42 +00004384 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
Philip Reames76ebd152015-01-07 22:48:01 +00004385 const int GCParamArgsEnd = StatepointCS.arg_size();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004386 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
4387 "gc.relocate: statepoint base index doesn't fall within the "
4388 "'gc parameters' section of the statepoint call",
Philip Reames9818dd72015-06-26 22:04:34 +00004389 CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004390 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
4391 "gc.relocate: statepoint derived index doesn't fall within the "
4392 "'gc parameters' section of the statepoint call",
Philip Reames9818dd72015-06-26 22:04:34 +00004393 CS);
Philip Reames38303a32014-12-03 19:53:15 +00004394
Philip Reames3e2cf532016-01-07 03:32:11 +00004395 // Relocated value must be either a pointer type or vector-of-pointer type,
4396 // but gc_relocate does not need to return the same pointer type as the
4397 // relocated pointer. It can be casted to the correct type later if it's
4398 // desired. However, they must have the same address space and 'vectorness'
Manuel Jacob83eefa62016-01-05 04:03:00 +00004399 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction());
Philip Reames3e2cf532016-01-07 03:32:11 +00004400 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(),
Philip Reames9818dd72015-06-26 22:04:34 +00004401 "gc.relocate: relocated value must be a gc pointer", CS);
Chen Li6d8635a2015-05-18 19:50:14 +00004402
Philip Reames3e2cf532016-01-07 03:32:11 +00004403 auto ResultType = CS.getType();
4404 auto DerivedType = Relocate.getDerivedPtr()->getType();
4405 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004406 "gc.relocate: vector relocates to vector and pointer to pointer",
4407 CS);
4408 Assert(
4409 ResultType->getPointerAddressSpace() ==
4410 DerivedType->getPointerAddressSpace(),
4411 "gc.relocate: relocating a pointer shouldn't change its address space",
4412 CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004413 break;
4414 }
Reid Kleckner72ba7042015-10-07 00:27:33 +00004415 case Intrinsic::eh_exceptioncode:
Joseph Tremoulet61efbc32015-09-03 09:15:32 +00004416 case Intrinsic::eh_exceptionpointer: {
4417 Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
4418 "eh.exceptionpointer argument must be a catchpad", CS);
4419 break;
4420 }
Philip Reamesf16d7812016-02-09 21:43:12 +00004421 case Intrinsic::masked_load: {
4422 Assert(CS.getType()->isVectorTy(), "masked_load: must return a vector", CS);
4423
4424 Value *Ptr = CS.getArgOperand(0);
4425 //Value *Alignment = CS.getArgOperand(1);
4426 Value *Mask = CS.getArgOperand(2);
4427 Value *PassThru = CS.getArgOperand(3);
4428 Assert(Mask->getType()->isVectorTy(),
4429 "masked_load: mask must be vector", CS);
4430
4431 // DataTy is the overloaded type
4432 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4433 Assert(DataTy == CS.getType(),
4434 "masked_load: return must match pointer type", CS);
4435 Assert(PassThru->getType() == DataTy,
4436 "masked_load: pass through and data type must match", CS);
4437 Assert(Mask->getType()->getVectorNumElements() ==
4438 DataTy->getVectorNumElements(),
4439 "masked_load: vector mask must be same length as data", CS);
4440 break;
4441 }
4442 case Intrinsic::masked_store: {
4443 Value *Val = CS.getArgOperand(0);
4444 Value *Ptr = CS.getArgOperand(1);
4445 //Value *Alignment = CS.getArgOperand(2);
4446 Value *Mask = CS.getArgOperand(3);
4447 Assert(Mask->getType()->isVectorTy(),
4448 "masked_store: mask must be vector", CS);
4449
4450 // DataTy is the overloaded type
4451 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4452 Assert(DataTy == Val->getType(),
4453 "masked_store: storee must match pointer type", CS);
4454 Assert(Mask->getType()->getVectorNumElements() ==
4455 DataTy->getVectorNumElements(),
4456 "masked_store: vector mask must be same length as data", CS);
4457 break;
4458 }
Sanjoy Dasb51325d2016-03-11 19:08:34 +00004459
Sanjoy Das021de052016-03-31 00:18:46 +00004460 case Intrinsic::experimental_guard: {
4461 Assert(CS.isCall(), "experimental_guard cannot be invoked", CS);
4462 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
4463 "experimental_guard must have exactly one "
4464 "\"deopt\" operand bundle");
4465 break;
4466 }
4467
Sanjoy Dasb51325d2016-03-11 19:08:34 +00004468 case Intrinsic::experimental_deoptimize: {
4469 Assert(CS.isCall(), "experimental_deoptimize cannot be invoked", CS);
4470 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
4471 "experimental_deoptimize must have exactly one "
4472 "\"deopt\" operand bundle");
4473 Assert(CS.getType() == CS.getInstruction()->getFunction()->getReturnType(),
4474 "experimental_deoptimize return type must match caller return type");
4475
4476 if (CS.isCall()) {
4477 auto *DeoptCI = CS.getInstruction();
4478 auto *RI = dyn_cast<ReturnInst>(DeoptCI->getNextNode());
4479 Assert(RI,
4480 "calls to experimental_deoptimize must be followed by a return");
4481
4482 if (!CS.getType()->isVoidTy() && RI)
4483 Assert(RI->getReturnValue() == DeoptCI,
4484 "calls to experimental_deoptimize must be followed by a return "
4485 "of the value computed by experimental_deoptimize");
4486 }
4487
4488 break;
4489 }
Philip Reames337c4bd2014-12-01 21:18:12 +00004490 };
Chris Lattner0e851da2002-04-18 20:37:37 +00004491}
4492
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004493/// \brief Carefully grab the subprogram from a local scope.
4494///
4495/// This carefully grabs the subprogram from a local scope, avoiding the
4496/// built-in assertions that would typically fire.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004497static DISubprogram *getSubprogram(Metadata *LocalScope) {
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004498 if (!LocalScope)
4499 return nullptr;
4500
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004501 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004502 return SP;
4503
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004504 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004505 return getSubprogram(LB->getRawScope());
4506
4507 // Just return null; broken scope chains are checked elsewhere.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004508 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004509 return nullptr;
4510}
4511
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004512template <class DbgIntrinsicTy>
4513void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
4514 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
Adrian Prantl541a9c52016-05-06 19:26:47 +00004515 AssertDI(isa<ValueAsMetadata>(MD) ||
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004516 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
4517 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
Adrian Prantl541a9c52016-05-06 19:26:47 +00004518 AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004519 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
4520 DII.getRawVariable());
Adrian Prantl541a9c52016-05-06 19:26:47 +00004521 AssertDI(isa<DIExpression>(DII.getRawExpression()),
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004522 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
4523 DII.getRawExpression());
Duncan P. N. Exon Smith81f522a2015-04-03 16:54:30 +00004524
4525 // Ignore broken !dbg attachments; they're checked elsewhere.
4526 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004527 if (!isa<DILocation>(N))
Duncan P. N. Exon Smith81f522a2015-04-03 16:54:30 +00004528 return;
4529
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004530 BasicBlock *BB = DII.getParent();
4531 Function *F = BB ? BB->getParent() : nullptr;
4532
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004533 // The scopes for variables and !dbg attachments must agree.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004534 DILocalVariable *Var = DII.getVariable();
4535 DILocation *Loc = DII.getDebugLoc();
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004536 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
4537 &DII, BB, F);
4538
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004539 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
4540 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004541 if (!VarSP || !LocSP)
4542 return; // Broken scope chains are checked elsewhere.
4543
Adrian Prantla2ef0472016-09-14 17:30:37 +00004544 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
4545 " variable and !dbg attachment",
4546 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
4547 Loc->getScope()->getSubprogram());
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004548}
4549
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00004550static uint64_t getVariableSize(const DILocalVariable &V) {
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004551 // Be careful of broken types (checked elsewhere).
4552 const Metadata *RawType = V.getRawType();
4553 while (RawType) {
4554 // Try to get the size directly.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004555 if (auto *T = dyn_cast<DIType>(RawType))
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004556 if (uint64_t Size = T->getSizeInBits())
4557 return Size;
4558
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004559 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004560 // Look at the base type.
4561 RawType = DT->getRawBaseType();
4562 continue;
4563 }
4564
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004565 // Missing type or size.
4566 break;
4567 }
4568
4569 // Fail gracefully.
4570 return 0;
4571}
4572
Adrian Prantl941fa752016-12-05 18:04:47 +00004573void Verifier::verifyFragmentExpression(const DbgInfoIntrinsic &I) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004574 DILocalVariable *V;
4575 DIExpression *E;
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004576 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004577 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
4578 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004579 } else {
4580 auto *DDI = cast<DbgDeclareInst>(&I);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004581 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
4582 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004583 }
4584
4585 // We don't know whether this intrinsic verified correctly.
4586 if (!V || !E || !E->isValid())
4587 return;
4588
Keno Fischer253a7bd2016-01-15 02:12:38 +00004589 // Nothing to do if this isn't a bit piece expression.
Adrian Prantl941fa752016-12-05 18:04:47 +00004590 if (!E->isFragment())
Keno Fischer253a7bd2016-01-15 02:12:38 +00004591 return;
4592
Adrian Prantlba6ec4b2015-04-29 16:52:17 +00004593 // The frontend helps out GDB by emitting the members of local anonymous
4594 // unions as artificial local variables with shared storage. When SROA splits
4595 // the storage for artificial local variables that are smaller than the entire
4596 // union, the overhang piece will be outside of the allotted space for the
4597 // variable and this check fails.
4598 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
4599 if (V->isArtificial())
4600 return;
4601
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004602 // If there's no size, the type is broken, but that should be checked
4603 // elsewhere.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00004604 uint64_t VarSize = getVariableSize(*V);
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004605 if (!VarSize)
4606 return;
4607
Adrian Prantl941fa752016-12-05 18:04:47 +00004608 unsigned FragSize = E->getFragmentSizeInBits();
4609 unsigned FragOffset = E->getFragmentOffsetInBits();
4610 AssertDI(FragSize + FragOffset <= VarSize,
4611 "fragment is larger than or outside of variable", &I, V, E);
4612 AssertDI(FragSize != VarSize, "fragment covers entire variable", &I, V, E);
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004613}
4614
Adrian Prantlfaebbb02016-03-28 21:06:26 +00004615void Verifier::verifyCompileUnits() {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004616 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
Adrian Prantlfaebbb02016-03-28 21:06:26 +00004617 SmallPtrSet<const Metadata *, 2> Listed;
4618 if (CUs)
4619 Listed.insert(CUs->op_begin(), CUs->op_end());
Adrian Prantla2ef0472016-09-14 17:30:37 +00004620 AssertDI(
David Majnemer0a16c222016-08-11 21:15:00 +00004621 all_of(CUVisited,
4622 [&Listed](const Metadata *CU) { return Listed.count(CU); }),
Adrian Prantlfaebbb02016-03-28 21:06:26 +00004623 "All DICompileUnits must be listed in llvm.dbg.cu");
4624 CUVisited.clear();
4625}
4626
Sanjoy Dase0aa4142016-05-12 01:17:38 +00004627void Verifier::verifyDeoptimizeCallingConvs() {
4628 if (DeoptimizeDeclarations.empty())
4629 return;
4630
4631 const Function *First = DeoptimizeDeclarations[0];
Sanjoy Das8d3b1792016-05-12 01:38:08 +00004632 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
Sanjoy Dase0aa4142016-05-12 01:17:38 +00004633 Assert(First->getCallingConv() == F->getCallingConv(),
4634 "All llvm.experimental.deoptimize declarations must have the same "
4635 "calling convention",
4636 First, F);
Sanjoy Das8d3b1792016-05-12 01:38:08 +00004637 }
Sanjoy Dase0aa4142016-05-12 01:17:38 +00004638}
4639
Chris Lattner0e851da2002-04-18 20:37:37 +00004640//===----------------------------------------------------------------------===//
4641// Implement the public interfaces to this file...
4642//===----------------------------------------------------------------------===//
4643
Chandler Carruth043949d2014-01-19 02:22:18 +00004644bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
Chandler Carruthbf2b6522014-01-17 11:09:34 +00004645 Function &F = const_cast<Function &>(f);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004646
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +00004647 // Don't use a raw_null_ostream. Printing IR is expensive.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004648 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
Chandler Carruth043949d2014-01-19 02:22:18 +00004649
4650 // Note that this function's return value is inverted from what you would
4651 // expect of a function called "verify".
4652 return !V.verify(F);
Chris Lattnerd02f08d2002-02-20 17:55:43 +00004653}
4654
Adrian Prantlfe7a3822016-05-09 19:57:15 +00004655bool llvm::verifyModule(const Module &M, raw_ostream *OS,
4656 bool *BrokenDebugInfo) {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +00004657 // Don't use a raw_null_ostream. Printing IR is expensive.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004658 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
Nick Lewycky3fc89802009-09-07 20:44:51 +00004659
Chandler Carruth043949d2014-01-19 02:22:18 +00004660 bool Broken = false;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00004661 for (const Function &F : M)
Peter Collingbournebb738172016-06-06 23:21:27 +00004662 Broken |= !V.verify(F);
Chandler Carruth043949d2014-01-19 02:22:18 +00004663
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004664 Broken |= !V.verify();
Adrian Prantlfe7a3822016-05-09 19:57:15 +00004665 if (BrokenDebugInfo)
4666 *BrokenDebugInfo = V.hasBrokenDebugInfo();
Chandler Carruth043949d2014-01-19 02:22:18 +00004667 // Note that this function's return value is inverted from what you would
4668 // expect of a function called "verify".
Adrian Prantlfe7a3822016-05-09 19:57:15 +00004669 return Broken;
Chris Lattner2f7c9632001-06-06 20:29:01 +00004670}
Chandler Carruth043949d2014-01-19 02:22:18 +00004671
4672namespace {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00004673
Chandler Carruth4d356312014-01-20 11:34:08 +00004674struct VerifierLegacyPass : public FunctionPass {
Chandler Carruth043949d2014-01-19 02:22:18 +00004675 static char ID;
4676
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004677 std::unique_ptr<Verifier> V;
Adrian Prantl94a903e2016-05-25 21:33:20 +00004678 bool FatalErrors = true;
Chandler Carruth043949d2014-01-19 02:22:18 +00004679
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004680 VerifierLegacyPass() : FunctionPass(ID) {
Chandler Carruth4d356312014-01-20 11:34:08 +00004681 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth043949d2014-01-19 02:22:18 +00004682 }
Chandler Carruth4d356312014-01-20 11:34:08 +00004683 explicit VerifierLegacyPass(bool FatalErrors)
Adrian Prantl541a9c52016-05-06 19:26:47 +00004684 : FunctionPass(ID),
Adrian Prantl541a9c52016-05-06 19:26:47 +00004685 FatalErrors(FatalErrors) {
Chandler Carruth4d356312014-01-20 11:34:08 +00004686 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth043949d2014-01-19 02:22:18 +00004687 }
4688
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004689 bool doInitialization(Module &M) override {
4690 V = llvm::make_unique<Verifier>(
4691 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
4692 return false;
4693 }
4694
Craig Topperf398d7c2014-03-05 06:35:38 +00004695 bool runOnFunction(Function &F) override {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004696 if (!V->verify(F) && FatalErrors)
Chandler Carruth043949d2014-01-19 02:22:18 +00004697 report_fatal_error("Broken function found, compilation aborted!");
4698
4699 return false;
4700 }
4701
Craig Topperf398d7c2014-03-05 06:35:38 +00004702 bool doFinalization(Module &M) override {
Peter Collingbournebb738172016-06-06 23:21:27 +00004703 bool HasErrors = false;
4704 for (Function &F : M)
4705 if (F.isDeclaration())
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004706 HasErrors |= !V->verify(F);
Peter Collingbournebb738172016-06-06 23:21:27 +00004707
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004708 HasErrors |= !V->verify();
Adrian Prantl94a903e2016-05-25 21:33:20 +00004709 if (FatalErrors) {
4710 if (HasErrors)
4711 report_fatal_error("Broken module found, compilation aborted!");
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004712 assert(!V->hasBrokenDebugInfo() && "Module contains invalid debug info");
Adrian Prantl94a903e2016-05-25 21:33:20 +00004713 }
Chandler Carruth043949d2014-01-19 02:22:18 +00004714
Adrian Prantl94a903e2016-05-25 21:33:20 +00004715 // Strip broken debug info.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004716 if (V->hasBrokenDebugInfo()) {
Adrian Prantl94a903e2016-05-25 21:33:20 +00004717 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M);
4718 M.getContext().diagnose(DiagInvalid);
4719 if (!StripDebugInfo(M))
4720 report_fatal_error("Failed to strip malformed debug info");
4721 }
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +00004722 return false;
4723 }
4724
4725 void getAnalysisUsage(AnalysisUsage &AU) const override {
4726 AU.setPreservesAll();
4727 }
4728};
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00004729
4730} // end anonymous namespace
Chandler Carruth043949d2014-01-19 02:22:18 +00004731
Chandler Carruth4d356312014-01-20 11:34:08 +00004732char VerifierLegacyPass::ID = 0;
4733INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
Chandler Carruth043949d2014-01-19 02:22:18 +00004734
4735FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
Chandler Carruth4d356312014-01-20 11:34:08 +00004736 return new VerifierLegacyPass(FatalErrors);
Chandler Carruth043949d2014-01-19 02:22:18 +00004737}
4738
Chandler Carruthdab4eae2016-11-23 17:53:26 +00004739AnalysisKey VerifierAnalysis::Key;
Chandler Carruth164a2aa62016-06-17 00:11:01 +00004740VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
4741 ModuleAnalysisManager &) {
Adrian Prantle3656182016-05-09 19:57:29 +00004742 Result Res;
4743 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
4744 return Res;
4745}
Chandler Carruth4d356312014-01-20 11:34:08 +00004746
Chandler Carruth164a2aa62016-06-17 00:11:01 +00004747VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
4748 FunctionAnalysisManager &) {
Adrian Prantle3656182016-05-09 19:57:29 +00004749 return { llvm::verifyFunction(F, &dbgs()), false };
4750}
4751
4752PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
4753 auto Res = AM.getResult<VerifierAnalysis>(M);
4754 if (FatalErrors) {
4755 if (Res.IRBroken)
4756 report_fatal_error("Broken module found, compilation aborted!");
4757 assert(!Res.DebugInfoBroken && "Module contains invalid debug info");
4758 }
4759
4760 // Strip broken debug info.
4761 if (Res.DebugInfoBroken) {
4762 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M);
4763 M.getContext().diagnose(DiagInvalid);
4764 if (!StripDebugInfo(M))
4765 report_fatal_error("Failed to strip malformed debug info");
4766 }
Chandler Carruth4d356312014-01-20 11:34:08 +00004767 return PreservedAnalyses::all();
4768}
4769
Adrian Prantle3656182016-05-09 19:57:29 +00004770PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
4771 auto res = AM.getResult<VerifierAnalysis>(F);
4772 if (res.IRBroken && FatalErrors)
Chandler Carruth4d356312014-01-20 11:34:08 +00004773 report_fatal_error("Broken function found, compilation aborted!");
4774
4775 return PreservedAnalyses::all();
4776}