LLVM 20.0.0git
SPIRVAsmPrinter.cpp
Go to the documentation of this file.
1//===-- SPIRVAsmPrinter.cpp - SPIR-V LLVM assembly writer ------*- C++ -*--===//
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 contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to the SPIR-V assembly language.
11//
12//===----------------------------------------------------------------------===//
13
15#include "SPIRV.h"
16#include "SPIRVInstrInfo.h"
17#include "SPIRVMCInstLower.h"
18#include "SPIRVModuleAnalysis.h"
19#include "SPIRVSubtarget.h"
20#include "SPIRVTargetMachine.h"
21#include "SPIRVUtils.h"
23#include "llvm/ADT/DenseMap.h"
31#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCAssembler.h"
33#include "llvm/MC/MCInst.h"
36#include "llvm/MC/MCStreamer.h"
37#include "llvm/MC/MCSymbol.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "asm-printer"
44
45namespace {
46class SPIRVAsmPrinter : public AsmPrinter {
47 unsigned NLabels = 0;
49
50public:
51 explicit SPIRVAsmPrinter(TargetMachine &TM,
52 std::unique_ptr<MCStreamer> Streamer)
53 : AsmPrinter(TM, std::move(Streamer)), ST(nullptr), TII(nullptr) {}
54 bool ModuleSectionsEmitted;
55 const SPIRVSubtarget *ST;
56 const SPIRVInstrInfo *TII;
57
58 StringRef getPassName() const override { return "SPIRV Assembly Printer"; }
59 void printOperand(const MachineInstr *MI, int OpNum, raw_ostream &O);
60 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
61 const char *ExtraCode, raw_ostream &O) override;
62
63 void outputMCInst(MCInst &Inst);
64 void outputInstruction(const MachineInstr *MI);
65 void outputModuleSection(SPIRV::ModuleSectionType MSType);
66 void outputGlobalRequirements();
67 void outputEntryPoints();
68 void outputDebugSourceAndStrings(const Module &M);
69 void outputOpExtInstImports(const Module &M);
70 void outputOpMemoryModel();
71 void outputOpFunctionEnd();
72 void outputExtFuncDecls();
73 void outputExecutionModeFromMDNode(Register Reg, MDNode *Node,
74 SPIRV::ExecutionMode::ExecutionMode EM,
75 unsigned ExpectMDOps, int64_t DefVal);
76 void outputExecutionModeFromNumthreadsAttribute(
77 const Register &Reg, const Attribute &Attr,
78 SPIRV::ExecutionMode::ExecutionMode EM);
79 void outputExecutionMode(const Module &M);
80 void outputAnnotations(const Module &M);
81 void outputModuleSections();
82 bool isHidden() {
83 return MF->getFunction()
84 .getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME)
85 .isValid();
86 }
87
88 void emitInstruction(const MachineInstr *MI) override;
89 void emitFunctionEntryLabel() override {}
90 void emitFunctionHeader() override;
91 void emitFunctionBodyStart() override {}
92 void emitFunctionBodyEnd() override;
93 void emitBasicBlockStart(const MachineBasicBlock &MBB) override;
94 void emitBasicBlockEnd(const MachineBasicBlock &MBB) override {}
95 void emitGlobalVariable(const GlobalVariable *GV) override {}
96 void emitOpLabel(const MachineBasicBlock &MBB);
97 void emitEndOfAsmFile(Module &M) override;
98 bool doInitialization(Module &M) override;
99
100 void getAnalysisUsage(AnalysisUsage &AU) const override;
102};
103} // namespace
104
105void SPIRVAsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
109}
110
111// If the module has no functions, we need output global info anyway.
112void SPIRVAsmPrinter::emitEndOfAsmFile(Module &M) {
113 if (ModuleSectionsEmitted == false) {
114 outputModuleSections();
115 ModuleSectionsEmitted = true;
116 }
117
118 ST = static_cast<const SPIRVTargetMachine &>(TM).getSubtargetImpl();
119 VersionTuple SPIRVVersion = ST->getSPIRVVersion();
120 uint32_t Major = SPIRVVersion.getMajor();
121 uint32_t Minor = SPIRVVersion.getMinor().value_or(0);
122 // Bound is an approximation that accounts for the maximum used register
123 // number and number of generated OpLabels
124 unsigned Bound = 2 * (ST->getBound() + 1) + NLabels;
125 if (MCAssembler *Asm = OutStreamer->getAssemblerPtr())
126 static_cast<SPIRVObjectWriter &>(Asm->getWriter())
127 .setBuildVersion(Major, Minor, Bound);
128}
129
130void SPIRVAsmPrinter::emitFunctionHeader() {
131 if (ModuleSectionsEmitted == false) {
132 outputModuleSections();
133 ModuleSectionsEmitted = true;
134 }
135 // Get the subtarget from the current MachineFunction.
136 ST = &MF->getSubtarget<SPIRVSubtarget>();
137 TII = ST->getInstrInfo();
138 const Function &F = MF->getFunction();
139
140 if (isVerbose() && !isHidden()) {
141 OutStreamer->getCommentOS()
142 << "-- Begin function "
143 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
144 }
145
146 auto Section = getObjFileLowering().SectionForGlobal(&F, TM);
147 MF->setSection(Section);
148}
149
150void SPIRVAsmPrinter::outputOpFunctionEnd() {
151 MCInst FunctionEndInst;
152 FunctionEndInst.setOpcode(SPIRV::OpFunctionEnd);
153 outputMCInst(FunctionEndInst);
154}
155
156void SPIRVAsmPrinter::emitFunctionBodyEnd() {
157 if (!isHidden())
158 outputOpFunctionEnd();
159}
160
161void SPIRVAsmPrinter::emitOpLabel(const MachineBasicBlock &MBB) {
162 // Do not emit anything if it's an internal service function.
163 if (isHidden())
164 return;
165
166 MCInst LabelInst;
167 LabelInst.setOpcode(SPIRV::OpLabel);
168 LabelInst.addOperand(MCOperand::createReg(MAI->getOrCreateMBBRegister(MBB)));
169 outputMCInst(LabelInst);
170 ++NLabels;
171 LabeledMBB.insert(&MBB);
172}
173
174void SPIRVAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
175 // Do not emit anything if it's an internal service function.
176 if (MBB.empty())
177 return;
178
179 // If it's the first MBB in MF, it has OpFunction and OpFunctionParameter, so
180 // OpLabel should be output after them.
181 if (MBB.getNumber() == MF->front().getNumber()) {
182 for (const MachineInstr &MI : MBB)
183 if (MI.getOpcode() == SPIRV::OpFunction)
184 return;
185 // TODO: this case should be checked by the verifier.
186 report_fatal_error("OpFunction is expected in the front MBB of MF");
187 }
188 emitOpLabel(MBB);
189}
190
191void SPIRVAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
192 raw_ostream &O) {
193 const MachineOperand &MO = MI->getOperand(OpNum);
194
195 switch (MO.getType()) {
198 break;
199
201 O << MO.getImm();
202 break;
203
205 O << MO.getFPImm();
206 break;
207
209 O << *MO.getMBB()->getSymbol();
210 break;
211
213 O << *getSymbol(MO.getGlobal());
214 break;
215
217 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
218 O << BA->getName();
219 break;
220 }
221
223 O << *GetExternalSymbolSymbol(MO.getSymbolName());
224 break;
225
228 default:
229 llvm_unreachable("<unknown operand type>");
230 }
231}
232
233bool SPIRVAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
234 const char *ExtraCode, raw_ostream &O) {
235 if (ExtraCode && ExtraCode[0])
236 return true; // Invalid instruction - SPIR-V does not have special modifiers
237
238 printOperand(MI, OpNo, O);
239 return false;
240}
241
243 const SPIRVInstrInfo *TII) {
244 return TII->isHeaderInstr(*MI) || MI->getOpcode() == SPIRV::OpFunction ||
245 MI->getOpcode() == SPIRV::OpFunctionParameter;
246}
247
248void SPIRVAsmPrinter::outputMCInst(MCInst &Inst) {
249 OutStreamer->emitInstruction(Inst, *OutContext.getSubtargetInfo());
250}
251
252void SPIRVAsmPrinter::outputInstruction(const MachineInstr *MI) {
253 SPIRVMCInstLower MCInstLowering;
254 MCInst TmpInst;
255 MCInstLowering.lower(MI, TmpInst, MAI);
256 outputMCInst(TmpInst);
257}
258
259void SPIRVAsmPrinter::emitInstruction(const MachineInstr *MI) {
260 SPIRV_MC::verifyInstructionPredicates(MI->getOpcode(),
261 getSubtargetInfo().getFeatureBits());
262
263 if (!MAI->getSkipEmission(MI))
264 outputInstruction(MI);
265
266 // Output OpLabel after OpFunction and OpFunctionParameter in the first MBB.
267 const MachineInstr *NextMI = MI->getNextNode();
268 if (!LabeledMBB.contains(MI->getParent()) && isFuncOrHeaderInstr(MI, TII) &&
269 (!NextMI || !isFuncOrHeaderInstr(NextMI, TII))) {
270 assert(MI->getParent()->getNumber() == MF->front().getNumber() &&
271 "OpFunction is not in the front MBB of MF");
272 emitOpLabel(*MI->getParent());
273 }
274}
275
276void SPIRVAsmPrinter::outputModuleSection(SPIRV::ModuleSectionType MSType) {
277 for (MachineInstr *MI : MAI->getMSInstrs(MSType))
278 outputInstruction(MI);
279}
280
281void SPIRVAsmPrinter::outputDebugSourceAndStrings(const Module &M) {
282 // Output OpSourceExtensions.
283 for (auto &Str : MAI->SrcExt) {
284 MCInst Inst;
285 Inst.setOpcode(SPIRV::OpSourceExtension);
286 addStringImm(Str.first(), Inst);
287 outputMCInst(Inst);
288 }
289 // Output OpString.
290 outputModuleSection(SPIRV::MB_DebugStrings);
291 // Output OpSource.
292 MCInst Inst;
293 Inst.setOpcode(SPIRV::OpSource);
294 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(MAI->SrcLang)));
295 Inst.addOperand(
296 MCOperand::createImm(static_cast<unsigned>(MAI->SrcLangVersion)));
297 outputMCInst(Inst);
298}
299
300void SPIRVAsmPrinter::outputOpExtInstImports(const Module &M) {
301 for (auto &CU : MAI->ExtInstSetMap) {
302 unsigned Set = CU.first;
303 Register Reg = CU.second;
304 MCInst Inst;
305 Inst.setOpcode(SPIRV::OpExtInstImport);
308 static_cast<SPIRV::InstructionSet::InstructionSet>(Set)),
309 Inst);
310 outputMCInst(Inst);
311 }
312}
313
314void SPIRVAsmPrinter::outputOpMemoryModel() {
315 MCInst Inst;
316 Inst.setOpcode(SPIRV::OpMemoryModel);
317 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(MAI->Addr)));
318 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(MAI->Mem)));
319 outputMCInst(Inst);
320}
321
322// Before the OpEntryPoints' output, we need to add the entry point's
323// interfaces. The interface is a list of IDs of global OpVariable instructions.
324// These declare the set of global variables from a module that form
325// the interface of this entry point.
326void SPIRVAsmPrinter::outputEntryPoints() {
327 // Find all OpVariable IDs with required StorageClass.
328 DenseSet<Register> InterfaceIDs;
329 for (MachineInstr *MI : MAI->GlobalVarList) {
330 assert(MI->getOpcode() == SPIRV::OpVariable);
331 auto SC = static_cast<SPIRV::StorageClass::StorageClass>(
332 MI->getOperand(2).getImm());
333 // Before version 1.4, the interface's storage classes are limited to
334 // the Input and Output storage classes. Starting with version 1.4,
335 // the interface's storage classes are all storage classes used in
336 // declaring all global variables referenced by the entry point call tree.
337 if (ST->isAtLeastSPIRVVer(VersionTuple(1, 4)) ||
338 SC == SPIRV::StorageClass::Input || SC == SPIRV::StorageClass::Output) {
339 MachineFunction *MF = MI->getMF();
340 Register Reg = MAI->getRegisterAlias(MF, MI->getOperand(0).getReg());
341 InterfaceIDs.insert(Reg);
342 }
343 }
344
345 // Output OpEntryPoints adding interface args to all of them.
346 for (MachineInstr *MI : MAI->getMSInstrs(SPIRV::MB_EntryPoints)) {
347 SPIRVMCInstLower MCInstLowering;
348 MCInst TmpInst;
349 MCInstLowering.lower(MI, TmpInst, MAI);
350 for (Register Reg : InterfaceIDs) {
351 assert(Reg.isValid());
352 TmpInst.addOperand(MCOperand::createReg(Reg));
353 }
354 outputMCInst(TmpInst);
355 }
356}
357
358// Create global OpCapability instructions for the required capabilities.
359void SPIRVAsmPrinter::outputGlobalRequirements() {
360 // Abort here if not all requirements can be satisfied.
361 MAI->Reqs.checkSatisfiable(*ST);
362
363 for (const auto &Cap : MAI->Reqs.getMinimalCapabilities()) {
364 MCInst Inst;
365 Inst.setOpcode(SPIRV::OpCapability);
367 outputMCInst(Inst);
368 }
369
370 // Generate the final OpExtensions with strings instead of enums.
371 for (const auto &Ext : MAI->Reqs.getExtensions()) {
372 MCInst Inst;
373 Inst.setOpcode(SPIRV::OpExtension);
375 SPIRV::OperandCategory::ExtensionOperand, Ext),
376 Inst);
377 outputMCInst(Inst);
378 }
379 // TODO add a pseudo instr for version number.
380}
381
382void SPIRVAsmPrinter::outputExtFuncDecls() {
383 // Insert OpFunctionEnd after each declaration.
385 I = MAI->getMSInstrs(SPIRV::MB_ExtFuncDecls).begin(),
386 E = MAI->getMSInstrs(SPIRV::MB_ExtFuncDecls).end();
387 for (; I != E; ++I) {
388 outputInstruction(*I);
389 if ((I + 1) == E || (*(I + 1))->getOpcode() == SPIRV::OpFunction)
390 outputOpFunctionEnd();
391 }
392}
393
394// Encode LLVM type by SPIR-V execution mode VecTypeHint.
395static unsigned encodeVecTypeHint(Type *Ty) {
396 if (Ty->isHalfTy())
397 return 4;
398 if (Ty->isFloatTy())
399 return 5;
400 if (Ty->isDoubleTy())
401 return 6;
402 if (IntegerType *IntTy = dyn_cast<IntegerType>(Ty)) {
403 switch (IntTy->getIntegerBitWidth()) {
404 case 8:
405 return 0;
406 case 16:
407 return 1;
408 case 32:
409 return 2;
410 case 64:
411 return 3;
412 default:
413 llvm_unreachable("invalid integer type");
414 }
415 }
416 if (FixedVectorType *VecTy = dyn_cast<FixedVectorType>(Ty)) {
417 Type *EleTy = VecTy->getElementType();
418 unsigned Size = VecTy->getNumElements();
419 return Size << 16 | encodeVecTypeHint(EleTy);
420 }
421 llvm_unreachable("invalid type");
422}
423
424static void addOpsFromMDNode(MDNode *MDN, MCInst &Inst,
426 for (const MDOperand &MDOp : MDN->operands()) {
427 if (auto *CMeta = dyn_cast<ConstantAsMetadata>(MDOp)) {
428 Constant *C = CMeta->getValue();
429 if (ConstantInt *Const = dyn_cast<ConstantInt>(C)) {
430 Inst.addOperand(MCOperand::createImm(Const->getZExtValue()));
431 } else if (auto *CE = dyn_cast<Function>(C)) {
432 Register FuncReg = MAI->getFuncReg(CE);
433 assert(FuncReg.isValid());
434 Inst.addOperand(MCOperand::createReg(FuncReg));
435 }
436 }
437 }
438}
439
440void SPIRVAsmPrinter::outputExecutionModeFromMDNode(
441 Register Reg, MDNode *Node, SPIRV::ExecutionMode::ExecutionMode EM,
442 unsigned ExpectMDOps, int64_t DefVal) {
443 MCInst Inst;
444 Inst.setOpcode(SPIRV::OpExecutionMode);
446 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(EM)));
447 addOpsFromMDNode(Node, Inst, MAI);
448 // reqd_work_group_size and work_group_size_hint require 3 operands,
449 // if metadata contains less operands, just add a default value
450 unsigned NodeSz = Node->getNumOperands();
451 if (ExpectMDOps > 0 && NodeSz < ExpectMDOps)
452 for (unsigned i = NodeSz; i < ExpectMDOps; ++i)
453 Inst.addOperand(MCOperand::createImm(DefVal));
454 outputMCInst(Inst);
455}
456
457void SPIRVAsmPrinter::outputExecutionModeFromNumthreadsAttribute(
458 const Register &Reg, const Attribute &Attr,
459 SPIRV::ExecutionMode::ExecutionMode EM) {
460 assert(Attr.isValid() && "Function called with an invalid attribute.");
461
462 MCInst Inst;
463 Inst.setOpcode(SPIRV::OpExecutionMode);
465 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(EM)));
466
467 SmallVector<StringRef> NumThreads;
468 Attr.getValueAsString().split(NumThreads, ',');
469 assert(NumThreads.size() == 3 && "invalid numthreads");
470 for (uint32_t i = 0; i < 3; ++i) {
471 uint32_t V;
472 [[maybe_unused]] bool Result = NumThreads[i].getAsInteger(10, V);
473 assert(!Result && "Failed to parse numthreads");
475 }
476
477 outputMCInst(Inst);
478}
479
480void SPIRVAsmPrinter::outputExecutionMode(const Module &M) {
481 NamedMDNode *Node = M.getNamedMetadata("spirv.ExecutionMode");
482 if (Node) {
483 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
484 MCInst Inst;
485 Inst.setOpcode(SPIRV::OpExecutionMode);
486 addOpsFromMDNode(cast<MDNode>(Node->getOperand(i)), Inst, MAI);
487 outputMCInst(Inst);
488 }
489 }
490 for (auto FI = M.begin(), E = M.end(); FI != E; ++FI) {
491 const Function &F = *FI;
492 // Only operands of OpEntryPoint instructions are allowed to be
493 // <Entry Point> operands of OpExecutionMode
494 if (F.isDeclaration() || !isEntryPoint(F))
495 continue;
496 Register FReg = MAI->getFuncReg(&F);
497 assert(FReg.isValid());
498 if (MDNode *Node = F.getMetadata("reqd_work_group_size"))
499 outputExecutionModeFromMDNode(FReg, Node, SPIRV::ExecutionMode::LocalSize,
500 3, 1);
501 if (Attribute Attr = F.getFnAttribute("hlsl.numthreads"); Attr.isValid())
502 outputExecutionModeFromNumthreadsAttribute(
503 FReg, Attr, SPIRV::ExecutionMode::LocalSize);
504 if (MDNode *Node = F.getMetadata("work_group_size_hint"))
505 outputExecutionModeFromMDNode(FReg, Node,
506 SPIRV::ExecutionMode::LocalSizeHint, 3, 1);
507 if (MDNode *Node = F.getMetadata("intel_reqd_sub_group_size"))
508 outputExecutionModeFromMDNode(FReg, Node,
509 SPIRV::ExecutionMode::SubgroupSize, 0, 0);
510 if (MDNode *Node = F.getMetadata("vec_type_hint")) {
511 MCInst Inst;
512 Inst.setOpcode(SPIRV::OpExecutionMode);
514 unsigned EM = static_cast<unsigned>(SPIRV::ExecutionMode::VecTypeHint);
516 unsigned TypeCode = encodeVecTypeHint(getMDOperandAsType(Node, 0));
517 Inst.addOperand(MCOperand::createImm(TypeCode));
518 outputMCInst(Inst);
519 }
520 if (ST->isOpenCLEnv() && !M.getNamedMetadata("spirv.ExecutionMode") &&
521 !M.getNamedMetadata("opencl.enable.FP_CONTRACT")) {
522 MCInst Inst;
523 Inst.setOpcode(SPIRV::OpExecutionMode);
525 unsigned EM = static_cast<unsigned>(SPIRV::ExecutionMode::ContractionOff);
527 outputMCInst(Inst);
528 }
529 }
530}
531
532void SPIRVAsmPrinter::outputAnnotations(const Module &M) {
533 outputModuleSection(SPIRV::MB_Annotations);
534 // Process llvm.global.annotations special global variable.
535 for (auto F = M.global_begin(), E = M.global_end(); F != E; ++F) {
536 if ((*F).getName() != "llvm.global.annotations")
537 continue;
538 const GlobalVariable *V = &(*F);
539 const ConstantArray *CA = cast<ConstantArray>(V->getOperand(0));
540 for (Value *Op : CA->operands()) {
541 ConstantStruct *CS = cast<ConstantStruct>(Op);
542 // The first field of the struct contains a pointer to
543 // the annotated variable.
544 Value *AnnotatedVar = CS->getOperand(0)->stripPointerCasts();
545 if (!isa<Function>(AnnotatedVar))
546 report_fatal_error("Unsupported value in llvm.global.annotations");
547 Function *Func = cast<Function>(AnnotatedVar);
548 Register Reg = MAI->getFuncReg(Func);
549 if (!Reg.isValid()) {
550 std::string DiagMsg;
551 raw_string_ostream OS(DiagMsg);
552 AnnotatedVar->print(OS);
553 DiagMsg = "Unknown function in llvm.global.annotations: " + DiagMsg;
554 report_fatal_error(DiagMsg.c_str());
555 }
556
557 // The second field contains a pointer to a global annotation string.
558 GlobalVariable *GV =
559 cast<GlobalVariable>(CS->getOperand(1)->stripPointerCasts());
560
561 StringRef AnnotationString;
562 getConstantStringInfo(GV, AnnotationString);
563 MCInst Inst;
564 Inst.setOpcode(SPIRV::OpDecorate);
566 unsigned Dec = static_cast<unsigned>(SPIRV::Decoration::UserSemantic);
568 addStringImm(AnnotationString, Inst);
569 outputMCInst(Inst);
570 }
571 }
572}
573
574void SPIRVAsmPrinter::outputModuleSections() {
575 const Module *M = MMI->getModule();
576 // Get the global subtarget to output module-level info.
577 ST = static_cast<const SPIRVTargetMachine &>(TM).getSubtargetImpl();
578 TII = ST->getInstrInfo();
580 assert(ST && TII && MAI && M && "Module analysis is required");
581 // Output instructions according to the Logical Layout of a Module:
582 // 1,2. All OpCapability instructions, then optional OpExtension instructions.
583 outputGlobalRequirements();
584 // 3. Optional OpExtInstImport instructions.
585 outputOpExtInstImports(*M);
586 // 4. The single required OpMemoryModel instruction.
587 outputOpMemoryModel();
588 // 5. All entry point declarations, using OpEntryPoint.
589 outputEntryPoints();
590 // 6. Execution-mode declarations, using OpExecutionMode or OpExecutionModeId.
591 outputExecutionMode(*M);
592 // 7a. Debug: all OpString, OpSourceExtension, OpSource, and
593 // OpSourceContinued, without forward references.
594 outputDebugSourceAndStrings(*M);
595 // 7b. Debug: all OpName and all OpMemberName.
596 outputModuleSection(SPIRV::MB_DebugNames);
597 // 7c. Debug: all OpModuleProcessed instructions.
598 outputModuleSection(SPIRV::MB_DebugModuleProcessed);
599 // 8. All annotation instructions (all decorations).
600 outputAnnotations(*M);
601 // 9. All type declarations (OpTypeXXX instructions), all constant
602 // instructions, and all global variable declarations. This section is
603 // the first section to allow use of: OpLine and OpNoLine debug information;
604 // non-semantic instructions with OpExtInst.
605 outputModuleSection(SPIRV::MB_TypeConstVars);
606 // 10. All global NonSemantic.Shader.DebugInfo.100 instructions.
607 outputModuleSection(SPIRV::MB_NonSemanticGlobalDI);
608 // 11. All function declarations (functions without a body).
609 outputExtFuncDecls();
610 // 12. All function definitions (functions with a body).
611 // This is done in regular function output.
612}
613
614bool SPIRVAsmPrinter::doInitialization(Module &M) {
615 ModuleSectionsEmitted = false;
616 // We need to call the parent's one explicitly.
618}
619
620// Force static initialization.
625}
MachineBasicBlock & MBB
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
This file defines the DenseMap class.
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void addOpsFromMDNode(MDNode *MDN, MCInst &Inst, SPIRV::ModuleAnalysisInfo *MAI)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSPIRVAsmPrinter()
static bool isFuncOrHeaderInstr(const MachineInstr *MI, const SPIRVInstrInfo *TII)
static unsigned encodeVecTypeHint(Type *Ty)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition: SPIRVUtils.h:382
raw_pwrite_stream & OS
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:86
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:561
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:723
virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:92
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:545
virtual void emitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
Definition: AsmPrinter.h:541
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:459
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
Definition: AsmPrinter.cpp:450
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
virtual void emitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition: AsmPrinter.h:549
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:392
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition: Attributes.h:208
ConstantArray - Constant Array Declarations.
Definition: Constants.h:427
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
This is an important base class in LLVM.
Definition: Constant.h:42
This class represents an Operation in the Expression.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Class to represent fixed width SIMD vectors.
Definition: DerivedTypes.h:563
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:567
Class to represent integer types.
Definition: DerivedTypes.h:42
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:185
void addOperand(const MCOperand Op)
Definition: MCInst.h:211
void setOpcode(unsigned Op)
Definition: MCInst.h:198
static MCOperand createReg(MCRegister Reg)
Definition: MCInst.h:135
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:142
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
Metadata node.
Definition: Metadata.h:1069
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1428
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:891
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Representation of each machine instruction.
Definition: MachineInstr.h:69
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
MachineBasicBlock * getMBB() const
const BlockAddress * getBlockAddress() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_FPImmediate
Floating-point immediate operand.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1731
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isValid() const
Definition: Register.h:116
static const char * getRegisterName(MCRegister Reg)
void lower(const MachineInstr *MI, MCInst &OutMI, SPIRV::ModuleAnalysisInfo *MAI) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
typename SuperClass::iterator iterator
Definition: SmallVector.h:577
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:700
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:153
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:142
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:156
op_range operands()
Definition: User.h:288
Value * getOperand(unsigned i) const
Definition: User.h:228
LLVM Value Representation.
Definition: Value.h:74
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:5061
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:694
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:71
std::optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
Definition: VersionTuple.h:74
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
Reg
All possible values of the reg field in the ModR/M byte.
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Target & getTheSPIRV32Target()
bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
std::string getExtInstSetName(SPIRV::InstructionSet::InstructionSet Set)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)
bool isEntryPoint(const Function &F)
Definition: SPIRVUtils.cpp:445
Target & getTheSPIRV64Target()
Target & getTheSPIRVLogicalTarget()
Type * getMDOperandAsType(const MDNode *N, unsigned I)
Definition: SPIRVUtils.cpp:338
void addStringImm(const StringRef &Str, MCInst &Inst)
Definition: SPIRVUtils.cpp:54
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...
static struct SPIRV::ModuleAnalysisInfo MAI
Register getFuncReg(const Function *F)