LLVM 24.0.0git
Verifier.cpp
Go to the documentation of this file.
1//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the function verifier interface, that can be used for some
10// basic correctness checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * All basic blocks should only end with terminator insts, not contain them
27// * The entry node to a function must not have predecessors
28// * All Instructions must be embedded into a basic block
29// * Functions cannot take a void-typed parameter
30// * Verify that a function's argument list agrees with it's declared type.
31// * It is illegal to specify a name for a void value.
32// * It is illegal to have a internal global value with no initializer
33// * It is illegal to have a ret instruction that returns a value that does not
34// agree with the function return value type.
35// * Function call argument types match the function prototype
36// * A landing pad is defined by a landingpad instruction, and can be jumped to
37// only by the unwind edge of an invoke instruction.
38// * A landingpad instruction must be the first non-PHI instruction in the
39// block.
40// * Landingpad instructions must be in a function with a personality function.
41// * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42// The applied restrictions are too numerous to list here.
43// * The convergence entry intrinsic and the loop heart must be the first
44// non-PHI instruction in their respective block. This does not conflict with
45// the landing pads, since these two kinds cannot occur in the same block.
46// * All other things that are tested by asserts spread about the code...
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/IR/Verifier.h"
51#include "VerifierInternal.h"
52#include "llvm/ADT/APFloat.h"
53#include "llvm/ADT/APInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/MapVector.h"
57#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/StringRef.h"
62#include "llvm/ADT/Twine.h"
64#include "llvm/IR/Argument.h"
66#include "llvm/IR/Attributes.h"
67#include "llvm/IR/AutoUpgrade.h"
68#include "llvm/IR/BasicBlock.h"
70#include "llvm/IR/CFG.h"
71#include "llvm/IR/CallingConv.h"
72#include "llvm/IR/Comdat.h"
73#include "llvm/IR/Constant.h"
76#include "llvm/IR/Constants.h"
78#include "llvm/IR/DataLayout.h"
79#include "llvm/IR/DebugInfo.h"
81#include "llvm/IR/DebugLoc.h"
83#include "llvm/IR/Dominators.h"
85#include "llvm/IR/FPEnv.h"
86#include "llvm/IR/Function.h"
87#include "llvm/IR/GCStrategy.h"
89#include "llvm/IR/GlobalAlias.h"
90#include "llvm/IR/GlobalValue.h"
92#include "llvm/IR/InlineAsm.h"
93#include "llvm/IR/InstVisitor.h"
94#include "llvm/IR/InstrTypes.h"
95#include "llvm/IR/Instruction.h"
98#include "llvm/IR/Intrinsics.h"
99#include "llvm/IR/IntrinsicsAArch64.h"
100#include "llvm/IR/IntrinsicsARM.h"
101#include "llvm/IR/IntrinsicsNVPTX.h"
102#include "llvm/IR/IntrinsicsRISCV.h"
103#include "llvm/IR/IntrinsicsWebAssembly.h"
104#include "llvm/IR/LLVMContext.h"
106#include "llvm/IR/Metadata.h"
107#include "llvm/IR/Module.h"
109#include "llvm/IR/PassManager.h"
111#include "llvm/IR/Statepoint.h"
112#include "llvm/IR/Type.h"
113#include "llvm/IR/Use.h"
114#include "llvm/IR/User.h"
116#include "llvm/IR/Value.h"
118#include "llvm/Pass.h"
121#include "llvm/Support/Casting.h"
122#include "llvm/Support/CodeGen.h"
127#include "llvm/Support/ModRef.h"
133#include <algorithm>
134#include <cassert>
135#include <cstdint>
136#include <limits>
137#include <memory>
138#include <optional>
139#include <queue>
140#include <string>
141#include <utility>
142
143using namespace llvm;
144
146 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
147 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
148 "scopes are not dominating"));
149
150namespace {
151
152class Verifier : public InstVisitor<Verifier>, VerifierSupport {
153 friend class InstVisitor<Verifier>;
154 DominatorTree DT;
155
156 /// When verifying a basic block, keep track of all of the
157 /// instructions we have seen so far.
158 ///
159 /// This allows us to do efficient dominance checks for the case when an
160 /// instruction has an operand that is an instruction in the same block.
161 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
162
163 /// Keep track of the metadata nodes that have been checked already.
165
166 /// Keep track which DISubprogram is attached to which function.
168
169 /// For each visited DIScope, whether walking its scope chain reaches a
170 /// repeated node.
171 DenseMap<const Metadata *, bool> DIScopeChainReachesCycle;
172
173 /// Track all DICompileUnits visited.
175
176 /// The result type for a landingpad.
177 Type *LandingPadResultTy;
178
179 /// Whether we've seen a call to @llvm.localescape in this function
180 /// already.
181 bool SawFrameEscape;
182
183 /// Whether the current function has a DISubprogram attached to it.
184 bool HasDebugInfo = false;
185
186 /// Stores the count of how many objects were passed to llvm.localescape for a
187 /// given function and the largest index passed to llvm.localrecover.
189
190 // Maps catchswitches and cleanuppads that unwind to siblings to the
191 // terminators that indicate the unwind, used to detect cycles therein.
193
194 /// Cache which blocks are in which funclet, if an EH funclet personality is
195 /// in use. Otherwise empty.
196 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
197
198 /// Cache of constants visited in search of ConstantExprs.
199 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
200
201 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
202 SmallVector<const Function *, 4> DeoptimizeDeclarations;
203
204 /// Cache of attribute lists verified.
205 SmallPtrSet<const void *, 32> AttributeListsVisited;
206
207 // Verify that this GlobalValue is only used in this module.
208 // This map is used to avoid visiting uses twice. We can arrive at a user
209 // twice, if they have multiple operands. In particular for very large
210 // constant expressions, we can arrive at a particular user many times.
211 SmallPtrSet<const Value *, 32> GlobalValueVisited;
212
213 // Keeps track of duplicate function argument debug info.
215
216 TBAAVerifier TBAAVerifyHelper;
217 ConvergenceVerifier ConvergenceVerifyHelper;
218
219 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
220
221 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
222
223public:
224 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
225 const Module &M)
226 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
227 SawFrameEscape(false), TBAAVerifyHelper(this) {
228 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
229 }
230
231 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
232
233 bool verify(const Function &F) {
234 llvm::TimeTraceScope timeScope("Verifier");
235 assert(F.getParent() == &M &&
236 "An instance of this class only works with a specific module!");
237
238 // First ensure the function is well-enough formed to compute dominance
239 // information, and directly compute a dominance tree. We don't rely on the
240 // pass manager to provide this as it isolates us from a potentially
241 // out-of-date dominator tree and makes it significantly more complex to run
242 // this code outside of a pass manager.
243
244 // First check that every basic block has a terminator, otherwise we can't
245 // even inspect the CFG.
246 for (const BasicBlock &BB : F) {
247 if (!BB.empty() && BB.back().isTerminator())
248 continue;
249
250 if (OS) {
251 *OS << "Basic Block in function '" << F.getName()
252 << "' does not have terminator!\n";
253 BB.printAsOperand(*OS, true, MST);
254 *OS << "\n";
255 }
256 return false;
257 }
258
259 // FIXME: It's really gross that we have to cast away constness here.
260 if (!F.empty())
261 DT.recalculate(const_cast<Function &>(F));
262
263 auto FailureCB = [this](const Twine &Message) {
264 this->CheckFailed(Message);
265 };
266 ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
267
268 Broken = false;
269 // FIXME: We strip const here because the inst visitor strips const.
270 visit(const_cast<Function &>(F));
271 verifySiblingFuncletUnwinds();
272
273 if (ConvergenceVerifyHelper.sawTokens())
274 ConvergenceVerifyHelper.verify(DT);
275
276 InstsInThisBlock.clear();
277 DebugFnArgs.clear();
278 DIScopeChainReachesCycle.clear();
279 LandingPadResultTy = nullptr;
280 SawFrameEscape = false;
281 SiblingFuncletInfo.clear();
282 verifyNoAliasScopeDecl();
283 NoAliasScopeDecls.clear();
284
285 return !Broken;
286 }
287
288 /// Verify the module that this instance of \c Verifier was initialized with.
289 bool verify() {
290 Broken = false;
291
292 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
293 for (const Function &F : M)
294 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
295 DeoptimizeDeclarations.push_back(&F);
296
297 // Now that we've visited every function, verify that we never asked to
298 // recover a frame index that wasn't escaped.
299 verifyFrameRecoverIndices();
300 for (const GlobalVariable &GV : M.globals())
301 visitGlobalVariable(GV);
302
303 for (const GlobalAlias &GA : M.aliases())
304 visitGlobalAlias(GA);
305
306 for (const GlobalIFunc &GI : M.ifuncs())
307 visitGlobalIFunc(GI);
308
309 for (const NamedMDNode &NMD : M.named_metadata())
310 visitNamedMDNode(NMD);
311
312 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
313 visitComdat(SMEC.getValue());
314
315 visitModuleFlags();
316 visitModuleIdents();
317 visitModuleCommandLines();
318 visitModuleErrnoTBAA();
319
320 verifyCompileUnits();
321
322 verifyDeoptimizeCallingConvs();
323 DISubprogramAttachments.clear();
324 DIScopeChainReachesCycle.clear();
325 return !Broken;
326 }
327
328private:
329 /// Whether a metadata node is allowed to be, or contain, a DILocation.
330 enum class AreDebugLocsAllowed { No, Yes };
331
332 /// Metadata that should be treated as a range, with slightly different
333 /// requirements.
334 enum class RangeLikeMetadataKind {
335 Range, // MD_range
336 AbsoluteSymbol, // MD_absolute_symbol
337 NoaliasAddrspace // MD_noalias_addrspace
338 };
339
340 // Verification methods...
341 void visitGlobalValue(const GlobalValue &GV);
342 void visitGlobalVariable(const GlobalVariable &GV);
343 void visitGlobalAlias(const GlobalAlias &GA);
344 void visitGlobalIFunc(const GlobalIFunc &GI);
345 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
346 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
347 const GlobalAlias &A, const Constant &C);
348 void visitNamedMDNode(const NamedMDNode &NMD);
349 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
350 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
351 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
352 void visitDIArgList(const DIArgList &AL, Function *F);
353 void visitComdat(const Comdat &C);
354 void visitModuleIdents();
355 void visitModuleCommandLines();
356 void visitModuleErrnoTBAA();
357 void visitModuleFlags();
358 void visitModuleFlag(const MDNode *Op,
359 DenseMap<const MDString *, const MDNode *> &SeenIDs,
360 SmallVectorImpl<const MDNode *> &Requirements);
361 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
362 void visitFunction(const Function &F);
363 void visitBasicBlock(BasicBlock &BB);
364 void verifyRangeLikeMetadata(const Value &V, const MDNode *Range, Type *Ty,
365 RangeLikeMetadataKind Kind);
366 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
367 void visitNoFPClassMetadata(Instruction &I, MDNode *Range, Type *Ty);
368 void visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range, Type *Ty);
369 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
370 void visitNoFreeObjMetadata(Instruction &I, MDNode *MD);
371 void visitProfMetadata(Instruction &I, MDNode *MD);
372 void visitCallStackMetadata(MDNode *MD);
373 void visitMemProfMetadata(Instruction &I, MDNode *MD);
374 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
375 void visitCalleeTypeMetadata(Instruction &I, MDNode *MD);
376 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
377 void visitMMRAMetadata(Instruction &I, MDNode *MD);
378 void visitAnnotationMetadata(MDNode *Annotation);
379 void visitAliasScopeMetadata(const MDNode *MD);
380 void visitAliasScopeListMetadata(const MDNode *MD);
381 void visitAccessGroupMetadata(const MDNode *MD);
382 void visitCapturesMetadata(Instruction &I, const MDNode *Captures);
383 void visitAllocTokenMetadata(Instruction &I, MDNode *MD);
384 void visitInlineHistoryMetadata(Instruction &I, MDNode *MD);
385 void visitMemCacheHintMetadata(Instruction &I, MDNode *MD);
386
387#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
388#include "llvm/IR/Metadata.def"
389 void visitDIType(const DIType &N);
390 void visitDIScope(const DIScope &N);
391 void visitDIScopeChain(const DIScope &N);
392 bool hasDIScopeCycle(const Metadata *S);
393 DISubprogram *getSubprogram(Metadata *LocalScope);
394 void visitDIVariable(const DIVariable &N);
395 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
396 void visitDITemplateParameter(const DITemplateParameter &N);
397
398 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
399
400 void visit(DbgLabelRecord &DLR);
401 void visit(DbgVariableRecord &DVR);
402 // InstVisitor overrides...
403 using InstVisitor<Verifier>::visit;
404 void visitDbgRecords(Instruction &I);
405 void visit(Instruction &I);
406
407 void visitTruncInst(TruncInst &I);
408 void visitZExtInst(ZExtInst &I);
409 void visitSExtInst(SExtInst &I);
410 void visitFPTruncInst(FPTruncInst &I);
411 void visitFPExtInst(FPExtInst &I);
412 void visitFPToUIInst(FPToUIInst &I);
413 void visitFPToSIInst(FPToSIInst &I);
414 void visitUIToFPInst(UIToFPInst &I);
415 void visitSIToFPInst(SIToFPInst &I);
416 void visitIntToPtrInst(IntToPtrInst &I);
417 void checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V);
418 void visitPtrToAddrInst(PtrToAddrInst &I);
419 void visitPtrToIntInst(PtrToIntInst &I);
420 void visitBitCastInst(BitCastInst &I);
421 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
422 void visitPHINode(PHINode &PN);
423 void visitCallBase(CallBase &Call);
424 void visitUnaryOperator(UnaryOperator &U);
425 void visitBinaryOperator(BinaryOperator &B);
426 void visitICmpInst(ICmpInst &IC);
427 void visitFCmpInst(FCmpInst &FC);
428 void visitExtractElementInst(ExtractElementInst &EI);
429 void visitInsertElementInst(InsertElementInst &EI);
430 void visitShuffleVectorInst(ShuffleVectorInst &EI);
431 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
432 void visitCallInst(CallInst &CI);
433 void visitInvokeInst(InvokeInst &II);
434 void visitGetElementPtrInst(GetElementPtrInst &GEP);
435 void visitLoadInst(LoadInst &LI);
436 void visitStoreInst(StoreInst &SI);
437 void verifyDominatesUse(Instruction &I, unsigned i);
438 void visitInstruction(Instruction &I);
439 void visitTerminator(Instruction &I);
440 void visitCondBrInst(CondBrInst &BI);
441 void visitReturnInst(ReturnInst &RI);
442 void visitSwitchInst(SwitchInst &SI);
443 void visitIndirectBrInst(IndirectBrInst &BI);
444 void visitCallBrInst(CallBrInst &CBI);
445 void visitSelectInst(SelectInst &SI);
446 void visitUserOp1(Instruction &I);
447 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
448 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
449 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
450 void visitVPIntrinsic(VPIntrinsic &VPI);
451 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
452 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
453 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
454 void visitFenceInst(FenceInst &FI);
455 void visitAllocaInst(AllocaInst &AI);
456 void visitExtractValueInst(ExtractValueInst &EVI);
457 void visitInsertValueInst(InsertValueInst &IVI);
458 void visitEHPadPredecessors(Instruction &I);
459 void visitLandingPadInst(LandingPadInst &LPI);
460 void visitResumeInst(ResumeInst &RI);
461 void visitCatchPadInst(CatchPadInst &CPI);
462 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
463 void visitCleanupPadInst(CleanupPadInst &CPI);
464 void visitFuncletPadInst(FuncletPadInst &FPI);
465 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
466 void visitCleanupReturnInst(CleanupReturnInst &CRI);
467
468 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
469 void verifySwiftErrorValue(const Value *SwiftErrorVal);
470 void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
471 void verifyMustTailCall(CallInst &CI);
472 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
473 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
474 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
475 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
476 const Value *V);
477 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
478 const Value *V, bool IsIntrinsic, bool IsInlineAsm);
479 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
480 void verifyUnknownProfileMetadata(MDNode *MD);
481 void visitConstantExprsRecursively(const Constant *EntryC);
482 void visitConstantExpr(const ConstantExpr *CE);
483 void visitConstantPtrAuth(const ConstantPtrAuth *CPA);
484 void verifyInlineAsmCall(const CallBase &Call);
485 void verifyStatepoint(const CallBase &Call);
486 void verifyFrameRecoverIndices();
487 void verifySiblingFuncletUnwinds();
488
489 void verifyFragmentExpression(const DbgVariableRecord &I);
490 template <typename ValueOrMetadata>
491 void verifyFragmentExpression(const DIVariable &V,
493 ValueOrMetadata *Desc);
494 void verifyFnArgs(const DbgVariableRecord &DVR);
495 void verifyNotEntryValue(const DbgVariableRecord &I);
496
497 /// Module-level debug info verification...
498 void verifyCompileUnits();
499
500 /// Module-level verification that all @llvm.experimental.deoptimize
501 /// declarations share the same calling convention.
502 void verifyDeoptimizeCallingConvs();
503
504 void verifyAttachedCallBundle(const CallBase &Call,
505 const OperandBundleUse &BU);
506
507 /// Verify the llvm.experimental.noalias.scope.decl declarations
508 void verifyNoAliasScopeDecl();
509};
510
511} // end anonymous namespace
512
513/// We know that cond should be true, if not print an error message.
514#define Check(C, ...) \
515 do { \
516 if (!(C)) { \
517 CheckFailed(__VA_ARGS__); \
518 return; \
519 } \
520 } while (false)
521
522/// We know that a debug info condition should be true, if not print
523/// an error message.
524#define CheckDI(C, ...) \
525 do { \
526 if (!(C)) { \
527 DebugInfoCheckFailed(__VA_ARGS__); \
528 return; \
529 } \
530 } while (false)
531
532void Verifier::visitDbgRecords(Instruction &I) {
533 if (!I.DebugMarker)
534 return;
535 CheckDI(I.DebugMarker->MarkedInstr == &I,
536 "Instruction has invalid DebugMarker", &I);
537 CheckDI(!isa<PHINode>(&I) || !I.hasDbgRecords(),
538 "PHI Node must not have any attached DbgRecords", &I);
539 for (DbgRecord &DR : I.getDbgRecordRange()) {
540 CheckDI(DR.getMarker() == I.DebugMarker,
541 "DbgRecord had invalid DebugMarker", &I, &DR);
542 if (auto *Loc =
543 dyn_cast_or_null<DILocation>(DR.getDebugLoc().getAsMDNode()))
544 visitMDNode(*Loc, AreDebugLocsAllowed::Yes);
545 if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR)) {
546 visit(*DVR);
547 // These have to appear after `visit` for consistency with existing
548 // intrinsic behaviour.
549 verifyFragmentExpression(*DVR);
550 verifyNotEntryValue(*DVR);
551 } else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
552 visit(*DLR);
553 }
554 }
555}
556
557void Verifier::visit(Instruction &I) {
558 visitDbgRecords(I);
559 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
560 Check(I.getOperand(i) != nullptr, "Operand is null", &I);
562}
563
564// Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
565static void forEachUser(const Value *User,
567 llvm::function_ref<bool(const Value *)> Callback) {
568 if (!Visited.insert(User).second)
569 return;
570
572 while (!WorkList.empty()) {
573 const Value *Cur = WorkList.pop_back_val();
574 if (!Visited.insert(Cur).second)
575 continue;
576 if (Callback(Cur))
577 append_range(WorkList, Cur->materialized_users());
578 }
579}
580
581void Verifier::visitGlobalValue(const GlobalValue &GV) {
583 "Global is external, but doesn't have external or weak linkage!", &GV);
584
585 if (const auto *GO = dyn_cast<GlobalObject>(&GV)) {
586 if (const MDNode *Associated =
587 GO->getMetadata(LLVMContext::MD_associated)) {
588 Check(Associated->getNumOperands() == 1,
589 "associated metadata must have one operand", &GV, Associated);
590 const Metadata *Op = Associated->getOperand(0).get();
591 Check(Op, "associated metadata must have a global value", GO, Associated);
592
593 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
594 Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
595 if (VM) {
596 Check(isa<PointerType>(VM->getValue()->getType()),
597 "associated value must be pointer typed", GV, Associated);
598
599 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
600 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
601 "associated metadata must point to a GlobalObject", GO, Stripped);
602 Check(Stripped != GO,
603 "global values should not associate to themselves", GO,
604 Associated);
605 }
606 }
607
608 // FIXME: Why is getMetadata on GlobalValue protected?
609 if (const MDNode *AbsoluteSymbol =
610 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
611 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
612 DL.getIntPtrType(GO->getType()),
613 RangeLikeMetadataKind::AbsoluteSymbol);
614 }
615
616 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
617 Check(!GO->isDeclaration(),
618 "ref metadata must not be placed on a declaration", GO);
619
621 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
622 for (const MDNode *MD : MDs) {
623 Check(MD->getNumOperands() == 1, "ref metadata must have one operand",
624 &GV, MD);
625 const Metadata *Op = MD->getOperand(0).get();
626 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
627 Check(VM, "ref metadata must be ValueAsMetadata", GO, MD);
628 if (VM) {
629 Check(isa<PointerType>(VM->getValue()->getType()),
630 "ref value must be pointer typed", GV, MD);
631
632 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
633 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
634 "ref metadata must point to a GlobalObject", GO, Stripped);
635 Check(Stripped != GO, "values should not reference themselves", GO,
636 MD);
637 }
638 }
639 }
640
641 if (auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
642 Check(Props->getNumOperands() == 2,
643 "elf_section_properties metadata must have two operands", GO,
644 Props);
645 if (Props->getNumOperands() == 2) {
646 auto *Type = dyn_cast<ConstantAsMetadata>(Props->getOperand(0));
647 Check(Type, "type field must be ConstantAsMetadata", GO, Props);
648 auto *TypeInt = dyn_cast<ConstantInt>(Type->getValue());
649 Check(TypeInt, "type field must be ConstantInt", GO, Props);
650
651 auto *Entsize = dyn_cast<ConstantAsMetadata>(Props->getOperand(1));
652 Check(Entsize, "entsize field must be ConstantAsMetadata", GO, Props);
653 auto *EntsizeInt = dyn_cast<ConstantInt>(Entsize->getValue());
654 Check(EntsizeInt, "entsize field must be ConstantInt", GO, Props);
655 }
656 }
657 }
658
660 "Only global variables can have appending linkage!", &GV);
661
662 if (GV.hasAppendingLinkage()) {
663 const auto *GVar = dyn_cast<GlobalVariable>(&GV);
664 Check(GVar && GVar->getValueType()->isArrayTy(),
665 "Only global arrays can have appending linkage!", GVar);
666 }
667
668 if (GV.isDeclarationForLinker())
669 Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
670
671 if (GV.hasDLLExportStorageClass()) {
673 "dllexport GlobalValue must have default or protected visibility",
674 &GV);
675 }
676 if (GV.hasDLLImportStorageClass()) {
678 "dllimport GlobalValue must have default visibility", &GV);
679 Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
680 &GV);
681
682 Check((GV.isDeclaration() &&
685 "Global is marked as dllimport, but not external", &GV);
686 }
687
688 if (GV.isImplicitDSOLocal())
689 Check(GV.isDSOLocal(),
690 "GlobalValue with local linkage or non-default "
691 "visibility must be dso_local!",
692 &GV);
693
694 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
695 if (const auto *I = dyn_cast<Instruction>(V)) {
696 if (!I->getParent() || !I->getParent()->getParent())
697 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
698 I);
699 else if (I->getParent()->getParent()->getParent() != &M)
700 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
701 I->getParent()->getParent(),
702 I->getParent()->getParent()->getParent());
703 return false;
704 } else if (const auto *F = dyn_cast<Function>(V)) {
705 if (F->getParent() != &M)
706 CheckFailed("Global is used by function in a different module", &GV, &M,
707 F, F->getParent());
708 return false;
709 }
710 return true;
711 });
712}
713
714void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
715 Type *GVType = GV.getValueType();
716
717 if (MaybeAlign A = GV.getAlign()) {
718 Check(A->value() <= Value::MaximumAlignment,
719 "huge alignment values are unsupported", &GV);
720 }
721
722 if (GV.hasInitializer()) {
723 Check(GV.getInitializer()->getType() == GVType,
724 "Global variable initializer type does not match global "
725 "variable type!",
726 &GV);
728 "Global variable initializer must be sized", &GV);
729 visitConstantExprsRecursively(GV.getInitializer());
730 // If the global has common linkage, it must have a zero initializer and
731 // cannot be constant.
732 if (GV.hasCommonLinkage()) {
734 "'common' global must have a zero initializer!", &GV);
735 Check(!GV.isConstant(), "'common' global may not be marked constant!",
736 &GV);
737 Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
738 }
739 }
740
741 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
742 GV.getName() == "llvm.global_dtors")) {
744 "invalid linkage for intrinsic global variable", &GV);
746 "invalid uses of intrinsic global variable", &GV);
747
748 // Don't worry about emitting an error for it not being an array,
749 // visitGlobalValue will complain on appending non-array.
750 if (const auto *ATy = dyn_cast<ArrayType>(GVType)) {
751 const auto *STy = dyn_cast<StructType>(ATy->getElementType());
752 PointerType *FuncPtrTy =
753 PointerType::get(Context, DL.getProgramAddressSpace());
754 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
755 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
756 STy->getTypeAtIndex(1) == FuncPtrTy,
757 "wrong type for intrinsic global variable", &GV);
758 Check(STy->getNumElements() == 3,
759 "the third field of the element type is mandatory, "
760 "specify ptr null to migrate from the obsoleted 2-field form");
761 Type *ETy = STy->getTypeAtIndex(2);
762 Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
763 &GV);
764 }
765
766 auto *Init = GV.hasInitializer()
768 : nullptr;
769 if (Init) {
770 for (const Use &U : Init->operands()) {
771 auto *Structor = dyn_cast<ConstantStruct>(U);
772 if (!Structor || Structor->getNumOperands() != 3)
773 continue;
774 Check(!isa<ConstantPtrAuth>(Structor->getOperand(1)),
775 "signing of ctors/dtors should be requested via module flags");
776 }
777 }
778 }
779
780 if (GV.hasName() && (GV.getName() == "llvm.used" ||
781 GV.getName() == "llvm.compiler.used")) {
783 "invalid linkage for intrinsic global variable", &GV);
785 "invalid uses of intrinsic global variable", &GV);
786
787 if (const auto *ATy = dyn_cast<ArrayType>(GVType)) {
788 const auto *PTy = dyn_cast<PointerType>(ATy->getElementType());
789 Check(PTy, "wrong type for intrinsic global variable", &GV);
790 if (GV.hasInitializer()) {
791 const Constant *Init = GV.getInitializer();
792 const auto *InitArray = dyn_cast<ConstantArray>(Init);
793 Check(InitArray, "wrong initializer for intrinsic global variable",
794 Init);
795 for (Value *Op : InitArray->operands()) {
796 Value *V = Op->stripPointerCasts();
799 Twine("invalid ") + GV.getName() + " member", V);
800 Check(V->hasName(),
801 Twine("members of ") + GV.getName() + " must be named", V);
802 }
803 }
804 }
805 }
806
807 // Visit any debug info attachments.
809 GV.getMetadata(LLVMContext::MD_dbg, MDs);
810 for (MDNode *MD : MDs) {
811 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
812 visitDIGlobalVariableExpression(*GVE);
813 else
814 CheckDI(false, "!dbg attachment of global variable must be a "
815 "DIGlobalVariableExpression");
816 }
817
818 // Scalable vectors cannot be global variables, since we don't know
819 // the runtime size.
820 Check(!GVType->isScalableTy(), "Globals cannot contain scalable types", &GV);
821
822 // Check if it is or contains a target extension type that disallows being
823 // used as a global.
825 "Global @" + GV.getName() + " has illegal target extension type",
826 GVType);
827
828 // Check that the the address space can hold all bits of the type, recognized
829 // by an access in the address space being able to reach all bytes of the
830 // type.
831 Check(!GVType->isSized() ||
832 isUIntN(DL.getAddressSizeInBits(GV.getAddressSpace()),
833 GV.getGlobalSize(DL)),
834 "Global variable is too large to fit into the address space", &GV,
835 GVType);
836
837 if (!GV.hasInitializer()) {
838 visitGlobalValue(GV);
839 return;
840 }
841
842 // Walk any aggregate initializers looking for bitcasts between address spaces
843 visitConstantExprsRecursively(GV.getInitializer());
844
845 visitGlobalValue(GV);
846}
847
848void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
849 SmallPtrSet<const GlobalAlias*, 4> Visited;
850 Visited.insert(&GA);
851 visitAliaseeSubExpr(Visited, GA, C);
852}
853
854void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
855 const GlobalAlias &GA, const Constant &C) {
858 cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
859 "available_externally alias must point to available_externally "
860 "global value",
861 &GA);
862 }
863 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
865 Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
866 &GA);
867 }
868
869 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
870 Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
871
872 Check(!GA2->isInterposable(),
873 "Alias cannot point to an interposable alias", &GA);
874 } else {
875 // Only continue verifying subexpressions of GlobalAliases.
876 // Do not recurse into global initializers.
877 return;
878 }
879 }
880
881 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
882 visitConstantExprsRecursively(CE);
883
884 for (const Use &U : C.operands()) {
885 Value *V = &*U;
886 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
887 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
888 else if (const auto *C2 = dyn_cast<Constant>(V))
889 visitAliaseeSubExpr(Visited, GA, *C2);
890 }
891}
892
893void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
895 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
896 "weak_odr, external, or available_externally linkage!",
897 &GA);
898 const Constant *Aliasee = GA.getAliasee();
899 Check(Aliasee, "Aliasee cannot be NULL!", &GA);
900 Check(GA.getType() == Aliasee->getType(),
901 "Alias and aliasee types should match!", &GA);
902
903 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
904 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
905
906 visitAliaseeSubExpr(GA, *Aliasee);
907
908 visitGlobalValue(GA);
909}
910
911void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
912 visitGlobalValue(GI);
913
915 GI.getAllMetadata(MDs);
916 for (const auto &I : MDs) {
917 CheckDI(I.first != LLVMContext::MD_dbg,
918 "an ifunc may not have a !dbg attachment", &GI);
919 Check(I.first != LLVMContext::MD_prof,
920 "an ifunc may not have a !prof attachment", &GI);
921 visitMDNode(*I.second, AreDebugLocsAllowed::No);
922 }
923
925 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
926 "weak_odr, or external linkage!",
927 &GI);
928 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
929 // is a Function definition.
930 const Function *Resolver = GI.getResolverFunction();
931 Check(Resolver, "IFunc must have a Function resolver", &GI);
932 Check(!Resolver->isDeclarationForLinker(),
933 "IFunc resolver must be a definition", &GI);
934
935 // Check that the immediate resolver operand (prior to any bitcasts) has the
936 // correct type.
937 const Type *ResolverTy = GI.getResolver()->getType();
938
940 "IFunc resolver must return a pointer", &GI);
941
942 Check(ResolverTy == PointerType::get(Context, GI.getAddressSpace()),
943 "IFunc resolver has incorrect type", &GI);
944}
945
946void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
947 // There used to be various other llvm.dbg.* nodes, but we don't support
948 // upgrading them and we want to reserve the namespace for future uses.
949 if (NMD.getName().starts_with("llvm.dbg."))
950 CheckDI(NMD.getName() == "llvm.dbg.cu",
951 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
952 for (const MDNode *MD : NMD.operands()) {
953 if (NMD.getName() == "llvm.dbg.cu")
954 CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
955
956 if (!MD)
957 continue;
958
959 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
960 }
961}
962
963/// Parent scope operand of \p S, or null if \p S has no parent (a \c DIFile,
964/// \c DICompileUnit, or non-scope). Mirrors \c DIScope::getScope() without
965/// asserting on unexpected metadata kinds.
966static const Metadata *getRawDIScopeParent(const Metadata *S) {
967 if (!S)
968 return nullptr;
969 if (auto *T = dyn_cast<DIType>(S))
970 return T->getRawScope();
971 if (auto *SP = dyn_cast<DISubprogram>(S))
972 return SP->getRawScope();
973 if (auto *LB = dyn_cast<DILexicalBlockBase>(S))
974 return LB->getRawScope();
975 if (auto *NS = dyn_cast<DINamespace>(S))
976 return NS->getRawScope();
977 if (auto *CB = dyn_cast<DICommonBlock>(S))
978 return CB->getRawScope();
979 if (auto *M = dyn_cast<DIModule>(S))
980 return M->getRawScope();
981 return nullptr;
982}
983
984/// True if following the scope operand from \p S repeats a node.
985bool Verifier::hasDIScopeCycle(const Metadata *S) {
986 SmallPtrSet<const Metadata *, 8> Seen;
987 auto CacheSeen = [&](bool HasCycle) {
988 for (const Metadata *M : Seen)
989 DIScopeChainReachesCycle[M] = HasCycle;
990 return HasCycle;
991 };
992
993 while (auto *Scope = dyn_cast_or_null<DIScope>(S)) {
994 auto It = DIScopeChainReachesCycle.find(Scope);
995 bool IsInCache = It != DIScopeChainReachesCycle.end();
996 if (IsInCache)
997 return CacheSeen(It->second);
998 bool AlreadySeen = !Seen.insert(Scope).second;
999 if (AlreadySeen) // New cycle detected
1000 return CacheSeen(true);
1001 // No new cycle detected
1002 S = getRawDIScopeParent(Scope);
1003 }
1004
1005 // Finished walking node chain without detecting any cycles
1006 return CacheSeen(false);
1007}
1008
1009void Verifier::visitDIScopeChain(const DIScope &N) {
1010 CheckDI(!hasDIScopeCycle(&N), "DIScope scope chain must not contain a cycle",
1011 &N);
1012}
1013
1014void Verifier::visitMDNode(const MDNode &BaseMD,
1015 AreDebugLocsAllowed AllowLocs) {
1016 // Only visit each node once. Metadata can be mutually recursive, so this
1017 // avoids infinite recursion here, as well as being an optimization.
1018 if (!MDNodes.insert(&BaseMD).second)
1019 return;
1020
1021 std::queue<const MDNode *> Worklist;
1022 Worklist.push(&BaseMD);
1023
1024 while (!Worklist.empty()) {
1025 const MDNode *CurrentMD = Worklist.front();
1026 Worklist.pop();
1027 Check(&CurrentMD->getContext() == &Context,
1028 "MDNode context does not match Module context!", CurrentMD);
1029
1030 switch (CurrentMD->getMetadataID()) {
1031 default:
1032 llvm_unreachable("Invalid MDNode subclass");
1033 case Metadata::MDTupleKind:
1034 break;
1035#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1036 case Metadata::CLASS##Kind: \
1037 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1038 break;
1039#include "llvm/IR/Metadata.def"
1040 }
1041
1042 // A scope chain must terminate.
1043 if (const auto *S = dyn_cast<DIScope>(CurrentMD))
1044 visitDIScopeChain(*S);
1045
1046 for (const Metadata *Op : CurrentMD->operands()) {
1047 if (!Op)
1048 continue;
1049 Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
1050 CurrentMD, Op);
1051 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1052 "DILocation not allowed within this metadata node", CurrentMD,
1053 Op);
1054 if (auto *N = dyn_cast<MDNode>(Op)) {
1055 if (MDNodes.insert(N).second)
1056 Worklist.push(N);
1057 continue;
1058 }
1059 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
1060 visitValueAsMetadata(*V, nullptr);
1061 continue;
1062 }
1063 }
1064
1065 // Check llvm.loop.estimated_trip_count.
1066 if (CurrentMD->getNumOperands() > 0 &&
1068 Check(CurrentMD->getNumOperands() == 2, "Expected two operands",
1069 CurrentMD);
1070 auto *Count =
1072 Check(Count && Count->getType()->isIntegerTy() &&
1073 cast<IntegerType>(Count->getType())->getBitWidth() <= 32,
1074 "Expected second operand to be an integer constant of type i32 or "
1075 "smaller",
1076 CurrentMD);
1077 }
1078
1079 // Enforce the single-operand form of the loop enable/disable pairs.
1080 if (CurrentMD->getNumOperands() > 0 &&
1081 any_of(OldBooleanLoopTags, [CurrentMD](const BooleanLoopTags &Tags) {
1082 return CurrentMD->getOperand(0).equalsStr(Tags.Enable) ||
1083 CurrentMD->getOperand(0).equalsStr(Tags.Disable);
1084 }))
1085 Check(CurrentMD->getNumOperands() == 1,
1086 "Expecting only the metadata name", CurrentMD);
1087
1088 // Check these last, so we diagnose problems in operands first.
1089 Check(!CurrentMD->isTemporary(), "Expected no forward declarations!",
1090 CurrentMD);
1091 Check(CurrentMD->isResolved(), "All nodes should be resolved!", CurrentMD);
1092 }
1093}
1094
1095void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
1096 Check(MD.getValue(), "Expected valid value", &MD);
1097 Check(!MD.getValue()->getType()->isMetadataTy(),
1098 "Unexpected metadata round-trip through values", &MD, MD.getValue());
1099
1100 auto *L = dyn_cast<LocalAsMetadata>(&MD);
1101 if (!L)
1102 return;
1103
1104 Check(F, "function-local metadata used outside a function", L);
1105
1106 // If this was an instruction, bb, or argument, verify that it is in the
1107 // function that we expect.
1108 Function *ActualF = nullptr;
1109 if (auto *I = dyn_cast<Instruction>(L->getValue())) {
1110 Check(I->getParent(), "function-local metadata not in basic block", L, I);
1111 ActualF = I->getParent()->getParent();
1112 } else if (auto *BB = dyn_cast<BasicBlock>(L->getValue())) {
1113 ActualF = BB->getParent();
1114 } else if (auto *A = dyn_cast<Argument>(L->getValue())) {
1115 ActualF = A->getParent();
1116 }
1117 assert(ActualF && "Unimplemented function local metadata case!");
1118
1119 Check(ActualF == F, "function-local metadata used in wrong function", L);
1120}
1121
1122void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
1123 for (const ValueAsMetadata *VAM : AL.getArgs())
1124 visitValueAsMetadata(*VAM, F);
1125}
1126
1127void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
1128 Metadata *MD = MDV.getMetadata();
1129 if (auto *N = dyn_cast<MDNode>(MD)) {
1130 visitMDNode(*N, AreDebugLocsAllowed::No);
1131 return;
1132 }
1133
1134 // Only visit each node once. Metadata can be mutually recursive, so this
1135 // avoids infinite recursion here, as well as being an optimization.
1136 if (!MDNodes.insert(MD).second)
1137 return;
1138
1139 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
1140 visitValueAsMetadata(*V, F);
1141
1142 if (auto *AL = dyn_cast<DIArgList>(MD))
1143 visitDIArgList(*AL, F);
1144}
1145
1146static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
1147static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
1148static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
1149static bool isMDTuple(const Metadata *MD) { return !MD || isa<MDTuple>(MD); }
1150
1151void Verifier::visitDILocation(const DILocation &N) {
1152 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1153 "location requires a valid scope", &N, N.getRawScope());
1154 if (auto *IA = N.getRawInlinedAt())
1155 CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
1156 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1157 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1158}
1159
1160void Verifier::visitGenericDINode(const GenericDINode &N) {
1161 CheckDI(N.getTag(), "invalid tag", &N);
1162}
1163
1164void Verifier::visitDIScope(const DIScope &N) {
1165 if (auto *F = N.getRawFile())
1166 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1167}
1168
1169void Verifier::visitDIType(const DIType &N) {
1170 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1171 visitDIScope(N);
1172 CheckDI(N.getRawFile() || N.getLine() == 0, "line specified with no file", &N,
1173 N.getLine());
1174}
1175
1176void Verifier::visitDISubrangeType(const DISubrangeType &N) {
1177 visitDIType(N);
1178
1179 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1180 auto *BaseType = N.getRawBaseType();
1181 CheckDI(!BaseType || isType(BaseType), "BaseType must be a type");
1182 auto *LBound = N.getRawLowerBound();
1183 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1184 isa<DIVariable>(LBound) || isa<DIExpression>(LBound) ||
1185 isa<DIDerivedType>(LBound),
1186 "LowerBound must be signed constant or DIVariable or DIExpression or "
1187 "DIDerivedType",
1188 &N);
1189 auto *UBound = N.getRawUpperBound();
1190 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1191 isa<DIVariable>(UBound) || isa<DIExpression>(UBound) ||
1192 isa<DIDerivedType>(UBound),
1193 "UpperBound must be signed constant or DIVariable or DIExpression or "
1194 "DIDerivedType",
1195 &N);
1196 auto *Stride = N.getRawStride();
1197 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1198 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1199 "Stride must be signed constant or DIVariable or DIExpression", &N);
1200 auto *Bias = N.getRawBias();
1201 CheckDI(!Bias || isa<ConstantAsMetadata>(Bias) || isa<DIVariable>(Bias) ||
1202 isa<DIExpression>(Bias),
1203 "Bias must be signed constant or DIVariable or DIExpression", &N);
1204 // Subrange types currently only support constant size.
1205 auto *Size = N.getRawSizeInBits();
1207 "SizeInBits must be a constant");
1208}
1209
1210void Verifier::visitDISubrange(const DISubrange &N) {
1211 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1212 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1213 "Subrange can have any one of count or upperBound", &N);
1214 auto *CBound = N.getRawCountNode();
1215 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1216 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1217 "Count must be signed constant or DIVariable or DIExpression", &N);
1218 auto Count = N.getCount();
1220 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1221 "invalid subrange count", &N);
1222 auto *LBound = N.getRawLowerBound();
1223 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1224 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1225 "LowerBound must be signed constant or DIVariable or DIExpression",
1226 &N);
1227 auto *UBound = N.getRawUpperBound();
1228 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1229 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1230 "UpperBound must be signed constant or DIVariable or DIExpression",
1231 &N);
1232 auto *Stride = N.getRawStride();
1233 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1234 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1235 "Stride must be signed constant or DIVariable or DIExpression", &N);
1236}
1237
1238void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1239 CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1240 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1241 "GenericSubrange can have any one of count or upperBound", &N);
1242 auto *CBound = N.getRawCountNode();
1243 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1244 "Count must be signed constant or DIVariable or DIExpression", &N);
1245 auto *LBound = N.getRawLowerBound();
1246 CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
1247 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1248 "LowerBound must be signed constant or DIVariable or DIExpression",
1249 &N);
1250 auto *UBound = N.getRawUpperBound();
1251 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1252 "UpperBound must be signed constant or DIVariable or DIExpression",
1253 &N);
1254 auto *Stride = N.getRawStride();
1255 CheckDI(Stride, "GenericSubrange must contain stride", &N);
1256 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1257 "Stride must be signed constant or DIVariable or DIExpression", &N);
1258}
1259
1260void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1261 CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1262}
1263
1264void Verifier::visitDIBasicType(const DIBasicType &N) {
1265 visitDIType(N);
1266
1267 CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1268 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1269 N.getTag() == dwarf::DW_TAG_string_type,
1270 "invalid tag", &N);
1271 // Basic types currently only support constant size.
1272 auto *Size = N.getRawSizeInBits();
1274 "SizeInBits must be a constant");
1275}
1276
1277void Verifier::visitDIFixedPointType(const DIFixedPointType &N) {
1278 visitDIBasicType(N);
1279
1280 CheckDI(N.getTag() == dwarf::DW_TAG_base_type, "invalid tag", &N);
1281 CheckDI(N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1282 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1283 "invalid encoding", &N);
1287 "invalid kind", &N);
1289 N.getFactorRaw() == 0,
1290 "factor should be 0 for rationals", &N);
1292 (N.getNumeratorRaw() == 0 && N.getDenominatorRaw() == 0),
1293 "numerator and denominator should be 0 for non-rationals", &N);
1294}
1295
1296void Verifier::visitDIStringType(const DIStringType &N) {
1297 visitDIType(N);
1298
1299 CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1300 CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
1301 &N);
1302}
1303
1304void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1305 // Common type checks.
1306 visitDIType(N);
1307
1308 CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
1309 N.getTag() == dwarf::DW_TAG_pointer_type ||
1310 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1311 N.getTag() == dwarf::DW_TAG_reference_type ||
1312 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1313 N.getTag() == dwarf::DW_TAG_const_type ||
1314 N.getTag() == dwarf::DW_TAG_immutable_type ||
1315 N.getTag() == dwarf::DW_TAG_volatile_type ||
1316 N.getTag() == dwarf::DW_TAG_restrict_type ||
1317 N.getTag() == dwarf::DW_TAG_atomic_type ||
1318 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1319 N.getTag() == dwarf::DW_TAG_member ||
1320 (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
1321 N.getTag() == dwarf::DW_TAG_inheritance ||
1322 N.getTag() == dwarf::DW_TAG_friend ||
1323 N.getTag() == dwarf::DW_TAG_set_type ||
1324 N.getTag() == dwarf::DW_TAG_template_alias,
1325 "invalid tag", &N);
1326 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1327 CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1328 N.getRawExtraData());
1329 } else if (N.getTag() == dwarf::DW_TAG_template_alias) {
1330 CheckDI(isMDTuple(N.getRawExtraData()), "invalid template parameters", &N,
1331 N.getRawExtraData());
1332 } else if (N.getTag() == dwarf::DW_TAG_inheritance ||
1333 N.getTag() == dwarf::DW_TAG_member ||
1334 N.getTag() == dwarf::DW_TAG_variable) {
1335 auto *ExtraData = N.getRawExtraData();
1336 auto IsValidExtraData = [&]() {
1337 if (ExtraData == nullptr)
1338 return true;
1339 if (isa<ConstantAsMetadata>(ExtraData) || isa<MDString>(ExtraData) ||
1340 isa<DIObjCProperty>(ExtraData))
1341 return true;
1342 if (auto *Tuple = dyn_cast<MDTuple>(ExtraData)) {
1343 if (Tuple->getNumOperands() != 1)
1344 return false;
1345 return isa_and_nonnull<ConstantAsMetadata>(Tuple->getOperand(0).get());
1346 }
1347 return false;
1348 };
1349 CheckDI(IsValidExtraData(),
1350 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1351 "or MDTuple with single ConstantAsMetadata operand",
1352 &N, ExtraData);
1353 }
1354
1355 if (N.getTag() == dwarf::DW_TAG_set_type) {
1356 if (auto *T = N.getRawBaseType()) {
1360 CheckDI(
1361 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1362 (Subrange && Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1363 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1364 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1365 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1366 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1367 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1368 "invalid set base type", &N, T);
1369 }
1370 }
1371
1372 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1373 N.getRawBaseType());
1374
1375 if (N.getDWARFAddressSpace()) {
1376 CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1377 N.getTag() == dwarf::DW_TAG_reference_type ||
1378 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1379 "DWARF address space only applies to pointer or reference types",
1380 &N);
1381 }
1382
1383 auto *Size = N.getRawSizeInBits();
1386 "SizeInBits must be a constant or DIVariable or DIExpression");
1387}
1388
1389/// Detect mutually exclusive flags.
1390static bool hasConflictingReferenceFlags(unsigned Flags) {
1391 return ((Flags & DINode::FlagLValueReference) &&
1392 (Flags & DINode::FlagRValueReference)) ||
1393 ((Flags & DINode::FlagTypePassByValue) &&
1394 (Flags & DINode::FlagTypePassByReference));
1395}
1396
1397void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1398 auto *Params = dyn_cast<MDTuple>(&RawParams);
1399 CheckDI(Params, "invalid template params", &N, &RawParams);
1400 for (Metadata *Op : Params->operands()) {
1401 CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1402 &N, Params, Op);
1403 }
1404}
1405
1406void Verifier::visitDICompositeType(const DICompositeType &N) {
1407 // Common type checks.
1408 visitDIType(N);
1409
1410 CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
1411 N.getTag() == dwarf::DW_TAG_structure_type ||
1412 N.getTag() == dwarf::DW_TAG_union_type ||
1413 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1414 N.getTag() == dwarf::DW_TAG_class_type ||
1415 N.getTag() == dwarf::DW_TAG_variant_part ||
1416 N.getTag() == dwarf::DW_TAG_variant ||
1417 N.getTag() == dwarf::DW_TAG_namelist,
1418 "invalid tag", &N);
1419
1420 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1421 N.getRawBaseType());
1422
1423 CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1424 "invalid composite elements", &N, N.getRawElements());
1425 CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1426 N.getRawVTableHolder());
1428 "invalid reference flags", &N);
1429 unsigned DIBlockByRefStruct = 1 << 4;
1430 CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
1431 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1432 CheckDI(llvm::all_of(N.getElements(), [](const DINode *N) { return N; }),
1433 "DISubprogram contains null entry in `elements` field", &N);
1434
1435 if (N.isVector()) {
1436 const DINodeArray Elements = N.getElements();
1437 CheckDI(Elements.size() == 1 &&
1438 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1439 "invalid vector, expected one element of type subrange", &N);
1440 }
1441
1442 if (auto *Params = N.getRawTemplateParams())
1443 visitTemplateParams(N, *Params);
1444
1445 if (auto *D = N.getRawDiscriminator()) {
1446 CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1447 "discriminator can only appear on variant part");
1448 }
1449
1450 if (N.getRawDataLocation()) {
1451 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1452 "dataLocation can only appear in array type");
1453 }
1454
1455 if (N.getRawAssociated()) {
1456 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1457 "associated can only appear in array type");
1458 }
1459
1460 if (N.getRawAllocated()) {
1461 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1462 "allocated can only appear in array type");
1463 }
1464
1465 if (N.getRawRank()) {
1466 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1467 "rank can only appear in array type");
1468 }
1469
1470 if (N.getTag() == dwarf::DW_TAG_array_type) {
1471 CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
1472 }
1473
1474 auto *Size = N.getRawSizeInBits();
1477 "SizeInBits must be a constant or DIVariable or DIExpression");
1478}
1479
1480void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1481 visitDIType(N);
1482 CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1483 if (auto *Types = N.getRawTypeArray()) {
1484 CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1485 for (Metadata *Ty : N.getTypeArray()->operands()) {
1486 CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1487 }
1488 }
1490 "invalid reference flags", &N);
1491}
1492
1493void Verifier::visitDIFile(const DIFile &N) {
1494 CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1495 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1496 if (Checksum) {
1497 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1498 "invalid checksum kind", &N);
1499 size_t Size;
1500 switch (Checksum->Kind) {
1501 case DIFile::CSK_MD5:
1502 Size = 32;
1503 break;
1504 case DIFile::CSK_SHA1:
1505 Size = 40;
1506 break;
1507 case DIFile::CSK_SHA256:
1508 Size = 64;
1509 break;
1510 }
1511 CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1512 CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1513 "invalid checksum", &N);
1514 }
1515}
1516
1517void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1518 CheckDI(N.isDistinct(), "compile units must be distinct", &N);
1519 CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1520
1521 // Don't bother verifying the compilation directory or producer string
1522 // as those could be empty.
1523 CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1524 N.getRawFile());
1525 CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1526 N.getFile());
1527
1528 CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1529 "invalid emission kind", &N);
1530
1531 CheckDI(N.getSourceLanguage().getDialect() <= dwarf::DW_LLVM_LANG_DIALECT_max,
1532 "invalid language dialect", &N);
1533
1534 if (auto *Array = N.getRawEnumTypes()) {
1535 CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1536 for (Metadata *Op : N.getEnumTypes()->operands()) {
1538 CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1539 "invalid enum type", &N, N.getEnumTypes(), Op);
1540 CheckDI(!Enum->getScope() || !isa<DILocalScope>(Enum->getScope()),
1541 "function-local enum in a DICompileUnit's enum list", &N,
1542 N.getEnumTypes(), Op);
1543 }
1544 }
1545 if (auto *Array = N.getRawRetainedTypes()) {
1546 CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1547 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1548 CheckDI(
1549 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1550 !cast<DISubprogram>(Op)->isDefinition())),
1551 "invalid retained type", &N, Op);
1552 }
1553 }
1554 if (auto *Array = N.getRawGlobalVariables()) {
1555 CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1556 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1558 CheckDI(GVE, "invalid global variable ref", &N, Op);
1559 CheckDI(!isa_and_nonnull<DILocalScope>(GVE->getVariable()->getScope()),
1560 "function-local variables are not allowed in a DICompileUnit's "
1561 "global variables list",
1562 &N, Op);
1563 }
1564 }
1565 if (auto *Array = N.getRawImportedEntities()) {
1566 CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1567 for (Metadata *Op : N.getImportedEntities()->operands()) {
1569 CheckDI(IE, "invalid imported entity ref", &N, Op);
1571 "function-local imports are not allowed in a DICompileUnit's "
1572 "imported entities list",
1573 &N, Op);
1574 }
1575 }
1576 if (auto *Array = N.getRawMacros()) {
1577 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1578 for (Metadata *Op : N.getMacros()->operands()) {
1579 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1580 }
1581 }
1582 CUVisited.insert(&N);
1583}
1584
1585void Verifier::visitDISubprogram(const DISubprogram &N) {
1586 CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1587 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1588 if (auto *F = N.getRawFile())
1589 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1590 else
1591 CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1592 auto *T = N.getRawType();
1593 CheckDI(T, "DISubprogram requires a non-null type", &N);
1594 CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1595 CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1596 N.getRawContainingType());
1597 if (auto *Params = N.getRawTemplateParams())
1598 visitTemplateParams(N, *Params);
1599 if (auto *S = N.getRawDeclaration())
1600 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1601 "invalid subprogram declaration", &N, S);
1602 if (auto *RawNode = N.getRawRetainedNodes()) {
1603 auto *Node = dyn_cast<MDTuple>(RawNode);
1604 CheckDI(Node, "invalid retained nodes list", &N, RawNode);
1605
1606 DenseMap<unsigned, DILocalVariable *> Args;
1607 for (Metadata *Op : Node->operands()) {
1608 CheckDI(Op, "nullptr in retained nodes", &N, Node);
1609
1610 auto True = [](const Metadata *) { return true; };
1611 auto False = [](const Metadata *) { return false; };
1612 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1613 Op, True, True, True, True, True, False);
1614 CheckDI(IsTypeCorrect,
1615 "invalid retained nodes, expected DILocalVariable, DILabel, "
1616 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1617 &N, Node, Op);
1618
1619 auto *RetainedNode = cast<MDNode>(Op);
1620 auto *RetainedNodeScope = dyn_cast_or_null<DILocalScope>(
1622 CheckDI(RetainedNodeScope,
1623 "invalid retained nodes, retained node is not local", &N, Node,
1624 RetainedNode);
1625
1626 DISubprogram *RetainedNodeSP = getSubprogram(RetainedNodeScope);
1627 DICompileUnit *RetainedNodeUnit =
1628 RetainedNodeSP ? RetainedNodeSP->getUnit() : nullptr;
1629 CheckDI(
1630 RetainedNodeSP == &N,
1631 "invalid retained nodes, retained node does not belong to subprogram",
1632 &N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1633 RetainedNodeUnit);
1634
1635 auto *DV = dyn_cast<DILocalVariable>(RetainedNode);
1636 if (!DV)
1637 continue;
1638 if (unsigned ArgNum = DV->getArg()) {
1639 auto [ArgI, Inserted] = Args.insert({ArgNum, DV});
1640 CheckDI(Inserted || DV == ArgI->second,
1641 "invalid retained nodes, more than one local variable with the "
1642 "same argument index",
1643 &N, N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1644 }
1645 }
1646 }
1648 "invalid reference flags", &N);
1649
1650 auto *Unit = N.getRawUnit();
1651 if (N.isDefinition()) {
1652 // Subprogram definitions (not part of the type hierarchy).
1653 CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1654 CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
1655 CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1656 // There's no good way to cross the CU boundary to insert a nested
1657 // DISubprogram definition in one CU into a type defined in another CU.
1658 auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
1659 if (CT && CT->getRawIdentifier() &&
1660 M.getContext().isODRUniquingDebugTypes())
1661 CheckDI(N.getDeclaration(),
1662 "definition subprograms cannot be nested within DICompositeType "
1663 "when enabling ODR",
1664 &N);
1665 } else {
1666 // Subprogram declarations (part of the type hierarchy).
1667 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1668 CheckDI(!N.getRawDeclaration(),
1669 "subprogram declaration must not have a declaration field");
1670 }
1671
1672 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1673 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1674 CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1675 for (Metadata *Op : ThrownTypes->operands())
1676 CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1677 Op);
1678 }
1679
1680 if (N.areAllCallsDescribed())
1681 CheckDI(N.isDefinition(),
1682 "DIFlagAllCallsDescribed must be attached to a definition");
1683}
1684
1685void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1686 CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1687 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1688 "invalid local scope", &N, N.getRawScope());
1689 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1690 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1691}
1692
1693void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1694 visitDILexicalBlockBase(N);
1695
1696 CheckDI(N.getLine() || !N.getColumn(),
1697 "cannot have column info without line info", &N);
1698}
1699
1700void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1701 visitDILexicalBlockBase(N);
1702}
1703
1704void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1705 CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1706 if (auto *S = N.getRawScope())
1707 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1708 if (auto *S = N.getRawDecl())
1709 CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1710}
1711
1712void Verifier::visitDINamespace(const DINamespace &N) {
1713 CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1714 if (auto *S = N.getRawScope())
1715 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1716}
1717
1718void Verifier::visitDIMacro(const DIMacro &N) {
1719 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1720 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1721 "invalid macinfo type", &N);
1722 CheckDI(!N.getName().empty(), "anonymous macro", &N);
1723 if (!N.getValue().empty()) {
1724 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1725 }
1726}
1727
1728void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1729 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1730 "invalid macinfo type", &N);
1731 if (auto *F = N.getRawFile())
1732 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1733
1734 if (auto *Array = N.getRawElements()) {
1735 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1736 for (Metadata *Op : N.getElements()->operands()) {
1737 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1738 }
1739 }
1740}
1741
1742void Verifier::visitDIModule(const DIModule &N) {
1743 CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1744 CheckDI(!N.getName().empty(), "anonymous module", &N);
1745}
1746
1747void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1748 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1749}
1750
1751void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1752 visitDITemplateParameter(N);
1753
1754 CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1755 &N);
1756}
1757
1758void Verifier::visitDITemplateValueParameter(
1759 const DITemplateValueParameter &N) {
1760 visitDITemplateParameter(N);
1761
1762 CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1763 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1764 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1765 "invalid tag", &N);
1766}
1767
1768void Verifier::visitDIVariable(const DIVariable &N) {
1769 if (auto *S = N.getRawScope())
1770 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1771 if (auto *F = N.getRawFile())
1772 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1773}
1774
1775void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1776 // Checks common to all variables.
1777 visitDIVariable(N);
1778
1779 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1780 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1781 // Check only if the global variable is not an extern
1782 if (N.isDefinition())
1783 CheckDI(N.getType(), "missing global variable type", &N);
1784 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1786 "invalid static data member declaration", &N, Member);
1787 }
1788}
1789
1790void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1791 // Checks common to all variables.
1792 visitDIVariable(N);
1793
1794 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1795 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1796 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1797 "local variable requires a valid scope", &N, N.getRawScope());
1798 if (auto Ty = N.getType())
1799 CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1800}
1801
1802void Verifier::visitDIAssignID(const DIAssignID &N) {
1803 CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1804 CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1805}
1806
1807void Verifier::visitDILabel(const DILabel &N) {
1808 if (auto *S = N.getRawScope())
1809 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1810 if (auto *F = N.getRawFile())
1811 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1812
1813 CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1814 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1815 "label requires a valid scope", &N, N.getRawScope());
1816}
1817
1818void Verifier::visitDIExpression(const DIExpression &N) {
1819 CheckDI(N.isValid(), "invalid expression", &N);
1820}
1821
1822void Verifier::visitDIGlobalVariableExpression(
1823 const DIGlobalVariableExpression &GVE) {
1824 CheckDI(GVE.getVariable(), "missing variable");
1825 if (auto *Var = GVE.getVariable())
1826 visitDIGlobalVariable(*Var);
1827 if (auto *Expr = GVE.getExpression()) {
1828 visitDIExpression(*Expr);
1829 if (auto Fragment = Expr->getFragmentInfo())
1830 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1831 }
1832}
1833
1834void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1835 CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1836 if (auto *T = N.getRawType())
1837 CheckDI(isType(T), "invalid type ref", &N, T);
1838 if (auto *F = N.getRawFile())
1839 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1840}
1841
1842void Verifier::visitDIProperty(const DIProperty &N) {
1843 CheckDI(N.getTag() == dwarf::DW_TAG_property, "invalid tag", &N);
1844 if (auto *T = N.getRawType())
1845 CheckDI(isType(T), "invalid type ref", &N, T);
1846 if (auto *F = N.getRawFile())
1847 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1848 // DWARF allows a property getter to forward to a subprogram, variable, or
1849 // constant too, but the backend only knows how to forward to a member.
1850 if (DINode *BackingStorage = N.getBackingStorage()) {
1851 auto *DT = dyn_cast<DIDerivedType>(BackingStorage);
1852 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
1853 "property backing storage must be a member", &N, BackingStorage);
1854 }
1855}
1856
1857void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1858 CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1859 N.getTag() == dwarf::DW_TAG_imported_declaration,
1860 "invalid tag", &N);
1861 if (auto *S = N.getRawScope())
1862 CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1863 CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1864 N.getRawEntity());
1865}
1866
1867void Verifier::visitComdat(const Comdat &C) {
1868 // In COFF the Module is invalid if the GlobalValue has private linkage.
1869 // Entities with private linkage don't have entries in the symbol table.
1870 if (TT.isOSBinFormatCOFF())
1871 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1872 Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1873 GV);
1874}
1875
1876void Verifier::visitModuleIdents() {
1877 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1878 if (!Idents)
1879 return;
1880
1881 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1882 // Scan each llvm.ident entry and make sure that this requirement is met.
1883 for (const MDNode *N : Idents->operands()) {
1884 Check(N->getNumOperands() == 1,
1885 "incorrect number of operands in llvm.ident metadata", N);
1886 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1887 ("invalid value for llvm.ident metadata entry operand"
1888 "(the operand should be a string)"),
1889 N->getOperand(0));
1890 }
1891}
1892
1893void Verifier::visitModuleCommandLines() {
1894 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1895 if (!CommandLines)
1896 return;
1897
1898 // llvm.commandline takes a list of metadata entry. Each entry has only one
1899 // string. Scan each llvm.commandline entry and make sure that this
1900 // requirement is met.
1901 for (const MDNode *N : CommandLines->operands()) {
1902 Check(N->getNumOperands() == 1,
1903 "incorrect number of operands in llvm.commandline metadata", N);
1904 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1905 ("invalid value for llvm.commandline metadata entry operand"
1906 "(the operand should be a string)"),
1907 N->getOperand(0));
1908 }
1909}
1910
1911void Verifier::visitModuleErrnoTBAA() {
1912 const NamedMDNode *ErrnoTBAA = M.getNamedMetadata("llvm.errno.tbaa");
1913 if (!ErrnoTBAA)
1914 return;
1915
1916 Check(ErrnoTBAA->getNumOperands() >= 1,
1917 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1918
1919 for (const MDNode *N : ErrnoTBAA->operands())
1920 TBAAVerifyHelper.visitTBAAMetadata(nullptr, N);
1921}
1922
1923void Verifier::visitModuleFlags() {
1924 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1925 if (!Flags) return;
1926
1927 // Scan each flag, and track the flags and requirements.
1928 DenseMap<const MDString*, const MDNode*> SeenIDs;
1929 SmallVector<const MDNode*, 16> Requirements;
1930
1931 // Either both aarch64-elf-pauthabi-* flags should be set or none at all.
1932 std::optional<uint64_t> PAuthABIPlatform;
1933 std::optional<uint64_t> PAuthABIVersion;
1934 // Signing of init/fini pointers: address diversity implies basic signing.
1935 uint64_t HasPtrauthInitFini = 0;
1936 uint64_t HasPtrauthInitFiniAddr = 0;
1937
1938 for (const MDNode *MDN : Flags->operands()) {
1939 visitModuleFlag(MDN, SeenIDs, Requirements);
1940 if (MDN->getNumOperands() != 3)
1941 continue;
1942
1943 if (const auto *FlagName = dyn_cast_or_null<MDString>(MDN->getOperand(1))) {
1944 auto GetFlagNamed = [&](StringRef Name) -> std::optional<uint64_t> {
1945 if (FlagName->getString() != Name)
1946 return std::nullopt;
1947 if (const auto *FlagValue =
1949 return FlagValue->getZExtValue();
1950
1951 CheckFailed(Name + ": module flag expects integer value");
1952 return std::nullopt;
1953 };
1954
1955 if (auto Value = GetFlagNamed("aarch64-elf-pauthabi-platform"))
1956 PAuthABIPlatform = *Value;
1957 else if (auto Value = GetFlagNamed("aarch64-elf-pauthabi-version"))
1958 PAuthABIVersion = *Value;
1959 else if (auto Value = GetFlagNamed("ptrauth-init-fini"))
1960 HasPtrauthInitFini = *Value;
1961 else if (auto Value =
1962 GetFlagNamed("ptrauth-init-fini-address-discrimination"))
1963 HasPtrauthInitFiniAddr = *Value;
1964 }
1965 }
1966
1967 Check(llvm::is_contained({0u, 1u}, HasPtrauthInitFini),
1968 "ptrauth-init-fini must be 0 or 1");
1969 Check(llvm::is_contained({0u, 1u}, HasPtrauthInitFiniAddr),
1970 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
1971 if (HasPtrauthInitFiniAddr)
1972 Check(HasPtrauthInitFini, "ptrauth-init-fini-address-discrimination module "
1973 "flag requires ptrauth-init-fini");
1974
1975 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
1976 CheckFailed("either both or no 'aarch64-elf-pauthabi-platform' and "
1977 "'aarch64-elf-pauthabi-version' module flags must be present");
1978
1979 // Validate that the requirements in the module are valid.
1980 for (const MDNode *Requirement : Requirements) {
1981 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1982 const Metadata *ReqValue = Requirement->getOperand(1);
1983
1984 const MDNode *Op = SeenIDs.lookup(Flag);
1985 if (!Op) {
1986 CheckFailed("invalid requirement on flag, flag is not present in module",
1987 Flag);
1988 continue;
1989 }
1990
1991 if (Op->getOperand(2) != ReqValue) {
1992 CheckFailed(("invalid requirement on flag, "
1993 "flag does not have the required value"),
1994 Flag);
1995 continue;
1996 }
1997 }
1998}
1999
2000void
2001Verifier::visitModuleFlag(const MDNode *Op,
2002 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2003 SmallVectorImpl<const MDNode *> &Requirements) {
2004 // Each module flag should have three arguments, the merge behavior (a
2005 // constant int), the flag ID (an MDString), and the value.
2006 Check(Op->getNumOperands() == 3,
2007 "incorrect number of operands in module flag", Op);
2008 Module::ModFlagBehavior MFB;
2009 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
2011 "invalid behavior operand in module flag (expected constant integer)",
2012 Op->getOperand(0));
2013 Check(false,
2014 "invalid behavior operand in module flag (unexpected constant)",
2015 Op->getOperand(0));
2016 }
2017 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
2018 Check(ID, "invalid ID operand in module flag (expected metadata string)",
2019 Op->getOperand(1));
2020
2021 // Check the values for behaviors with additional requirements.
2022 switch (MFB) {
2023 case Module::Error:
2024 case Module::Warning:
2025 case Module::Override:
2026 // These behavior types accept any value.
2027 break;
2028
2029 case Module::Min: {
2030 auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
2031 Check(V && V->getValue().isNonNegative(),
2032 "invalid value for 'min' module flag (expected constant non-negative "
2033 "integer)",
2034 Op->getOperand(2));
2035 break;
2036 }
2037
2038 case Module::Max: {
2040 "invalid value for 'max' module flag (expected constant integer)",
2041 Op->getOperand(2));
2042 break;
2043 }
2044
2045 case Module::Require: {
2046 // The value should itself be an MDNode with two operands, a flag ID (an
2047 // MDString), and a value.
2048 auto *Value = dyn_cast<MDNode>(Op->getOperand(2));
2049 Check(Value && Value->getNumOperands() == 2,
2050 "invalid value for 'require' module flag (expected metadata pair)",
2051 Op->getOperand(2));
2052 Check(isa<MDString>(Value->getOperand(0)),
2053 ("invalid value for 'require' module flag "
2054 "(first value operand should be a string)"),
2055 Value->getOperand(0));
2056
2057 // Append it to the list of requirements, to check once all module flags are
2058 // scanned.
2059 Requirements.push_back(Value);
2060 break;
2061 }
2062
2063 case Module::Append:
2064 case Module::AppendUnique: {
2065 // These behavior types require the operand be an MDNode.
2066 Check(isa<MDNode>(Op->getOperand(2)),
2067 "invalid value for 'append'-type module flag "
2068 "(expected a metadata node)",
2069 Op->getOperand(2));
2070 break;
2071 }
2072 }
2073
2074 // Unless this is a "requires" flag, check the ID is unique.
2075 if (MFB != Module::Require) {
2076 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
2077 Check(Inserted,
2078 "module flag identifiers must be unique (or of 'require' type)", ID);
2079 }
2080
2081 StringRef Name = ID->getString();
2082 if (Name == "wchar_size") {
2083 ConstantInt *Value
2085 Check(Value, "wchar_size metadata requires constant integer argument");
2086 return;
2087 }
2088
2089 if (Name == "long-double-type") {
2090 Check(MFB == Module::Error,
2091 "long-double-type module flag must use 'error' merge behavior", Op);
2092 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2093 Check(Value, "long-double-type metadata requires a string argument");
2094 if (Value)
2095 Check(parseLongDoubleFormat(Value->getString()).has_value(),
2096 "invalid long-double-type metadata value", Op);
2097 return;
2098 }
2099
2100 if (Name == "float-abi") {
2101 Check(MFB == Module::Error,
2102 "float-abi module flag must use 'error' merge behavior", Op);
2103 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2104 Check(Value, "float-abi metadata requires a string argument");
2105 if (Value)
2106 Check(FloatABI::parseABIType(Value->getString()).has_value(),
2107 "invalid float-abi metadata value", Op);
2108 return;
2109 }
2110
2111 if (Name == "target-abi") {
2112 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2113 Check(Value && !Value->getString().empty(),
2114 "target-abi metadata requires a non-empty string argument", Op);
2115 return;
2116 }
2117
2118 if (Name == "Linker Options") {
2119 // If the llvm.linker.options named metadata exists, we assume that the
2120 // bitcode reader has upgraded the module flag. Otherwise the flag might
2121 // have been created by a client directly.
2122 Check(M.getNamedMetadata("llvm.linker.options"),
2123 "'Linker Options' named metadata no longer supported");
2124 return;
2125 }
2126
2127 if (Name == "SemanticInterposition") {
2128 ConstantInt *Value =
2130 Check(Value,
2131 "SemanticInterposition metadata requires constant integer argument");
2132 return;
2133 }
2134
2135 if (Name == "CG Profile") {
2136 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
2137 visitModuleFlagCGProfileEntry(MDO);
2138 return;
2139 }
2140
2141 // Target-specific module flag checks.
2142 verifyAMDGPUModuleFlag(*this, ID, MFB, Op);
2143}
2144
2145void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
2146 auto CheckFunction = [&](const MDOperand &FuncMDO) {
2147 if (!FuncMDO)
2148 return;
2149 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
2150 Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
2151 "expected a Function or null", FuncMDO);
2152 };
2153 auto Node = dyn_cast_or_null<MDNode>(MDO);
2154 Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
2155 CheckFunction(Node->getOperand(0));
2156 CheckFunction(Node->getOperand(1));
2157 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
2158 Check(Count && Count->getType()->isIntegerTy(),
2159 "expected an integer constant", Node->getOperand(2));
2160}
2161
2162void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
2163 for (Attribute A : Attrs) {
2164
2165 if (A.isStringAttribute()) {
2166#define GET_ATTR_NAMES
2167#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2168#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2169 if (A.getKindAsString() == #DISPLAY_NAME) { \
2170 auto V = A.getValueAsString(); \
2171 if (!(V.empty() || V == "true" || V == "false")) \
2172 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2173 ""); \
2174 }
2175
2176#include "llvm/IR/Attributes.inc"
2177 continue;
2178 }
2179
2180 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
2181 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
2182 V);
2183 return;
2184 }
2185 }
2186}
2187
2188// VerifyParameterAttrs - Check the given attributes for an argument or return
2189// value of the specified type. The value V is printed in error messages.
2190void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
2191 const Value *V) {
2192 if (!Attrs.hasAttributes())
2193 return;
2194
2195 verifyAttributeTypes(Attrs, V);
2196
2197 for (Attribute Attr : Attrs)
2198 Check(Attr.isStringAttribute() ||
2199 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2200 "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
2201 V);
2202
2203 if (Attrs.hasAttribute(Attribute::ImmArg)) {
2204 unsigned AttrCount =
2205 Attrs.getNumAttributes() - Attrs.hasAttribute(Attribute::Range);
2206 Check(AttrCount == 1,
2207 "Attribute 'immarg' is incompatible with other attributes except the "
2208 "'range' attribute",
2209 V);
2210 }
2211
2212 // Check for mutually incompatible attributes. Only inreg is compatible with
2213 // sret.
2214 unsigned AttrCount = 0;
2215 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
2216 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
2217 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
2218 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
2219 Attrs.hasAttribute(Attribute::InReg);
2220 AttrCount += Attrs.hasAttribute(Attribute::Nest);
2221 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
2222 Check(AttrCount <= 1,
2223 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2224 "'byref', and 'sret' are incompatible!",
2225 V);
2226
2227 Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
2228 Attrs.hasAttribute(Attribute::ReadOnly)),
2229 "Attributes "
2230 "'inalloca and readonly' are incompatible!",
2231 V);
2232
2233 Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
2234 Attrs.hasAttribute(Attribute::Returned)),
2235 "Attributes "
2236 "'sret and returned' are incompatible!",
2237 V);
2238
2239 Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
2240 Attrs.hasAttribute(Attribute::SExt)),
2241 "Attributes "
2242 "'zeroext and signext' are incompatible!",
2243 V);
2244
2245 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2246 Attrs.hasAttribute(Attribute::ReadOnly)),
2247 "Attributes "
2248 "'readnone and readonly' are incompatible!",
2249 V);
2250
2251 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2252 Attrs.hasAttribute(Attribute::WriteOnly)),
2253 "Attributes "
2254 "'readnone and writeonly' are incompatible!",
2255 V);
2256
2257 Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
2258 Attrs.hasAttribute(Attribute::WriteOnly)),
2259 "Attributes "
2260 "'readonly and writeonly' are incompatible!",
2261 V);
2262
2263 Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
2264 Attrs.hasAttribute(Attribute::AlwaysInline)),
2265 "Attributes "
2266 "'noinline and alwaysinline' are incompatible!",
2267 V);
2268
2269 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2270 Attrs.hasAttribute(Attribute::ReadNone)),
2271 "Attributes writable and readnone are incompatible!", V);
2272
2273 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2274 Attrs.hasAttribute(Attribute::ReadOnly)),
2275 "Attributes writable and readonly are incompatible!", V);
2276
2277 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2278 for (Attribute Attr : Attrs) {
2279 if (!Attr.isStringAttribute() &&
2280 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
2281 CheckFailed("Attribute '" + Attr.getAsString() +
2282 "' applied to incompatible type!", V);
2283 return;
2284 }
2285 }
2286
2287 if (isa<PointerType>(Ty)) {
2288 if (Attrs.hasAttribute(Attribute::Alignment)) {
2289 Align AttrAlign = Attrs.getAlignment().valueOrOne();
2290 Check(AttrAlign.value() <= Value::MaximumAlignment,
2291 "huge alignment values are unsupported", V);
2292 }
2293 if (Attrs.hasAttribute(Attribute::ByVal)) {
2294 Type *ByValTy = Attrs.getByValType();
2295 SmallPtrSet<Type *, 4> Visited;
2296 Check(ByValTy->isSized(&Visited),
2297 "Attribute 'byval' does not support unsized types!", V);
2298 // Check if it is or contains a target extension type that disallows being
2299 // used on the stack.
2301 "'byval' argument has illegal target extension type", V);
2302 Check(DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2303 "huge 'byval' arguments are unsupported", V);
2304 }
2305 if (Attrs.hasAttribute(Attribute::ByRef)) {
2306 SmallPtrSet<Type *, 4> Visited;
2307 Check(Attrs.getByRefType()->isSized(&Visited),
2308 "Attribute 'byref' does not support unsized types!", V);
2309 Check(DL.getTypeAllocSize(Attrs.getByRefType()).getKnownMinValue() <
2310 (1ULL << 32),
2311 "huge 'byref' arguments are unsupported", V);
2312 }
2313 if (Attrs.hasAttribute(Attribute::InAlloca)) {
2314 SmallPtrSet<Type *, 4> Visited;
2315 Check(Attrs.getInAllocaType()->isSized(&Visited),
2316 "Attribute 'inalloca' does not support unsized types!", V);
2317 Check(DL.getTypeAllocSize(Attrs.getInAllocaType()).getKnownMinValue() <
2318 (1ULL << 32),
2319 "huge 'inalloca' arguments are unsupported", V);
2320 }
2321 if (Attrs.hasAttribute(Attribute::Preallocated)) {
2322 SmallPtrSet<Type *, 4> Visited;
2323 Check(Attrs.getPreallocatedType()->isSized(&Visited),
2324 "Attribute 'preallocated' does not support unsized types!", V);
2325 Check(
2326 DL.getTypeAllocSize(Attrs.getPreallocatedType()).getKnownMinValue() <
2327 (1ULL << 32),
2328 "huge 'preallocated' arguments are unsupported", V);
2329 }
2330 }
2331
2332 if (Attrs.hasAttribute(Attribute::Initializes)) {
2333 auto Inits = Attrs.getAttribute(Attribute::Initializes).getInitializes();
2334 Check(!Inits.empty(), "Attribute 'initializes' does not support empty list",
2335 V);
2337 "Attribute 'initializes' does not support unordered ranges", V);
2338 }
2339
2340 if (Attrs.hasAttribute(Attribute::NoFPClass)) {
2341 uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2342 Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
2343 V);
2344 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
2345 "Invalid value for 'nofpclass' test mask", V);
2346 }
2347 if (Attrs.hasAttribute(Attribute::Range)) {
2348 const ConstantRange &CR =
2349 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2351 "Range bit width must match type bit width!", V);
2352 }
2353}
2354
2355void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2356 const Value *V) {
2357 if (Attrs.hasFnAttr(Attr)) {
2358 StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
2359 unsigned N;
2360 if (S.getAsInteger(10, N))
2361 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
2362 }
2363}
2364
2365// Check parameter attributes against a function type.
2366// The value V is printed in error messages.
2367void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2368 const Value *V, bool IsIntrinsic,
2369 bool IsInlineAsm) {
2370 if (Attrs.isEmpty())
2371 return;
2372
2373 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
2374 Check(Attrs.hasParentContext(Context),
2375 "Attribute list does not match Module context!", &Attrs, V);
2376 for (const auto &AttrSet : Attrs) {
2377 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2378 "Attribute set does not match Module context!", &AttrSet, V);
2379 for (const auto &A : AttrSet) {
2380 Check(A.hasParentContext(Context),
2381 "Attribute does not match Module context!", &A, V);
2382 }
2383 }
2384 }
2385
2386 bool SawNest = false;
2387 bool SawReturned = false;
2388 bool SawSRet = false;
2389 bool SawSwiftSelf = false;
2390 bool SawSwiftAsync = false;
2391 bool SawSwiftError = false;
2392
2393 // Verify return value attributes.
2394 AttributeSet RetAttrs = Attrs.getRetAttrs();
2395 for (Attribute RetAttr : RetAttrs)
2396 Check(RetAttr.isStringAttribute() ||
2397 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2398 "Attribute '" + RetAttr.getAsString() +
2399 "' does not apply to function return values",
2400 V);
2401
2402 unsigned MaxParameterWidth = 0;
2403 auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
2404 if (Ty->isVectorTy()) {
2405 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2406 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2407 if (Size > MaxParameterWidth)
2408 MaxParameterWidth = Size;
2409 }
2410 }
2411 };
2412 GetMaxParameterWidth(FT->getReturnType());
2413 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2414
2415 // Verify parameter attributes.
2416 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2417 Type *Ty = FT->getParamType(i);
2418 AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
2419
2420 if (!IsIntrinsic) {
2421 Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
2422 "immarg attribute only applies to intrinsics", V);
2423 if (!IsInlineAsm)
2424 Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
2425 "Attribute 'elementtype' can only be applied to intrinsics"
2426 " and inline asm.",
2427 V);
2428 }
2429
2430 verifyParameterAttrs(ArgAttrs, Ty, V);
2431 GetMaxParameterWidth(Ty);
2432
2433 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2434 Check(!SawNest, "More than one parameter has attribute nest!", V);
2435 SawNest = true;
2436 }
2437
2438 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2439 Check(!SawReturned, "More than one parameter has attribute returned!", V);
2440 Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
2441 "Incompatible argument and return types for 'returned' attribute",
2442 V);
2443 SawReturned = true;
2444 }
2445
2446 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
2447 Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
2448 Check(i == 0 || i == 1,
2449 "Attribute 'sret' is not on first or second parameter!", V);
2450 SawSRet = true;
2451 }
2452
2453 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
2454 Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
2455 SawSwiftSelf = true;
2456 }
2457
2458 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
2459 Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2460 SawSwiftAsync = true;
2461 }
2462
2463 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
2464 Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
2465 SawSwiftError = true;
2466 }
2467
2468 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
2469 Check(i == FT->getNumParams() - 1,
2470 "inalloca isn't on the last parameter!", V);
2471 }
2472 }
2473
2474 if (!Attrs.hasFnAttrs())
2475 return;
2476
2477 verifyAttributeTypes(Attrs.getFnAttrs(), V);
2478 for (Attribute FnAttr : Attrs.getFnAttrs())
2479 Check(FnAttr.isStringAttribute() ||
2480 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2481 "Attribute '" + FnAttr.getAsString() +
2482 "' does not apply to functions!",
2483 V);
2484
2485 Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2486 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2487 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2488
2489 if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2490 Check(Attrs.hasFnAttr(Attribute::NoInline),
2491 "Attribute 'optnone' requires 'noinline'!", V);
2492
2493 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2494 "Attributes 'optsize and optnone' are incompatible!", V);
2495
2496 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2497 "Attributes 'minsize and optnone' are incompatible!", V);
2498
2499 Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2500 "Attributes 'optdebug and optnone' are incompatible!", V);
2501 }
2502
2503 Check(!(Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2504 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2505 "Attributes "
2506 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2507 V);
2508
2509 if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2510 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2511 "Attributes 'optsize and optdebug' are incompatible!", V);
2512
2513 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2514 "Attributes 'minsize and optdebug' are incompatible!", V);
2515 }
2516
2517 Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
2518 isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2519 "Attribute writable and memory without argmem: write are incompatible!",
2520 V);
2521
2522 if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2523 Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2524 "Attributes 'aarch64_pstate_sm_enabled and "
2525 "aarch64_pstate_sm_compatible' are incompatible!",
2526 V);
2527 }
2528
2529 Check((Attrs.hasFnAttr("aarch64_new_za") + Attrs.hasFnAttr("aarch64_in_za") +
2530 Attrs.hasFnAttr("aarch64_inout_za") +
2531 Attrs.hasFnAttr("aarch64_out_za") +
2532 Attrs.hasFnAttr("aarch64_preserves_za") +
2533 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2534 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2535 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2536 "'aarch64_za_state_agnostic' are mutually exclusive",
2537 V);
2538
2539 Check((Attrs.hasFnAttr("aarch64_new_zt0") +
2540 Attrs.hasFnAttr("aarch64_in_zt0") +
2541 Attrs.hasFnAttr("aarch64_inout_zt0") +
2542 Attrs.hasFnAttr("aarch64_out_zt0") +
2543 Attrs.hasFnAttr("aarch64_preserves_zt0") +
2544 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2545 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2546 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2547 "'aarch64_za_state_agnostic' are mutually exclusive",
2548 V);
2549
2550 if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2551 const GlobalValue *GV = cast<GlobalValue>(V);
2553 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2554 }
2555
2556 if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
2557 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2558 if (ParamNo >= FT->getNumParams()) {
2559 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2560 return false;
2561 }
2562
2563 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2564 CheckFailed("'allocsize' " + Name +
2565 " argument must refer to an integer parameter",
2566 V);
2567 return false;
2568 }
2569
2570 return true;
2571 };
2572
2573 if (!CheckParam("element size", Args->first))
2574 return;
2575
2576 if (Args->second && !CheckParam("number of elements", *Args->second))
2577 return;
2578 }
2579
2580 if (Attrs.hasFnAttr(Attribute::AllocKind)) {
2581 AllocFnKind K = Attrs.getAllocKind();
2583 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2584 if (!is_contained(
2585 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2586 Type))
2587 CheckFailed(
2588 "'allockind()' requires exactly one of alloc, realloc, and free");
2589 if ((Type == AllocFnKind::Free) &&
2590 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2591 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2592 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2593 "or aligned modifiers.");
2594 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2595 if ((K & ZeroedUninit) == ZeroedUninit)
2596 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2597 }
2598
2599 if (Attribute A = Attrs.getFnAttr("alloc-variant-zeroed"); A.isValid()) {
2600 StringRef S = A.getValueAsString();
2601 Check(!S.empty(), "'alloc-variant-zeroed' must not be empty");
2602 Function *Variant = M.getFunction(S);
2603 if (Variant) {
2604 Attribute Family = Attrs.getFnAttr("alloc-family");
2605 Attribute VariantFamily = Variant->getFnAttribute("alloc-family");
2606 if (Family.isValid())
2607 Check(VariantFamily.isValid() &&
2608 VariantFamily.getValueAsString() == Family.getValueAsString(),
2609 "'alloc-variant-zeroed' must name a function belonging to the "
2610 "same 'alloc-family'");
2611
2612 Check(Variant->hasFnAttribute(Attribute::AllocKind) &&
2613 (Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2614 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2615 "'alloc-variant-zeroed' must name a function with "
2616 "'allockind(\"zeroed\")'");
2617
2618 Check(FT == Variant->getFunctionType(),
2619 "'alloc-variant-zeroed' must name a function with the same "
2620 "signature");
2621
2622 if (const auto *F = dyn_cast<Function>(V))
2623 Check(F->getCallingConv() == Variant->getCallingConv(),
2624 "'alloc-variant-zeroed' must name a function with the same "
2625 "calling convention");
2626 }
2627 }
2628
2629 if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2630 unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2631 if (VScaleMin == 0)
2632 CheckFailed("'vscale_range' minimum must be greater than 0", V);
2633 else if (!isPowerOf2_32(VScaleMin))
2634 CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2635 std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2636 if (VScaleMax && VScaleMin > VScaleMax)
2637 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2638 else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
2639 CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2640 }
2641
2642 if (Attribute FPAttr = Attrs.getFnAttr("frame-pointer"); FPAttr.isValid()) {
2643 StringRef FP = FPAttr.getValueAsString();
2644 if (FP != "all" && FP != "non-leaf" && FP != "none" && FP != "reserved" &&
2645 FP != "non-leaf-no-reserve")
2646 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2647 }
2648
2649 checkUnsignedBaseTenFuncAttr(Attrs, "tail-pad-to-size", V);
2650 checkUnsignedBaseTenFuncAttr(Attrs, "tail-pad-value", V);
2651 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2652 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2653 if (Attrs.hasFnAttr("patchable-function-entry-section"))
2654 Check(!Attrs.getFnAttr("patchable-function-entry-section")
2655 .getValueAsString()
2656 .empty(),
2657 "\"patchable-function-entry-section\" must not be empty");
2658 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2659
2660 if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
2661 StringRef S = A.getValueAsString();
2662 if (S != "none" && S != "all" && S != "non-leaf")
2663 CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
2664 }
2665
2666 if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
2667 StringRef S = A.getValueAsString();
2668 if (S != "a_key" && S != "b_key")
2669 CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
2670 V);
2671 if (auto AA = Attrs.getFnAttr("sign-return-address"); !AA.isValid()) {
2672 CheckFailed(
2673 "'sign-return-address-key' present without `sign-return-address`");
2674 }
2675 }
2676
2677 if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
2678 StringRef S = A.getValueAsString();
2679 if (S != "" && S != "true" && S != "false")
2680 CheckFailed(
2681 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2682 }
2683
2684 if (auto A = Attrs.getFnAttr("branch-protection-pauth-lr"); A.isValid()) {
2685 StringRef S = A.getValueAsString();
2686 if (S != "" && S != "true" && S != "false")
2687 CheckFailed(
2688 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2689 }
2690
2691 if (auto A = Attrs.getFnAttr("guarded-control-stack"); A.isValid()) {
2692 StringRef S = A.getValueAsString();
2693 if (S != "" && S != "true" && S != "false")
2694 CheckFailed("invalid value for 'guarded-control-stack' attribute: " + S,
2695 V);
2696 }
2697
2698 if (auto A = Attrs.getFnAttr("vector-function-abi-variant"); A.isValid()) {
2699 StringRef S = A.getValueAsString();
2700 const std::optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, FT);
2701 if (!Info)
2702 CheckFailed("invalid name for a VFABI variant: " + S, V);
2703 }
2704
2705 if (auto A = Attrs.getFnAttr("modular-format"); A.isValid()) {
2706 StringRef S = A.getValueAsString();
2708 S.split(Args, ',');
2709 Check(Args.size() >= 5,
2710 "modular-format attribute requires at least 5 arguments", V);
2711 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2712 unsigned FormatIdx;
2713 Check(!Args[1].getAsInteger(10, FormatIdx),
2714 "modular-format attribute format string index is not an integer", V);
2715 Check(FormatIdx > 0,
2716 "modular-format attribute format string index must be greater than 0",
2717 V);
2718 Check(FormatIdx <= UpperBound,
2719 "modular-format attribute format string index is out of bounds", V);
2720 unsigned FirstArgIdx;
2721 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2722 "modular-format attribute first arg index is not an integer", V);
2723 Check(FirstArgIdx <= UpperBound,
2724 "modular-format attribute first arg index is out of bounds", V);
2725 Check(!Args[3].empty(),
2726 "modular-format attribute modular implementation function name "
2727 "cannot be empty",
2728 V);
2729 Check(!Args[4].empty(),
2730 "modular-format attribute implementation name cannot be empty", V);
2731 }
2732
2733 if (auto A = Attrs.getFnAttr("target-features"); A.isValid()) {
2734 StringRef S = A.getValueAsString();
2735 if (!S.empty()) {
2736 for (auto FeatureFlag : split(S, ',')) {
2737 if (FeatureFlag.empty())
2738 CheckFailed(
2739 "target-features attribute should not contain an empty string");
2740 else
2741 Check(FeatureFlag[0] == '+' || FeatureFlag[0] == '-',
2742 "target feature '" + FeatureFlag +
2743 "' must start with a '+' or '-'",
2744 V);
2745 }
2746 }
2747 }
2748}
2749void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2750 Check(MD->getNumOperands() == 2,
2751 "'unknown' !prof should have a single additional operand", MD);
2752 auto *PassName = dyn_cast<MDString>(MD->getOperand(1));
2753 Check(PassName != nullptr,
2754 "'unknown' !prof should have an additional operand of type "
2755 "string");
2756 Check(!PassName->getString().empty(),
2757 "the 'unknown' !prof operand should not be an empty string");
2758}
2759
2760void Verifier::verifyFunctionMetadata(
2761 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2762 for (const auto &Pair : MDs) {
2763 if (Pair.first == LLVMContext::MD_prof) {
2764 MDNode *MD = Pair.second;
2765 Check(MD->getNumOperands() >= 2,
2766 "!prof annotations should have no less than 2 operands", MD);
2767 // We may have functions that are synthesized by the compiler, e.g. in
2768 // WPD, that we can't currently determine the entry count.
2769 if (MD->getOperand(0).equalsStr(
2771 verifyUnknownProfileMetadata(MD);
2772 continue;
2773 }
2774
2775 // Check first operand.
2776 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
2777 MD);
2779 "expected string with name of the !prof annotation", MD);
2780 MDString *MDS = cast<MDString>(MD->getOperand(0));
2781 StringRef ProfName = MDS->getString();
2784 "first operand should be 'function_entry_count'"
2785 " or 'synthetic_function_entry_count'",
2786 MD);
2787
2788 // Check second operand.
2789 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
2790 MD);
2792 "expected integer argument to function_entry_count", MD);
2793 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2794 MDNode *MD = Pair.second;
2795 Check(MD->getNumOperands() == 1,
2796 "!kcfi_type must have exactly one operand", MD);
2797 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2798 MD);
2800 "expected a constant operand for !kcfi_type", MD);
2801 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2802 Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2803 "expected a constant integer operand for !kcfi_type", MD);
2805 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2806 } else if (Pair.first == Context.getMDKindID("reqd_work_group_size")) {
2807 MDNode *MD = Pair.second;
2808 Check(MD->getNumOperands() == 3,
2809 "reqd_work_group_size must have exactly three operands", MD);
2810 if (MD->getNumOperands() != 3)
2811 continue;
2812
2813 uint64_t Product = 1;
2814 for (unsigned I = 0; I != 3; ++I) {
2815 ConstantInt *C = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
2816 Check(C, "reqd_work_group_size operands must be integer constants", MD);
2817 if (!C)
2818 break;
2819
2820 const APInt &Value = C->getValue();
2821 Check(Value.getActiveBits() <= 64,
2822 "reqd_work_group_size operands must fit in 64 bits", MD);
2823 if (Value.getActiveBits() > 64)
2824 break;
2825
2826 uint64_t Dim = Value.getZExtValue();
2827 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2828 "reqd_work_group_size product must fit in 64 bits", MD);
2829 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2830 break;
2831 Product *= Dim;
2832 }
2833 }
2834 }
2835}
2836
2837void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2838 if (EntryC->getNumOperands() == 0)
2839 return;
2840
2841 if (!ConstantExprVisited.insert(EntryC).second)
2842 return;
2843
2845 Stack.push_back(EntryC);
2846
2847 while (!Stack.empty()) {
2848 const Constant *C = Stack.pop_back_val();
2849
2850 // Check this constant expression.
2851 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2852 visitConstantExpr(CE);
2853
2854 if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C))
2855 visitConstantPtrAuth(CPA);
2856
2857 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2858 // Global Values get visited separately, but we do need to make sure
2859 // that the global value is in the correct module
2860 Check(GV->getParent() == &M, "Referencing global in another module!",
2861 EntryC, &M, GV, GV->getParent());
2862 continue;
2863 }
2864
2865 // Visit all sub-expressions.
2866 for (const Use &U : C->operands()) {
2867 const auto *OpC = dyn_cast<Constant>(U);
2868 if (!OpC)
2869 continue;
2870 if (!ConstantExprVisited.insert(OpC).second)
2871 continue;
2872 Stack.push_back(OpC);
2873 }
2874 }
2875}
2876
2877void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2878 if (CE->getOpcode() == Instruction::BitCast)
2879 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2880 CE->getType()),
2881 "Invalid bitcast", CE);
2882 else if (CE->getOpcode() == Instruction::PtrToAddr)
2883 checkPtrToAddr(CE->getOperand(0)->getType(), CE->getType(), *CE);
2884}
2885
2886void Verifier::visitConstantPtrAuth(const ConstantPtrAuth *CPA) {
2887 Check(CPA->getPointer()->getType()->isPointerTy(),
2888 "signed ptrauth constant base pointer must have pointer type");
2889
2890 Check(CPA->getType() == CPA->getPointer()->getType(),
2891 "signed ptrauth constant must have same type as its base pointer");
2892
2893 Check(CPA->getKey()->getBitWidth() == 32,
2894 "signed ptrauth constant key must be i32 constant integer");
2895
2897 "signed ptrauth constant address discriminator must be a pointer");
2898
2899 Check(CPA->getDiscriminator()->getBitWidth() == 64,
2900 "signed ptrauth constant discriminator must be i64 constant integer");
2901
2903 "signed ptrauth constant deactivation symbol must be a pointer");
2904
2907 "signed ptrauth constant deactivation symbol must be a global value "
2908 "or null");
2909}
2910
2911bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2912 // There shouldn't be more attribute sets than there are parameters plus the
2913 // function and return value.
2914 return Attrs.getNumAttrSets() <= Params + 2;
2915}
2916
2917void Verifier::verifyInlineAsmCall(const CallBase &Call) {
2918 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
2919 unsigned ArgNo = 0;
2920 unsigned LabelNo = 0;
2921 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2922 if (CI.Type == InlineAsm::isLabel) {
2923 ++LabelNo;
2924 continue;
2925 }
2926
2927 // Only deal with constraints that correspond to call arguments.
2928 if (!CI.hasArg())
2929 continue;
2930
2931 if (CI.isIndirect) {
2932 const Value *Arg = Call.getArgOperand(ArgNo);
2933 Check(Arg->getType()->isPointerTy(),
2934 "Operand for indirect constraint must have pointer type", &Call);
2935
2937 "Operand for indirect constraint must have elementtype attribute",
2938 &Call);
2939 } else {
2940 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
2941 "Elementtype attribute can only be applied for indirect "
2942 "constraints",
2943 &Call);
2944 }
2945
2946 ArgNo++;
2947 }
2948
2949 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2950 Check(LabelNo == CallBr->getNumIndirectDests(),
2951 "Number of label constraints does not match number of callbr dests",
2952 &Call);
2953 } else {
2954 Check(LabelNo == 0, "Label constraints can only be used with callbr",
2955 &Call);
2956 }
2957}
2958
2959/// Verify that statepoint intrinsic is well formed.
2960void Verifier::verifyStatepoint(const CallBase &Call) {
2961 assert(Call.getIntrinsicID() == Intrinsic::experimental_gc_statepoint);
2962
2965 "gc.statepoint must read and write all memory to preserve "
2966 "reordering restrictions required by safepoint semantics",
2967 Call);
2968
2969 const int64_t NumPatchBytes =
2970 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2971 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2972 Check(NumPatchBytes >= 0,
2973 "gc.statepoint number of patchable bytes must be "
2974 "positive",
2975 Call);
2976
2977 Type *TargetElemType = Call.getParamElementType(2);
2978 Check(TargetElemType,
2979 "gc.statepoint callee argument must have elementtype attribute", Call);
2980 auto *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2981 Check(TargetFuncType,
2982 "gc.statepoint callee elementtype must be function type", Call);
2983
2984 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2985 Check(NumCallArgs >= 0,
2986 "gc.statepoint number of arguments to underlying call "
2987 "must be positive",
2988 Call);
2989 const int NumParams = (int)TargetFuncType->getNumParams();
2990 if (TargetFuncType->isVarArg()) {
2991 Check(NumCallArgs >= NumParams,
2992 "gc.statepoint mismatch in number of vararg call args", Call);
2993
2994 // TODO: Remove this limitation
2995 Check(TargetFuncType->getReturnType()->isVoidTy(),
2996 "gc.statepoint doesn't support wrapping non-void "
2997 "vararg functions yet",
2998 Call);
2999 } else
3000 Check(NumCallArgs == NumParams,
3001 "gc.statepoint mismatch in number of call args", Call);
3002
3003 const uint64_t Flags
3004 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
3005 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
3006 "unknown flag used in gc.statepoint flags argument", Call);
3007
3008 // Verify that the types of the call parameter arguments match
3009 // the type of the wrapped callee.
3010 AttributeList Attrs = Call.getAttributes();
3011 for (int i = 0; i < NumParams; i++) {
3012 Type *ParamType = TargetFuncType->getParamType(i);
3013 Type *ArgType = Call.getArgOperand(5 + i)->getType();
3014 Check(ArgType == ParamType,
3015 "gc.statepoint call argument does not match wrapped "
3016 "function type",
3017 Call);
3018
3019 if (TargetFuncType->isVarArg()) {
3020 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
3021 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
3022 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
3023 }
3024 }
3025
3026 const int EndCallArgsInx = 4 + NumCallArgs;
3027
3028 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
3029 Check(isa<ConstantInt>(NumTransitionArgsV),
3030 "gc.statepoint number of transition arguments "
3031 "must be constant integer",
3032 Call);
3033 const int NumTransitionArgs =
3034 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
3035 Check(NumTransitionArgs == 0,
3036 "gc.statepoint w/inline transition bundle is deprecated", Call);
3037 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3038
3039 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
3040 Check(isa<ConstantInt>(NumDeoptArgsV),
3041 "gc.statepoint number of deoptimization arguments "
3042 "must be constant integer",
3043 Call);
3044 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
3045 Check(NumDeoptArgs == 0,
3046 "gc.statepoint w/inline deopt operands is deprecated", Call);
3047
3048 const int ExpectedNumArgs = 7 + NumCallArgs;
3049 Check(ExpectedNumArgs == (int)Call.arg_size(),
3050 "gc.statepoint too many arguments", Call);
3051
3052 // Check that the only uses of this gc.statepoint are gc.result or
3053 // gc.relocate calls which are tied to this statepoint and thus part
3054 // of the same statepoint sequence
3055 for (const User *U : Call.users()) {
3056 const auto *UserCall = dyn_cast<const CallInst>(U);
3057 Check(UserCall, "illegal use of statepoint token", Call, U);
3058 if (!UserCall)
3059 continue;
3060 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
3061 "gc.result or gc.relocate are the only value uses "
3062 "of a gc.statepoint",
3063 Call, U);
3064 if (isa<GCResultInst>(UserCall)) {
3065 Check(UserCall->getArgOperand(0) == &Call,
3066 "gc.result connected to wrong gc.statepoint", Call, UserCall);
3067 } else if (isa<GCRelocateInst>(Call)) {
3068 Check(UserCall->getArgOperand(0) == &Call,
3069 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
3070 }
3071 }
3072
3073 // Note: It is legal for a single derived pointer to be listed multiple
3074 // times. It's non-optimal, but it is legal. It can also happen after
3075 // insertion if we strip a bitcast away.
3076 // Note: It is really tempting to check that each base is relocated and
3077 // that a derived pointer is never reused as a base pointer. This turns
3078 // out to be problematic since optimizations run after safepoint insertion
3079 // can recognize equality properties that the insertion logic doesn't know
3080 // about. See example statepoint.ll in the verifier subdirectory
3081}
3082
3083void Verifier::verifyFrameRecoverIndices() {
3084 for (auto &Counts : FrameEscapeInfo) {
3085 Function *F = Counts.first;
3086 unsigned EscapedObjectCount = Counts.second.first;
3087 unsigned MaxRecoveredIndex = Counts.second.second;
3088 Check(MaxRecoveredIndex <= EscapedObjectCount,
3089 "all indices passed to llvm.localrecover must be less than the "
3090 "number of arguments passed to llvm.localescape in the parent "
3091 "function",
3092 F);
3093 }
3094}
3095
3096static Instruction *getSuccPad(Instruction *Terminator) {
3097 BasicBlock *UnwindDest;
3098 if (auto *II = dyn_cast<InvokeInst>(Terminator))
3099 UnwindDest = II->getUnwindDest();
3100 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
3101 UnwindDest = CSI->getUnwindDest();
3102 else
3103 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
3104 return &*UnwindDest->getFirstNonPHIIt();
3105}
3106
3107void Verifier::verifySiblingFuncletUnwinds() {
3108 llvm::TimeTraceScope timeScope("Verifier verify sibling funclet unwinds");
3109 SmallPtrSet<Instruction *, 8> Visited;
3110 SmallPtrSet<Instruction *, 8> Active;
3111 for (const auto &Pair : SiblingFuncletInfo) {
3112 Instruction *PredPad = Pair.first;
3113 if (Visited.count(PredPad))
3114 continue;
3115 Active.insert(PredPad);
3116 Instruction *Terminator = Pair.second;
3117 do {
3118 Instruction *SuccPad = getSuccPad(Terminator);
3119 if (Active.count(SuccPad)) {
3120 // Found a cycle; report error
3121 Instruction *CyclePad = SuccPad;
3122 SmallVector<Instruction *, 8> CycleNodes;
3123 do {
3124 CycleNodes.push_back(CyclePad);
3125 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3126 if (CycleTerminator != CyclePad)
3127 CycleNodes.push_back(CycleTerminator);
3128 CyclePad = getSuccPad(CycleTerminator);
3129 } while (CyclePad != SuccPad);
3130 Check(false, "EH pads can't handle each other's exceptions",
3131 ArrayRef<Instruction *>(CycleNodes));
3132 }
3133 // Don't re-walk a node we've already checked
3134 if (!Visited.insert(SuccPad).second)
3135 break;
3136 // Walk to this successor if it has a map entry.
3137 PredPad = SuccPad;
3138 auto TermI = SiblingFuncletInfo.find(PredPad);
3139 if (TermI == SiblingFuncletInfo.end())
3140 break;
3141 Terminator = TermI->second;
3142 Active.insert(PredPad);
3143 } while (true);
3144 // Each node only has one successor, so we've walked all the active
3145 // nodes' successors.
3146 Active.clear();
3147 }
3148}
3149
3150// visitFunction - Verify that a function is ok.
3151//
3152void Verifier::visitFunction(const Function &F) {
3153 visitGlobalValue(F);
3154
3155 // Check function arguments.
3156 FunctionType *FT = F.getFunctionType();
3157 unsigned NumArgs = F.arg_size();
3158
3159 Check(&Context == &F.getContext(),
3160 "Function context does not match Module context!", &F);
3161
3162 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
3163 Check(FT->getNumParams() == NumArgs,
3164 "# formal arguments must match # of arguments for function type!", &F,
3165 FT);
3166 Check(F.getReturnType()->isFirstClassType() ||
3167 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
3168 "Functions cannot return aggregate values!", &F);
3169
3170 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
3171 "Invalid struct return type!", &F);
3172
3173 if (MaybeAlign A = F.getAlign()) {
3174 Check(A->value() <= Value::MaximumAlignment,
3175 "huge alignment values are unsupported", &F);
3176 }
3177
3178 AttributeList Attrs = F.getAttributes();
3179
3180 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3181 "Attribute after last parameter!", &F);
3182
3183 bool IsIntrinsic = F.isIntrinsic();
3184
3185 // Check function attributes.
3186 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
3187
3188 // On function declarations/definitions, we do not support the builtin
3189 // attribute. We do not check this in VerifyFunctionAttrs since that is
3190 // checking for Attributes that can/can not ever be on functions.
3191 Check(!Attrs.hasFnAttr(Attribute::Builtin),
3192 "Attribute 'builtin' can only be applied to a callsite.", &F);
3193
3194 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
3195 "Attribute 'elementtype' can only be applied to a callsite.", &F);
3196
3197 if (Attrs.hasFnAttr(Attribute::Naked))
3198 for (const Argument &Arg : F.args())
3199 Check(Arg.use_empty(), "cannot use argument of naked function", &Arg);
3200
3201 // Check that this function meets the restrictions on this calling convention.
3202 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
3203 // restrictions can be lifted.
3204 switch (F.getCallingConv()) {
3205 default:
3206 case CallingConv::C:
3207 break;
3208 case CallingConv::X86_INTR: {
3209 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
3210 "Calling convention parameter requires byval", &F);
3211 break;
3212 }
3213 case CallingConv::AMDGPU_KERNEL:
3214 case CallingConv::SPIR_KERNEL:
3215 case CallingConv::AMDGPU_CS_Chain:
3216 case CallingConv::AMDGPU_CS_ChainPreserve:
3217 Check(F.getReturnType()->isVoidTy(),
3218 "Calling convention requires void return type", &F);
3219 [[fallthrough]];
3220 case CallingConv::AMDGPU_VS:
3221 case CallingConv::AMDGPU_HS:
3222 case CallingConv::AMDGPU_GS:
3223 case CallingConv::AMDGPU_PS:
3224 case CallingConv::AMDGPU_CS:
3225 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
3226 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3227 const unsigned StackAS = DL.getAllocaAddrSpace();
3228 unsigned i = 0;
3229 for (const Argument &Arg : F.args()) {
3230 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
3231 "Calling convention disallows byval", &F);
3232 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
3233 "Calling convention disallows preallocated", &F);
3234 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
3235 "Calling convention disallows inalloca", &F);
3236
3237 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
3238 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
3239 // value here.
3240 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3241 "Calling convention disallows stack byref", &F);
3242 }
3243
3244 ++i;
3245 }
3246 }
3247
3248 [[fallthrough]];
3249 case CallingConv::Fast:
3250 case CallingConv::Cold:
3251 case CallingConv::Intel_OCL_BI:
3252 case CallingConv::PTX_Kernel:
3253 case CallingConv::PTX_Device:
3254 Check(!F.isVarArg(),
3255 "Calling convention does not support varargs or "
3256 "perfect forwarding!",
3257 &F);
3258 break;
3259 case CallingConv::AMDGPU_Gfx_WholeWave:
3260 Check(!F.arg_empty() && F.arg_begin()->getType()->isIntegerTy(1),
3261 "Calling convention requires first argument to be i1", &F);
3262 Check(!F.arg_begin()->hasInRegAttr(),
3263 "Calling convention requires first argument to not be inreg", &F);
3264 Check(!F.isVarArg(),
3265 "Calling convention does not support varargs or "
3266 "perfect forwarding!",
3267 &F);
3268 break;
3269 }
3270
3271 // Check that the argument values match the function type for this function...
3272 unsigned i = 0;
3273 for (const Argument &Arg : F.args()) {
3274 Check(Arg.getType() == FT->getParamType(i),
3275 "Argument value does not match function argument type!", &Arg,
3276 FT->getParamType(i));
3277 Check(Arg.getType()->isFirstClassType(),
3278 "Function arguments must have first-class types!", &Arg);
3279 if (!IsIntrinsic) {
3280 Check(!Arg.getType()->isMetadataTy(),
3281 "Function takes metadata but isn't an intrinsic", &Arg, &F);
3282 Check(!Arg.getType()->isTokenLikeTy(),
3283 "Function takes token but isn't an intrinsic", &Arg, &F);
3284 Check(!Arg.getType()->isX86_AMXTy(),
3285 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
3286 }
3287
3288 // Check that swifterror argument is only used by loads and stores.
3289 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3290 verifySwiftErrorValue(&Arg);
3291 }
3292 ++i;
3293 }
3294
3295 if (!IsIntrinsic) {
3296 Check(!F.getReturnType()->isTokenLikeTy(),
3297 "Function returns a token but isn't an intrinsic", &F);
3298 Check(!F.getReturnType()->isX86_AMXTy(),
3299 "Function returns a x86_amx but isn't an intrinsic", &F);
3300 }
3301
3302 // Get the function metadata attachments.
3304 F.getAllMetadata(MDs);
3305 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
3306 verifyFunctionMetadata(MDs);
3307
3308 // Target-specific function metadata checks.
3310
3311 // Check validity of the personality function
3312 if (F.hasPersonalityFn()) {
3313 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
3314 if (Per)
3315 Check(Per->getParent() == F.getParent(),
3316 "Referencing personality function in another module!", &F,
3317 F.getParent(), Per, Per->getParent());
3318 }
3319
3320 // EH funclet coloring can be expensive, recompute on-demand
3321 BlockEHFuncletColors.clear();
3322
3323 if (F.isMaterializable()) {
3324 // Function has a body somewhere we can't see.
3325 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
3326 MDs.empty() ? nullptr : MDs.front().second);
3327 } else if (F.isDeclaration()) {
3328 for (const auto &I : MDs) {
3329 // This is used for call site debug information.
3330 CheckDI(I.first != LLVMContext::MD_dbg ||
3331 !cast<DISubprogram>(I.second)->isDistinct(),
3332 "function declaration may only have a unique !dbg attachment",
3333 &F);
3334 Check(I.first != LLVMContext::MD_prof,
3335 "function declaration may not have a !prof attachment", &F);
3336
3337 // Verify the metadata itself.
3338 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
3339 }
3340 Check(!F.hasPersonalityFn(),
3341 "Function declaration shouldn't have a personality routine", &F);
3342 } else {
3343 // Verify that this function (which has a body) is not named "llvm.*". It
3344 // is not legal to define intrinsics.
3345 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
3346
3347 // Check the entry node
3348 const BasicBlock *Entry = &F.getEntryBlock();
3349 Check(pred_empty(Entry),
3350 "Entry block to function must not have predecessors!", Entry);
3351
3352 // The address of the entry block cannot be taken, unless it is dead.
3353 if (Entry->hasAddressTaken()) {
3354 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
3355 "blockaddress may not be used with the entry block!", Entry);
3356 }
3357
3358 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3359 NumKCFIAttachments = 0;
3360 // Visit metadata attachments.
3361 for (const auto &I : MDs) {
3362 // Verify that the attachment is legal.
3363 auto AllowLocs = AreDebugLocsAllowed::No;
3364 switch (I.first) {
3365 default:
3366 break;
3367 case LLVMContext::MD_dbg: {
3368 ++NumDebugAttachments;
3369 CheckDI(NumDebugAttachments == 1,
3370 "function must have a single !dbg attachment", &F, I.second);
3371 CheckDI(isa<DISubprogram>(I.second),
3372 "function !dbg attachment must be a subprogram", &F, I.second);
3373 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
3374 "function definition may only have a distinct !dbg attachment",
3375 &F);
3376
3377 auto *SP = cast<DISubprogram>(I.second);
3378 const Function *&AttachedTo = DISubprogramAttachments[SP];
3379 CheckDI(!AttachedTo || AttachedTo == &F,
3380 "DISubprogram attached to more than one function", SP, &F);
3381 AttachedTo = &F;
3382 AllowLocs = AreDebugLocsAllowed::Yes;
3383 break;
3384 }
3385 case LLVMContext::MD_prof:
3386 ++NumProfAttachments;
3387 Check(NumProfAttachments == 1,
3388 "function must have a single !prof attachment", &F, I.second);
3389 break;
3390 case LLVMContext::MD_kcfi_type:
3391 ++NumKCFIAttachments;
3392 Check(NumKCFIAttachments == 1,
3393 "function must have a single !kcfi_type attachment", &F,
3394 I.second);
3395 break;
3396 }
3397
3398 // Verify the metadata itself.
3399 visitMDNode(*I.second, AllowLocs);
3400 }
3401 }
3402
3403 // If this function is actually an intrinsic, verify that it is only used in
3404 // direct call/invokes, never having its "address taken".
3405 // Only do this if the module is materialized, otherwise we don't have all the
3406 // uses.
3407 bool isMaterialized = F.getParent()->isMaterialized();
3408 if (F.isIntrinsic() && isMaterialized) {
3409 const User *U;
3410 if (F.hasAddressTaken(&U, false, true, false,
3411 /*IgnoreARCAttachedCall=*/true))
3412 Check(false, "Invalid user of intrinsic instruction!", U);
3413 }
3414
3415 // Verify if the intrinsic's signature and name are valid. We do this if
3416 // the intrinsic has at least one materialized use, or if the module is fully
3417 // materialized.
3418 Intrinsic::ID IID = F.getIntrinsicID();
3419 if (IID && (isMaterialized || !F.materialized_use_empty())) {
3420 // Verify that the intrinsic prototype lines up with what the .td files
3421 // describe.
3422 std::string ErrMsg;
3423 raw_string_ostream ErrOS(ErrMsg);
3424 SmallVector<Type *, 4> OverloadTys;
3425 bool IsValid = Intrinsic::isSignatureValid(IID, FT, OverloadTys, ErrOS);
3426 Printable PrintDecl([&F](raw_ostream &OS) { F.print(OS); });
3427 Check(IsValid, ErrMsg, PrintDecl);
3428
3429 // Now that we have the intrinsic ID and the actual argument types (and we
3430 // know they are legal for the intrinsic!) get the intrinsic name through
3431 // the usual means. This allows us to verify the mangling of argument types
3432 // into the name.
3433 const std::string ExpectedName = Intrinsic::getName(
3434 IID, OverloadTys, const_cast<Module *>(F.getParent()), FT);
3435 Check(ExpectedName == F.getName(),
3436 "Intrinsic name not mangled correctly for type arguments! "
3437 "Should be: " +
3438 ExpectedName,
3439 PrintDecl);
3440 }
3441
3442 auto *N = F.getSubprogram();
3443 HasDebugInfo = (N != nullptr);
3444 if (!HasDebugInfo)
3445 return;
3446
3447 // Check that all !dbg attachments lead to back to N.
3448 //
3449 // FIXME: Check this incrementally while visiting !dbg attachments.
3450 // FIXME: Only check when N is the canonical subprogram for F.
3451 SmallPtrSet<const MDNode *, 32> Seen;
3452 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
3453 // Be careful about using DILocation here since we might be dealing with
3454 // broken code (this is the Verifier after all).
3455 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
3456 if (!DL)
3457 return;
3458 if (!Seen.insert(DL).second)
3459 return;
3460
3461 Metadata *Parent = DL->getRawScope();
3462 CheckDI(Parent && isa<DILocalScope>(Parent),
3463 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
3464
3465 DILocalScope *Scope = DL->getInlinedAtScope();
3466 Check(Scope, "Failed to find DILocalScope", DL);
3467
3468 if (!Seen.insert(Scope).second)
3469 return;
3470
3471 // Cycles are diagnosed when the DIScope nodes themselves are visited.
3472 if (hasDIScopeCycle(Scope))
3473 return;
3474
3475 DISubprogram *SP = Scope->getSubprogram();
3476
3477 // Scope and SP could be the same MDNode and we don't want to skip
3478 // validation in that case
3479 if ((Scope != SP) && !Seen.insert(SP).second)
3480 return;
3481
3482 CheckDI(SP->describes(&F),
3483 "!dbg attachment points at wrong subprogram for function", N, &F,
3484 &I, DL, Scope, SP);
3485 };
3486 for (auto &BB : F)
3487 for (auto &I : BB) {
3488 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
3489 // The llvm.loop annotations also contain two DILocations.
3490 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
3491 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
3492 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
3493 if (BrokenDebugInfo)
3494 return;
3495 }
3496}
3497
3498// verifyBasicBlock - Verify that a basic block is well formed...
3499//
3500void Verifier::visitBasicBlock(BasicBlock &BB) {
3501 InstsInThisBlock.clear();
3502 ConvergenceVerifyHelper.visit(BB);
3503
3504 // Ensure that basic blocks have terminators!
3505 Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
3506
3507 // Check constraints that this basic block imposes on all of the PHI nodes in
3508 // it.
3509 if (isa<PHINode>(BB.front())) {
3510 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
3512 llvm::sort(Preds);
3513 for (const PHINode &PN : BB.phis()) {
3514 Check(PN.getNumIncomingValues() == Preds.size(),
3515 "PHINode should have one entry for each predecessor of its "
3516 "parent basic block!",
3517 &PN);
3518
3519 // Get and sort all incoming values in the PHI node...
3520 Values.clear();
3521 Values.reserve(PN.getNumIncomingValues());
3522 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3523 Values.push_back(
3524 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3526
3527 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
3528 // Check to make sure that if there is more than one entry for a
3529 // particular basic block in this PHI node, that the incoming values are
3530 // all identical.
3531 //
3532 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3533 Values[i].second == Values[i - 1].second,
3534 "PHI node has multiple entries for the same basic block with "
3535 "different incoming values!",
3536 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3537
3538 // Check to make sure that the predecessors and PHI node entries are
3539 // matched up.
3540 Check(Values[i].first == Preds[i],
3541 "PHI node entries do not match predecessors!", &PN,
3542 Values[i].first, Preds[i]);
3543 }
3544 }
3545 }
3546
3547 // Check that all instructions have their parent pointers set up correctly.
3548 for (auto &I : BB)
3549 {
3550 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
3551 }
3552
3553 // Confirm that no issues arise from the debug program.
3554 CheckDI(!BB.getTrailingDbgRecords(), "Basic Block has trailing DbgRecords!",
3555 &BB);
3556}
3557
3558void Verifier::visitTerminator(Instruction &I) {
3559 // Ensure that terminators only exist at the end of the basic block.
3560 Check(&I == I.getParent()->getTerminator(),
3561 "Terminator found in the middle of a basic block!", I.getParent());
3562 visitInstruction(I);
3563}
3564
3565void Verifier::visitCondBrInst(CondBrInst &BI) {
3567 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
3568 visitTerminator(BI);
3569}
3570
3571void Verifier::visitReturnInst(ReturnInst &RI) {
3572 Function *F = RI.getParent()->getParent();
3573 unsigned N = RI.getNumOperands();
3574 if (F->getReturnType()->isVoidTy())
3575 Check(N == 0,
3576 "Found return instr that returns non-void in Function of void "
3577 "return type!",
3578 &RI, F->getReturnType());
3579 else
3580 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
3581 "Function return type does not match operand "
3582 "type of return inst!",
3583 &RI, F->getReturnType());
3584
3585 // Check to make sure that the return value has necessary properties for
3586 // terminators...
3587 visitTerminator(RI);
3588}
3589
3590void Verifier::visitSwitchInst(SwitchInst &SI) {
3591 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
3592 // Check to make sure that all of the constants in the switch instruction
3593 // have the same type as the switched-on value.
3594 Type *SwitchTy = SI.getCondition()->getType();
3595 SmallPtrSet<ConstantInt*, 32> Constants;
3596 for (auto &Case : SI.cases()) {
3597 Check(isa<ConstantInt>(Case.getCaseValue()),
3598 "Case value is not a constant integer.", &SI);
3599 Check(Case.getCaseValue()->getType() == SwitchTy,
3600 "Switch constants must all be same type as switch value!", &SI);
3601 Check(Constants.insert(Case.getCaseValue()).second,
3602 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3603 }
3604
3605 visitTerminator(SI);
3606}
3607
3608void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3610 "Indirectbr operand must have pointer type!", &BI);
3611 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
3613 "Indirectbr destinations must all have pointer type!", &BI);
3614
3615 visitTerminator(BI);
3616}
3617
3619 // Currently we only support callbr for amdgcn.kill. Add more checks here as
3620 // needed.
3621 return isAMDGPUCallBrIntrinsic(ID);
3622}
3623
3624void Verifier::visitCallBrInst(CallBrInst &CBI) {
3625 if (!CBI.isInlineAsm()) {
3627 "callbr: indirect function / invalid signature");
3628 Check(!CBI.hasOperandBundles(),
3629 "callbr for intrinsics currently doesn't support operand bundles");
3630
3632 CheckFailed(
3633 "callbr currently only supports asm-goto and selected intrinsics");
3634 }
3635 visitIntrinsicCall(CBI.getIntrinsicID(), CBI);
3636 } else {
3637 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
3638 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
3639
3640 verifyInlineAsmCall(CBI);
3641 }
3642 visitTerminator(CBI);
3643}
3644
3645void Verifier::visitSelectInst(SelectInst &SI) {
3646 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
3647 SI.getOperand(2)),
3648 "Invalid operands for select instruction!", &SI);
3649
3650 Check(SI.getTrueValue()->getType() == SI.getType(),
3651 "Select values must have same type as select instruction!", &SI);
3652 visitInstruction(SI);
3653}
3654
3655/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3656/// a pass, if any exist, it's an error.
3657///
3658void Verifier::visitUserOp1(Instruction &I) {
3659 Check(false, "User-defined operators should not live outside of a pass!", &I);
3660}
3661
3662void Verifier::visitTruncInst(TruncInst &I) {
3663 // Get the source and destination types
3664 Type *SrcTy = I.getOperand(0)->getType();
3665 Type *DestTy = I.getType();
3666
3667 // Get the size of the types in bits, we'll need this later
3668 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3669 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3670
3671 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
3672 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
3673 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3674 "trunc source and destination must both be a vector or neither", &I);
3675 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
3676
3677 visitInstruction(I);
3678}
3679
3680void Verifier::visitZExtInst(ZExtInst &I) {
3681 // Get the source and destination types
3682 Type *SrcTy = I.getOperand(0)->getType();
3683 Type *DestTy = I.getType();
3684
3685 // Get the size of the types in bits, we'll need this later
3686 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
3687 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
3688 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3689 "zext source and destination must both be a vector or neither", &I);
3690 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3691 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3692
3693 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
3694
3695 visitInstruction(I);
3696}
3697
3698void Verifier::visitSExtInst(SExtInst &I) {
3699 // Get the source and destination types
3700 Type *SrcTy = I.getOperand(0)->getType();
3701 Type *DestTy = I.getType();
3702
3703 // Get the size of the types in bits, we'll need this later
3704 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3705 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3706
3707 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
3708 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
3709 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3710 "sext source and destination must both be a vector or neither", &I);
3711 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
3712
3713 visitInstruction(I);
3714}
3715
3716void Verifier::visitFPTruncInst(FPTruncInst &I) {
3717 // Get the source and destination types
3718 Type *SrcTy = I.getOperand(0)->getType();
3719 Type *DestTy = I.getType();
3720 // Get the size of the types in bits, we'll need this later
3721 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3722 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3723
3724 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
3725 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
3726 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3727 "fptrunc source and destination must both be a vector or neither", &I);
3728 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
3729
3730 visitInstruction(I);
3731}
3732
3733void Verifier::visitFPExtInst(FPExtInst &I) {
3734 // Get the source and destination types
3735 Type *SrcTy = I.getOperand(0)->getType();
3736 Type *DestTy = I.getType();
3737
3738 // Get the size of the types in bits, we'll need this later
3739 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3740 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3741
3742 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
3743 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
3744 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3745 "fpext source and destination must both be a vector or neither", &I);
3746 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
3747
3748 visitInstruction(I);
3749}
3750
3751void Verifier::visitUIToFPInst(UIToFPInst &I) {
3752 // Get the source and destination types
3753 Type *SrcTy = I.getOperand(0)->getType();
3754 Type *DestTy = I.getType();
3755
3756 bool SrcVec = SrcTy->isVectorTy();
3757 bool DstVec = DestTy->isVectorTy();
3758
3759 Check(SrcVec == DstVec,
3760 "UIToFP source and dest must both be vector or scalar", &I);
3761 Check(SrcTy->isIntOrIntVectorTy(),
3762 "UIToFP source must be integer or integer vector", &I);
3763 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3764 &I);
3765
3766 if (SrcVec && DstVec)
3767 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3768 cast<VectorType>(DestTy)->getElementCount(),
3769 "UIToFP source and dest vector length mismatch", &I);
3770
3771 visitInstruction(I);
3772}
3773
3774void Verifier::visitSIToFPInst(SIToFPInst &I) {
3775 // Get the source and destination types
3776 Type *SrcTy = I.getOperand(0)->getType();
3777 Type *DestTy = I.getType();
3778
3779 bool SrcVec = SrcTy->isVectorTy();
3780 bool DstVec = DestTy->isVectorTy();
3781
3782 Check(SrcVec == DstVec,
3783 "SIToFP source and dest must both be vector or scalar", &I);
3784 Check(SrcTy->isIntOrIntVectorTy(),
3785 "SIToFP source must be integer or integer vector", &I);
3786 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3787 &I);
3788
3789 if (SrcVec && DstVec)
3790 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3791 cast<VectorType>(DestTy)->getElementCount(),
3792 "SIToFP source and dest vector length mismatch", &I);
3793
3794 visitInstruction(I);
3795}
3796
3797void Verifier::visitFPToUIInst(FPToUIInst &I) {
3798 // Get the source and destination types
3799 Type *SrcTy = I.getOperand(0)->getType();
3800 Type *DestTy = I.getType();
3801
3802 bool SrcVec = SrcTy->isVectorTy();
3803 bool DstVec = DestTy->isVectorTy();
3804
3805 Check(SrcVec == DstVec,
3806 "FPToUI source and dest must both be vector or scalar", &I);
3807 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
3808 Check(DestTy->isIntOrIntVectorTy(),
3809 "FPToUI result must be integer or integer vector", &I);
3810
3811 if (SrcVec && DstVec)
3812 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3813 cast<VectorType>(DestTy)->getElementCount(),
3814 "FPToUI source and dest vector length mismatch", &I);
3815
3816 visitInstruction(I);
3817}
3818
3819void Verifier::visitFPToSIInst(FPToSIInst &I) {
3820 // Get the source and destination types
3821 Type *SrcTy = I.getOperand(0)->getType();
3822 Type *DestTy = I.getType();
3823
3824 bool SrcVec = SrcTy->isVectorTy();
3825 bool DstVec = DestTy->isVectorTy();
3826
3827 Check(SrcVec == DstVec,
3828 "FPToSI source and dest must both be vector or scalar", &I);
3829 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
3830 Check(DestTy->isIntOrIntVectorTy(),
3831 "FPToSI result must be integer or integer vector", &I);
3832
3833 if (SrcVec && DstVec)
3834 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3835 cast<VectorType>(DestTy)->getElementCount(),
3836 "FPToSI source and dest vector length mismatch", &I);
3837
3838 visitInstruction(I);
3839}
3840
3841void Verifier::checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V) {
3842 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToAddr source must be pointer", V);
3843 Check(DestTy->isIntOrIntVectorTy(), "PtrToAddr result must be integral", V);
3844 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToAddr type mismatch",
3845 V);
3846
3847 if (SrcTy->isVectorTy()) {
3848 auto *VSrc = cast<VectorType>(SrcTy);
3849 auto *VDest = cast<VectorType>(DestTy);
3850 Check(VSrc->getElementCount() == VDest->getElementCount(),
3851 "PtrToAddr vector length mismatch", V);
3852 }
3853
3854 Type *AddrTy = DL.getAddressType(SrcTy);
3855 Check(AddrTy == DestTy, "PtrToAddr result must be address width", V);
3856}
3857
3858void Verifier::visitPtrToAddrInst(PtrToAddrInst &I) {
3859 checkPtrToAddr(I.getOperand(0)->getType(), I.getType(), I);
3860 visitInstruction(I);
3861}
3862
3863void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
3864 // Get the source and destination types
3865 Type *SrcTy = I.getOperand(0)->getType();
3866 Type *DestTy = I.getType();
3867
3868 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3869
3870 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3871 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3872 &I);
3873
3874 if (SrcTy->isVectorTy()) {
3875 auto *VSrc = cast<VectorType>(SrcTy);
3876 auto *VDest = cast<VectorType>(DestTy);
3877 Check(VSrc->getElementCount() == VDest->getElementCount(),
3878 "PtrToInt Vector length mismatch", &I);
3879 }
3880
3881 visitInstruction(I);
3882}
3883
3884void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3885 // Get the source and destination types
3886 Type *SrcTy = I.getOperand(0)->getType();
3887 Type *DestTy = I.getType();
3888
3889 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
3890 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3891
3892 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3893 &I);
3894 if (SrcTy->isVectorTy()) {
3895 auto *VSrc = cast<VectorType>(SrcTy);
3896 auto *VDest = cast<VectorType>(DestTy);
3897 Check(VSrc->getElementCount() == VDest->getElementCount(),
3898 "IntToPtr Vector length mismatch", &I);
3899 }
3900 visitInstruction(I);
3901}
3902
3903void Verifier::visitBitCastInst(BitCastInst &I) {
3904 Check(
3905 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3906 "Invalid bitcast", &I);
3907 visitInstruction(I);
3908}
3909
3910void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3911 Type *SrcTy = I.getOperand(0)->getType();
3912 Type *DestTy = I.getType();
3913
3914 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3915 &I);
3916 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3917 &I);
3919 "AddrSpaceCast must be between different address spaces", &I);
3920 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3921 Check(SrcVTy->getElementCount() ==
3922 cast<VectorType>(DestTy)->getElementCount(),
3923 "AddrSpaceCast vector pointer number of elements mismatch", &I);
3924 visitInstruction(I);
3925}
3926
3927/// visitPHINode - Ensure that a PHI node is well formed.
3928///
3929void Verifier::visitPHINode(PHINode &PN) {
3930 // Ensure that the PHI nodes are all grouped together at the top of the block.
3931 // This can be tested by checking whether the instruction before this is
3932 // either nonexistent (because this is begin()) or is a PHI node. If not,
3933 // then there is some other instruction before a PHI.
3934 Check(&PN == &PN.getParent()->front() ||
3936 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3937
3938 // Check that a PHI doesn't yield a Token.
3939 Check(!PN.getType()->isTokenLikeTy(), "PHI nodes cannot have token type!");
3940
3941 // Check that all of the values of the PHI node have the same type as the
3942 // result.
3943 for (Value *IncValue : PN.incoming_values()) {
3944 Check(PN.getType() == IncValue->getType(),
3945 "PHI node operands are not the same type as the result!", &PN);
3946 }
3947
3948 // All other PHI node constraints are checked in the visitBasicBlock method.
3949
3950 visitInstruction(PN);
3951}
3952
3953void Verifier::visitCallBase(CallBase &Call) {
3955 "Called function must be a pointer!", Call);
3956 FunctionType *FTy = Call.getFunctionType();
3957
3958 // Verify that the correct number of arguments are being passed
3959 if (FTy->isVarArg())
3960 Check(Call.arg_size() >= FTy->getNumParams(),
3961 "Called function requires more parameters than were provided!", Call);
3962 else
3963 Check(Call.arg_size() == FTy->getNumParams(),
3964 "Incorrect number of arguments passed to called function!", Call);
3965
3966 // Verify that all arguments to the call match the function type.
3967 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3968 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3969 "Call parameter type does not match function signature!",
3970 Call.getArgOperand(i), FTy->getParamType(i), Call);
3971
3972 AttributeList Attrs = Call.getAttributes();
3973
3974 Check(verifyAttributeCount(Attrs, Call.arg_size()),
3975 "Attribute after last parameter!", Call);
3976
3977 auto *Callee =
3979 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3980 if (IsIntrinsic)
3981 Check(Callee->getFunctionType() == FTy,
3982 "Intrinsic called with incompatible signature", Call);
3983
3984 // Verify if the calling convention of the callee is callable.
3986 "calling convention does not permit calls", Call);
3987
3988 // Disallow passing/returning values with alignment higher than we can
3989 // represent.
3990 // FIXME: Consider making DataLayout cap the alignment, so this isn't
3991 // necessary.
3992 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
3993 if (!Ty->isSized())
3994 return;
3995 Align ABIAlign = DL.getABITypeAlign(Ty);
3996 Check(ABIAlign.value() <= Value::MaximumAlignment,
3997 "Incorrect alignment of " + Message + " to called function!", Call);
3998 };
3999
4000 if (!IsIntrinsic) {
4001 VerifyTypeAlign(FTy->getReturnType(), "return type");
4002 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4003 Type *Ty = FTy->getParamType(i);
4004 VerifyTypeAlign(Ty, "argument passed");
4005 }
4006 }
4007
4008 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
4009 // Don't allow speculatable on call sites, unless the underlying function
4010 // declaration is also speculatable.
4011 Check(Callee && Callee->isSpeculatable(),
4012 "speculatable attribute may not apply to call sites", Call);
4013 }
4014
4015 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
4016 Check(Call.getIntrinsicID() == Intrinsic::call_preallocated_arg,
4017 "preallocated as a call site attribute can only be on "
4018 "llvm.call.preallocated.arg");
4019 }
4020
4021 Check(!Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4022 "denormal_fpenv attribute may not apply to call sites", Call);
4023
4024 // Verify call attributes.
4025 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
4026
4027 // Conservatively check the inalloca argument.
4028 // We have a bug if we can find that there is an underlying alloca without
4029 // inalloca.
4030 if (Call.hasInAllocaArgument()) {
4031 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
4032 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
4033 Check(AI->isUsedWithInAlloca(),
4034 "inalloca argument for call has mismatched alloca", AI, Call);
4035 }
4036
4037 // For each argument of the callsite, if it has the swifterror argument,
4038 // make sure the underlying alloca/parameter it comes from has a swifterror as
4039 // well.
4040 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4041 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
4042 Value *SwiftErrorArg = Call.getArgOperand(i);
4043 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
4044 Check(AI->isSwiftError(),
4045 "swifterror argument for call has mismatched alloca", AI, Call);
4046 continue;
4047 }
4048 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
4049 Check(ArgI, "swifterror argument should come from an alloca or parameter",
4050 SwiftErrorArg, Call);
4051 Check(ArgI->hasSwiftErrorAttr(),
4052 "swifterror argument for call has mismatched parameter", ArgI,
4053 Call);
4054 }
4055
4056 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4057 // Don't allow immarg on call sites, unless the underlying declaration
4058 // also has the matching immarg.
4059 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
4060 "immarg may not apply only to call sites", Call.getArgOperand(i),
4061 Call);
4062 }
4063
4064 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
4065 Value *ArgVal = Call.getArgOperand(i);
4066 Check((isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal)) &&
4067 !isa<VectorType>(ArgVal->getType()),
4068 "immarg operand has non-immediate parameter", ArgVal, Call);
4069
4070 // If the imm-arg is an integer and also has a range attached,
4071 // check if the given value is within the range.
4072 if (Call.paramHasAttr(i, Attribute::Range)) {
4073 if (auto *CI = dyn_cast<ConstantInt>(ArgVal)) {
4074 const ConstantRange &CR =
4075 Call.getParamAttr(i, Attribute::Range).getValueAsConstantRange();
4076 Check(CR.contains(CI->getValue()),
4077 formatv("immarg value {} for arg {} out of range {}",
4078 CI->getValue(), i, CR),
4079 Call);
4080 }
4081 }
4082 if (auto *CI = dyn_cast<ConstantInt>(ArgVal))
4084 CI->getValue()),
4085 formatv("immarg value {} for arg {} out of range set",
4086 CI->getValue(), i),
4087 Call);
4088 }
4089
4090 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
4091 Value *ArgVal = Call.getArgOperand(i);
4092 bool hasOB =
4094 bool isMustTail = Call.isMustTailCall();
4095 Check(hasOB != isMustTail,
4096 "preallocated operand either requires a preallocated bundle or "
4097 "the call to be musttail (but not both)",
4098 ArgVal, Call);
4099 }
4100 }
4101
4102 if (FTy->isVarArg()) {
4103 // FIXME? is 'nest' even legal here?
4104 bool SawNest = false;
4105 bool SawReturned = false;
4106
4107 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4108 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
4109 SawNest = true;
4110 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
4111 SawReturned = true;
4112 }
4113
4114 // Check attributes on the varargs part.
4115 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
4116 Type *Ty = Call.getArgOperand(Idx)->getType();
4117 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
4118 verifyParameterAttrs(ArgAttrs, Ty, &Call);
4119
4120 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
4121 Check(!SawNest, "More than one parameter has attribute nest!", Call);
4122 SawNest = true;
4123 }
4124
4125 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
4126 Check(!SawReturned, "More than one parameter has attribute returned!",
4127 Call);
4128 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
4129 "Incompatible argument and return types for 'returned' "
4130 "attribute",
4131 Call);
4132 SawReturned = true;
4133 }
4134
4135 // Statepoint intrinsic is vararg but the wrapped function may be not.
4136 // Allow sret here and check the wrapped function in verifyStatepoint.
4137 if (Call.getIntrinsicID() != Intrinsic::experimental_gc_statepoint)
4138 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
4139 "Attribute 'sret' cannot be used for vararg call arguments!",
4140 Call);
4141
4142 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
4143 Check(Idx == Call.arg_size() - 1,
4144 "inalloca isn't on the last argument!", Call);
4145 }
4146 }
4147
4148 // Verify that there's no metadata unless it's a direct call to an intrinsic.
4149 if (!IsIntrinsic) {
4150 for (Type *ParamTy : FTy->params()) {
4151 Check(!ParamTy->isMetadataTy(),
4152 "Function has metadata parameter but isn't an intrinsic", Call);
4153 Check(!ParamTy->isTokenLikeTy(),
4154 "Function has token parameter but isn't an intrinsic", Call);
4155 }
4156 }
4157
4158 // Verify that indirect calls don't return tokens.
4159 if (!Call.getCalledFunction()) {
4160 Check(!FTy->getReturnType()->isTokenLikeTy(),
4161 "Return type cannot be token for indirect call!");
4162 Check(!FTy->getReturnType()->isX86_AMXTy(),
4163 "Return type cannot be x86_amx for indirect call!");
4164 }
4165
4167 visitIntrinsicCall(ID, Call);
4168
4169 // Verify that a callsite has at most one "deopt", at most one "funclet", at
4170 // most one "gc-transition", at most one "cfguardtarget", at most one
4171 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
4172 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
4173 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
4174 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
4175 FoundPtrauthBundle = false, FoundKCFIBundle = false,
4176 FoundAttachedCallBundle = false;
4177 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
4178 OperandBundleUse BU = Call.getOperandBundleAt(i);
4179 for (const Value *Input : BU.Inputs)
4180 Check(!Input->getType()->isLabelTy(),
4181 "Operand bundle operands cannot be labels", Call);
4182 uint32_t Tag = BU.getTagID();
4183 if (Tag == LLVMContext::OB_deopt) {
4184 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
4185 FoundDeoptBundle = true;
4186 } else if (Tag == LLVMContext::OB_gc_transition) {
4187 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
4188 Call);
4189 FoundGCTransitionBundle = true;
4190 } else if (Tag == LLVMContext::OB_funclet) {
4191 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
4192 FoundFuncletBundle = true;
4193 Check(BU.Inputs.size() == 1,
4194 "Expected exactly one funclet bundle operand", Call);
4195 Check(isa<FuncletPadInst>(BU.Inputs.front()),
4196 "Funclet bundle operands should correspond to a FuncletPadInst",
4197 Call);
4198 } else if (Tag == LLVMContext::OB_cfguardtarget) {
4199 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
4200 Call);
4201 FoundCFGuardTargetBundle = true;
4202 Check(BU.Inputs.size() == 1,
4203 "Expected exactly one cfguardtarget bundle operand", Call);
4204 } else if (Tag == LLVMContext::OB_ptrauth) {
4205 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
4206 FoundPtrauthBundle = true;
4207 Check(BU.Inputs.size() == 2,
4208 "Expected exactly two ptrauth bundle operands", Call);
4209 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4210 BU.Inputs[0]->getType()->isIntegerTy(32),
4211 "Ptrauth bundle key operand must be an i32 constant", Call);
4212 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
4213 "Ptrauth bundle discriminator operand must be an i64", Call);
4214 } else if (Tag == LLVMContext::OB_kcfi) {
4215 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
4216 FoundKCFIBundle = true;
4217 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
4218 Call);
4219 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4220 BU.Inputs[0]->getType()->isIntegerTy(32),
4221 "Kcfi bundle operand must be an i32 constant", Call);
4222 } else if (Tag == LLVMContext::OB_preallocated) {
4223 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
4224 Call);
4225 FoundPreallocatedBundle = true;
4226 Check(BU.Inputs.size() == 1,
4227 "Expected exactly one preallocated bundle operand", Call);
4228 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
4229 Check(Input &&
4230 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4231 "\"preallocated\" argument must be a token from "
4232 "llvm.call.preallocated.setup",
4233 Call);
4234 } else if (Tag == LLVMContext::OB_gc_live) {
4235 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
4236 FoundGCLiveBundle = true;
4238 Check(!FoundAttachedCallBundle,
4239 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
4240 FoundAttachedCallBundle = true;
4241 verifyAttachedCallBundle(Call, BU);
4242 }
4243 }
4244
4245 // Verify that callee and callsite agree on whether to use pointer auth.
4246 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
4247 "Direct call cannot have a ptrauth bundle", Call);
4248
4249 // Verify that each inlinable callsite of a debug-info-bearing function in a
4250 // debug-info-bearing function has a debug location attached to it. Failure to
4251 // do so causes assertion failures when the inliner sets up inline scope info
4252 // (Interposable functions are not inlinable, neither are functions without
4253 // definitions.)
4259 "inlinable function call in a function with "
4260 "debug info must have a !dbg location",
4261 Call);
4262
4263 if (Call.isInlineAsm())
4264 verifyInlineAsmCall(Call);
4265
4266 ConvergenceVerifyHelper.visit(Call);
4267
4268 visitInstruction(Call);
4269}
4270
4271void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
4272 StringRef Context) {
4273 Check(!Attrs.contains(Attribute::InAlloca),
4274 Twine("inalloca attribute not allowed in ") + Context);
4275 Check(!Attrs.contains(Attribute::InReg),
4276 Twine("inreg attribute not allowed in ") + Context);
4277 Check(!Attrs.contains(Attribute::SwiftError),
4278 Twine("swifterror attribute not allowed in ") + Context);
4279 Check(!Attrs.contains(Attribute::Preallocated),
4280 Twine("preallocated attribute not allowed in ") + Context);
4281 Check(!Attrs.contains(Attribute::ByRef),
4282 Twine("byref attribute not allowed in ") + Context);
4283}
4284
4285static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
4286 static const Attribute::AttrKind ABIAttrs[] = {
4287 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4288 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4289 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4290 Attribute::ByRef};
4291 AttrBuilder Copy(C);
4292 for (auto AK : ABIAttrs) {
4293 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
4294 if (Attr.isValid())
4295 Copy.addAttribute(Attr);
4296 }
4297
4298 // `align` is ABI-affecting only in combination with `byval` or `byref`.
4299 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
4300 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
4301 Attrs.hasParamAttr(I, Attribute::ByRef)))
4302 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
4303 return Copy;
4304}
4305
4306void Verifier::verifyMustTailCall(CallInst &CI) {
4307 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
4308
4309 Function *F = CI.getParent()->getParent();
4310 FunctionType *CallerTy = F->getFunctionType();
4311 FunctionType *CalleeTy = CI.getFunctionType();
4312 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4313 "cannot guarantee tail call due to mismatched varargs", &CI);
4314 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4315 "cannot guarantee tail call due to mismatched return types", &CI);
4316
4317 // - The calling conventions of the caller and callee must match.
4318 Check(F->getCallingConv() == CI.getCallingConv(),
4319 "cannot guarantee tail call due to mismatched calling conv", &CI);
4320
4321 // - The call must immediately precede a :ref:`ret <i_ret>` instruction.
4322 // - The ret instruction must return the value produced by the call or void.
4324
4325 // Check the return.
4326 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
4327 Check(Ret, "musttail call must precede a ret", &CI);
4328 Check(!Ret->getReturnValue() || Ret->getReturnValue() == &CI ||
4330 "musttail call result must be returned", Ret);
4331
4332 AttributeList CallerAttrs = F->getAttributes();
4333 AttributeList CalleeAttrs = CI.getAttributes();
4334 if (CI.getCallingConv() == CallingConv::SwiftTail ||
4335 CI.getCallingConv() == CallingConv::Tail) {
4336 StringRef CCName =
4337 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
4338
4339 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
4340 // are allowed in swifttailcc call
4341 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4342 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4343 SmallString<32> Context{CCName, StringRef(" musttail caller")};
4344 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4345 }
4346 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
4347 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4348 SmallString<32> Context{CCName, StringRef(" musttail callee")};
4349 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4350 }
4351 // - Varargs functions are not allowed
4352 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
4353 " tail call for varargs function");
4354 return;
4355 }
4356
4357 // - The caller and callee prototypes must match.
4358 if (!CI.getIntrinsicID()) {
4359 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4360 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4361 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4362 Check(CallerTy->getParamType(I) == CalleeTy->getParamType(I),
4363 "cannot guarantee tail call due to mismatched parameter types",
4364 &CI);
4365 }
4366 }
4367
4368 // - All ABI-impacting function attributes, such as sret, byval, inreg,
4369 // returned, preallocated, and inalloca, must match.
4370 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4371 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4372 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4373 Check(CallerABIAttrs == CalleeABIAttrs,
4374 "cannot guarantee tail call due to mismatched ABI impacting "
4375 "function attributes",
4376 &CI, CI.getOperand(I));
4377 }
4378}
4379
4380void Verifier::visitCallInst(CallInst &CI) {
4381 visitCallBase(CI);
4382
4383 if (CI.isMustTailCall())
4384 verifyMustTailCall(CI);
4385}
4386
4387void Verifier::visitInvokeInst(InvokeInst &II) {
4388 visitCallBase(II);
4389
4390 // Verify that the first non-PHI instruction of the unwind destination is an
4391 // exception handling instruction.
4392 Check(
4393 II.getUnwindDest()->isEHPad(),
4394 "The unwind destination does not have an exception handling instruction!",
4395 &II);
4396
4397 visitTerminator(II);
4398}
4399
4400/// visitUnaryOperator - Check the argument to the unary operator.
4401///
4402void Verifier::visitUnaryOperator(UnaryOperator &U) {
4403 Check(U.getType() == U.getOperand(0)->getType(),
4404 "Unary operators must have same type for"
4405 "operands and result!",
4406 &U);
4407
4408 switch (U.getOpcode()) {
4409 // Check that floating-point arithmetic operators are only used with
4410 // floating-point operands.
4411 case Instruction::FNeg:
4412 Check(U.getType()->isFPOrFPVectorTy(),
4413 "FNeg operator only works with float types!", &U);
4414 break;
4415 default:
4416 llvm_unreachable("Unknown UnaryOperator opcode!");
4417 }
4418
4419 visitInstruction(U);
4420}
4421
4422/// visitBinaryOperator - Check that both arguments to the binary operator are
4423/// of the same type!
4424///
4425void Verifier::visitBinaryOperator(BinaryOperator &B) {
4426 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
4427 "Both operands to a binary operator are not of the same type!", &B);
4428
4429 switch (B.getOpcode()) {
4430 // Check that integer arithmetic operators are only used with
4431 // integral operands.
4432 case Instruction::Add:
4433 case Instruction::Sub:
4434 case Instruction::Mul:
4435 case Instruction::SDiv:
4436 case Instruction::UDiv:
4437 case Instruction::SRem:
4438 case Instruction::URem:
4439 Check(B.getType()->isIntOrIntVectorTy(),
4440 "Integer arithmetic operators only work with integral types!", &B);
4441 Check(B.getType() == B.getOperand(0)->getType(),
4442 "Integer arithmetic operators must have same type "
4443 "for operands and result!",
4444 &B);
4445 break;
4446 // Check that floating-point arithmetic operators are only used with
4447 // floating-point operands.
4448 case Instruction::FAdd:
4449 case Instruction::FSub:
4450 case Instruction::FMul:
4451 case Instruction::FDiv:
4452 case Instruction::FRem:
4453 Check(B.getType()->isFPOrFPVectorTy(),
4454 "Floating-point arithmetic operators only work with "
4455 "floating-point types!",
4456 &B);
4457 Check(B.getType() == B.getOperand(0)->getType(),
4458 "Floating-point arithmetic operators must have same type "
4459 "for operands and result!",
4460 &B);
4461 break;
4462 // Check that logical operators are only used with integral operands.
4463 case Instruction::And:
4464 case Instruction::Or:
4465 case Instruction::Xor:
4466 Check(B.getType()->isIntOrIntVectorTy(),
4467 "Logical operators only work with integral types!", &B);
4468 Check(B.getType() == B.getOperand(0)->getType(),
4469 "Logical operators must have same type for operands and result!", &B);
4470 break;
4471 case Instruction::Shl:
4472 case Instruction::LShr:
4473 case Instruction::AShr:
4474 Check(B.getType()->isIntOrIntVectorTy(),
4475 "Shifts only work with integral types!", &B);
4476 Check(B.getType() == B.getOperand(0)->getType(),
4477 "Shift return type must be same as operands!", &B);
4478 break;
4479 default:
4480 llvm_unreachable("Unknown BinaryOperator opcode!");
4481 }
4482
4483 visitInstruction(B);
4484}
4485
4486void Verifier::visitICmpInst(ICmpInst &IC) {
4487 // Check that the operands are the same type
4488 Type *Op0Ty = IC.getOperand(0)->getType();
4489 Type *Op1Ty = IC.getOperand(1)->getType();
4490 Check(Op0Ty == Op1Ty,
4491 "Both operands to ICmp instruction are not of the same type!", &IC);
4492 // Check that the operands are the right type
4493 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
4494 "Invalid operand types for ICmp instruction", &IC);
4495 // Check that the predicate is valid.
4496 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
4497
4498 visitInstruction(IC);
4499}
4500
4501void Verifier::visitFCmpInst(FCmpInst &FC) {
4502 // Check that the operands are the same type
4503 Type *Op0Ty = FC.getOperand(0)->getType();
4504 Type *Op1Ty = FC.getOperand(1)->getType();
4505 Check(Op0Ty == Op1Ty,
4506 "Both operands to FCmp instruction are not of the same type!", &FC);
4507 // Check that the operands are the right type
4508 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
4509 &FC);
4510 // Check that the predicate is valid.
4511 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
4512
4513 visitInstruction(FC);
4514}
4515
4516void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4518 "Invalid extractelement operands!", &EI);
4519 visitInstruction(EI);
4520}
4521
4522void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4523 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
4524 IE.getOperand(2)),
4525 "Invalid insertelement operands!", &IE);
4526 visitInstruction(IE);
4527}
4528
4529void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4531 SV.getShuffleMask()),
4532 "Invalid shufflevector operands!", &SV);
4533 visitInstruction(SV);
4534}
4535
4536void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4538 GEP.getModule()->getModuleFlag("require-logical-pointer")))
4539 Check(!MD->getZExtValue(),
4540 "Non-logical getelementptr disallowed for this module.");
4541
4542 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
4543
4544 Check(isa<PointerType>(TargetTy),
4545 "GEP base pointer is not a vector or a vector of pointers", &GEP);
4546 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
4547
4548 if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
4549 Check(!STy->isScalableTy(),
4550 "getelementptr cannot target structure that contains scalable vector"
4551 "type",
4552 &GEP);
4553 }
4554
4555 SmallVector<Value *, 16> Idxs(GEP.indices());
4556 Check(
4557 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
4558 "GEP indexes must be integers", &GEP);
4559 Type *ElTy =
4560 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
4561 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
4562
4563 auto *PtrTy = dyn_cast<PointerType>(GEP.getType()->getScalarType());
4564
4565 Check(PtrTy && GEP.getResultElementType() == ElTy,
4566 "GEP is not of right type for indices!", &GEP, ElTy);
4567
4568 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
4569 // Additional checks for vector GEPs.
4570 ElementCount GEPWidth = GEPVTy->getElementCount();
4571 if (GEP.getPointerOperandType()->isVectorTy())
4572 Check(
4573 GEPWidth ==
4574 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
4575 "Vector GEP result width doesn't match operand's", &GEP);
4576 for (Value *Idx : Idxs) {
4577 Type *IndexTy = Idx->getType();
4578 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
4579 ElementCount IndexWidth = IndexVTy->getElementCount();
4580 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
4581 }
4582 Check(IndexTy->isIntOrIntVectorTy(),
4583 "All GEP indices should be of integer type");
4584 }
4585 }
4586
4587 // Check that GEP does not index into a vector with non-byte-addressable
4588 // elements.
4590 GTI != GTE; ++GTI) {
4591 if (GTI.isVector()) {
4592 Type *ElemTy = GTI.getIndexedType();
4593 Check(DL.typeSizeEqualsStoreSize(ElemTy),
4594 "GEP into vector with non-byte-addressable element type", &GEP);
4595 }
4596 }
4597
4598 Check(GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4599 "GEP address space doesn't match type", &GEP);
4600
4601 visitInstruction(GEP);
4602}
4603
4604static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
4605 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
4606}
4607
4608/// Verify !range and !absolute_symbol metadata. These have the same
4609/// restrictions, except !absolute_symbol allows the full set.
4610void Verifier::verifyRangeLikeMetadata(const Value &I, const MDNode *Range,
4611 Type *Ty, RangeLikeMetadataKind Kind) {
4612 unsigned NumOperands = Range->getNumOperands();
4613 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
4614 unsigned NumRanges = NumOperands / 2;
4615 Check(NumRanges >= 1, "It should have at least one range!", Range);
4616
4617 ConstantRange LastRange(1, true); // Dummy initial value
4618 for (unsigned i = 0; i < NumRanges; ++i) {
4619 ConstantInt *Low =
4620 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
4621 Check(Low, "The lower limit must be an integer!", Low);
4622 ConstantInt *High =
4623 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
4624 Check(High, "The upper limit must be an integer!", High);
4625
4626 Check(High->getType() == Low->getType(), "Range pair types must match!",
4627 &I);
4628
4629 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4630 Check(High->getType()->isIntegerTy(32),
4631 "noalias.addrspace type must be i32!", &I);
4632 } else {
4633 Check(High->getType() == Ty->getScalarType(),
4634 "Range types must match instruction type!", &I);
4635 }
4636
4637 APInt HighV = High->getValue();
4638 APInt LowV = Low->getValue();
4639
4640 // ConstantRange asserts if the ranges are the same except for the min/max
4641 // value. Leave the cases it tolerates for the empty range error below.
4642 Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
4643 "The upper and lower limits cannot be the same value", &I);
4644
4645 ConstantRange CurRange(LowV, HighV);
4646 Check(!CurRange.isEmptySet() &&
4647 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4648 !CurRange.isFullSet()),
4649 "Range must not be empty!", Range);
4650 if (i != 0) {
4651 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4652 "Intervals are overlapping", Range);
4653 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
4654 Range);
4655 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
4656 Range);
4657 }
4658 LastRange = ConstantRange(LowV, HighV);
4659 }
4660 if (NumRanges > 2) {
4661 APInt FirstLow =
4662 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
4663 APInt FirstHigh =
4664 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
4665 ConstantRange FirstRange(FirstLow, FirstHigh);
4666 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4667 "Intervals are overlapping", Range);
4668 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
4669 Range);
4670 }
4671}
4672
4673void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
4674 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
4675 "precondition violation");
4676 verifyRangeLikeMetadata(I, Range, Ty, RangeLikeMetadataKind::Range);
4677}
4678
4679void Verifier::visitNoFPClassMetadata(Instruction &I, MDNode *NoFPClass,
4680 Type *Ty) {
4681 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4682 "nofpclass only applies to floating-point typed loads", I);
4683
4684 Check(NoFPClass->getNumOperands() == 1,
4685 "nofpclass must have exactly one entry", NoFPClass);
4686 ConstantInt *MaskVal =
4688 Check(MaskVal && MaskVal->getType()->isIntegerTy(32),
4689 "nofpclass entry must be a constant i32", NoFPClass);
4690 uint32_t Val = MaskVal->getZExtValue();
4691 Check(Val != 0, "'nofpclass' must have at least one test bit set", NoFPClass,
4692 I);
4693
4694 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
4695 "Invalid value for 'nofpclass' test mask", NoFPClass, I);
4696}
4697
4698void Verifier::visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range,
4699 Type *Ty) {
4700 assert(Range && Range == I.getMetadata(LLVMContext::MD_noalias_addrspace) &&
4701 "precondition violation");
4702 verifyRangeLikeMetadata(I, Range, Ty,
4703 RangeLikeMetadataKind::NoaliasAddrspace);
4704}
4705
4706void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
4707 unsigned Size = DL.getTypeSizeInBits(Ty).getFixedValue();
4708 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
4709 Check(!(Size & (Size - 1)),
4710 "atomic memory access' operand must have a power-of-two size", Ty, I);
4711}
4712
4713void Verifier::visitLoadInst(LoadInst &LI) {
4714 auto *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
4715 Check(PTy, "Load operand must be a pointer.", &LI);
4716 Type *ElTy = LI.getType();
4717 if (MaybeAlign A = LI.getAlign()) {
4718 Check(A->value() <= Value::MaximumAlignment,
4719 "huge alignment values are unsupported", &LI);
4720 }
4721 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
4722 if (LI.isAtomic()) {
4723 Check(LI.getOrdering() != AtomicOrdering::Release &&
4724 LI.getOrdering() != AtomicOrdering::AcquireRelease,
4725 "Load cannot have Release ordering", &LI);
4726
4727 if (LI.isElementwise()) {
4728 Check(LI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4729 "atomic elementwise load cannot be sequentially consistent.", &LI);
4730 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
4731 Check(VecTy,
4732 "atomic elementwise load operand must have fixed vector type!", &LI,
4733 ElTy);
4734 if (VecTy)
4735 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
4736 }
4737
4738 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4739 ElTy->getScalarType()->isByteTy() ||
4741 "atomic load operand must have integer, byte, pointer, floating "
4742 "point, or vector type!",
4743 ElTy, &LI);
4744
4745 checkAtomicMemAccessSize(ElTy, &LI);
4746 } else {
4747 Check(!LI.isElementwise(), "non-atomic load cannot be elementwise", &LI);
4749 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4750 }
4751
4752 visitInstruction(LI);
4753}
4754
4755void Verifier::visitStoreInst(StoreInst &SI) {
4756 auto *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
4757 Check(PTy, "Store operand must be a pointer.", &SI);
4758 Type *ElTy = SI.getOperand(0)->getType();
4759 if (MaybeAlign A = SI.getAlign()) {
4760 Check(A->value() <= Value::MaximumAlignment,
4761 "huge alignment values are unsupported", &SI);
4762 }
4763 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
4764 if (SI.isAtomic()) {
4765 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
4766 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4767 "Store cannot have Acquire ordering", &SI);
4768
4769 if (SI.isElementwise()) {
4770 Check(SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4771 "atomic elementwise store cannot be sequentially consistent.", &SI);
4772
4773 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
4774 Check(VecTy,
4775 "atomic elementwise store operand must have fixed vector type!",
4776 &SI, ElTy);
4777 if (VecTy)
4778 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
4779 }
4780
4781 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4782 ElTy->getScalarType()->isByteTy() ||
4784 "atomic store operand must have integer, byte, pointer, floating "
4785 "point, or vector type!",
4786 ElTy, &SI);
4787 checkAtomicMemAccessSize(ElTy, &SI);
4788 } else {
4789 Check(!SI.isElementwise(), "non-atomic store cannot be elementwise", &SI);
4790 Check(SI.getSyncScopeID() == SyncScope::System,
4791 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4792 }
4793 visitInstruction(SI);
4794}
4795
4796/// Check that SwiftErrorVal is used as a swifterror argument in CS.
4797void Verifier::verifySwiftErrorCall(CallBase &Call,
4798 const Value *SwiftErrorVal) {
4799 for (const auto &I : llvm::enumerate(Call.args())) {
4800 if (I.value() == SwiftErrorVal) {
4801 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
4802 "swifterror value when used in a callsite should be marked "
4803 "with swifterror attribute",
4804 SwiftErrorVal, Call);
4805 }
4806 }
4807}
4808
4809void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
4810 // Check that swifterror value is only used by loads, stores, or as
4811 // a swifterror argument.
4812 for (const User *U : SwiftErrorVal->users()) {
4814 isa<InvokeInst>(U),
4815 "swifterror value can only be loaded and stored from, or "
4816 "as a swifterror argument!",
4817 SwiftErrorVal, U);
4818 // If it is used by a store, check it is the second operand.
4819 if (auto StoreI = dyn_cast<StoreInst>(U))
4820 Check(StoreI->getOperand(1) == SwiftErrorVal,
4821 "swifterror value should be the second operand when used "
4822 "by stores",
4823 SwiftErrorVal, U);
4824 if (auto *Call = dyn_cast<CallBase>(U))
4825 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
4826 }
4827}
4828
4829void Verifier::visitAllocaInst(AllocaInst &AI) {
4831 AI.getModule()->getModuleFlag("require-logical-pointer")))
4832 Check(!MD->getZExtValue(),
4833 "Non-logical alloca disallowed for this module.");
4834
4835 Type *Ty = AI.getAllocatedType();
4836 SmallPtrSet<Type*, 4> Visited;
4837 Check(Ty->isSized(&Visited), "Cannot allocate unsized type", &AI);
4838 // Check if it's a target extension type that disallows being used on the
4839 // stack.
4841 "Alloca has illegal target extension type", &AI);
4843 "Alloca array size must have integer type", &AI);
4844 if (MaybeAlign A = AI.getAlign()) {
4845 Check(A->value() <= Value::MaximumAlignment,
4846 "huge alignment values are unsupported", &AI);
4847 }
4848
4849 if (AI.isSwiftError()) {
4850 Check(Ty->isPointerTy(), "swifterror alloca must have pointer type", &AI);
4852 "swifterror alloca must not be array allocation", &AI);
4853 verifySwiftErrorValue(&AI);
4854 }
4855
4856 visitInstruction(AI);
4857
4858 // Target-specific alloca checks.
4859 verifyAMDGPUAlloca(*this, AI);
4860}
4861
4862void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4863 Type *ElTy = CXI.getOperand(1)->getType();
4864 Check(ElTy->isIntOrPtrTy(),
4865 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4866 checkAtomicMemAccessSize(ElTy, &CXI);
4867 visitInstruction(CXI);
4868}
4869
4870void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4871 Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
4872 "atomicrmw instructions cannot be unordered.", &RMWI);
4873 auto Op = RMWI.getOperation();
4874 Type *ElTy = RMWI.getOperand(1)->getType();
4875 Check(!ElTy->isScalableTy(), "atomicrmw operand may not be scalable", &RMWI);
4876 if (RMWI.isElementwise()) {
4877 Check(RMWI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4878 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
4879 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
4880 Check(VecTy, "atomicrmw elementwise operand must have fixed vector type!",
4881 &RMWI, ElTy);
4882 if (VecTy)
4883 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
4884 }
4885
4886 if (Op == AtomicRMWInst::Xchg) {
4887 Check((ElTy->isIntOrIntVectorTy() || ElTy->isFPOrFPVectorTy() ||
4888 ElTy->isPtrOrPtrVectorTy()),
4889 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4890 " operand must be an integer type, a floating-point type, a "
4891 "pointer type, or a fixed vector of any of these types!",
4892 &RMWI, ElTy);
4893 } else if (AtomicRMWInst::isFPOperation(Op)) {
4894 Check(ElTy->isFPOrFPVectorTy(),
4895 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4896 " operand must have floating-point or fixed vector of "
4897 "floating-point "
4898 "type!",
4899 &RMWI, ElTy);
4900 } else {
4901 Check(ElTy->isIntOrIntVectorTy(),
4902 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4903 " operand must have integer or fixed vector of integer type!",
4904 &RMWI, ElTy);
4905 }
4906 checkAtomicMemAccessSize(ElTy, &RMWI);
4908 "Invalid binary operation!", &RMWI);
4909 visitInstruction(RMWI);
4910}
4911
4912void Verifier::visitFenceInst(FenceInst &FI) {
4913 const AtomicOrdering Ordering = FI.getOrdering();
4914 Check(Ordering == AtomicOrdering::Acquire ||
4915 Ordering == AtomicOrdering::Release ||
4916 Ordering == AtomicOrdering::AcquireRelease ||
4917 Ordering == AtomicOrdering::SequentiallyConsistent,
4918 "fence instructions may only have acquire, release, acq_rel, or "
4919 "seq_cst ordering.",
4920 &FI);
4921 visitInstruction(FI);
4922}
4923
4924void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4926 EVI.getIndices()) == EVI.getType(),
4927 "Invalid ExtractValueInst operands!", &EVI);
4928
4929 visitInstruction(EVI);
4930}
4931
4932void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4934 IVI.getIndices()) ==
4935 IVI.getOperand(1)->getType(),
4936 "Invalid InsertValueInst operands!", &IVI);
4937
4938 visitInstruction(IVI);
4939}
4940
4941static Value *getParentPad(Value *EHPad) {
4942 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4943 return FPI->getParentPad();
4944
4945 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4946}
4947
4948void Verifier::visitEHPadPredecessors(Instruction &I) {
4949 assert(I.isEHPad());
4950
4951 BasicBlock *BB = I.getParent();
4952 Function *F = BB->getParent();
4953
4954 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
4955
4956 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
4957 // The landingpad instruction defines its parent as a landing pad block. The
4958 // landing pad block may be branched to only by the unwind edge of an
4959 // invoke.
4960 for (BasicBlock *PredBB : predecessors(BB)) {
4961 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4962 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4963 "Block containing LandingPadInst must be jumped to "
4964 "only by the unwind edge of an invoke.",
4965 LPI);
4966 }
4967 return;
4968 }
4969 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
4970 if (!pred_empty(BB))
4971 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4972 "Block containg CatchPadInst must be jumped to "
4973 "only by its catchswitch.",
4974 CPI);
4975 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4976 "Catchswitch cannot unwind to one of its catchpads",
4977 CPI->getCatchSwitch(), CPI);
4978 return;
4979 }
4980
4981 // Verify that each pred has a legal terminator with a legal to/from EH
4982 // pad relationship.
4983 Instruction *ToPad = &I;
4984 Value *ToPadParent = getParentPad(ToPad);
4985 for (BasicBlock *PredBB : predecessors(BB)) {
4986 Instruction *TI = PredBB->getTerminator();
4987 Value *FromPad;
4988 if (auto *II = dyn_cast<InvokeInst>(TI)) {
4989 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4990 "EH pad must be jumped to via an unwind edge", ToPad, II);
4991 auto *CalledFn =
4992 dyn_cast<Function>(II->getCalledOperand()->stripPointerCasts());
4993 if (CalledFn && CalledFn->isIntrinsic() && II->doesNotThrow() &&
4994 !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
4995 continue;
4996 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
4997 FromPad = Bundle->Inputs[0];
4998 else
4999 FromPad = ConstantTokenNone::get(II->getContext());
5000 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5001 FromPad = CRI->getOperand(0);
5002 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
5003 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5004 FromPad = CSI;
5005 } else {
5006 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
5007 }
5008
5009 // The edge may exit from zero or more nested pads.
5010 SmallPtrSet<Value *, 8> Seen;
5011 for (;; FromPad = getParentPad(FromPad)) {
5012 Check(FromPad != ToPad,
5013 "EH pad cannot handle exceptions raised within it", FromPad, TI);
5014 if (FromPad == ToPadParent) {
5015 // This is a legal unwind edge.
5016 break;
5017 }
5018 Check(!isa<ConstantTokenNone>(FromPad),
5019 "A single unwind edge may only enter one EH pad", TI);
5020 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
5021 FromPad);
5022
5023 // This will be diagnosed on the corresponding instruction already. We
5024 // need the extra check here to make sure getParentPad() works.
5025 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
5026 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
5027 }
5028 }
5029}
5030
5031void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
5032 // The landingpad instruction is ill-formed if it doesn't have any clauses and
5033 // isn't a cleanup.
5034 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
5035 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
5036
5037 visitEHPadPredecessors(LPI);
5038
5039 if (!LandingPadResultTy)
5040 LandingPadResultTy = LPI.getType();
5041 else
5042 Check(LandingPadResultTy == LPI.getType(),
5043 "The landingpad instruction should have a consistent result type "
5044 "inside a function.",
5045 &LPI);
5046
5047 Function *F = LPI.getParent()->getParent();
5048 Check(F->hasPersonalityFn(),
5049 "LandingPadInst needs to be in a function with a personality.", &LPI);
5050
5051 // The landingpad instruction must be the first non-PHI instruction in the
5052 // block.
5053 Check(LPI.getParent()->getLandingPadInst() == &LPI,
5054 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5055
5056 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
5057 Constant *Clause = LPI.getClause(i);
5058 if (LPI.isCatch(i)) {
5059 Check(isa<PointerType>(Clause->getType()),
5060 "Catch operand does not have pointer type!", &LPI);
5061 } else {
5062 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
5064 "Filter operand is not an array of constants!", &LPI);
5065 }
5066 }
5067
5068 visitInstruction(LPI);
5069}
5070
5071void Verifier::visitResumeInst(ResumeInst &RI) {
5073 "ResumeInst needs to be in a function with a personality.", &RI);
5074
5075 if (!LandingPadResultTy)
5076 LandingPadResultTy = RI.getValue()->getType();
5077 else
5078 Check(LandingPadResultTy == RI.getValue()->getType(),
5079 "The resume instruction should have a consistent result type "
5080 "inside a function.",
5081 &RI);
5082
5083 visitTerminator(RI);
5084}
5085
5086void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5087 BasicBlock *BB = CPI.getParent();
5088
5089 Function *F = BB->getParent();
5090 Check(F->hasPersonalityFn(),
5091 "CatchPadInst needs to be in a function with a personality.", &CPI);
5092
5094 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5095 CPI.getParentPad());
5096
5097 // The catchpad instruction must be the first non-PHI instruction in the
5098 // block.
5099 Check(&*BB->getFirstNonPHIIt() == &CPI,
5100 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5101
5103 [](Use &U) {
5104 auto *V = U.get();
5105 return isa<Constant>(V) || isa<AllocaInst>(V);
5106 }),
5107 "Argument operand must be alloca or constant.", &CPI);
5108
5109 visitEHPadPredecessors(CPI);
5110 visitFuncletPadInst(CPI);
5111}
5112
5113void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5114 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
5115 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5116 CatchReturn.getOperand(0));
5117
5118 visitTerminator(CatchReturn);
5119}
5120
5121void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5122 BasicBlock *BB = CPI.getParent();
5123
5124 Function *F = BB->getParent();
5125 Check(F->hasPersonalityFn(),
5126 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5127
5128 // The cleanuppad instruction must be the first non-PHI instruction in the
5129 // block.
5130 Check(&*BB->getFirstNonPHIIt() == &CPI,
5131 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5132
5133 auto *ParentPad = CPI.getParentPad();
5134 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5135 "CleanupPadInst has an invalid parent.", &CPI);
5136
5137 visitEHPadPredecessors(CPI);
5138 visitFuncletPadInst(CPI);
5139}
5140
5141void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5142 User *FirstUser = nullptr;
5143 Value *FirstUnwindPad = nullptr;
5144 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
5145 SmallPtrSet<FuncletPadInst *, 8> Seen;
5146
5147 while (!Worklist.empty()) {
5148 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5149 Check(Seen.insert(CurrentPad).second,
5150 "FuncletPadInst must not be nested within itself", CurrentPad);
5151 Value *UnresolvedAncestorPad = nullptr;
5152 for (User *U : CurrentPad->users()) {
5153 BasicBlock *UnwindDest;
5154 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
5155 UnwindDest = CRI->getUnwindDest();
5156 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
5157 // We allow catchswitch unwind to caller to nest
5158 // within an outer pad that unwinds somewhere else,
5159 // because catchswitch doesn't have a nounwind variant.
5160 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
5161 if (CSI->unwindsToCaller())
5162 continue;
5163 UnwindDest = CSI->getUnwindDest();
5164 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
5165 UnwindDest = II->getUnwindDest();
5166 } else if (isa<CallInst>(U)) {
5167 // Calls which don't unwind may be found inside funclet
5168 // pads that unwind somewhere else. We don't *require*
5169 // such calls to be annotated nounwind.
5170 continue;
5171 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
5172 // The unwind dest for a cleanup can only be found by
5173 // recursive search. Add it to the worklist, and we'll
5174 // search for its first use that determines where it unwinds.
5175 Worklist.push_back(CPI);
5176 continue;
5177 } else {
5178 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
5179 continue;
5180 }
5181
5182 Value *UnwindPad;
5183 bool ExitsFPI;
5184 if (UnwindDest) {
5185 UnwindPad = &*UnwindDest->getFirstNonPHIIt();
5186 if (!cast<Instruction>(UnwindPad)->isEHPad())
5187 continue;
5188 Value *UnwindParent = getParentPad(UnwindPad);
5189 // Ignore unwind edges that don't exit CurrentPad.
5190 if (UnwindParent == CurrentPad)
5191 continue;
5192 // Determine whether the original funclet pad is exited,
5193 // and if we are scanning nested pads determine how many
5194 // of them are exited so we can stop searching their
5195 // children.
5196 Value *ExitedPad = CurrentPad;
5197 ExitsFPI = false;
5198 do {
5199 if (ExitedPad == &FPI) {
5200 ExitsFPI = true;
5201 // Now we can resolve any ancestors of CurrentPad up to
5202 // FPI, but not including FPI since we need to make sure
5203 // to check all direct users of FPI for consistency.
5204 UnresolvedAncestorPad = &FPI;
5205 break;
5206 }
5207 Value *ExitedParent = getParentPad(ExitedPad);
5208 if (ExitedParent == UnwindParent) {
5209 // ExitedPad is the ancestor-most pad which this unwind
5210 // edge exits, so we can resolve up to it, meaning that
5211 // ExitedParent is the first ancestor still unresolved.
5212 UnresolvedAncestorPad = ExitedParent;
5213 break;
5214 }
5215 ExitedPad = ExitedParent;
5216 } while (!isa<ConstantTokenNone>(ExitedPad));
5217 } else {
5218 // Unwinding to caller exits all pads.
5219 UnwindPad = ConstantTokenNone::get(FPI.getContext());
5220 ExitsFPI = true;
5221 UnresolvedAncestorPad = &FPI;
5222 }
5223
5224 if (ExitsFPI) {
5225 // This unwind edge exits FPI. Make sure it agrees with other
5226 // such edges.
5227 if (FirstUser) {
5228 Check(UnwindPad == FirstUnwindPad,
5229 "Unwind edges out of a funclet "
5230 "pad must have the same unwind "
5231 "dest",
5232 &FPI, U, FirstUser);
5233 } else {
5234 FirstUser = U;
5235 FirstUnwindPad = UnwindPad;
5236 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
5237 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
5238 getParentPad(UnwindPad) == getParentPad(&FPI))
5239 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
5240 }
5241 }
5242 // Make sure we visit all uses of FPI, but for nested pads stop as
5243 // soon as we know where they unwind to.
5244 if (CurrentPad != &FPI)
5245 break;
5246 }
5247 if (UnresolvedAncestorPad) {
5248 if (CurrentPad == UnresolvedAncestorPad) {
5249 // When CurrentPad is FPI itself, we don't mark it as resolved even if
5250 // we've found an unwind edge that exits it, because we need to verify
5251 // all direct uses of FPI.
5252 assert(CurrentPad == &FPI);
5253 continue;
5254 }
5255 // Pop off the worklist any nested pads that we've found an unwind
5256 // destination for. The pads on the worklist are the uncles,
5257 // great-uncles, etc. of CurrentPad. We've found an unwind destination
5258 // for all ancestors of CurrentPad up to but not including
5259 // UnresolvedAncestorPad.
5260 Value *ResolvedPad = CurrentPad;
5261 while (!Worklist.empty()) {
5262 Value *UnclePad = Worklist.back();
5263 Value *AncestorPad = getParentPad(UnclePad);
5264 // Walk ResolvedPad up the ancestor list until we either find the
5265 // uncle's parent or the last resolved ancestor.
5266 while (ResolvedPad != AncestorPad) {
5267 Value *ResolvedParent = getParentPad(ResolvedPad);
5268 if (ResolvedParent == UnresolvedAncestorPad) {
5269 break;
5270 }
5271 ResolvedPad = ResolvedParent;
5272 }
5273 // If the resolved ancestor search didn't find the uncle's parent,
5274 // then the uncle is not yet resolved.
5275 if (ResolvedPad != AncestorPad)
5276 break;
5277 // This uncle is resolved, so pop it from the worklist.
5278 Worklist.pop_back();
5279 }
5280 }
5281 }
5282
5283 if (FirstUnwindPad) {
5284 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
5285 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5286 Value *SwitchUnwindPad;
5287 if (SwitchUnwindDest)
5288 SwitchUnwindPad = &*SwitchUnwindDest->getFirstNonPHIIt();
5289 else
5290 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
5291 Check(SwitchUnwindPad == FirstUnwindPad,
5292 "Unwind edges out of a catch must have the same unwind dest as "
5293 "the parent catchswitch",
5294 &FPI, FirstUser, CatchSwitch);
5295 }
5296 }
5297
5298 visitInstruction(FPI);
5299}
5300
5301void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5302 BasicBlock *BB = CatchSwitch.getParent();
5303
5304 Function *F = BB->getParent();
5305 Check(F->hasPersonalityFn(),
5306 "CatchSwitchInst needs to be in a function with a personality.",
5307 &CatchSwitch);
5308
5309 // The catchswitch instruction must be the first non-PHI instruction in the
5310 // block.
5311 Check(&*BB->getFirstNonPHIIt() == &CatchSwitch,
5312 "CatchSwitchInst not the first non-PHI instruction in the block.",
5313 &CatchSwitch);
5314
5315 auto *ParentPad = CatchSwitch.getParentPad();
5316 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5317 "CatchSwitchInst has an invalid parent.", ParentPad);
5318
5319 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
5320 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5321 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5322 "CatchSwitchInst must unwind to an EH block which is not a "
5323 "landingpad.",
5324 &CatchSwitch);
5325
5326 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
5327 if (getParentPad(&*I) == ParentPad)
5328 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5329 }
5330
5331 Check(CatchSwitch.getNumHandlers() != 0,
5332 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5333
5334 for (BasicBlock *Handler : CatchSwitch.handlers()) {
5335 Check(isa<CatchPadInst>(Handler->getFirstNonPHIIt()),
5336 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5337 }
5338
5339 visitEHPadPredecessors(CatchSwitch);
5340 visitTerminator(CatchSwitch);
5341}
5342
5343void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5345 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5346 CRI.getOperand(0));
5347
5348 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
5349 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5350 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5351 "CleanupReturnInst must unwind to an EH block which is not a "
5352 "landingpad.",
5353 &CRI);
5354 }
5355
5356 visitTerminator(CRI);
5357}
5358
5359void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
5360 Instruction *Op = cast<Instruction>(I.getOperand(i));
5361 // If the we have an invalid invoke, don't try to compute the dominance.
5362 // We already reject it in the invoke specific checks and the dominance
5363 // computation doesn't handle multiple edges.
5364 if (auto *II = dyn_cast<InvokeInst>(Op)) {
5365 if (II->getNormalDest() == II->getUnwindDest())
5366 return;
5367 }
5368
5369 // Quick check whether the def has already been encountered in the same block.
5370 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
5371 // uses are defined to happen on the incoming edge, not at the instruction.
5372 //
5373 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
5374 // wrapping an SSA value, assert that we've already encountered it. See
5375 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
5376 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
5377 return;
5378
5379 const Use &U = I.getOperandUse(i);
5380 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
5381}
5382
5383void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
5384 Check(I.getType()->isPointerTy(),
5385 "dereferenceable, dereferenceable_or_null "
5386 "apply only to pointer types",
5387 &I);
5389 "dereferenceable, dereferenceable_or_null apply only to load"
5390 " and inttoptr instructions, use attributes for calls or invokes",
5391 &I);
5392 Check(MD->getNumOperands() == 1,
5393 "dereferenceable, dereferenceable_or_null "
5394 "take one operand!",
5395 &I);
5396 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
5397 Check(CI && CI->getType()->isIntegerTy(64),
5398 "dereferenceable, "
5399 "dereferenceable_or_null metadata value must be an i64!",
5400 &I);
5401}
5402
5403void Verifier::visitNoFreeObjMetadata(Instruction &I, MDNode *MD) {
5404 Check(I.getType()->isPointerTy(), "nofreeobj applies only to pointer types",
5405 &I);
5407 "nofreeobj applies only to inttoptr instruction", &I);
5408 Check(MD->getNumOperands() == 0, "nofreeobj metadata must be empty", &I);
5409}
5410
5411void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
5412 auto GetBranchingTerminatorNumOperands = [&]() {
5413 unsigned ExpectedNumOperands = 0;
5414 if (auto *BI = dyn_cast<CondBrInst>(&I))
5415 ExpectedNumOperands = BI->getNumSuccessors();
5416 else if (auto *SI = dyn_cast<SwitchInst>(&I))
5417 ExpectedNumOperands = SI->getNumSuccessors();
5418 else if (isa<CallInst>(&I))
5419 ExpectedNumOperands = 1;
5420 else if (auto *IBI = dyn_cast<IndirectBrInst>(&I))
5421 ExpectedNumOperands = IBI->getNumDestinations();
5422 else if (isa<SelectInst>(&I))
5423 ExpectedNumOperands = 2;
5424 else if (auto *CI = dyn_cast<CallBrInst>(&I))
5425 ExpectedNumOperands = CI->getNumSuccessors();
5426 return ExpectedNumOperands;
5427 };
5428 Check(MD->getNumOperands() >= 1,
5429 "!prof annotations should have at least 1 operand", MD);
5430 // Check first operand.
5431 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
5433 "expected string with name of the !prof annotation", MD);
5434 MDString *MDS = cast<MDString>(MD->getOperand(0));
5435 StringRef ProfName = MDS->getString();
5436
5438 Check(GetBranchingTerminatorNumOperands() != 0 || isa<InvokeInst>(I),
5439 "'unknown' !prof should only appear on instructions on which "
5440 "'branch_weights' would",
5441 MD);
5442 verifyUnknownProfileMetadata(MD);
5443 return;
5444 }
5445
5446 Check(MD->getNumOperands() >= 2,
5447 "!prof annotations should have no less than 2 operands", MD);
5448
5449 // Check consistency of !prof branch_weights metadata.
5450 if (ProfName == MDProfLabels::BranchWeights) {
5451 unsigned NumBranchWeights = getNumBranchWeights(*MD);
5452 if (isa<InvokeInst>(&I)) {
5453 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5454 "Wrong number of InvokeInst branch_weights operands", MD);
5455 } else {
5456 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5457 if (ExpectedNumOperands == 0)
5458 CheckFailed("!prof branch_weights are not allowed for this instruction",
5459 MD);
5460
5461 Check(NumBranchWeights == ExpectedNumOperands, "Wrong number of operands",
5462 MD);
5463 }
5464 for (unsigned i = getBranchWeightOffset(MD); i < MD->getNumOperands();
5465 ++i) {
5466 auto &MDO = MD->getOperand(i);
5467 Check(MDO, "second operand should not be null", MD);
5469 "!prof brunch_weights operand is not a const int");
5470 }
5471 } else if (ProfName == MDProfLabels::ValueProfile) {
5472 Check(isValueProfileMD(MD), "invalid value profiling metadata", MD);
5473 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
5474 Check(KindInt, "VP !prof missing kind argument", MD);
5475
5476 auto Kind = KindInt->getZExtValue();
5477 Check(Kind >= InstrProfValueKind::IPVK_First &&
5478 Kind <= InstrProfValueKind::IPVK_Last,
5479 "Invalid VP !prof kind", MD);
5480 Check(MD->getNumOperands() % 2 == 1,
5481 "VP !prof should have an even number "
5482 "of arguments after 'VP'",
5483 MD);
5484 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5485 Kind == InstrProfValueKind::IPVK_MemOPSize)
5487 "VP !prof indirect call or memop size expected to be applied to "
5488 "CallBase instructions only",
5489 MD);
5490
5491 DenseSet<uint64_t> ProfileValues;
5492 for (unsigned I = 3; I < MD->getNumOperands(); I += 2) {
5493 ConstantInt *ProfileValue =
5495 Check(ProfileValue, "VP !prof value operand is not a const int", MD);
5496 uint64_t ProfileValueInt = ProfileValue->getZExtValue();
5497 auto [ValueIt, Inserted] = ProfileValues.insert(ProfileValueInt);
5498 Check(Inserted, "VP !prof should not have duplicate profile values", MD);
5499 }
5500 } else {
5501 CheckFailed("expected either branch_weights or VP profile name", MD);
5502 }
5503}
5504
5505void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
5506 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
5507 // DIAssignID metadata must be attached to either an alloca or some form of
5508 // store/memory-writing instruction.
5509 // FIXME: We allow all intrinsic insts here to avoid trying to enumerate all
5510 // possible store intrinsics.
5511 bool ExpectedInstTy =
5513 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
5514 I, MD);
5515 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
5516 // only be found as DbgAssignIntrinsic operands.
5517 if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
5518 for (auto *User : AsValue->users()) {
5520 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5521 MD, User);
5522 // All of the dbg.assign intrinsics should be in the same function as I.
5523 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
5524 CheckDI(DAI->getFunction() == I.getFunction(),
5525 "dbg.assign not in same function as inst", DAI, &I);
5526 }
5527 }
5528 for (DbgVariableRecord *DVR :
5529 cast<DIAssignID>(MD)->getAllDbgVariableRecordUsers()) {
5530 CheckDI(DVR->isDbgAssign(),
5531 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5532 CheckDI(DVR->getFunction() == I.getFunction(),
5533 "DVRAssign not in same function as inst", DVR, &I);
5534 }
5535}
5536
5537void Verifier::visitMMRAMetadata(Instruction &I, MDNode *MD) {
5539 "!mmra metadata attached to unexpected instruction kind", I, MD);
5540
5541 // MMRA Metadata should either be a tag, e.g. !{!"foo", !"bar"}, or a
5542 // list of tags such as !2 in the following example:
5543 // !0 = !{!"a", !"b"}
5544 // !1 = !{!"c", !"d"}
5545 // !2 = !{!0, !1}
5546 if (MMRAMetadata::isTagMD(MD))
5547 return;
5548
5549 Check(isa<MDTuple>(MD), "!mmra expected to be a metadata tuple", I, MD);
5550 for (const MDOperand &MDOp : MD->operands())
5551 Check(MMRAMetadata::isTagMD(MDOp.get()),
5552 "!mmra metadata tuple operand is not an MMRA tag", I, MDOp.get());
5553}
5554
5555void Verifier::visitCallStackMetadata(MDNode *MD) {
5556 // Call stack metadata should consist of a list of at least 1 constant int
5557 // (representing a hash of the location).
5558 Check(MD->getNumOperands() >= 1,
5559 "call stack metadata should have at least 1 operand", MD);
5560
5561 for (const auto &Op : MD->operands())
5563 "call stack metadata operand should be constant integer", Op);
5564}
5565
5566void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
5567 Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
5568 if (isa<CallBase>(I))
5569 Check(I.hasMetadata(LLVMContext::MD_callsite),
5570 "!memprof metadata requires !callsite metadata", &I, MD);
5571 Check(MD->getNumOperands() >= 1,
5572 "!memprof annotations should have at least 1 metadata operand "
5573 "(MemInfoBlock)",
5574 MD);
5575
5576 // Check each MIB
5577 for (auto &MIBOp : MD->operands()) {
5578 auto *MIB = dyn_cast<MDNode>(MIBOp);
5579 // The first operand of an MIB should be the call stack metadata.
5580 // There rest of the operands should be MDString tags, and there should be
5581 // at least one.
5582 Check(MIB->getNumOperands() >= 2,
5583 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5584
5585 // Check call stack metadata (first operand).
5586 Check(MIB->getOperand(0) != nullptr,
5587 "!memprof MemInfoBlock first operand should not be null", MIB);
5588 Check(isa<MDNode>(MIB->getOperand(0)),
5589 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5590 auto *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
5591 visitCallStackMetadata(StackMD);
5592
5593 // The second MIB operand should be MDString.
5594 Check(isa<MDString>(MIB->getOperand(1)),
5595 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5596
5597 // Any remaining should be MDNode that are pairs of integers
5598 for (unsigned I = 2; I < MIB->getNumOperands(); ++I) {
5599 auto *OpNode = dyn_cast<MDNode>(MIB->getOperand(I));
5600 Check(OpNode, "Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5601 MIB);
5602 Check(OpNode->getNumOperands() == 2,
5603 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5604 "operands",
5605 MIB);
5606 // Check that all of Op's operands are ConstantInt.
5607 Check(llvm::all_of(OpNode->operands(),
5608 [](const MDOperand &Op) {
5609 return mdconst::hasa<ConstantInt>(Op);
5610 }),
5611 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5612 "ConstantInt operands",
5613 MIB);
5614 }
5615 }
5616}
5617
5618void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
5619 Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
5620 // Verify the partial callstack annotated from memprof profiles. This callsite
5621 // is a part of a profiled allocation callstack.
5622 visitCallStackMetadata(MD);
5623}
5624
5625void Verifier::visitCalleeTypeMetadata(Instruction &I, MDNode *MD) {
5626 Check(isa<CallBase>(I), "!callee_type metadata should only exist on calls",
5627 &I);
5628 for (Metadata *Op : MD->operands()) {
5630 "The callee_type metadata must be a list of callgraph metadata nodes",
5631 Op);
5632 auto *CallgraphMD = cast<MDNode>(Op);
5633 Check(CallgraphMD->getNumOperands() == 1,
5634 "Well-formed callgraph metadata must contain exactly one "
5635 "operand",
5636 Op);
5637 Check(isa<MDString>(CallgraphMD->getOperand(0)),
5638 "The operand of callgraph metadata for functions must be an MDString",
5639 Op);
5640 }
5641}
5642
5643void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5644 Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
5645 Check(Annotation->getNumOperands() >= 1,
5646 "annotation must have at least one operand");
5647 for (const MDOperand &Op : Annotation->operands()) {
5648 bool TupleOfStrings =
5649 isa<MDTuple>(Op.get()) &&
5650 all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
5651 return isa<MDString>(Annotation.get());
5652 });
5653 Check(isa<MDString>(Op.get()) || TupleOfStrings,
5654 "operands must be a string or a tuple of strings");
5655 }
5656}
5657
5658void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
5659 unsigned NumOps = MD->getNumOperands();
5660 Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
5661 MD);
5662 Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
5663 "first scope operand must be self-referential or string", MD);
5664 if (NumOps == 3)
5666 "third scope operand must be string (if used)", MD);
5667
5668 auto *Domain = dyn_cast<MDNode>(MD->getOperand(1));
5669 Check(Domain != nullptr, "second scope operand must be MDNode", MD);
5670
5671 unsigned NumDomainOps = Domain->getNumOperands();
5672 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5673 "domain must have one or two operands", Domain);
5674 Check(Domain->getOperand(0).get() == Domain ||
5675 isa<MDString>(Domain->getOperand(0)),
5676 "first domain operand must be self-referential or string", Domain);
5677 if (NumDomainOps == 2)
5678 Check(isa<MDString>(Domain->getOperand(1)),
5679 "second domain operand must be string (if used)", Domain);
5680}
5681
5682void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
5683 for (const MDOperand &Op : MD->operands()) {
5684 const auto *OpMD = dyn_cast<MDNode>(Op);
5685 Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
5686 visitAliasScopeMetadata(OpMD);
5687 }
5688}
5689
5690void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
5691 auto IsValidAccessScope = [](const MDNode *MD) {
5692 return MD->getNumOperands() == 0 && MD->isDistinct();
5693 };
5694
5695 // An empty node is an access scope, and it must be 'distinct'. It is never a
5696 // list, because an empty list is not allowed: it would look the same as an
5697 // access scope.
5698 if (MD->getNumOperands() == 0) {
5699 Check(MD->isDistinct(), "Access scope must be 'distinct'", MD);
5700 return;
5701 }
5702
5703 // A non-empty node is a list of access scopes.
5704 for (const MDOperand &Op : MD->operands()) {
5705 const auto *OpMD = dyn_cast<MDNode>(Op);
5706 Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
5707 Check(IsValidAccessScope(OpMD),
5708 "Access scope list contains invalid access scope", MD);
5709 }
5710}
5711
5712void Verifier::visitCapturesMetadata(Instruction &I, const MDNode *Captures) {
5713 static const char *ValidArgs[] = {"address_is_null", "address",
5714 "read_provenance", "provenance"};
5715
5716 auto *SI = dyn_cast<StoreInst>(&I);
5717 Check(SI, "!captures metadata can only be applied to store instructions", &I);
5718 Check(SI->getValueOperand()->getType()->isPointerTy(),
5719 "!captures metadata can only be applied to store with value operand of "
5720 "pointer type",
5721 &I);
5722 Check(Captures->getNumOperands() != 0, "!captures metadata cannot be empty",
5723 &I);
5724
5725 for (Metadata *Op : Captures->operands()) {
5726 auto *Str = dyn_cast<MDString>(Op);
5727 Check(Str, "!captures metadata must be a list of strings", &I);
5728 Check(is_contained(ValidArgs, Str->getString()),
5729 "invalid entry in !captures metadata", &I, Str);
5730 }
5731}
5732
5733void Verifier::visitAllocTokenMetadata(Instruction &I, MDNode *MD) {
5734 Check(isa<CallBase>(I), "!alloc_token should only exist on calls", &I);
5735 Check(MD->getNumOperands() == 2, "!alloc_token must have 2 operands", MD);
5736 Check(isa<MDString>(MD->getOperand(0)), "expected string", MD);
5738 "expected integer constant", MD);
5739}
5740
5741void Verifier::visitInlineHistoryMetadata(Instruction &I, MDNode *MD) {
5742 Check(isa<CallBase>(I), "!inline_history should only exist on calls", &I);
5743 for (Metadata *Op : MD->operands()) {
5744 // Can be null when a function is erased.
5745 if (!Op)
5746 continue;
5749 ->getValue()
5750 ->stripPointerCastsAndAliases()),
5751 "!inline_history operands must be functions or null", MD);
5752 }
5753}
5754
5755void Verifier::visitMemCacheHintMetadata(Instruction &I, MDNode *MD) {
5756 Check(I.mayReadOrWriteMemory(),
5757 "!mem.cache_hint is only valid on memory operations", &I);
5758
5759 Check(MD->getNumOperands() % 2 == 0,
5760 "!mem.cache_hint must have even number of operands "
5761 "(operand_no, hint_node pairs)",
5762 MD);
5763
5764 const auto *CB = dyn_cast<CallBase>(&I);
5765 if (CB)
5766 Check(CB->getIntrinsicID() != Intrinsic::not_intrinsic,
5767 "!mem.cache_hint is not supported on non-intrinsic calls", &I);
5768
5769 unsigned NumOperands = CB ? CB->arg_size() : I.getNumOperands();
5770
5771 SmallDenseSet<unsigned, 4> SeenOperandNos;
5772 std::optional<uint64_t> LastOperandNo;
5773
5774 // Top-level metadata alternates: i32 operand_no, MDNode hint_node.
5775 for (unsigned J = 0; J + 1 < MD->getNumOperands(); J += 2) {
5776 auto *OpNoCI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(J));
5777 Check(OpNoCI,
5778 "!mem.cache_hint must alternate between i32 operand numbers and "
5779 "metadata hint nodes",
5780 MD);
5781
5782 Check(OpNoCI->getValue().isNonNegative(),
5783 "!mem.cache_hint operand number must be non-negative", MD);
5784
5785 uint64_t OperandNo = OpNoCI->getZExtValue();
5786 Check(OperandNo < NumOperands,
5787 "!mem.cache_hint operand number is out of range", &I);
5788
5789 Value *Operand =
5790 CB ? CB->getArgOperand(OperandNo) : I.getOperand(OperandNo);
5791 Check(Operand->getType()->isPtrOrPtrVectorTy(),
5792 "!mem.cache_hint operand number must refer to a pointer operand", &I);
5793
5794 bool Inserted = SeenOperandNos.insert(OperandNo).second;
5795 Check(Inserted, "!mem.cache_hint contains duplicate operand number", MD);
5796
5797 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5798 "!mem.cache_hint operand numbers must be in increasing order", MD);
5799 LastOperandNo = OperandNo;
5800
5801 const auto *Node = dyn_cast<MDNode>(MD->getOperand(J + 1));
5802 Check(Node,
5803 "!mem.cache_hint must alternate between i32 operand numbers and "
5804 "metadata hint nodes",
5805 MD);
5806
5807 Check(Node->getNumOperands() % 2 == 0,
5808 "!mem.cache_hint hint node must have even number of operands "
5809 "(key-value pairs)",
5810 Node);
5811
5812 StringSet<> SeenKeys;
5813 for (unsigned K = 0; K + 1 < Node->getNumOperands(); K += 2) {
5814 const auto *Key = dyn_cast<MDString>(Node->getOperand(K));
5815 Check(Key, "!mem.cache_hint key must be a string", Node);
5816
5817 StringRef KeyStr = Key->getString();
5818 Check(SeenKeys.insert(KeyStr).second,
5819 "!mem.cache_hint hint node contains duplicate key", Node);
5820
5821 const Metadata *Value = Node->getOperand(K + 1).get();
5824 "!mem.cache_hint value must be a string or integer", Node);
5825 }
5826 }
5827}
5828
5829/// verifyInstruction - Verify that an instruction is well formed.
5830///
5831void Verifier::visitInstruction(Instruction &I) {
5832 BasicBlock *BB = I.getParent();
5833 Check(BB, "Instruction not embedded in basic block!", &I);
5834
5835 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
5836 for (User *U : I.users()) {
5837 Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
5838 "Only PHI nodes may reference their own value!", &I);
5839 }
5840 }
5841
5842 // Check that void typed values don't have names
5843 Check(!I.getType()->isVoidTy() || !I.hasName(),
5844 "Instruction has a name, but provides a void value!", &I);
5845
5846 // Check that the return value of the instruction is either void or a legal
5847 // value type.
5848 Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
5849 "Instruction returns a non-scalar type!", &I);
5850
5851 // Check that the instruction doesn't produce metadata. Calls are already
5852 // checked against the callee type.
5853 Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
5854 "Invalid use of metadata!", &I);
5855
5856 // Check that all uses of the instruction, if they are instructions
5857 // themselves, actually have parent basic blocks. If the use is not an
5858 // instruction, it is an error!
5859 for (Use &U : I.uses()) {
5860 if (auto *Used = dyn_cast<Instruction>(U.getUser()))
5861 Check(Used->getParent() != nullptr,
5862 "Instruction referencing"
5863 " instruction not embedded in a basic block!",
5864 &I, Used);
5865 else {
5866 CheckFailed("Use of instruction is not an instruction!", U);
5867 return;
5868 }
5869 }
5870
5871 // Get a pointer to the call base of the instruction if it is some form of
5872 // call.
5873 const auto *CBI = dyn_cast<CallBase>(&I);
5874
5875 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
5876 Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
5877
5878 // Check to make sure that only first-class-values are operands to
5879 // instructions.
5880 if (!I.getOperand(i)->getType()->isFirstClassType()) {
5881 Check(false, "Instruction operands must be first-class values!", &I);
5882 }
5883
5884 if (auto *F = dyn_cast<Function>(I.getOperand(i))) {
5885 // This code checks whether the function is used as the operand of a
5886 // clang_arc_attachedcall operand bundle.
5887 auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
5888 int Idx) {
5889 return CBI && CBI->isOperandBundleOfType(
5891 };
5892
5893 // Check to make sure that the "address of" an intrinsic function is never
5894 // taken. Ignore cases where the address of the intrinsic function is used
5895 // as the argument of operand bundle "clang.arc.attachedcall" as those
5896 // cases are handled in verifyAttachedCallBundle.
5897 Check((!F->isIntrinsic() ||
5898 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
5899 IsAttachedCallOperand(F, CBI, i)),
5900 "Cannot take the address of an intrinsic!", &I);
5901 Check(!F->isIntrinsic() || isa<CallInst>(I) || isa<CallBrInst>(I) ||
5902 F->getIntrinsicID() == Intrinsic::donothing ||
5903 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5904 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5905 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5906 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5907 F->getIntrinsicID() == Intrinsic::coro_resume ||
5908 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5909 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5910 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5911 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5912 F->getIntrinsicID() ==
5913 Intrinsic::experimental_patchpoint_void ||
5914 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5915 F->getIntrinsicID() == Intrinsic::fake_use ||
5916 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5917 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5918 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5919 IsAttachedCallOperand(F, CBI, i),
5920 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5921 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5922 "wasm.(re)throw",
5923 &I);
5924 Check(F->getParent() == &M, "Referencing function in another module!", &I,
5925 &M, F, F->getParent());
5926 } else if (auto *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
5927 Check(OpBB->getParent() == BB->getParent(),
5928 "Referring to a basic block in another function!", &I);
5929 } else if (auto *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
5930 Check(OpArg->getParent() == BB->getParent(),
5931 "Referring to an argument in another function!", &I);
5932 } else if (auto *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
5933 Check(GV->getParent() == &M, "Referencing global in another module!", &I,
5934 &M, GV, GV->getParent());
5935 } else if (auto *OpInst = dyn_cast<Instruction>(I.getOperand(i))) {
5936 Check(OpInst->getFunction() == BB->getParent(),
5937 "Referring to an instruction in another function!", &I);
5938 verifyDominatesUse(I, i);
5939 } else if (isa<InlineAsm>(I.getOperand(i))) {
5940 Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
5941 "Cannot take the address of an inline asm!", &I);
5942 } else if (auto *C = dyn_cast<Constant>(I.getOperand(i))) {
5943 visitConstantExprsRecursively(C);
5944 }
5945 }
5946
5947 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
5949 "fpmath requires a floating point result!", &I);
5950 Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
5951 if (ConstantFP *CFP0 =
5953 const APFloat &Accuracy = CFP0->getValueAPF();
5954 Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
5955 "fpmath accuracy must have float type", &I);
5956 Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
5957 "fpmath accuracy not a positive number!", &I);
5958 } else {
5959 Check(false, "invalid fpmath accuracy!", &I);
5960 }
5961 }
5962
5963 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
5965 "Ranges are only for loads, calls and invokes!", &I);
5966 visitRangeMetadata(I, Range, I.getType());
5967 }
5968
5969 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofpclass)) {
5970 Check(isa<LoadInst>(I), "nofpclass is only for loads", &I);
5971 visitNoFPClassMetadata(I, MD, I.getType());
5972 }
5973
5974 if (MDNode *Range = I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5977 "noalias.addrspace are only for memory operations!", &I);
5978 visitNoaliasAddrspaceMetadata(I, Range, I.getType());
5979 }
5980
5981 if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
5983 "invariant.group metadata is only for loads and stores", &I);
5984 }
5985
5986 if (I.hasMetadata(LLVMContext::MD_invariant_load)) {
5987 auto *II = dyn_cast<IntrinsicInst>(&I);
5988 Check(isa<LoadInst>(I) || (II && II->onlyReadsMemory()),
5989 "invariant.load metadata is only for loads and readonly "
5990 "intrinsic calls",
5991 &I);
5992 }
5993
5994 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
5995 Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
5996 &I);
5998 "nonnull applies only to load instructions, use attributes"
5999 " for calls or invokes",
6000 &I);
6001 Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
6002 }
6003
6004 if (MDNode *MD = I.getMetadata(LLVMContext::MD_noundef)) {
6005 Check(isa<LoadInst>(I), "noundef applies only to load instructions", &I);
6006 Check(MD->getNumOperands() == 0, "noundef metadata must be empty", &I);
6007 }
6008
6009 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
6010 visitDereferenceableMetadata(I, MD);
6011
6012 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
6013 visitDereferenceableMetadata(I, MD);
6014
6015 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofreeobj))
6016 visitNoFreeObjMetadata(I, MD);
6017
6018 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
6019 TBAAVerifyHelper.visitTBAAMetadata(&I, TBAA);
6020
6021 if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
6022 visitAliasScopeListMetadata(MD);
6023 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
6024 visitAliasScopeListMetadata(MD);
6025
6026 if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
6027 visitAccessGroupMetadata(MD);
6028
6029 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
6030 Check(I.getType()->isPointerTy(), "align applies only to pointer types",
6031 &I);
6033 "align applies only to load instructions, "
6034 "use attributes for calls or invokes",
6035 &I);
6036 Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
6037 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
6038 Check(CI && CI->getType()->isIntegerTy(64),
6039 "align metadata value must be an i64!", &I);
6040 uint64_t Align = CI->getZExtValue();
6041 Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
6042 &I);
6043 Check(Align <= Value::MaximumAlignment,
6044 "alignment is larger that implementation defined limit", &I);
6045 }
6046
6047 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
6048 visitProfMetadata(I, MD);
6049
6050 if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
6051 visitMemProfMetadata(I, MD);
6052
6053 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
6054 visitCallsiteMetadata(I, MD);
6055
6056 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callee_type))
6057 visitCalleeTypeMetadata(I, MD);
6058
6059 if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
6060 visitDIAssignIDMetadata(I, MD);
6061
6062 if (MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra))
6063 visitMMRAMetadata(I, MMRA);
6064
6065 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
6066 visitAnnotationMetadata(Annotation);
6067
6068 if (MDNode *Captures = I.getMetadata(LLVMContext::MD_captures))
6069 visitCapturesMetadata(I, Captures);
6070
6071 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alloc_token))
6072 visitAllocTokenMetadata(I, MD);
6073
6074 if (MDNode *MD = I.getMetadata(LLVMContext::MD_inline_history))
6075 visitInlineHistoryMetadata(I, MD);
6076
6077 if (MDNode *MD = I.getMetadata(LLVMContext::MD_mem_cache_hint))
6078 visitMemCacheHintMetadata(I, MD);
6079
6080 if (MDNode *MD = I.getMetadata("amdgpu.expected.active.lanes")) {
6081 Check(MD->getNumOperands() == 1,
6082 "!amdgpu.expected.active.lanes must have exactly one operand", &I,
6083 MD);
6084 ConstantInt *CI =
6086 Check(CI && CI->getType()->isIntegerTy(32),
6087 "!amdgpu.expected.active.lanes operand must be an i32 constant", &I,
6088 MD);
6089 }
6090
6091 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
6092 CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
6093 visitMDNode(*N, AreDebugLocsAllowed::Yes);
6094
6095 if (auto *DL = dyn_cast<DILocation>(N)) {
6096 if (DL->getAtomGroup()) {
6097 DISubprogram *SP = getSubprogram(DL->getRawScope());
6098 CheckDI(SP && SP->getKeyInstructionsEnabled(),
6099 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6100 "Instructions enabled",
6101 DL, SP);
6102 }
6103 }
6104 }
6105
6107 I.getAllMetadata(MDs);
6108 for (auto Attachment : MDs) {
6109 unsigned Kind = Attachment.first;
6110 auto AllowLocs =
6111 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
6112 ? AreDebugLocsAllowed::Yes
6113 : AreDebugLocsAllowed::No;
6114 visitMDNode(*Attachment.second, AllowLocs);
6115 }
6116
6117 InstsInThisBlock.insert(&I);
6118}
6119
6120/// Allow intrinsics to be verified in different ways.
6121void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
6123
6124 // If the intrinsic takes MDNode arguments, verify that they are either global
6125 // or are local to *this* function.
6126 for (Value *V : Call.args()) {
6127 if (auto *MD = dyn_cast<MetadataAsValue>(V))
6128 visitMetadataAsValue(*MD, Call.getCaller());
6129 if (auto *Const = dyn_cast<Constant>(V))
6130 Check(!Const->getType()->isX86_AMXTy(),
6131 "const x86_amx is not allowed in argument!");
6132 }
6133
6134 switch (ID) {
6135 default:
6136 break;
6137 case Intrinsic::assume: {
6138 if (Call.hasOperandBundles()) {
6140 Check(Cond && Cond->isOne(),
6141 "assume with operand bundles must have i1 true condition", Call);
6142 }
6143 for (auto OBU : Call.operand_bundles()) {
6144 // Separate storage assumptions are special insofar as they're the only
6145 // operand bundles allowed on assumes that aren't parameter attributes.
6146
6147 auto GetTypeAt = [&](unsigned Index) {
6148 return OBU.Inputs[Index]->getType();
6149 };
6150
6151 switch (getBundleAttrFromOBU(OBU)) {
6152 case BundleAttr::None:
6153 CheckFailed("tags must be valid attribute names", Call);
6154 break;
6155 case BundleAttr::Align:
6156 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6157 "alignment assumptions should have 2 or 3 arguments", Call);
6158 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6159 Call);
6160 Check(GetTypeAt(1)->isIntegerTy() &&
6161 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6162 "second argument should be an integer with a maximum width of 64 "
6163 "bits",
6164 Call);
6165 Check(OBU.Inputs.size() < 3 ||
6166 (GetTypeAt(2)->isIntegerTy() &&
6167 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6168 "third argument should be an integer with a maximum width of 64 "
6169 "bits if present",
6170 Call);
6171 break;
6172 case BundleAttr::Cold:
6173 Check(OBU.Inputs.size() == 0,
6174 "cold assumptions should have no arguments", Call);
6175 break;
6176 case BundleAttr::Dereferenceable:
6177 case BundleAttr::DereferenceableOrNull:
6178 Check(OBU.Inputs.size() == 2,
6179 "dereferenceable assumptions should have 2 arguments", Call);
6180 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6181 Call);
6182 Check(GetTypeAt(1)->isIntegerTy() &&
6183 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6184 "second argument should be an integer with a maximum width of 64 "
6185 "bits",
6186 Call);
6187 break;
6188 case BundleAttr::Ignore:
6189 break;
6190 case BundleAttr::NonNull:
6191 Check(OBU.Inputs.size() == 1,
6192 "nonnull assumptions should have 1 argument", Call);
6193 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6194 Call);
6195 break;
6196 case BundleAttr::NoUndef:
6197 Check(OBU.Inputs.size() == 1,
6198 "noundef assumptions should have 1 argument", Call);
6199 break;
6200 case BundleAttr::SeparateStorage:
6201 Check(OBU.Inputs.size() == 2,
6202 "separate_storage assumptions should have 2 arguments", Call);
6203 Check(GetTypeAt(0)->isPointerTy() && GetTypeAt(1)->isPointerTy(),
6204 "arguments to separate_storage assumptions should be pointers",
6205 Call);
6206 break;
6207 }
6208 }
6209 break;
6210 }
6211 case Intrinsic::ucmp:
6212 case Intrinsic::scmp: {
6213 Type *SrcTy = Call.getOperand(0)->getType();
6214 Type *DestTy = Call.getType();
6215
6216 Check(DestTy->getScalarSizeInBits() >= 2,
6217 "result type must be at least 2 bits wide", Call);
6218
6219 bool IsDestTypeVector = DestTy->isVectorTy();
6220 Check(SrcTy->isVectorTy() == IsDestTypeVector,
6221 "ucmp/scmp argument and result types must both be either vector or "
6222 "scalar types",
6223 Call);
6224 if (IsDestTypeVector) {
6225 auto SrcVecLen = cast<VectorType>(SrcTy)->getElementCount();
6226 auto DestVecLen = cast<VectorType>(DestTy)->getElementCount();
6227 Check(SrcVecLen == DestVecLen,
6228 "return type and arguments must have the same number of "
6229 "elements",
6230 Call);
6231 }
6232 break;
6233 }
6234 case Intrinsic::coro_begin:
6235 case Intrinsic::coro_begin_custom_abi:
6237 "id argument of llvm.coro.begin must refer to coro.id");
6238 break;
6239 case Intrinsic::coro_id: {
6241 "align argument only accepts constants");
6242 auto *Promise = Call.getArgOperand(1);
6243 Check(isa<ConstantPointerNull>(Promise) || isa<AllocaInst>(Promise),
6244 "promise argument must refer to an alloca");
6245
6246 auto *CoroAddr = Call.getArgOperand(2)->stripPointerCastsAndAliases();
6247 bool BeforeCoroEarly = isa<ConstantPointerNull>(CoroAddr);
6248 Check(BeforeCoroEarly || isa<Function>(CoroAddr),
6249 "coro argument must refer to a function");
6250
6251 auto *InfoArg = Call.getArgOperand(3);
6252 bool BeforeCoroSplit = isa<ConstantPointerNull>(InfoArg);
6253 if (BeforeCoroSplit)
6254 break;
6255
6256 Check(!BeforeCoroEarly, "cannot run CoroSplit before CoroEarly");
6257 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
6258 Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
6259 "info argument of llvm.coro.id must refer to an initialized "
6260 "constant");
6261 Constant *Init = GV->getInitializer();
6263 "info argument of llvm.coro.id must refer to either a struct or "
6264 "an array");
6265 break;
6266 }
6267 case Intrinsic::is_fpclass: {
6268 const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
6269 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
6270 "unsupported bits for llvm.is.fpclass test mask");
6271 break;
6272 }
6273 case Intrinsic::fptrunc_round: {
6274 // Check the rounding mode
6275 Metadata *MD = nullptr;
6277 if (MAV)
6278 MD = MAV->getMetadata();
6279
6280 Check(MD != nullptr, "missing rounding mode argument", Call);
6281
6282 Check(isa<MDString>(MD),
6283 ("invalid value for llvm.fptrunc.round metadata operand"
6284 " (the operand should be a string)"),
6285 MD);
6286
6287 std::optional<RoundingMode> RoundMode =
6288 convertStrToRoundingMode(cast<MDString>(MD)->getString());
6289 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6290 "unsupported rounding mode argument", Call);
6291 break;
6292 }
6293 case Intrinsic::convert_to_arbitrary_fp: {
6294 // Check that vector element counts are consistent.
6295 Type *ValueTy = Call.getArgOperand(0)->getType();
6296 Type *IntTy = Call.getType();
6297
6298 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6299 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6300 Check(IntVecTy,
6301 "if floating-point operand is a vector, integer operand must also "
6302 "be a vector",
6303 Call);
6304 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6305 "floating-point and integer vector operands must have the same "
6306 "element count",
6307 Call);
6308 }
6309
6310 // Check interpretation metadata (argoperand 1).
6311 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6312 Check(InterpMAV, "missing interpretation metadata operand", Call);
6313 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6314 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6315 StringRef Interp = InterpStr->getString();
6316
6317 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6318 Call);
6319
6320 // Valid interpretation strings: mini-float format names.
6322 "unsupported interpretation metadata string", Call);
6323
6324 // The integer type width must equal the arbitrary FP format width.
6325 if (unsigned FormatBits =
6327 Check(IntTy->getScalarSizeInBits() == FormatBits,
6328 "integer type bit width must equal the arbitrary FP format width",
6329 Call);
6330
6331 // Check rounding mode metadata (argoperand 2).
6332 auto *RoundingMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(2));
6333 Check(RoundingMAV, "missing rounding mode metadata operand", Call);
6334 auto *RoundingStr = dyn_cast<MDString>(RoundingMAV->getMetadata());
6335 Check(RoundingStr, "rounding mode metadata operand must be a string", Call);
6336
6337 std::optional<RoundingMode> RM =
6338 convertStrToRoundingMode(RoundingStr->getString());
6339 Check(RM && *RM != RoundingMode::Dynamic,
6340 "unsupported rounding mode argument", Call);
6341 break;
6342 }
6343 case Intrinsic::convert_from_arbitrary_fp: {
6344 // Check that vector element counts are consistent.
6345 Type *IntTy = Call.getArgOperand(0)->getType();
6346 Type *ValueTy = Call.getType();
6347
6348 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6349 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6350 Check(IntVecTy,
6351 "if floating-point operand is a vector, integer operand must also "
6352 "be a vector",
6353 Call);
6354 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6355 "floating-point and integer vector operands must have the same "
6356 "element count",
6357 Call);
6358 }
6359
6360 // Check interpretation metadata (argoperand 1).
6361 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6362 Check(InterpMAV, "missing interpretation metadata operand", Call);
6363 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6364 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6365 StringRef Interp = InterpStr->getString();
6366
6367 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6368 Call);
6369
6370 // Valid interpretation strings: mini-float format names.
6372 "unsupported interpretation metadata string", Call);
6373
6374 // The integer type width must equal the arbitrary FP format width.
6375 if (unsigned FormatBits =
6377 Check(IntTy->getScalarSizeInBits() == FormatBits,
6378 "integer type bit width must equal the arbitrary FP format width",
6379 Call);
6380 break;
6381 }
6382#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6383#include "llvm/IR/VPIntrinsics.def"
6384#undef BEGIN_REGISTER_VP_INTRINSIC
6385 visitVPIntrinsic(cast<VPIntrinsic>(Call));
6386 break;
6387#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6388 case Intrinsic::INTRINSIC:
6389#include "llvm/IR/ConstrainedOps.def"
6390#undef INSTRUCTION
6391 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
6392 break;
6393 case Intrinsic::dbg_declare: // llvm.dbg.declare
6394 case Intrinsic::dbg_value: // llvm.dbg.value
6395 case Intrinsic::dbg_assign: // llvm.dbg.assign
6396 case Intrinsic::dbg_label: // llvm.dbg.label
6397 // We no longer interpret debug intrinsics (the old variable-location
6398 // design). They're meaningless as far as LLVM is concerned we could make
6399 // it an error for them to appear, but it's possible we'll have users
6400 // converting back to intrinsics for the forseeable future (such as DXIL),
6401 // so tolerate their existance.
6402 break;
6403 case Intrinsic::memcpy:
6404 case Intrinsic::memcpy_inline:
6405 case Intrinsic::memmove:
6406 case Intrinsic::memset:
6407 case Intrinsic::memset_inline:
6408 break;
6409 case Intrinsic::experimental_memset_pattern: {
6410 const auto Memset = cast<MemSetPatternInst>(&Call);
6411 Check(Memset->getValue()->getType()->isSized(),
6412 "unsized types cannot be used as memset patterns", Call);
6413 break;
6414 }
6415 case Intrinsic::memcpy_element_unordered_atomic:
6416 case Intrinsic::memmove_element_unordered_atomic:
6417 case Intrinsic::memset_element_unordered_atomic: {
6418 const auto *AMI = cast<AnyMemIntrinsic>(&Call);
6419
6420 ConstantInt *ElementSizeCI =
6421 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
6422 const APInt &ElementSizeVal = ElementSizeCI->getValue();
6423 Check(ElementSizeVal.isPowerOf2(),
6424 "element size of the element-wise atomic memory intrinsic "
6425 "must be a power of 2",
6426 Call);
6427
6428 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6429 return Alignment && ElementSizeVal.ule(Alignment->value());
6430 };
6431 Check(IsValidAlignment(AMI->getDestAlign()),
6432 "incorrect alignment of the destination argument", Call);
6433 if (const auto *AMT = dyn_cast<AnyMemTransferInst>(AMI)) {
6434 Check(IsValidAlignment(AMT->getSourceAlign()),
6435 "incorrect alignment of the source argument", Call);
6436 }
6437 break;
6438 }
6439 case Intrinsic::call_preallocated_setup: {
6440 auto *NumArgs = cast<ConstantInt>(Call.getArgOperand(0));
6441 bool FoundCall = false;
6442 for (User *U : Call.users()) {
6443 auto *UseCall = dyn_cast<CallBase>(U);
6444 Check(UseCall != nullptr,
6445 "Uses of llvm.call.preallocated.setup must be calls");
6446 Intrinsic::ID IID = UseCall->getIntrinsicID();
6447 if (IID == Intrinsic::call_preallocated_arg) {
6448 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
6449 Check(AllocArgIndex != nullptr,
6450 "llvm.call.preallocated.alloc arg index must be a constant");
6451 auto AllocArgIndexInt = AllocArgIndex->getValue();
6452 Check(AllocArgIndexInt.sge(0) &&
6453 AllocArgIndexInt.slt(NumArgs->getValue()),
6454 "llvm.call.preallocated.alloc arg index must be between 0 and "
6455 "corresponding "
6456 "llvm.call.preallocated.setup's argument count");
6457 } else if (IID == Intrinsic::call_preallocated_teardown) {
6458 // nothing to do
6459 } else {
6460 Check(!FoundCall, "Can have at most one call corresponding to a "
6461 "llvm.call.preallocated.setup");
6462 FoundCall = true;
6463 size_t NumPreallocatedArgs = 0;
6464 for (unsigned i = 0; i < UseCall->arg_size(); i++) {
6465 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6466 ++NumPreallocatedArgs;
6467 }
6468 }
6469 Check(NumPreallocatedArgs != 0,
6470 "cannot use preallocated intrinsics on a call without "
6471 "preallocated arguments");
6472 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6473 "llvm.call.preallocated.setup arg size must be equal to number "
6474 "of preallocated arguments "
6475 "at call site",
6476 Call, *UseCall);
6477 // getOperandBundle() cannot be called if more than one of the operand
6478 // bundle exists. There is already a check elsewhere for this, so skip
6479 // here if we see more than one.
6480 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
6481 1) {
6482 return;
6483 }
6484 auto PreallocatedBundle =
6485 UseCall->getOperandBundle(LLVMContext::OB_preallocated);
6486 Check(PreallocatedBundle,
6487 "Use of llvm.call.preallocated.setup outside intrinsics "
6488 "must be in \"preallocated\" operand bundle");
6489 Check(PreallocatedBundle->Inputs.front().get() == &Call,
6490 "preallocated bundle must have token from corresponding "
6491 "llvm.call.preallocated.setup");
6492 }
6493 }
6494 break;
6495 }
6496 case Intrinsic::call_preallocated_arg: {
6497 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6498 Check(Token &&
6499 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6500 "llvm.call.preallocated.arg token argument must be a "
6501 "llvm.call.preallocated.setup");
6502 Check(Call.hasFnAttr(Attribute::Preallocated),
6503 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6504 "call site attribute");
6505 break;
6506 }
6507 case Intrinsic::call_preallocated_teardown: {
6508 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6509 Check(Token &&
6510 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6511 "llvm.call.preallocated.teardown token argument must be a "
6512 "llvm.call.preallocated.setup");
6513 break;
6514 }
6515 case Intrinsic::gcroot:
6516 case Intrinsic::gcwrite:
6517 case Intrinsic::gcread:
6518 if (ID == Intrinsic::gcroot) {
6519 auto *AI =
6521 Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
6523 "llvm.gcroot parameter #2 must be a constant.", Call);
6524 if (!AI->getAllocatedType()->isPointerTy()) {
6526 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6527 "or argument #2 must be a non-null constant.",
6528 Call);
6529 }
6530 }
6531
6532 Check(Call.getParent()->getParent()->hasGC(),
6533 "Enclosing function does not use GC.", Call);
6534 break;
6535 case Intrinsic::init_trampoline:
6537 "llvm.init_trampoline parameter #2 must resolve to a function.",
6538 Call);
6539 break;
6540 case Intrinsic::reloc_none: {
6542 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata()),
6543 "llvm.reloc.none argument must be a metadata string", &Call);
6544 break;
6545 }
6546 case Intrinsic::stackprotector:
6548 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
6549 break;
6550 case Intrinsic::localescape: {
6551 BasicBlock *BB = Call.getParent();
6552 Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
6553 Call);
6554 Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
6555 Call);
6556 for (Value *Arg : Call.args()) {
6557 if (isa<ConstantPointerNull>(Arg))
6558 continue; // Null values are allowed as placeholders.
6559 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
6560 Check(AI && AI->isStaticAlloca(),
6561 "llvm.localescape only accepts static allocas", Call);
6562 }
6563 FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
6564 SawFrameEscape = true;
6565 break;
6566 }
6567 case Intrinsic::localrecover: {
6569 auto *Fn = dyn_cast<Function>(FnArg);
6570 Check(Fn && !Fn->isDeclaration(),
6571 "llvm.localrecover first "
6572 "argument must be function defined in this module",
6573 Call);
6574 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
6575 auto &Entry = FrameEscapeInfo[Fn];
6576 Entry.second = unsigned(
6577 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6578 break;
6579 }
6580
6581 case Intrinsic::experimental_gc_statepoint:
6582 if (auto *CI = dyn_cast<CallInst>(&Call))
6583 Check(!CI->isInlineAsm(),
6584 "gc.statepoint support for inline assembly unimplemented", CI);
6585 Check(Call.getParent()->getParent()->hasGC(),
6586 "Enclosing function does not use GC.", Call);
6587
6588 verifyStatepoint(Call);
6589 break;
6590 case Intrinsic::experimental_gc_result: {
6591 Check(Call.getParent()->getParent()->hasGC(),
6592 "Enclosing function does not use GC.", Call);
6593
6594 auto *Statepoint = Call.getArgOperand(0);
6595 if (isa<UndefValue>(Statepoint))
6596 break;
6597
6598 // Are we tied to a statepoint properly?
6599 const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
6600 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6601 Intrinsic::experimental_gc_statepoint,
6602 "gc.result operand #1 must be from a statepoint", Call,
6603 Call.getArgOperand(0));
6604
6605 // Check that result type matches wrapped callee.
6606 auto *TargetFuncType =
6607 cast<FunctionType>(StatepointCall->getParamElementType(2));
6608 Check(Call.getType() == TargetFuncType->getReturnType(),
6609 "gc.result result type does not match wrapped callee", Call);
6610 break;
6611 }
6612 case Intrinsic::experimental_gc_relocate: {
6613 Check(Call.arg_size() == 3, "wrong number of arguments", Call);
6614
6616 "gc.relocate must return a pointer or a vector of pointers", Call);
6617
6618 // Check that this relocate is correctly tied to the statepoint
6619
6620 // This is case for relocate on the unwinding path of an invoke statepoint
6621 if (auto *LandingPad = dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
6622
6623 const BasicBlock *InvokeBB =
6624 LandingPad->getParent()->getUniquePredecessor();
6625
6626 // Landingpad relocates should have only one predecessor with invoke
6627 // statepoint terminator
6628 Check(InvokeBB, "safepoints should have unique landingpads",
6629 LandingPad->getParent());
6630 Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
6631 InvokeBB);
6633 "gc relocate should be linked to a statepoint", InvokeBB);
6634 } else {
6635 // In all other cases relocate should be tied to the statepoint directly.
6636 // This covers relocates on a normal return path of invoke statepoint and
6637 // relocates of a call statepoint.
6638 auto *Token = Call.getArgOperand(0);
6640 "gc relocate is incorrectly tied to the statepoint", Call, Token);
6641 }
6642
6643 // Verify rest of the relocate arguments.
6644 const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
6645
6646 // Both the base and derived must be piped through the safepoint.
6649 "gc.relocate operand #2 must be integer offset", Call);
6650
6651 Value *Derived = Call.getArgOperand(2);
6652 Check(isa<ConstantInt>(Derived),
6653 "gc.relocate operand #3 must be integer offset", Call);
6654
6655 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
6656 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
6657
6658 // Check the bounds
6659 if (isa<UndefValue>(StatepointCall))
6660 break;
6661 if (auto Opt = cast<GCStatepointInst>(StatepointCall)
6662 .getOperandBundle(LLVMContext::OB_gc_live)) {
6663 Check(BaseIndex < Opt->Inputs.size(),
6664 "gc.relocate: statepoint base index out of bounds", Call);
6665 Check(DerivedIndex < Opt->Inputs.size(),
6666 "gc.relocate: statepoint derived index out of bounds", Call);
6667 }
6668
6669 // Relocated value must be either a pointer type or vector-of-pointer type,
6670 // but gc_relocate does not need to return the same pointer type as the
6671 // relocated pointer. It can be casted to the correct type later if it's
6672 // desired. However, they must have the same address space and 'vectorness'
6673 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
6674 auto *ResultType = Call.getType();
6675 auto *DerivedType = Relocate.getDerivedPtr()->getType();
6676 auto *BaseType = Relocate.getBasePtr()->getType();
6677
6678 Check(BaseType->isPtrOrPtrVectorTy(),
6679 "gc.relocate: relocated value must be a pointer", Call);
6680 Check(DerivedType->isPtrOrPtrVectorTy(),
6681 "gc.relocate: relocated value must be a pointer", Call);
6682
6683 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6684 "gc.relocate: vector relocates to vector and pointer to pointer",
6685 Call);
6686 Check(
6687 ResultType->getPointerAddressSpace() ==
6688 DerivedType->getPointerAddressSpace(),
6689 "gc.relocate: relocating a pointer shouldn't change its address space",
6690 Call);
6691
6692 auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
6693 Check(GC, "gc.relocate: calling function must have GCStrategy",
6694 Call.getFunction());
6695 if (GC) {
6696 auto isGCPtr = [&GC](Type *PTy) {
6697 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
6698 };
6699 Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
6700 Check(isGCPtr(BaseType),
6701 "gc.relocate: relocated value must be a gc pointer", Call);
6702 Check(isGCPtr(DerivedType),
6703 "gc.relocate: relocated value must be a gc pointer", Call);
6704 }
6705 break;
6706 }
6707 case Intrinsic::experimental_patchpoint: {
6708 if (Call.getCallingConv() == CallingConv::AnyReg) {
6710 "patchpoint: invalid return type used with anyregcc", Call);
6711 }
6712 break;
6713 }
6714 case Intrinsic::eh_exceptioncode:
6715 case Intrinsic::eh_exceptionpointer: {
6717 "eh.exceptionpointer argument must be a catchpad", Call);
6718 break;
6719 }
6720 case Intrinsic::get_active_lane_mask: {
6721 Type *ElemTy = Call.getType()->getScalarType();
6722 Check(ElemTy->isIntegerTy(1),
6723 "get_active_lane_mask: element type is not i1", Call);
6724 break;
6725 }
6726 case Intrinsic::experimental_get_vector_length: {
6727 auto *VF = cast<ConstantInt>(Call.getArgOperand(1));
6728 Check(!VF->isNegative() && !VF->isZero(),
6729 "get_vector_length: VF must be positive", Call);
6730 break;
6731 }
6732 case Intrinsic::experimental_guard: {
6733 Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
6735 "experimental_guard must have exactly one "
6736 "\"deopt\" operand bundle");
6737 break;
6738 }
6739
6740 case Intrinsic::experimental_deoptimize: {
6741 Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
6742 Call);
6744 "experimental_deoptimize must have exactly one "
6745 "\"deopt\" operand bundle");
6747 "experimental_deoptimize return type must match caller return type");
6748
6749 if (isa<CallInst>(Call)) {
6751 Check(RI,
6752 "calls to experimental_deoptimize must be followed by a return");
6753
6754 if (!Call.getType()->isVoidTy() && RI)
6755 Check(RI->getReturnValue() == &Call,
6756 "calls to experimental_deoptimize must be followed by a return "
6757 "of the value computed by experimental_deoptimize");
6758 }
6759
6760 break;
6761 }
6762 case Intrinsic::vastart: {
6764 "va_start called in a non-varargs function");
6765 break;
6766 }
6767 case Intrinsic::get_dynamic_area_offset: {
6768 auto *IntTy = dyn_cast<IntegerType>(Call.getType());
6769 Check(IntTy && DL.getPointerSizeInBits(DL.getAllocaAddrSpace()) ==
6770 IntTy->getBitWidth(),
6771 "get_dynamic_area_offset result type must be scalar integer matching "
6772 "alloca address space width",
6773 Call);
6774 break;
6775 }
6776 case Intrinsic::smul_fix:
6777 case Intrinsic::smul_fix_sat:
6778 case Intrinsic::umul_fix:
6779 case Intrinsic::umul_fix_sat:
6780 case Intrinsic::sdiv_fix:
6781 case Intrinsic::sdiv_fix_sat:
6782 case Intrinsic::udiv_fix:
6783 case Intrinsic::udiv_fix_sat: {
6784 Value *Op1 = Call.getArgOperand(0);
6785 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
6786
6787 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6788 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6789 Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
6790 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6791 "the operands");
6792 } else {
6793 Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
6794 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6795 "to the width of the operands");
6796 }
6797 break;
6798 }
6799 case Intrinsic::lrint:
6800 case Intrinsic::llrint:
6801 case Intrinsic::lround:
6802 case Intrinsic::llround: {
6803 Type *ValTy = Call.getArgOperand(0)->getType();
6804 Type *ResultTy = Call.getType();
6805 Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
6806 IF->getName() + ": argument and result disagree on vector use",
6807 &Call);
6808 if (auto *VTy = dyn_cast<VectorType>(ValTy)) {
6809 auto *RTy = dyn_cast<VectorType>(ResultTy);
6810 Check(VTy->getElementCount() == RTy->getElementCount(),
6811 IF->getName() + ": argument must be same length as result", &Call);
6812 }
6813 break;
6814 }
6815 case Intrinsic::bswap: {
6816 Type *Ty = Call.getType();
6817 unsigned Size = Ty->getScalarSizeInBits();
6818 Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
6819 break;
6820 }
6821 case Intrinsic::invariant_start: {
6822 auto *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
6823 Check(InvariantSize &&
6824 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6825 "invariant_start parameter must be -1, 0 or a positive number",
6826 &Call);
6827 break;
6828 }
6829 case Intrinsic::matrix_multiply:
6830 case Intrinsic::matrix_transpose:
6831 case Intrinsic::matrix_column_major_load:
6832 case Intrinsic::matrix_column_major_store: {
6834 Value *Stride = nullptr;
6835 ConstantInt *NumRows;
6836 ConstantInt *NumColumns;
6837 VectorType *ResultTy;
6838 Type *Op0ElemTy = nullptr;
6839 Type *Op1ElemTy = nullptr;
6840 switch (ID) {
6841 case Intrinsic::matrix_multiply: {
6842 NumRows = cast<ConstantInt>(Call.getArgOperand(2));
6843 ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
6844 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6846 ->getNumElements() ==
6847 NumRows->getZExtValue() * N->getZExtValue(),
6848 "First argument of a matrix operation does not match specified "
6849 "shape!");
6851 ->getNumElements() ==
6852 N->getZExtValue() * NumColumns->getZExtValue(),
6853 "Second argument of a matrix operation does not match specified "
6854 "shape!");
6855
6856 ResultTy = cast<VectorType>(Call.getType());
6857 Op0ElemTy =
6858 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6859 Op1ElemTy =
6860 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
6861 break;
6862 }
6863 case Intrinsic::matrix_transpose:
6864 NumRows = cast<ConstantInt>(Call.getArgOperand(1));
6865 NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
6866 ResultTy = cast<VectorType>(Call.getType());
6867 Op0ElemTy =
6868 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6869 break;
6870 case Intrinsic::matrix_column_major_load: {
6871 Stride = Call.getArgOperand(1);
6872 NumRows = cast<ConstantInt>(Call.getArgOperand(3));
6873 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6874 ResultTy = cast<VectorType>(Call.getType());
6875 break;
6876 }
6877 case Intrinsic::matrix_column_major_store: {
6878 Stride = Call.getArgOperand(2);
6879 NumRows = cast<ConstantInt>(Call.getArgOperand(4));
6880 NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
6881 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
6882 Op0ElemTy =
6883 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6884 break;
6885 }
6886 default:
6887 llvm_unreachable("unexpected intrinsic");
6888 }
6889
6890 Check(ResultTy->getElementType()->isIntegerTy() ||
6891 ResultTy->getElementType()->isFloatingPointTy(),
6892 "Result type must be an integer or floating-point type!", IF);
6893
6894 if (Op0ElemTy)
6895 Check(ResultTy->getElementType() == Op0ElemTy,
6896 "Vector element type mismatch of the result and first operand "
6897 "vector!",
6898 IF);
6899
6900 if (Op1ElemTy)
6901 Check(ResultTy->getElementType() == Op1ElemTy,
6902 "Vector element type mismatch of the result and second operand "
6903 "vector!",
6904 IF);
6905
6907 NumRows->getZExtValue() * NumColumns->getZExtValue(),
6908 "Result of a matrix operation does not fit in the returned vector!");
6909
6910 if (Stride)
6911 Check(Stride->getType()->getIntegerBitWidth() <= 64,
6912 "Stride bitwidth cannot exceed 64!", IF);
6913
6914 break;
6915 }
6916 case Intrinsic::stepvector: {
6917 auto *VecTy = dyn_cast<VectorType>(Call.getType());
6918 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6919 VecTy->getScalarSizeInBits() >= 8,
6920 "stepvector only supported for vectors of integers "
6921 "with a bitwidth of at least 8.",
6922 &Call);
6923 break;
6924 }
6925 case Intrinsic::experimental_vector_match: {
6926 Value *Op1 = Call.getArgOperand(0);
6927 Value *Op2 = Call.getArgOperand(1);
6929
6930 auto *Op1Ty = dyn_cast<VectorType>(Op1->getType());
6931 auto *Op2Ty = dyn_cast<VectorType>(Op2->getType());
6932 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
6933
6934 Check(Op1Ty && Op2Ty && MaskTy, "Operands must be vectors.", &Call);
6936 "Second operand must be a fixed length vector.", &Call);
6937 Check(Op1Ty->getElementType()->isIntegerTy(),
6938 "First operand must be a vector of integers.", &Call);
6939 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6940 "First two operands must have the same element type.", &Call);
6941 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6942 "First operand and mask must have the same number of elements.",
6943 &Call);
6944 Check(MaskTy->getElementType()->isIntegerTy(1),
6945 "Mask must be a vector of i1's.", &Call);
6946 Check(Call.getType() == MaskTy, "Return type must match the mask type.",
6947 &Call);
6948 break;
6949 }
6950 case Intrinsic::vector_insert: {
6951 Value *Vec = Call.getArgOperand(0);
6952 Value *SubVec = Call.getArgOperand(1);
6953 Value *Idx = Call.getArgOperand(2);
6954 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6955
6956 VectorType *VecTy = cast<VectorType>(Vec->getType());
6957 VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
6958
6959 ElementCount VecEC = VecTy->getElementCount();
6960 ElementCount SubVecEC = SubVecTy->getElementCount();
6961 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6962 "vector_insert parameters must have the same element "
6963 "type.",
6964 &Call);
6965 Check(IdxN % SubVecEC.getKnownMinValue() == 0,
6966 "vector_insert index must be a constant multiple of "
6967 "the subvector's known minimum vector length.");
6968
6969 // The only allowed 'mixed' case is inserting a fixed vector into a
6970 // scalable vector.
6971 if (SubVecEC.isScalable()) {
6972 Check(VecEC.isScalable(), "cannot vector_insert a scalable vector into "
6973 "a fixed vector.");
6974 }
6975
6976 // If this insertion is not the 'mixed' case where a fixed vector is
6977 // inserted into a scalable vector, ensure that the insertion of the
6978 // subvector does not overrun the parent vector.
6979 if (VecEC.isScalable() == SubVecEC.isScalable()) {
6980 Check(IdxN < VecEC.getKnownMinValue() &&
6981 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
6982 "subvector operand of vector_insert would overrun the "
6983 "vector being inserted into.");
6984 }
6985 break;
6986 }
6987 case Intrinsic::vector_extract: {
6988 Value *Vec = Call.getArgOperand(0);
6989 Value *Idx = Call.getArgOperand(1);
6990 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6991
6992 VectorType *ResultTy = cast<VectorType>(Call.getType());
6993 VectorType *VecTy = cast<VectorType>(Vec->getType());
6994
6995 ElementCount VecEC = VecTy->getElementCount();
6996 ElementCount ResultEC = ResultTy->getElementCount();
6997
6998 Check(ResultTy->getElementType() == VecTy->getElementType(),
6999 "vector_extract result must have the same element "
7000 "type as the input vector.",
7001 &Call);
7002 Check(IdxN % ResultEC.getKnownMinValue() == 0,
7003 "vector_extract index must be a constant multiple of "
7004 "the result type's known minimum vector length.");
7005
7006 // The only allowed 'mixed' case is extracting a fixed vector from a
7007 // scalable vector.
7008 if (ResultEC.isScalable()) {
7009 Check(VecEC.isScalable(), "cannot vector_extract a scalable vector from "
7010 "a fixed vector.");
7011 }
7012
7013 // If this extraction is not the 'mixed' case where a fixed vector is
7014 // extracted from a scalable vector, ensure that the extraction does not
7015 // overrun the parent vector.
7016 if (VecEC.isScalable() == ResultEC.isScalable()) {
7017 Check(IdxN < VecEC.getKnownMinValue() &&
7018 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
7019 "vector_extract would overrun.");
7020 }
7021 break;
7022 }
7023 case Intrinsic::vector_partial_reduce_fadd:
7024 case Intrinsic::vector_partial_reduce_add: {
7027
7028 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7029 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7030
7031 Check((VecWidth % AccWidth) == 0,
7032 "Invalid vector widths for partial "
7033 "reduction. The width of the input vector "
7034 "must be a positive integer multiple of "
7035 "the width of the accumulator vector.");
7036 break;
7037 }
7038 case Intrinsic::experimental_noalias_scope_decl: {
7039 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
7040 break;
7041 }
7042 case Intrinsic::preserve_array_access_index:
7043 case Intrinsic::preserve_struct_access_index:
7044 case Intrinsic::aarch64_ldaxr:
7045 case Intrinsic::aarch64_ldxr:
7046 case Intrinsic::arm_ldaex:
7047 case Intrinsic::arm_ldrex: {
7048 Type *ElemTy = Call.getParamElementType(0);
7049 Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
7050 &Call);
7051 break;
7052 }
7053 case Intrinsic::aarch64_stlxr:
7054 case Intrinsic::aarch64_stxr:
7055 case Intrinsic::arm_stlex:
7056 case Intrinsic::arm_strex: {
7057 Type *ElemTy = Call.getAttributes().getParamElementType(1);
7058 Check(ElemTy,
7059 "Intrinsic requires elementtype attribute on second argument.",
7060 &Call);
7061 break;
7062 }
7063 case Intrinsic::aarch64_prefetch: {
7064 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7065 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7066 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
7067 "target argument to llvm.aarch64.prefetch must be 0-3", Call);
7068 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
7069 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7070 Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
7071 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7072 break;
7073 }
7074 case Intrinsic::aarch64_range_prefetch: {
7075 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7076 "write argument to llvm.aarch64.range.prefetch must be 0 or 1", Call);
7077 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 2,
7078 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7079 Call);
7080 break;
7081 }
7082 case Intrinsic::riscv_vsetvli:
7083 case Intrinsic::riscv_vsetvlimax: {
7084 // The result models VLMAX (or a VL bounded by it) and is only defined for
7085 // XLen (i32/i64). Narrower types cannot represent the architectural VLMAX
7086 // range of [1, 65536], which value analyses rely on.
7088 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &Call);
7089
7090 // VSEW and VLMUL select the vtype and must encode a valid SEW/LMUL pair.
7091 bool HasAVL = ID == Intrinsic::riscv_vsetvli;
7092 unsigned Offset = HasAVL ? 1 : 0;
7093 uint64_t VSEW =
7094 cast<ConstantInt>(Call.getArgOperand(Offset))->getZExtValue();
7095 uint64_t VLMUL =
7096 cast<ConstantInt>(Call.getArgOperand(Offset + 1))->getZExtValue();
7097 Check(VSEW <= 3, "llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &Call);
7098 Check(VLMUL <= 7 && VLMUL != RISCVVType::LMUL_RESERVED,
7099 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &Call);
7100 break;
7101 }
7102 case Intrinsic::callbr_landingpad: {
7103 const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
7104 Check(CBR, "intrinstic requires callbr operand", &Call);
7105 if (!CBR)
7106 break;
7107
7108 const BasicBlock *LandingPadBB = Call.getParent();
7109 const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
7110 if (!PredBB) {
7111 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
7112 break;
7113 }
7114 if (!isa<CallBrInst>(PredBB->getTerminator())) {
7115 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
7116 &Call);
7117 break;
7118 }
7119 Check(llvm::is_contained(CBR->getIndirectDests(), LandingPadBB),
7120 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7121 "block in indirect destination list",
7122 &Call);
7123 const Instruction &First = *LandingPadBB->begin();
7124 Check(&First == &Call, "No other instructions may proceed intrinsic",
7125 &Call);
7126 break;
7127 }
7128 case Intrinsic::structured_gep: {
7129 // Parser should refuse those 2 cases.
7130 assert(Call.arg_size() >= 1);
7132
7133 Check(Call.paramHasAttr(0, Attribute::ElementType),
7134 "Intrinsic first parameter is missing an ElementType attribute",
7135 &Call);
7136
7137 Type *T = Call.getParamAttr(0, Attribute::ElementType).getValueAsType();
7138 for (unsigned I = 1; I < Call.arg_size(); ++I) {
7140 auto *CI = dyn_cast<ConstantInt>(Index);
7141 Check(Index->getType()->isIntegerTy(),
7142 "Index operand type must be an integer", &Call);
7143
7144 if (auto *AT = dyn_cast<ArrayType>(T)) {
7145 T = AT->getElementType();
7146 } else if (auto *ST = dyn_cast<StructType>(T)) {
7147 Check(CI, "Indexing into a struct requires a constant int", &Call);
7148 Check(CI->getZExtValue() < ST->getNumElements(),
7149 "Indexing in a struct should be inbounds", &Call);
7150 T = ST->getElementType(CI->getZExtValue());
7151 } else if (auto *VT = dyn_cast<VectorType>(T)) {
7152 T = VT->getElementType();
7153 } else {
7154 CheckFailed("Reached a non-composite type with more indices to process",
7155 &Call);
7156 }
7157 }
7158 break;
7159 }
7160 case Intrinsic::structured_alloca:
7161 Check(Call.hasRetAttr(Attribute::ElementType),
7162 "@llvm.structured.alloca calls require elementtype attribute.",
7163 &Call);
7164 break;
7165 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7166 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7167 Value *V = Call.getArgOperand(0);
7168 unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
7169 Check(RegCount % 8 == 0,
7170 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7171 break;
7172 }
7173 case Intrinsic::experimental_convergence_entry:
7174 case Intrinsic::experimental_convergence_anchor:
7175 break;
7176 case Intrinsic::experimental_convergence_loop:
7177 break;
7178 case Intrinsic::ptrmask: {
7179 Type *Ty0 = Call.getArgOperand(0)->getType();
7180 Type *Ty1 = Call.getArgOperand(1)->getType();
7182 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7183 "of pointers",
7184 &Call);
7185 Check(
7186 Ty0->isVectorTy() == Ty1->isVectorTy(),
7187 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7188 &Call);
7189 if (Ty0->isVectorTy())
7190 Check(cast<VectorType>(Ty0)->getElementCount() ==
7191 cast<VectorType>(Ty1)->getElementCount(),
7192 "llvm.ptrmask intrinsic arguments must have the same number of "
7193 "elements",
7194 &Call);
7195 Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
7196 "llvm.ptrmask intrinsic second argument bitwidth must match "
7197 "pointer index type size of first argument",
7198 &Call);
7199 break;
7200 }
7201 case Intrinsic::thread_pointer: {
7203 DL.getDefaultGlobalsAddressSpace(),
7204 "llvm.thread.pointer intrinsic return type must be for the globals "
7205 "address space",
7206 &Call);
7207 break;
7208 }
7209 case Intrinsic::threadlocal_address: {
7210 const Value &Arg0 = *Call.getArgOperand(0);
7211 Check(isa<GlobalValue>(Arg0),
7212 "llvm.threadlocal.address first argument must be a GlobalValue");
7213 Check(cast<GlobalValue>(Arg0).isThreadLocal(),
7214 "llvm.threadlocal.address operand isThreadLocal() must be true");
7215 break;
7216 }
7217 case Intrinsic::lifetime_start:
7218 case Intrinsic::lifetime_end: {
7219 Value *Ptr = Call.getArgOperand(0);
7220 auto *II = dyn_cast<IntrinsicInst>(Ptr);
7221 Check(isa<AllocaInst>(Ptr) || isa<PoisonValue>(Ptr) ||
7222 (II && II->getIntrinsicID() == Intrinsic::structured_alloca),
7223 "llvm.lifetime.start/end can only be used on alloca or poison",
7224 &Call);
7225 break;
7226 }
7227 case Intrinsic::sponentry: {
7228 const unsigned StackAS = DL.getAllocaAddrSpace();
7229 const Type *RetTy = Call.getFunctionType()->getReturnType();
7230 Check(RetTy->getPointerAddressSpace() == StackAS,
7231 "llvm.sponentry must return a pointer to the stack", &Call);
7232 break;
7233 }
7234 case Intrinsic::write_volatile_register: {
7235 auto *MD = cast<MDNode>(
7236 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata());
7237 Check(MD->getNumOperands() == 1 && isa<MDString>(MD->getOperand(0)),
7238 "llvm.write_volatile_register metadata must be a single MDString",
7239 &Call);
7240 break;
7241 }
7242 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7243 // Verify that the auth key is IA (0) or IB (1), not DA (2) or DB (3)
7244 auto *AuthKey = cast<ConstantInt>(Call.getArgOperand(1));
7245 uint64_t Key = AuthKey->getZExtValue();
7246 Check(Key == 0 || Key == 1,
7247 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7248 &Call);
7249 break;
7250 }
7251 };
7252
7253 // Verify that there aren't any unmediated control transfers between funclets.
7255 Function *F = Call.getParent()->getParent();
7256 if (F->hasPersonalityFn() &&
7257 isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
7258 // Run EH funclet coloring on-demand and cache results for other intrinsic
7259 // calls in this function
7260 if (BlockEHFuncletColors.empty())
7261 BlockEHFuncletColors = colorEHFunclets(*F);
7262
7263 // Check for catch-/cleanup-pad in first funclet block
7264 bool InEHFunclet = false;
7265 BasicBlock *CallBB = Call.getParent();
7266 const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
7267 assert(CV.size() > 0 && "Uncolored block");
7268 for (BasicBlock *ColorFirstBB : CV)
7269 if (auto It = ColorFirstBB->getFirstNonPHIIt();
7270 It != ColorFirstBB->end())
7272 InEHFunclet = true;
7273
7274 // Check for funclet operand bundle
7275 bool HasToken = false;
7276 for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
7278 HasToken = true;
7279
7280 // This would cause silent code truncation in WinEHPrepare
7281 if (InEHFunclet)
7282 Check(HasToken, "Missing funclet token on intrinsic call", &Call);
7283 }
7284 }
7285
7286 // Target-specific intrinsic call checks.
7287 verifyAMDGPUIntrinsicCall(*this, ID, Call);
7288}
7289
7290/// Carefully grab the subprogram from a local scope.
7291///
7292/// This carefully grabs the subprogram from a local scope, avoiding the
7293/// built-in assertions that would typically fire.
7294DISubprogram *Verifier::getSubprogram(Metadata *LocalScope) {
7295 if (hasDIScopeCycle(LocalScope))
7296 return nullptr;
7297
7298 if (!LocalScope)
7299 return nullptr;
7300
7301 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
7302 return SP;
7303
7304 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
7305 return getSubprogram(LB->getRawScope());
7306
7307 // Just return null; broken scope chains are checked elsewhere.
7308 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
7309 return nullptr;
7310}
7311
7312void Verifier::visit(DbgLabelRecord &DLR) {
7314 "invalid #dbg_label intrinsic variable", &DLR, DLR.getRawLabel());
7315
7316 // Ignore broken !dbg attachments; they're checked elsewhere.
7317 if (MDNode *N = DLR.getDebugLoc().getAsMDNode())
7318 if (!isa<DILocation>(N))
7319 return;
7320
7321 BasicBlock *BB = DLR.getParent();
7322 Function *F = BB ? BB->getParent() : nullptr;
7323
7324 // The scopes for variables and !dbg attachments must agree.
7325 DILabel *Label = DLR.getLabel();
7326 DILocation *Loc = DLR.getDebugLoc();
7327 CheckDI(Loc, "#dbg_label record requires a !dbg attachment", &DLR, BB, F);
7328
7329 DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
7330 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7331 if (!LabelSP || !LocSP)
7332 return;
7333
7334 CheckDI(LabelSP == LocSP,
7335 "mismatched subprogram between #dbg_label label and !dbg attachment",
7336 &DLR, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
7337 Loc->getScope()->getSubprogram());
7338}
7339
7340void Verifier::visit(DbgVariableRecord &DVR) {
7341 BasicBlock *BB = DVR.getParent();
7342 Function *F = BB->getParent();
7343
7344 CheckDI(DVR.getType() == DbgVariableRecord::LocationType::Value ||
7345 DVR.getType() == DbgVariableRecord::LocationType::Declare ||
7346 DVR.getType() == DbgVariableRecord::LocationType::DeclareValue ||
7347 DVR.getType() == DbgVariableRecord::LocationType::Assign,
7348 "invalid #dbg record type", &DVR, DVR.getType(), BB, F);
7349
7350 // The location for a DbgVariableRecord must be either a ValueAsMetadata,
7351 // DIArgList, or an empty MDNode (which is a legacy representation for an
7352 // "undef" location).
7353 auto *MD = DVR.getRawLocation();
7354 CheckDI(MD && (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
7355 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands())),
7356 "invalid #dbg record address/value", &DVR, MD, BB, F);
7357 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
7358 visitValueAsMetadata(*VAM, F);
7359 if (DVR.isDbgDeclare()) {
7360 // Allow integers here to support inttoptr salvage.
7361 Type *Ty = VAM->getValue()->getType();
7362 CheckDI(Ty->isPointerTy() || Ty->isIntegerTy(),
7363 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7364 F);
7365 }
7366 } else if (auto *AL = dyn_cast<DIArgList>(MD)) {
7367 visitDIArgList(*AL, F);
7368 }
7369
7371 "invalid #dbg record variable", &DVR, DVR.getRawVariable(), BB, F);
7372 visitMDNode(*DVR.getRawVariable(), AreDebugLocsAllowed::No);
7373
7375 "invalid #dbg record expression", &DVR, DVR.getRawExpression(), BB,
7376 F);
7377 visitMDNode(*DVR.getExpression(), AreDebugLocsAllowed::No);
7378
7379 if (DVR.isDbgAssign()) {
7381 "invalid #dbg_assign DIAssignID", &DVR, DVR.getRawAssignID(), BB,
7382 F);
7383 visitMDNode(*cast<DIAssignID>(DVR.getRawAssignID()),
7384 AreDebugLocsAllowed::No);
7385
7386 const auto *RawAddr = DVR.getRawAddress();
7387 // Similarly to the location above, the address for an assign
7388 // DbgVariableRecord must be a ValueAsMetadata or an empty MDNode, which
7389 // represents an undef address.
7390 CheckDI(
7391 isa<ValueAsMetadata>(RawAddr) ||
7392 (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
7393 "invalid #dbg_assign address", &DVR, DVR.getRawAddress(), BB, F);
7394 if (auto *VAM = dyn_cast<ValueAsMetadata>(RawAddr))
7395 visitValueAsMetadata(*VAM, F);
7396
7398 "invalid #dbg_assign address expression", &DVR,
7399 DVR.getRawAddressExpression(), BB, F);
7400 visitMDNode(*DVR.getAddressExpression(), AreDebugLocsAllowed::No);
7401
7402 // All of the linked instructions should be in the same function as DVR.
7403 for (Instruction *I : at::getAssignmentInsts(&DVR))
7404 CheckDI(DVR.getFunction() == I->getFunction(),
7405 "inst not in same function as #dbg_assign", I, &DVR, BB, F);
7406 }
7407
7408 // This check is redundant with one in visitLocalVariable().
7409 DILocalVariable *Var = DVR.getVariable();
7410 CheckDI(isType(Var->getRawType()), "invalid type ref", Var, Var->getRawType(),
7411 BB, F);
7412
7413 auto *DLNode = DVR.getDebugLoc().getAsMDNode();
7414 CheckDI(isa_and_nonnull<DILocation>(DLNode), "invalid #dbg record DILocation",
7415 &DVR, DLNode, BB, F);
7416 DILocation *Loc = DVR.getDebugLoc();
7417
7418 // The scopes for variables and !dbg attachments must agree.
7419 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
7420 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7421 if (!VarSP || !LocSP)
7422 return; // Broken scope chains are checked elsewhere.
7423
7424 CheckDI(VarSP == LocSP,
7425 "mismatched subprogram between #dbg record variable and DILocation",
7426 &DVR, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
7427 Loc->getScope()->getSubprogram(), BB, F);
7428
7429 verifyFnArgs(DVR);
7430}
7431
7432void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7433 switch (VPI.getIntrinsicID()) {
7434 case Intrinsic::experimental_vp_splice: {
7435 VectorType *VecTy = cast<VectorType>(VPI.getType());
7436 int64_t Idx = cast<ConstantInt>(VPI.getArgOperand(2))->getSExtValue();
7437 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7438 if (VPI.getParent() && VPI.getParent()->getParent()) {
7439 AttributeList Attrs = VPI.getParent()->getParent()->getAttributes();
7440 if (Attrs.hasFnAttr(Attribute::VScaleRange))
7441 KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
7442 }
7443 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7444 (Idx >= 0 && Idx < KnownMinNumElements),
7445 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7446 "known minimum number of elements in the vector. For scalable "
7447 "vectors the minimum number of elements is determined from "
7448 "vscale_range.",
7449 &VPI);
7450 break;
7451 }
7452 }
7453}
7454
7455void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7456 unsigned NumOperands = FPI.getNonMetadataArgCount();
7457 bool HasRoundingMD =
7459
7460 // Add the expected number of metadata operands.
7461 NumOperands += (1 + HasRoundingMD);
7462
7463 // Compare intrinsics carry an extra predicate metadata operand.
7465 NumOperands += 1;
7466 Check((FPI.arg_size() == NumOperands),
7467 "invalid arguments for constrained FP intrinsic", &FPI);
7468
7469 switch (FPI.getIntrinsicID()) {
7470 case Intrinsic::experimental_constrained_fcmp:
7471 case Intrinsic::experimental_constrained_fcmps: {
7472 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
7474 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7475 break;
7476 }
7477
7478 case Intrinsic::experimental_constrained_fptosi:
7479 case Intrinsic::experimental_constrained_fptoui: {
7480 Value *Operand = FPI.getArgOperand(0);
7481 ElementCount SrcEC;
7482 Check(Operand->getType()->isFPOrFPVectorTy(),
7483 "Intrinsic first argument must be floating point", &FPI);
7484 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7485 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7486 }
7487
7488 Operand = &FPI;
7489 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7490 "Intrinsic first argument and result disagree on vector use", &FPI);
7491 Check(Operand->getType()->isIntOrIntVectorTy(),
7492 "Intrinsic result must be an integer", &FPI);
7493 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7494 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7495 "Intrinsic first argument and result vector lengths must be equal",
7496 &FPI);
7497 }
7498 break;
7499 }
7500
7501 case Intrinsic::experimental_constrained_sitofp:
7502 case Intrinsic::experimental_constrained_uitofp: {
7503 Value *Operand = FPI.getArgOperand(0);
7504 ElementCount SrcEC;
7505 Check(Operand->getType()->isIntOrIntVectorTy(),
7506 "Intrinsic first argument must be integer", &FPI);
7507 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7508 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7509 }
7510
7511 Operand = &FPI;
7512 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7513 "Intrinsic first argument and result disagree on vector use", &FPI);
7514 Check(Operand->getType()->isFPOrFPVectorTy(),
7515 "Intrinsic result must be a floating point", &FPI);
7516 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7517 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7518 "Intrinsic first argument and result vector lengths must be equal",
7519 &FPI);
7520 }
7521 break;
7522 }
7523
7524 case Intrinsic::experimental_constrained_fptrunc:
7525 case Intrinsic::experimental_constrained_fpext: {
7526 Value *Operand = FPI.getArgOperand(0);
7527 Type *OperandTy = Operand->getType();
7528 Value *Result = &FPI;
7529 Type *ResultTy = Result->getType();
7530 Check(OperandTy->isFPOrFPVectorTy(),
7531 "Intrinsic first argument must be FP or FP vector", &FPI);
7532 Check(ResultTy->isFPOrFPVectorTy(),
7533 "Intrinsic result must be FP or FP vector", &FPI);
7534 Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
7535 "Intrinsic first argument and result disagree on vector use", &FPI);
7536 if (OperandTy->isVectorTy()) {
7537 Check(cast<VectorType>(OperandTy)->getElementCount() ==
7538 cast<VectorType>(ResultTy)->getElementCount(),
7539 "Intrinsic first argument and result vector lengths must be equal",
7540 &FPI);
7541 }
7542 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7543 Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
7544 "Intrinsic first argument's type must be larger than result type",
7545 &FPI);
7546 } else {
7547 Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
7548 "Intrinsic first argument's type must be smaller than result type",
7549 &FPI);
7550 }
7551 break;
7552 }
7553
7554 default:
7555 break;
7556 }
7557
7558 // If a non-metadata argument is passed in a metadata slot then the
7559 // error will be caught earlier when the incorrect argument doesn't
7560 // match the specification in the intrinsic call table. Thus, no
7561 // argument type check is needed here.
7562
7563 Check(FPI.getExceptionBehavior().has_value(),
7564 "invalid exception behavior argument", &FPI);
7565 if (HasRoundingMD) {
7566 Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
7567 &FPI);
7568 }
7569}
7570
7571void Verifier::verifyFragmentExpression(const DbgVariableRecord &DVR) {
7572 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(DVR.getRawVariable());
7573 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7574
7575 // We don't know whether this intrinsic verified correctly.
7576 if (!V || !E || !E->isValid())
7577 return;
7578
7579 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
7580 auto Fragment = E->getFragmentInfo();
7581 if (!Fragment)
7582 return;
7583
7584 // The frontend helps out GDB by emitting the members of local anonymous
7585 // unions as artificial local variables with shared storage. When SROA splits
7586 // the storage for artificial local variables that are smaller than the entire
7587 // union, the overhang piece will be outside of the allotted space for the
7588 // variable and this check fails.
7589 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
7590 if (V->isArtificial())
7591 return;
7592
7593 verifyFragmentExpression(*V, *Fragment, &DVR);
7594}
7595
7596template <typename ValueOrMetadata>
7597void Verifier::verifyFragmentExpression(const DIVariable &V,
7599 ValueOrMetadata *Desc) {
7600 // If there's no size, the type is broken, but that should be checked
7601 // elsewhere.
7602 auto VarSize = V.getSizeInBits();
7603 if (!VarSize)
7604 return;
7605
7606 unsigned FragSize = Fragment.SizeInBits;
7607 unsigned FragOffset = Fragment.OffsetInBits;
7608 CheckDI(FragSize + FragOffset <= *VarSize,
7609 "fragment is larger than or outside of variable", Desc, &V);
7610 CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
7611}
7612
7613void Verifier::verifyFnArgs(const DbgVariableRecord &DVR) {
7614 // This function does not take the scope of noninlined function arguments into
7615 // account. Don't run it if current function is nodebug, because it may
7616 // contain inlined debug intrinsics.
7617 if (!HasDebugInfo)
7618 return;
7619
7620 // For performance reasons only check non-inlined ones.
7621 if (DVR.getDebugLoc()->getInlinedAt())
7622 return;
7623
7624 DILocalVariable *Var = DVR.getVariable();
7625 CheckDI(Var, "#dbg record without variable");
7626
7627 unsigned ArgNo = Var->getArg();
7628 if (!ArgNo)
7629 return;
7630
7631 // Verify there are no duplicate function argument debug info entries.
7632 // These will cause hard-to-debug assertions in the DWARF backend.
7633 if (DebugFnArgs.size() < ArgNo)
7634 DebugFnArgs.resize(ArgNo, nullptr);
7635
7636 auto *Prev = DebugFnArgs[ArgNo - 1];
7637 DebugFnArgs[ArgNo - 1] = Var;
7638 CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &DVR,
7639 Prev, Var);
7640}
7641
7642void Verifier::verifyNotEntryValue(const DbgVariableRecord &DVR) {
7643 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7644
7645 // We don't know whether this intrinsic verified correctly.
7646 if (!E || !E->isValid())
7647 return;
7648
7650 Value *VarValue = DVR.getVariableLocationOp(0);
7651 if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
7652 return;
7653 // We allow EntryValues for swift async arguments, as they have an
7654 // ABI-guarantee to be turned into a specific register.
7655 if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
7656 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7657 return;
7658 }
7659
7660 CheckDI(!E->isEntryValue(),
7661 "Entry values are only allowed in MIR unless they target a "
7662 "swiftasync Argument",
7663 &DVR);
7664}
7665
7666void Verifier::verifyCompileUnits() {
7667 // When more than one Module is imported into the same context, such as during
7668 // an LTO build before linking the modules, ODR type uniquing may cause types
7669 // to point to a different CU. This check does not make sense in this case.
7670 if (M.getContext().isODRUniquingDebugTypes())
7671 return;
7672 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
7673 SmallPtrSet<const Metadata *, 2> Listed;
7674 if (CUs)
7675 Listed.insert_range(CUs->operands());
7676 for (const auto *CU : CUVisited)
7677 CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
7678 CUVisited.clear();
7679}
7680
7681void Verifier::verifyDeoptimizeCallingConvs() {
7682 if (DeoptimizeDeclarations.empty())
7683 return;
7684
7685 const Function *First = DeoptimizeDeclarations[0];
7686 for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
7687 Check(First->getCallingConv() == F->getCallingConv(),
7688 "All llvm.experimental.deoptimize declarations must have the same "
7689 "calling convention",
7690 First, F);
7691 }
7692}
7693
7694void Verifier::verifyAttachedCallBundle(const CallBase &Call,
7695 const OperandBundleUse &BU) {
7696 FunctionType *FTy = Call.getFunctionType();
7697
7698 Check((FTy->getReturnType()->isPointerTy() ||
7699 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
7700 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7701 "function returning a pointer or a non-returning function that has a "
7702 "void return type",
7703 Call);
7704
7705 Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
7706 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7707 "an argument",
7708 Call);
7709
7710 auto *Fn = cast<Function>(BU.Inputs.front());
7711 Intrinsic::ID IID = Fn->getIntrinsicID();
7712
7713 if (IID) {
7714 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7715 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7716 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7717 "invalid function argument", Call);
7718 } else {
7719 StringRef FnName = Fn->getName();
7720 Check((FnName == "objc_retainAutoreleasedReturnValue" ||
7721 FnName == "objc_claimAutoreleasedReturnValue" ||
7722 FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
7723 "invalid function argument", Call);
7724 }
7725}
7726
7727void Verifier::verifyNoAliasScopeDecl() {
7728 if (NoAliasScopeDecls.empty())
7729 return;
7730
7731 // only a single scope must be declared at a time.
7732 for (auto *II : NoAliasScopeDecls) {
7733 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7734 "Not a llvm.experimental.noalias.scope.decl ?");
7735 const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
7737 Check(ScopeListMV != nullptr,
7738 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7739 "argument",
7740 II);
7741
7742 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
7743 Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
7744 Check(ScopeListMD->getNumOperands() == 1,
7745 "!id.scope.list must point to a list with a single scope", II);
7746 visitAliasScopeListMetadata(ScopeListMD);
7747 }
7748
7749 // Only check the domination rule when requested. Once all passes have been
7750 // adapted this option can go away.
7752 return;
7753
7754 // Now sort the intrinsics based on the scope MDNode so that declarations of
7755 // the same scopes are next to each other.
7756 auto GetScope = [](IntrinsicInst *II) {
7757 const auto *ScopeListMV = cast<MetadataAsValue>(
7759 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7760 };
7761
7762 // We are sorting on MDNode pointers here. For valid input IR this is ok.
7763 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
7764 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7765 return GetScope(Lhs) < GetScope(Rhs);
7766 };
7767
7768 llvm::sort(NoAliasScopeDecls, Compare);
7769
7770 // Go over the intrinsics and check that for the same scope, they are not
7771 // dominating each other.
7772 auto ItCurrent = NoAliasScopeDecls.begin();
7773 while (ItCurrent != NoAliasScopeDecls.end()) {
7774 auto CurScope = GetScope(*ItCurrent);
7775 auto ItNext = ItCurrent;
7776 do {
7777 ++ItNext;
7778 } while (ItNext != NoAliasScopeDecls.end() &&
7779 GetScope(*ItNext) == CurScope);
7780
7781 // [ItCurrent, ItNext) represents the declarations for the same scope.
7782 // Ensure they are not dominating each other.. but only if it is not too
7783 // expensive.
7784 if (ItNext - ItCurrent < 32)
7785 for (auto *I : llvm::make_range(ItCurrent, ItNext))
7786 for (auto *J : llvm::make_range(ItCurrent, ItNext))
7787 if (I != J)
7788 Check(!DT.dominates(I, J),
7789 "llvm.experimental.noalias.scope.decl dominates another one "
7790 "with the same scope",
7791 I);
7792 ItCurrent = ItNext;
7793 }
7794}
7795
7796//===----------------------------------------------------------------------===//
7797// Implement the public interfaces to this file...
7798//===----------------------------------------------------------------------===//
7799
7801 Function &F = const_cast<Function &>(f);
7802
7803 // Don't use a raw_null_ostream. Printing IR is expensive.
7804 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
7805
7806 // Note that this function's return value is inverted from what you would
7807 // expect of a function called "verify".
7808 return !V.verify(F);
7809}
7810
7812 bool *BrokenDebugInfo) {
7813 // Don't use a raw_null_ostream. Printing IR is expensive.
7814 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
7815
7816 bool Broken = false;
7817 for (const Function &F : M)
7818 Broken |= !V.verify(F);
7819
7820 Broken |= !V.verify();
7821 if (BrokenDebugInfo)
7822 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7823 // Note that this function's return value is inverted from what you would
7824 // expect of a function called "verify".
7825 return Broken;
7826}
7827
7828namespace {
7829
7830struct VerifierLegacyPass : public FunctionPass {
7831 static char ID;
7832
7833 std::unique_ptr<Verifier> V;
7834 bool FatalErrors = true;
7835
7836 VerifierLegacyPass() : FunctionPass(ID) {}
7837 explicit VerifierLegacyPass(bool FatalErrors)
7838 : FunctionPass(ID), FatalErrors(FatalErrors) {}
7839
7840 bool doInitialization(Module &M) override {
7841 V = std::make_unique<Verifier>(
7842 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
7843 return false;
7844 }
7845
7846 bool runOnFunction(Function &F) override {
7847 if (!V->verify(F) && FatalErrors) {
7848 errs() << "in function " << F.getName() << '\n';
7849 report_fatal_error("Broken function found, compilation aborted!");
7850 }
7851 return false;
7852 }
7853
7854 bool doFinalization(Module &M) override {
7855 bool HasErrors = false;
7856 for (Function &F : M)
7857 if (F.isDeclaration())
7858 HasErrors |= !V->verify(F);
7859
7860 HasErrors |= !V->verify();
7861 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
7862 report_fatal_error("Broken module found, compilation aborted!");
7863 return false;
7864 }
7865
7866 void getAnalysisUsage(AnalysisUsage &AU) const override {
7867 AU.setPreservesAll();
7868 }
7869};
7870
7871} // end anonymous namespace
7872
7873/// Helper to issue failure from the TBAA verification
7874template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
7875 if (Diagnostic)
7876 return Diagnostic->CheckFailed(Args...);
7877}
7878
7879#define CheckTBAA(C, ...) \
7880 do { \
7881 if (!(C)) { \
7882 CheckFailed(__VA_ARGS__); \
7883 return false; \
7884 } \
7885 } while (false)
7886
7887/// Verify that \p BaseNode can be used as the "base type" in the struct-path
7888/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
7889/// struct-type node describing an aggregate data structure (like a struct).
7890TBAAVerifier::TBAABaseNodeSummary
7891TBAAVerifier::verifyTBAABaseNode(const Instruction *I, const MDNode *BaseNode,
7892 bool IsNewFormat) {
7893 if (BaseNode->getNumOperands() < 2) {
7894 CheckFailed("Base nodes must have at least two operands", I, BaseNode);
7895 return {true, ~0u};
7896 }
7897
7898 auto Itr = TBAABaseNodes.find(BaseNode);
7899 if (Itr != TBAABaseNodes.end())
7900 return Itr->second;
7901
7902 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
7903 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7904 (void)InsertResult;
7905 assert(InsertResult.second && "We just checked!");
7906 return Result;
7907}
7908
7909TBAAVerifier::TBAABaseNodeSummary
7910TBAAVerifier::verifyTBAABaseNodeImpl(const Instruction *I,
7911 const MDNode *BaseNode, bool IsNewFormat) {
7912 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
7913
7914 if (BaseNode->getNumOperands() == 2) {
7915 // Scalar nodes can only be accessed at offset 0.
7916 return isValidScalarTBAANode(BaseNode)
7917 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
7918 : InvalidNode;
7919 }
7920
7921 if (IsNewFormat) {
7922 if (BaseNode->getNumOperands() % 3 != 0) {
7923 CheckFailed("Access tag nodes must have the number of operands that is a "
7924 "multiple of 3!", BaseNode);
7925 return InvalidNode;
7926 }
7927 } else {
7928 if (BaseNode->getNumOperands() % 2 != 1) {
7929 CheckFailed("Struct tag nodes must have an odd number of operands!",
7930 BaseNode);
7931 return InvalidNode;
7932 }
7933 }
7934
7935 // Check the type size field.
7936 if (IsNewFormat) {
7937 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
7938 BaseNode->getOperand(1));
7939 if (!TypeSizeNode) {
7940 CheckFailed("Type size nodes must be constants!", I, BaseNode);
7941 return InvalidNode;
7942 }
7943 }
7944
7945 // Check the type name field. In the new format it can be anything.
7946 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
7947 CheckFailed("Struct tag nodes have a string as their first operand",
7948 BaseNode);
7949 return InvalidNode;
7950 }
7951
7952 bool Failed = false;
7953
7954 std::optional<APInt> PrevOffset;
7955 unsigned BitWidth = ~0u;
7956
7957 // We've already checked that BaseNode is not a degenerate root node with one
7958 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
7959 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7960 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7961 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
7962 Idx += NumOpsPerField) {
7963 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
7964 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
7965 if (!isa<MDNode>(FieldTy)) {
7966 CheckFailed("Incorrect field entry in struct type node!", I, BaseNode);
7967 Failed = true;
7968 continue;
7969 }
7970
7971 auto *OffsetEntryCI =
7973 if (!OffsetEntryCI) {
7974 CheckFailed("Offset entries must be constants!", I, BaseNode);
7975 Failed = true;
7976 continue;
7977 }
7978
7979 if (BitWidth == ~0u)
7980 BitWidth = OffsetEntryCI->getBitWidth();
7981
7982 if (OffsetEntryCI->getBitWidth() != BitWidth) {
7983 CheckFailed(
7984 "Bitwidth between the offsets and struct type entries must match", I,
7985 BaseNode);
7986 Failed = true;
7987 continue;
7988 }
7989
7990 // NB! As far as I can tell, we generate a non-strictly increasing offset
7991 // sequence only from structs that have zero size bit fields. When
7992 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
7993 // pick the field lexically the latest in struct type metadata node. This
7994 // mirrors the actual behavior of the alias analysis implementation.
7995 bool IsAscending =
7996 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7997
7998 if (!IsAscending) {
7999 CheckFailed("Offsets must be increasing!", I, BaseNode);
8000 Failed = true;
8001 }
8002
8003 PrevOffset = OffsetEntryCI->getValue();
8004
8005 if (IsNewFormat) {
8006 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8007 BaseNode->getOperand(Idx + 2));
8008 if (!MemberSizeNode) {
8009 CheckFailed("Member size entries must be constants!", I, BaseNode);
8010 Failed = true;
8011 continue;
8012 }
8013 }
8014 }
8015
8016 return Failed ? InvalidNode
8017 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
8018}
8019
8020static bool IsRootTBAANode(const MDNode *MD) {
8021 return MD->getNumOperands() < 2;
8022}
8023
8024static bool IsScalarTBAANodeImpl(const MDNode *MD,
8026 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
8027 return false;
8028
8029 if (!isa<MDString>(MD->getOperand(0)))
8030 return false;
8031
8032 if (MD->getNumOperands() == 3) {
8034 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
8035 return false;
8036 }
8037
8038 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8039 return Parent && Visited.insert(Parent).second &&
8040 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
8041}
8042
8043bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
8044 auto ResultIt = TBAAScalarNodes.find(MD);
8045 if (ResultIt != TBAAScalarNodes.end())
8046 return ResultIt->second;
8047
8048 SmallPtrSet<const MDNode *, 4> Visited;
8049 bool Result = IsScalarTBAANodeImpl(MD, Visited);
8050 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
8051 (void)InsertResult;
8052 assert(InsertResult.second && "Just checked!");
8053
8054 return Result;
8055}
8056
8057/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
8058/// Offset in place to be the offset within the field node returned.
8059///
8060/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
8061MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(const Instruction *I,
8062 const MDNode *BaseNode,
8063 APInt &Offset,
8064 bool IsNewFormat) {
8065 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
8066
8067 // Scalar nodes have only one possible "field" -- their parent in the access
8068 // hierarchy. Offset must be zero at this point, but our caller is supposed
8069 // to check that.
8070 if (BaseNode->getNumOperands() == 2)
8071 return cast<MDNode>(BaseNode->getOperand(1));
8072
8073 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8074 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8075 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8076 Idx += NumOpsPerField) {
8077 auto *OffsetEntryCI =
8078 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
8079 if (OffsetEntryCI->getValue().ugt(Offset)) {
8080 if (Idx == FirstFieldOpNo) {
8081 CheckFailed("Could not find TBAA parent in struct type node", I,
8082 BaseNode, &Offset);
8083 return nullptr;
8084 }
8085
8086 unsigned PrevIdx = Idx - NumOpsPerField;
8087 auto *PrevOffsetEntryCI =
8088 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
8089 Offset -= PrevOffsetEntryCI->getValue();
8090 return cast<MDNode>(BaseNode->getOperand(PrevIdx));
8091 }
8092 }
8093
8094 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
8095 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
8096 BaseNode->getOperand(LastIdx + 1));
8097 Offset -= LastOffsetEntryCI->getValue();
8098 return cast<MDNode>(BaseNode->getOperand(LastIdx));
8099}
8100
8102 if (!Type || Type->getNumOperands() < 3)
8103 return false;
8104
8105 // In the new format type nodes shall have a reference to the parent type as
8106 // its first operand.
8107 return isa_and_nonnull<MDNode>(Type->getOperand(0));
8108}
8109
8111 CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands", I,
8112 MD);
8113
8114 if (I)
8118 "This instruction shall not have a TBAA access tag!", I);
8119
8120 bool IsStructPathTBAA =
8121 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
8122
8123 CheckTBAA(IsStructPathTBAA,
8124 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8125 I);
8126
8127 auto *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
8128 auto *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8129
8130 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
8131
8132 if (IsNewFormat) {
8133 CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
8134 "Access tag metadata must have either 4 or 5 operands", I, MD);
8135 } else {
8136 CheckTBAA(MD->getNumOperands() < 5,
8137 "Struct tag metadata must have either 3 or 4 operands", I, MD);
8138 }
8139
8140 // Check the access size field.
8141 if (IsNewFormat) {
8142 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8143 MD->getOperand(3));
8144 CheckTBAA(AccessSizeNode, "Access size field must be a constant", I, MD);
8145 }
8146
8147 // Check the immutability flag.
8148 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8149 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
8150 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
8151 MD->getOperand(ImmutabilityFlagOpNo));
8152 CheckTBAA(IsImmutableCI,
8153 "Immutability tag on struct tag metadata must be a constant", I,
8154 MD);
8155 CheckTBAA(
8156 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8157 "Immutability part of the struct tag metadata must be either 0 or 1", I,
8158 MD);
8159 }
8160
8161 CheckTBAA(BaseNode && AccessType,
8162 "Malformed struct tag metadata: base and access-type "
8163 "should be non-null and point to Metadata nodes",
8164 I, MD, BaseNode, AccessType);
8165
8166 if (!IsNewFormat) {
8167 CheckTBAA(isValidScalarTBAANode(AccessType),
8168 "Access type node must be a valid scalar type", I, MD,
8169 AccessType);
8170 }
8171
8173 CheckTBAA(OffsetCI, "Offset must be constant integer", I, MD);
8174
8175 APInt Offset = OffsetCI->getValue();
8176 bool SeenAccessTypeInPath = false;
8177
8178 SmallPtrSet<MDNode *, 4> StructPath;
8179
8180 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
8181 BaseNode =
8182 getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, IsNewFormat)) {
8183 if (!StructPath.insert(BaseNode).second) {
8184 CheckFailed("Cycle detected in struct path", I, MD);
8185 return false;
8186 }
8187
8188 bool Invalid;
8189 unsigned BaseNodeBitWidth;
8190 std::tie(Invalid, BaseNodeBitWidth) =
8191 verifyTBAABaseNode(I, BaseNode, IsNewFormat);
8192
8193 // If the base node is invalid in itself, then we've already printed all the
8194 // errors we wanted to print.
8195 if (Invalid)
8196 return false;
8197
8198 SeenAccessTypeInPath |= BaseNode == AccessType;
8199
8200 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8201 CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access", I,
8202 MD, &Offset);
8203
8204 CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
8205 (BaseNodeBitWidth == 0 && Offset == 0) ||
8206 (IsNewFormat && BaseNodeBitWidth == ~0u),
8207 "Access bit-width not the same as description bit-width", I, MD,
8208 BaseNodeBitWidth, Offset.getBitWidth());
8209
8210 if (IsNewFormat && SeenAccessTypeInPath)
8211 break;
8212 }
8213
8214 CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", I,
8215 MD);
8216 return true;
8217}
8218
8219char VerifierLegacyPass::ID = 0;
8220INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
8221
8223 return new VerifierLegacyPass(FatalErrors);
8224}
8225
8226AnalysisKey VerifierAnalysis::Key;
8233
8238
8240 auto Res = AM.getResult<VerifierAnalysis>(M);
8241 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8242 report_fatal_error("Broken module found, compilation aborted!");
8243
8244 return PreservedAnalyses::all();
8245}
8246
8248 auto res = AM.getResult<VerifierAnalysis>(F);
8249 if (res.IRBroken && FatalErrors)
8250 report_fatal_error("Broken function found, compilation aborted!");
8251
8252 return PreservedAnalyses::all();
8253}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
@ RetAttr
@ FnAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
#define Check(C,...)
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
Definition Verifier.cpp:524
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
Definition Verifier.cpp:565
static const Metadata * getRawDIScopeParent(const Metadata *S)
Parent scope operand of S, or null if S has no parent (a DIFile, DICompileUnit, or non-scope).
Definition Verifier.cpp:966
static bool isDINode(const Metadata *MD)
static bool isSupportedCallBrIntrinsic(Intrinsic::ID ID)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
#define CheckTBAA(C,...)
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
Definition APFloat.cpp:6127
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
Definition APFloat.cpp:6110
bool isFiniteNonZero() const
Definition APFloat.h:1593
bool isNegative() const
Definition APFloat.h:1583
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
Class for arbitrary precision integers.
Definition APInt.h:78
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:414
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition APInt.h:396
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
Definition BasicBlock.h:469
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
auto operand_bundles() const
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
Definition InstrTypes.h:845
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
Value * getCondition() const
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1264
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
Definition Constants.h:1251
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1254
Constant * getDeactivationSymbol() const
Definition Constants.h:1273
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1257
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static LLVM_ABI const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for types.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.cpp:76
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool empty() const
Definition DenseMap.h:171
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This instruction extracts a single (scalar) element from a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:890
const Function & getFunction() const
Definition Function.h:167
const std::string & getGC() const
Definition Function.cpp:820
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:759
static bool isValidLinkage(LinkageTypes L)
Definition GlobalIFunc.h:86
const Constant * getResolver() const
Definition GlobalIFunc.h:73
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
bool hasComdat() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool isElementwise() const
Return true if this is an elementwise atomic load.
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
bool isTemporary() const
Definition Metadata.h:1253
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
bool isDistinct() const
Definition Metadata.h:1252
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1249
LLVMContext & getContext() const
Definition Metadata.h:1233
bool equalsStr(StringRef Str) const
Definition Metadata.h:913
Metadata * get() const
Definition Metadata.h:920
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:633
static LLVM_ABI bool isTagMD(const Metadata *MD)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:119
Metadata * getMetadata() const
Definition Metadata.h:202
Root of the metadata hierarchy.
Definition Metadata.h:64
unsigned getMetadataID() const
Definition Metadata.h:104
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1851
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
Verify that the TBAA Metadatas are valid.
Definition Verifier.h:40
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
unsigned size() const
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
Definition Type.cpp:74
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
Definition Type.cpp:90
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1138
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Definition Type.cpp:153
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getValue() const
Definition Metadata.h:499
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > materialized_users()
Definition Value.h:420
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:717
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:828
iterator_range< user_iterator > users()
Definition Value.h:426
bool materialized_use_empty() const
Definition Value.h:351
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319