LLVM 24.0.0git
PISATargetStreamer.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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/// \file
10/// This file implements the PISA target streamer.
11///
12//===----------------------------------------------------------------------===//
13
17#include "PISAInstPrinter.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/MC/MCAsmInfo.h"
24#include "llvm/MC/MCContext.h"
25#include "llvm/MC/MCStreamer.h"
30
31using namespace llvm;
32using namespace llvm::PISA;
33
49
51 switch (SS) {
53 return "private";
55 return "global";
57 return "const";
59 return "shared";
61 return "generic";
62 }
63 llvm_unreachable("Invalid storage space!");
64}
65
67 switch (AS) {
69 return "global";
71 return "const";
73 return "shared";
75 return "generic";
76 default:
77 break;
78 }
79 llvm_unreachable("Invalid parameter address space!");
80}
81
83 switch (Linkage) {
84 case DEFAULT:
85 return "default";
86 case EXPORT:
87 return "export";
88 case IMPORT:
89 return "import";
90 }
91 llvm_unreachable("Invalid linkage type!");
92}
93
94static StringRef getFunctionDirectiveRepr(bool IsKernel) {
95 return IsKernel ? ".kernel" : ".function";
96}
97
98static std::string getKernelAttributeRepr(const KernelAttribute &Attr) {
99
100 DenseMap<PISA::KernelAttributeType, StringRef> AvailableMetadataNodeTypes = {
102 ".reqd_work_group_size"},
103 {PISA::KernelAttributeType::VEC_TYPE_HINT, ".vec_type_hint"}};
104
105 std::string Result;
107 AvailableMetadataNodeTypes.find(Attr.KernelAttrType);
108 if (It != AvailableMetadataNodeTypes.end()) {
109 Result = It->second;
110 }
111
112 switch (Attr.KernelAttrType) {
114 Result += "(";
115 const std::vector<uint32_t> &Values =
116 std::get<std::vector<uint32_t>>(Attr.KernelAttrValues);
117 if (!Values.empty()) {
118 Result +=
119 std::accumulate(std::next(Values.begin()), Values.end(),
120 std::to_string(Values.front()),
121 [](const std::string &Acc, uint32_t El) {
122 return Acc + std::string(", ") + std::to_string(El);
123 });
124 }
125 Result += ")";
126 } break;
128 Result += "(";
129 const std::string &Arg = std::get<std::string>(Attr.KernelAttrValues);
130 Result += Arg;
131 Result += ")";
132 } break;
133 }
134 return Result;
135}
136
137static void emitTypeString(uint32_t TypeSizeInBits, uint32_t NumElts,
138 raw_ostream &OS) {
139 assert(NumElts > 0);
140 if (NumElts == 1 && TypeSizeInBits == 1) {
141 OS << ".pred";
142 return;
143 }
144
145 if (NumElts > 1)
146 OS << ".v" << NumElts;
147 OS << "." << TypeSizeInBits << "b";
148}
149
150static void emitTypeString(const LLT &T, raw_ostream &OS) {
151 uint32_t TypeBitSize = T.getScalarSizeInBits();
152 uint32_t NumElts = T.isVector() ? T.getNumElements() : 1;
153 emitTypeString(TypeBitSize, NumElts, OS);
154}
155
156static void printOffset(int64_t Val, raw_ostream &OS) {
157 // Print an immediate offset only when it is nonzero.
158 if (Val > 0) {
159 OS << "+" << format("%" PRId64, Val);
160 } else if (Val < 0) {
161 if (Val == std::numeric_limits<int64_t>::min())
162 OS << "-" << format("%" PRIu64, Val);
163 else
164 OS << "-" << format("%" PRId64, -Val);
165 }
166}
167
168namespace {
169
170class PISATargetAsmStreamer final : public PISATargetStreamer {
171 formatted_raw_ostream &OS;
172 const MCAsmInfo *MAI = nullptr;
173 void printName(raw_ostream &OS, StringRef Name) {
175 }
176
177public:
178 PISATargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS)
179 : PISATargetStreamer(S), OS(OS), MAI(&S.getContext().getAsmInfo()) {}
180 ~PISATargetAsmStreamer() override;
181
182 StringRef emitHeader(const PISA::HeaderDcl &HD) override {
183 if (HD.Version != 0)
184 OS << ".version " << (HD.Version / 100) << "." << (HD.Version % 100)
185 << ";\n";
186 if (!HD.Target.empty())
187 OS << ".target " << HD.Target << ";\n";
188 return HD.Target;
189 }
190
191 void emitGlobalVariable(const PISA::GlobalVariableDcl &GV) override {
192 if (GV.Dcl.Linkage != PISA::LinkageTy::DEFAULT)
193 OS << "." << getLinkageTyName(GV.Dcl.Linkage) << " ";
194
195 // globals must have .const or .global addrspace
196 switch (GV.Dcl.SS) {
197 case PISA::StorageSpace::GLOBAL:
198 OS << ".global ";
199 break;
200 case PISA::StorageSpace::CONSTANT:
201 OS << ".const ";
202 break;
203 default:
204 llvm_unreachable("Invalid storage space for global variables");
205 }
206
207 OS << " .align " << GV.Dcl.Alignment.value() << " ";
208
209 if (!GV.Dcl.Section.empty())
210 OS << ".section(\"" << GV.Dcl.Section << "\") ";
211
212 if (!GV.Dcl.HostAccessName.empty())
213 OS << ".host_access(\"" << GV.Dcl.HostAccessName << "\") ";
214
215 OS << "@";
216 printName(OS, GV.Dcl.Name);
217
218 if (GV.Init.Initializer.empty()) {
219 OS << "[" << GV.Dcl.Size << "]";
220 } else {
221 OS << " = { ";
222 ListSeparator LS;
223 for (const auto &[I, X] : enumerate(GV.Init.Initializer)) {
224 OS << LS;
225 DenseMap<uint64_t, PISA::VariableInit::SpecialEntry>::const_iterator
226 Iter = GV.Init.Exprs.find(I);
227 if (Iter != GV.Init.Exprs.end()) {
228 const PISA::VariableInit::SpecialEntry &Entry = Iter->second;
229 if (const PISA::VariableInit::GlobalExpr *G =
230 std::get_if<PISA::VariableInit::GlobalExpr>(&Entry)) {
231 OS << "." << X.Type.getSizeInBits() << "b ";
232 OS << "@" << G->Name;
233 printOffset(G->Offset, OS);
234 } else if (const PISA::VariableInit::Zeros *Z =
235 std::get_if<PISA::VariableInit::Zeros>(&Entry)) {
236 OS << ".zero " << Z->N;
237 } else {
238 llvm_unreachable("unknown construct!");
239 }
240 } else {
241 TypeSize SizeInBits = X.Type.getSizeInBits();
242 OS << "." << SizeInBits << "b ";
243 OS << format_hex(X.Value & maskTrailingOnes<uint64_t>(SizeInBits), 1);
244 }
245 }
246 OS << " }";
247 }
248
249 OS << ";\n";
250 }
251
252 void emitFunctionSignature(const PISA::FunctionSignature &Sig) override {
253 if (!Sig.DN.IsKernel) {
254 switch (Sig.DN.Linkage) {
255 case PISA::LinkageTy::EXPORT:
256 OS << ".export ";
257 break;
258 case PISA::LinkageTy::IMPORT:
259 OS << ".import ";
260 break;
261 default:
262 break;
263 }
264 }
265
266 OS << getFunctionDirectiveRepr(Sig.DN.IsKernel) << " ";
267
268 for (const PISA::KernelAttribute &KernelAttr : Sig.DN.KernelAttrs) {
269 OS << getKernelAttributeRepr(KernelAttr) << " ";
270 }
271
272 if (!Sig.DN.IsKernel) {
273 if (Sig.DN.RetLLT.isValid())
274 emitTypeString(Sig.DN.RetLLT, OS);
275 else
276 OS << "void";
277 OS << " ";
278 }
279
280 OS << "@";
281 printName(OS, Sig.DN.Name);
282
283 OS << "(";
284 if (!Sig.DN.IsKernel) {
285 ListSeparator LS;
286 for (const PISA::FunctionParameter &Param : Sig.FunctionParams) {
287 OS << LS << ".reg ";
288 emitTypeString(Param.Ty, OS);
289 OS << " " << Param.Prefix << Param.Idx;
290 }
291 } else {
292 ListSeparator LS;
293 for (const auto &[I, Param] : enumerate(Sig.KernelParams)) {
294 OS << LS << ".param[" << Param.Size << "] ";
295 if (Param.hasAlign())
296 OS << ".align(" << Param.Align << ") ";
297 if (Param.hasAS())
298 OS << ".addrspace("
299 << getParamASRepr(static_cast<PISAAS::AddressSpace>(Param.AS))
300 << ") ";
301 if (Param.hasPtrAlign())
302 OS << ".ptr_align(" << Param.PtrAlign << ") ";
303 if (!Param.ArgName.empty())
304 OS << "%" << Param.ArgName;
305 else
306 OS << "%arg" << I;
307 }
308 }
309
310 OS << ")";
311
312 OS << "\n";
313 }
314
315 void emitFunctionDeclaration(const PISA::FunctionDeclaration &Dcl) override {
316 assert(!Dcl.DN.IsKernel);
317
318 if (Dcl.DN.Linkage != PISA::LinkageTy::IMPORT) {
319 return;
320 }
321
322 OS << ".import ";
323 OS << getFunctionDirectiveRepr(Dcl.DN.IsKernel) << " ";
324
325 if (Dcl.DN.RetLLT.isValid()) {
326 emitTypeString(Dcl.DN.RetLLT, OS);
327 } else
328 OS << "void";
329
330 OS << " @";
331 printName(OS, Dcl.DN.Name);
332
333 OS << "(";
334 ListSeparator LS;
335 for (const PISA::FunctionDeclParam &Param : Dcl.FunctionParams) {
336 OS << LS << ".reg ";
337 emitTypeString(Param.Ty, OS);
338 }
339 OS << ");";
340 }
341
342 void addRegDcl(unsigned NumElts, unsigned EltSize, unsigned RegType,
343 RegNamesRange RegNames, bool MustAdd) override {
344 llvm_unreachable("Never used.");
345 }
346
347 void emitRegDcls(const PISA::RegDcls &Dcls,
348 const PISA::DataTypes &DTs) override {
349 for (const std::pair<std::tuple<unsigned, unsigned, unsigned>,
350 PISA::TypeInfo> &Entry : DTs) {
351 const std::tuple<unsigned, unsigned, unsigned> &Key = Entry.first;
352 const PISA::TypeInfo &TI = Entry.second;
353 // Skip if 0 registers of this type were declared
354 if (TI.RegStart == TI.RegCounter)
355 continue;
356
357 unsigned NumElts = std::get<0>(Key);
358 unsigned BitWidth = std::get<1>(Key);
359 unsigned RegType = std::get<2>(Key);
360
361 switch (RegType) {
363 OS << "\t.pred ";
364 break;
366 OS << "\t.reg ";
367 emitTypeString(BitWidth, NumElts, OS);
368 OS << " ";
369 break;
370 default:
371 llvm_unreachable("unknown reg type!");
372 }
373
374 // Do not use range syntax if only 5 or fewer registers were declared
375 if (TI.RegCounter - TI.RegStart <= 5) {
376 ListSeparator LS;
377 for (unsigned I = TI.RegStart; I < TI.RegCounter; ++I)
378 OS << LS << TI.Prefix << I;
379 OS << ";\n";
380 } else {
381 OS << TI.Prefix << "<" << TI.RegStart << "~" << (TI.RegCounter)
382 << ">;\n";
383 }
384 }
385 }
386
387 void addLocalVariableDecl(const PISA::LocalVariableDcl &V) override {
388 OS << "\t." << getStorageSpaceRepr(V.SS) << " ";
389 OS << ".align " << V.Alignment.value() << " ";
390 OS << "@";
391 // If PISA comes from PISA reader StackIndex won't be set, so we fall
392 // back and use already parsed name.
393 if (V.StackIndex == -1) {
394 OS << V.Name;
395 } else {
396 OS << "R" << V.StackIndex;
397 }
398 OS << '[' << V.Size << "];\n";
399 }
400
401 void emitLocalVariableDcls(const PISA::LocalVariableDcls &Dcls) override {
402 for (const PISA::LocalVariableDcl &V : Dcls.Vars)
403 addLocalVariableDecl(V);
404 }
405
406 void emitFuncBodyStart() override { OS << "{\n"; }
407 void emitFuncBodyEnd() override { OS << "}\n"; }
408
409 bool isAsmStreamer() const override { return true; }
410 int getCurLine() const override {
411 // getLine() in OS is 0 based
412 return OS.getLine() + 1;
413 }
414};
415
416class PISATargetELFStreamer final : public PISATargetStreamer {
417public:
418 PISATargetELFStreamer(MCStreamer &S) : PISATargetStreamer(S) {}
419 ~PISATargetELFStreamer() override;
420
421 StringRef emitHeader(const PISA::HeaderDcl &) override {
422 llvm_unreachable("Not implemented yet!");
423 }
424 void emitGlobalVariable(const PISA::GlobalVariableDcl &) override {
425 llvm_unreachable("Not implemented yet!");
426 }
427 void emitFunctionSignature(const PISA::FunctionSignature &) override {
428 llvm_unreachable("Not implemented yet!");
429 }
430 void emitFunctionDeclaration(const PISA::FunctionDeclaration &) override {
431 llvm_unreachable("Not implemented yet!");
432 }
433 void emitRegDcls(const PISA::RegDcls &, const PISA::DataTypes &) override {
434 llvm_unreachable("Not implemented yet!");
435 }
436 void emitLocalVariableDcls(const PISA::LocalVariableDcls &) override {
437 llvm_unreachable("Not implemented yet!");
438 }
439 void emitFuncBodyStart() override {
440 llvm_unreachable("Not implemented yet!");
441 }
442 void emitFuncBodyEnd() override { llvm_unreachable("Not implemented yet!"); }
443
444 void addRegDcl(unsigned NumElts, unsigned EltSize, unsigned RegType,
445 RegNamesRange RegNames, bool MustAdd = true) override {
446 llvm_unreachable("Not implemented yet!");
447 }
448 void addLocalVariableDecl(const PISA::LocalVariableDcl &) override {
449 llvm_unreachable("Not implemented yet!");
450 }
451};
452
453class PISATargetNullStreamer final : public PISATargetStreamer {
454public:
455 PISATargetNullStreamer(MCStreamer &S) : PISATargetStreamer(S) {}
456 ~PISATargetNullStreamer() override;
457
458 StringRef emitHeader(const PISA::HeaderDcl &) override { return ""; }
459 void emitGlobalVariable(const PISA::GlobalVariableDcl &) override {}
460 void emitFunctionSignature(const PISA::FunctionSignature &) override {}
461 void emitFunctionDeclaration(const PISA::FunctionDeclaration &) override {}
462 void emitRegDcls(const PISA::RegDcls &, const PISA::DataTypes &) override {}
463 void emitLocalVariableDcls(const PISA::LocalVariableDcls &) override {}
464 void emitFuncBodyStart() override {}
465 void emitFuncBodyEnd() override {}
466
467 void addRegDcl(unsigned NumElts, unsigned EltSize, unsigned RegType,
468 RegNamesRange RegNames, bool MustAdd = true) override {}
469 void addLocalVariableDecl(const PISA::LocalVariableDcl &) override {}
470};
471
472} // namespace
473
475PISATargetAsmStreamer::~PISATargetAsmStreamer() = default;
476PISATargetELFStreamer::~PISATargetELFStreamer() = default;
477PISATargetNullStreamer::~PISATargetNullStreamer() = default;
478
481 MCInstPrinter *InstPrinter) {
482 return new PISATargetAsmStreamer(S, OS);
483}
484
487 const MCSubtargetInfo &STI) {
488 const Triple &TT = STI.getTargetTriple();
489 if (TT.isOSBinFormatELF())
490 return new PISATargetELFStreamer(S);
491 return nullptr;
492}
493
495 return new PISATargetNullStreamer(S);
496}
497
499 unsigned NumElts = Ty.isScalar() ? 1 : Ty.getNumElements();
500 unsigned EltSize = Ty.getScalarSizeInBits();
501 unsigned RegType =
503 return DataType{NumElts, EltSize, RegType};
504}
505
507 if (Ty.NumElts == 1)
508 return LLT::integer(Ty.EltSize);
509 return LLT::vector(ElementCount::getFixed(Ty.NumElts), Ty.EltSize);
510}
511
513 unsigned NumElts = Ty.isScalar() ? 1 : Ty.getNumElements();
514 unsigned EltSize = Ty.getScalarSizeInBits();
516 PISA::RegEncoder::getRegBank(NumElts, EltSize);
518}
519
521 std::tuple<unsigned, unsigned, unsigned> Result =
523 .Case("%p", {1, 1, PISA::RegEncoder::PRED})
524 .Case("%b", {1, 8, PISA::RegEncoder::REG})
525 .Case("%h", {1, 16, PISA::RegEncoder::REG})
526 .Case("%w", {1, 32, PISA::RegEncoder::REG})
527 .Case("%d", {1, 64, PISA::RegEncoder::REG})
528 .Case("%q", {1, 128, PISA::RegEncoder::REG})
529 .Case("%v2b", {2, 8, PISA::RegEncoder::REG})
530 .Case("%v3b", {3, 8, PISA::RegEncoder::REG})
531 .Case("%v4b", {4, 8, PISA::RegEncoder::REG})
532 .Case("%v2h", {2, 16, PISA::RegEncoder::REG})
533 .Case("%v3h", {3, 16, PISA::RegEncoder::REG})
534 .Case("%v4h", {4, 16, PISA::RegEncoder::REG})
535 .Case("%v2w", {2, 32, PISA::RegEncoder::REG})
536 .Case("%v3w", {3, 32, PISA::RegEncoder::REG})
537 .Case("%v4w", {4, 32, PISA::RegEncoder::REG})
538 .Case("%v5w", {5, 32, PISA::RegEncoder::REG})
539 .Case("%v6w", {6, 32, PISA::RegEncoder::REG})
540 .Case("%v7w", {7, 32, PISA::RegEncoder::REG})
541 .Case("%v8w", {8, 32, PISA::RegEncoder::REG})
542 .Case("%v16w", {16, 32, PISA::RegEncoder::REG})
543 .Case("%v32w", {32, 32, PISA::RegEncoder::REG})
544 .Case("%v64w", {64, 32, PISA::RegEncoder::REG})
545 .Case("%v2d", {2, 64, PISA::RegEncoder::REG})
546 .Case("%v3d", {3, 64, PISA::RegEncoder::REG})
547 .Case("%v4d", {4, 64, PISA::RegEncoder::REG})
548 .Default({0, 0, 0});
549
550 assert(std::get<0>(Result) != 0 && "Unknown type prefix");
551
552 return DataType{std::get<0>(Result), std::get<1>(Result),
553 std::get<2>(Result)};
554}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
return Result
Implement a low-level type suitable for MachineInstr level instruction selection.
static void printName(raw_ostream &OS, StringRef Name)
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
This file defines the address spaces used by the PISA target.
This file declares the PISA MCInst printer.
This file declares the PISA MC target descriptions.
This file declares encoding of PISA virtual registers.
static void emitTypeString(uint32_t TypeSizeInBits, uint32_t NumElts, raw_ostream &OS)
static StringRef getFunctionDirectiveRepr(bool IsKernel)
static StringRef getParamASRepr(PISAAS::AddressSpace AS)
static std::string getKernelAttributeRepr(const KernelAttribute &Attr)
static StringRef getStorageSpaceRepr(PISA::StorageSpace SS)
static void printOffset(int64_t Val, raw_ostream &OS)
This file declares the PISA target streamer.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
constexpr bool isValid() const
static LLT integer(unsigned SizeInBits)
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Streaming machine code generation interface.
Definition MCStreamer.h:221
Generic base class for all target subtargets.
const Triple & getTargetTriple() const
Target specific streamer interface.
Definition MCStreamer.h:94
static void printSymbolName(raw_ostream &OS, StringRef Name, const MCAsmInfo *MAI)
~PISATargetStreamer() override
static DataType getTypeFromPrefix(StringRef Prefix)
static DataType getTypeFromLLT(LLT Ty)
static LLT getLLTFromType(const DataType &Ty)
static std::string getPrefixFromLLT(LLT Ty)
static RegBank getRegBank(unsigned NumElts, unsigned EltSize)
static const char * getPrefixFromBank(RegBank Bank)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A switch()-like statement whose cases are string literals.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
StorageSpace mapAddrSpaceToStorageSpace(unsigned AS)
VariableDcl LocalVariableDcl
VariableDclInit GlobalVariableDcl
StringRef getLinkageTyName(LinkageTy Linkage)
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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
MCTargetStreamer * createPISAAsmTargetStreamer(MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint)
MCTargetStreamer * createPISAObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI)
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition Format.h:164
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
constexpr unsigned BitWidth
MCTargetStreamer * createPISANullTargetStreamer(MCStreamer &S)
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
SmallVector< FunctionDeclParam > FunctionParams
SmallVector< KernelAttribute > KernelAttrs
FunctionDirectiveAndName DN
SmallVector< KernelParameter > KernelParams
SmallVector< FunctionParameter > FunctionParams
KernelAttributeType KernelAttrType
std::variant< std::vector< uint32_t >, std::string, std::vector< std::string >, uint32_t > KernelAttrValues
SmallVector< LocalVariableDcl > Vars
std::variant< GlobalExpr, Zeros > SpecialEntry
DenseMap< uint64_t, SpecialEntry > Exprs
SmallVector< InitElement > Initializer