1//===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
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 class wraps target description classes used by the various code
10// generation TableGen backends. This makes it easier to access the data and
11// provides a single place that needs to check it for validity. All of these
12// classes abort on error conditions.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CodeGenTarget.h"
17#include "CodeGenInstruction.h"
18#include "CodeGenRegisters.h"
19#include "CodeGenSchedule.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
27#include <tuple>
28using namespace llvm;
29
30static cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
31static cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
32
33static cl::opt<unsigned>
34 AsmParserNum("asmparsernum", cl::init(Val: 0),
35 cl::desc("Make -gen-asm-parser emit assembly parser #N"),
36 cl::cat(AsmParserCat));
37
38static cl::opt<unsigned>
39 AsmWriterNum("asmwriternum", cl::init(Val: 0),
40 cl::desc("Make -gen-asm-writer emit assembly writer #N"),
41 cl::cat(AsmWriterCat));
42
43/// Returns the MVT that the specified TableGen
44/// record corresponds to.
45MVT llvm::getValueType(const Record *Rec) {
46 static const DenseMap<StringRef, MVT> ValueTypes = {
47#define GET_VT_ATTR(Ty, Sz, Any, Int, FP, Vec, Sc, Tup, NF, NElem, EltTy) \
48 {#Ty, MVT::Ty},
49#include "llvm/CodeGen/GenVT.inc"
50#undef GET_VT_ATTR
51 {"INVALID_SIMPLE_VALUE_TYPE", MVT::INVALID_SIMPLE_VALUE_TYPE}};
52 return ValueTypes.lookup(Val: Rec->getValueAsString(FieldName: "LLVMName"));
53}
54
55StringRef llvm::getEnumName(MVT T) {
56 // clang-format off
57 switch (T.SimpleTy) {
58#define GET_VT_ATTR(Ty, Sz, Any, Int, FP, Vec, Sc, Tup, NF, NElem, EltTy) \
59 case MVT::Ty: return "MVT::" # Ty;
60#include "llvm/CodeGen/GenVT.inc"
61#undef GET_VT_ATTR
62 default: llvm_unreachable("ILLEGAL VALUE TYPE!");
63 }
64 // clang-format on
65}
66
67/// getQualifiedName - Return the name of the specified record, with a
68/// namespace qualifier if the record contains one.
69///
70std::string llvm::getQualifiedName(const Record *R) {
71 std::string Namespace;
72 if (R->getValue(Name: "Namespace"))
73 Namespace = R->getValueAsString(FieldName: "Namespace").str();
74 if (Namespace.empty())
75 return R->getName().str();
76 return Namespace + "::" + R->getName().str();
77}
78
79CodeGenTarget::CodeGenTarget(const RecordKeeper &records)
80 : Records(records), CGH(records), Intrinsics(records) {
81 ArrayRef<const Record *> Targets = Records.getAllDerivedDefinitions(ClassName: "Target");
82 if (Targets.size() == 0)
83 PrintFatalError(Msg: "No 'Target' subclasses defined!");
84 if (Targets.size() != 1)
85 PrintFatalError(Msg: "Multiple subclasses of Target defined!");
86 TargetRec = Targets[0];
87 MacroFusions = Records.getAllDerivedDefinitions(ClassName: "FusionPredicates");
88 llvm::sort(C&: MacroFusions, Comp: [](const Record *LHS, const Record *RHS) {
89 return std::tuple(getMacroFusionName(Fusion: LHS), LHS->getID()) <
90 std::tuple(getMacroFusionName(Fusion: RHS), RHS->getID());
91 });
92
93 auto Dup = adjacent_find(Range&: MacroFusions, P: [](const Record *A, const Record *B) {
94 return getMacroFusionName(Fusion: A) == getMacroFusionName(Fusion: B);
95 });
96 if (Dup != MacroFusions.end()) {
97 const Record *Fusion = *std::next(x: Dup);
98 PrintError(Rec: Fusion, Msg: "duplicate macro fusion for '" +
99 getMacroFusionName(Fusion) + "'");
100 PrintFatalNote(Rec: *Dup, Msg: "previous definition here");
101 }
102}
103
104StringRef CodeGenTarget::getMacroFusionName(const Record *Fusion) {
105 if (Fusion->isSubClassOf(Name: "FusionFor"))
106 return Fusion->getValueAsDef(FieldName: "Feature")->getName();
107 return Fusion->getName();
108}
109
110CodeGenTarget::~CodeGenTarget() = default;
111
112StringRef CodeGenTarget::getName() const { return TargetRec->getName(); }
113
114ArrayRef<const Record *> CodeGenTarget::getAllRegClassByHwMode() const {
115 if (!RegClassByHwModeList) {
116 RegClassByHwModeList.emplace();
117 for (const Record *R :
118 Records.getAllDerivedDefinitions(ClassName: "RegClassByHwMode")) {
119 if (!R->getValueAsListOfDefs(FieldName: "Objects").empty())
120 RegClassByHwModeList->push_back(x: R);
121 }
122 }
123
124 return *RegClassByHwModeList;
125}
126
127/// getInstNamespace - Find and return the target machine's instruction
128/// namespace. The namespace is cached because it is requested multiple times.
129StringRef CodeGenTarget::getInstNamespace() const {
130 if (InstNamespace.empty()) {
131 for (const CodeGenInstruction *Inst : getInstructions()) {
132 // We are not interested in the "TargetOpcode" namespace.
133 if (Inst->Namespace != "TargetOpcode") {
134 InstNamespace = Inst->Namespace;
135 break;
136 }
137 }
138 }
139
140 return InstNamespace;
141}
142
143StringRef CodeGenTarget::getRegNamespace() const {
144 auto &RegClasses = RegBank->getRegClasses();
145 return RegClasses.size() > 0 ? RegClasses.front().Namespace : "";
146}
147
148const Record *CodeGenTarget::getInstructionSet() const {
149 return TargetRec->getValueAsDef(FieldName: "InstructionSet");
150}
151
152bool CodeGenTarget::getAllowRegisterRenaming() const {
153 return TargetRec->getValueAsBit(FieldName: "AllowRegisterRenaming");
154}
155
156bool CodeGenTarget::getRegistersAreIntervals() const {
157 return TargetRec->getValueAsBit(FieldName: "RegistersAreIntervals");
158}
159
160/// getAsmParser - Return the AssemblyParser definition for this target.
161///
162const Record *CodeGenTarget::getAsmParser() const {
163 std::vector<const Record *> LI =
164 TargetRec->getValueAsListOfDefs(FieldName: "AssemblyParsers");
165 if (AsmParserNum >= LI.size())
166 PrintFatalError(Msg: "Target does not have an AsmParser #" +
167 Twine(AsmParserNum) + "!");
168 return LI[AsmParserNum];
169}
170
171/// getAsmParserVariant - Return the AssemblyParserVariant definition for
172/// this target.
173///
174const Record *CodeGenTarget::getAsmParserVariant(unsigned Idx) const {
175 std::vector<const Record *> LI =
176 TargetRec->getValueAsListOfDefs(FieldName: "AssemblyParserVariants");
177 if (Idx >= LI.size())
178 PrintFatalError(Msg: "Target does not have an AsmParserVariant #" + Twine(Idx) +
179 "!");
180 return LI[Idx];
181}
182
183/// getAsmParserVariantCount - Return the AssemblyParserVariant definition
184/// available for this target.
185///
186unsigned CodeGenTarget::getAsmParserVariantCount() const {
187 return TargetRec->getValueAsListOfDefs(FieldName: "AssemblyParserVariants").size();
188}
189
190/// getAsmWriter - Return the AssemblyWriter definition for this target.
191///
192const Record *CodeGenTarget::getAsmWriter() const {
193 std::vector<const Record *> LI =
194 TargetRec->getValueAsListOfDefs(FieldName: "AssemblyWriters");
195 if (AsmWriterNum >= LI.size())
196 PrintFatalError(Msg: "Target does not have an AsmWriter #" +
197 Twine(AsmWriterNum) + "!");
198 return LI[AsmWriterNum];
199}
200
201CodeGenRegBank &CodeGenTarget::getRegBank() const {
202 if (!RegBank)
203 RegBank = std::make_unique<CodeGenRegBank>(args: Records, args: getHwModes(),
204 args: getRegistersAreIntervals());
205 return *RegBank;
206}
207
208/// getRegisterByName - If there is a register with the specific AsmName,
209/// return it.
210const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
211 return getRegBank().getRegistersByName().lookup(Key: Name);
212}
213
214const CodeGenRegisterClass &
215CodeGenTarget::getRegisterClass(const Record *R, ArrayRef<SMLoc> Loc) const {
216 return *getRegBank().getRegClass(R, Loc);
217}
218
219std::vector<ValueTypeByHwMode>
220CodeGenTarget::getRegisterVTs(const Record *R) const {
221 const CodeGenRegister *Reg = getRegBank().getReg(R);
222 std::vector<ValueTypeByHwMode> Result;
223 for (const auto &RC : getRegBank().getRegClasses()) {
224 if (RC.contains(Reg)) {
225 ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
226 llvm::append_range(C&: Result, R&: InVTs);
227 }
228 }
229
230 // Remove duplicates.
231 llvm::sort(C&: Result);
232 Result.erase(first: llvm::unique(R&: Result), last: Result.end());
233 return Result;
234}
235
236void CodeGenTarget::ReadLegalValueTypes() const {
237 for (const auto &RC : getRegBank().getRegClasses())
238 llvm::append_range(C&: LegalValueTypes, R: RC.VTs);
239
240 // Remove duplicates.
241 llvm::sort(C&: LegalValueTypes);
242 LegalValueTypes.erase(CS: llvm::unique(R&: LegalValueTypes), CE: LegalValueTypes.end());
243}
244
245const Record *CodeGenTarget::getInitValueAsRegClass(
246 const Init *V, bool AssumeRegClassByHwModeIsDefault) const {
247 const Record *RegClassLike = getInitValueAsRegClassLike(V);
248 if (!RegClassLike || RegClassLike->isSubClassOf(Name: "RegisterClass"))
249 return RegClassLike;
250
251 // FIXME: We should figure out the hwmode and dispatch. But this interface
252 // is broken, we should be returning a register class. The expected uses
253 // will use the same RegBanks in all modes.
254 if (AssumeRegClassByHwModeIsDefault &&
255 RegClassLike->isSubClassOf(Name: "RegClassByHwMode")) {
256 const HwModeSelect &ModeSelect = getHwModes().getHwModeSelect(R: RegClassLike);
257 if (ModeSelect.Items.empty())
258 return nullptr;
259 return ModeSelect.Items.front().second;
260 }
261
262 return nullptr;
263}
264
265const Record *CodeGenTarget::getInitValueAsRegClassLike(const Init *V) const {
266 const DefInit *VDefInit = dyn_cast<DefInit>(Val: V);
267 if (!VDefInit)
268 return nullptr;
269 return getAsRegClassLike(V: VDefInit->getDef());
270}
271
272const Record *CodeGenTarget::getAsRegClassLike(const Record *Rec) const {
273 if (Rec->isSubClassOf(Name: "RegisterOperand"))
274 return Rec->getValueAsDef(FieldName: "RegClass");
275
276 return Rec->isSubClassOf(Name: "RegisterClassLike") ? Rec : nullptr;
277}
278
279CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
280 if (!SchedModels)
281 SchedModels = std::make_unique<CodeGenSchedModels>(args: Records, args: *this);
282 return *SchedModels;
283}
284
285void CodeGenTarget::ReadInstructions() const {
286 ArrayRef<const Record *> Insts =
287 Records.getAllDerivedDefinitions(ClassName: "Instruction");
288 if (Insts.size() <= 2)
289 PrintFatalError(Msg: "No 'Instruction' subclasses defined!");
290
291 // Parse the instructions defined in the .td file.
292 for (const Record *R : Insts) {
293 auto [II, _] =
294 InstructionMap.try_emplace(Key: R, Args: std::make_unique<CodeGenInstruction>(args&: R));
295 HasVariableLengthEncodings |= II->second->isVariableLengthEncoding();
296 }
297}
298
299static const CodeGenInstruction *GetInstByName(
300 StringRef Name,
301 const DenseMap<const Record *, std::unique_ptr<CodeGenInstruction>> &Insts,
302 const RecordKeeper &Records) {
303 const Record *Rec = Records.getDef(Name);
304
305 const auto I = Insts.find(Val: Rec);
306 if (!Rec || I == Insts.end())
307 PrintFatalError(Msg: "Could not find '" + Name + "' instruction!");
308 return I->second.get();
309}
310
311static const char *FixedInstrs[] = {
312#define HANDLE_TARGET_OPCODE(OPC) #OPC,
313#include "llvm/Support/TargetOpcodes.def"
314};
315
316unsigned CodeGenTarget::getNumFixedInstructions() {
317 return std::size(FixedInstrs);
318}
319
320/// Return all of the instructions defined by the target, ordered by
321/// their enum value.
322void CodeGenTarget::ComputeInstrsByEnum() const {
323 const auto &InstMap = getInstructionMap();
324 for (const char *Name : FixedInstrs) {
325 const CodeGenInstruction *Instr = GetInstByName(Name, Insts: InstMap, Records);
326 assert(Instr && "Missing target independent instruction");
327 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
328 InstrsByEnum.push_back(x: Instr);
329 }
330 unsigned EndOfPredefines = InstrsByEnum.size();
331 assert(EndOfPredefines == getNumFixedInstructions() &&
332 "Missing generic opcode");
333
334 [[maybe_unused]] unsigned SkippedInsts = 0;
335
336 for (const auto &[_, CGIUp] : InstMap) {
337 const CodeGenInstruction *CGI = CGIUp.get();
338 if (CGI->Namespace != "TargetOpcode") {
339
340 if (CGI->TheDef->isSubClassOf(
341 Name: "TargetSpecializedStandardPseudoInstruction")) {
342 ++SkippedInsts;
343 continue;
344 }
345
346 InstrsByEnum.push_back(x: CGI);
347 NumPseudoInstructions += CGI->TheDef->getValueAsBit(FieldName: "isPseudo");
348 }
349 }
350
351 assert(InstrsByEnum.size() + SkippedInsts == InstMap.size() &&
352 "Missing predefined instr");
353
354 // All of the instructions are now in random order based on the map iteration.
355 llvm::sort(
356 Start: InstrsByEnum.begin() + EndOfPredefines, End: InstrsByEnum.end(),
357 Comp: [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
358 const Record &D1 = *Rec1->TheDef;
359 const Record &D2 = *Rec2->TheDef;
360 // Sort all pseudo instructions before non-pseudo ones, and sort by name
361 // within.
362 return std::tuple(!Rec1->isPseudo, D1.getName()) <
363 std::tuple(!Rec2->isPseudo, D2.getName());
364 });
365
366 // Assign an enum value to each instruction according to the sorted order.
367 for (const auto &[Idx, Inst] : enumerate(First&: InstrsByEnum))
368 Inst->EnumVal = Idx;
369}
370
371/// isLittleEndianEncoding - Return whether this target encodes its instruction
372/// in little-endian format, i.e. bits laid out in the order [0..n]
373///
374bool CodeGenTarget::isLittleEndianEncoding() const {
375 return getInstructionSet()->getValueAsBit(FieldName: "isLittleEndianEncoding");
376}
377
378ArrayRef<const Init *>
379CodeGenTarget::getInstructionEncodingBits(const Record *EncodingDef) const {
380 ArrayRef<const Init *> Bits =
381 EncodingDef->getValueAsBitsInit(FieldName: "Inst")->getBits();
382 if (!isLittleEndianEncoding())
383 return Bits;
384
385 // Pseudo instructions are not encoded.
386 if (EncodingDef->isSubClassOf(Name: "Instruction") &&
387 (EncodingDef->getValueAsString(FieldName: "Namespace") == "TargetOpcode" ||
388 EncodingDef->getValueAsBit(FieldName: "isPseudo")))
389 return Bits;
390
391 auto [It, Inserted] = ReversedEncodingBits.try_emplace(Key: EncodingDef);
392 if (Inserted) {
393 const Init **Reversed =
394 ReversedEncodingBitsAllocator.Allocate<const Init *>(Num: Bits.size());
395 llvm::copy(Range: reverse(C&: Bits), Out: Reversed);
396 It->second = ArrayRef(Reversed, Bits.size());
397 }
398 return It->second;
399}
400
401/// guessInstructionProperties - Return true if it's OK to guess instruction
402/// properties instead of raising an error.
403///
404/// This is configurable as a temporary migration aid. It will eventually be
405/// permanently false.
406bool CodeGenTarget::guessInstructionProperties() const {
407 return getInstructionSet()->getValueAsBit(FieldName: "guessInstructionProperties");
408}
409
410//===----------------------------------------------------------------------===//
411// ComplexPattern implementation
412//
413ComplexPattern::ComplexPattern(const Record *R) {
414 Ty = R->getValueAsDef(FieldName: "Ty");
415 NumOperands = R->getValueAsInt(FieldName: "NumOperands");
416 SelectFunc = R->getValueAsString(FieldName: "SelectFunc").str();
417 RootNodes = R->getValueAsListOfDefs(FieldName: "RootNodes");
418
419 // FIXME: This is a hack to statically increase the priority of patterns which
420 // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
421 // possible pattern match we'll need to dynamically calculate the complexity
422 // of all patterns a dag can potentially map to.
423 int64_t RawComplexity = R->getValueAsInt(FieldName: "Complexity");
424 if (RawComplexity == -1)
425 Complexity = NumOperands * 3;
426 else
427 Complexity = RawComplexity;
428
429 // FIXME: Why is this different from parseSDPatternOperatorProperties?
430 // Parse the properties.
431 Properties = 0;
432 for (const Record *Prop : R->getValueAsListOfDefs(FieldName: "Properties")) {
433 if (Prop->getName() == "SDNPHasChain") {
434 Properties |= 1 << SDNPHasChain;
435 } else if (Prop->getName() == "SDNPOptInGlue") {
436 Properties |= 1 << SDNPOptInGlue;
437 } else if (Prop->getName() == "SDNPMayStore") {
438 Properties |= 1 << SDNPMayStore;
439 } else if (Prop->getName() == "SDNPMayLoad") {
440 Properties |= 1 << SDNPMayLoad;
441 } else if (Prop->getName() == "SDNPSideEffect") {
442 Properties |= 1 << SDNPSideEffect;
443 } else if (Prop->getName() == "SDNPMemOperand") {
444 Properties |= 1 << SDNPMemOperand;
445 } else if (Prop->getName() == "SDNPVariadic") {
446 Properties |= 1 << SDNPVariadic;
447 } else {
448 PrintFatalError(ErrorLoc: R->getLoc(),
449 Msg: "Unsupported SD Node property '" + Prop->getName() +
450 "' on ComplexPattern '" + R->getName() + "'!");
451 }
452 }
453
454 WantsRoot = R->getValueAsBit(FieldName: "WantsRoot");
455 WantsParent = R->getValueAsBit(FieldName: "WantsParent");
456}
457