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