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: "Fusion");
88}
89
90CodeGenTarget::~CodeGenTarget() = default;
91
92StringRef CodeGenTarget::getName() const { return TargetRec->getName(); }
93
94/// getInstNamespace - Find and return the target machine's instruction
95/// namespace. The namespace is cached because it is requested multiple times.
96StringRef CodeGenTarget::getInstNamespace() const {
97 if (InstNamespace.empty()) {
98 for (const CodeGenInstruction *Inst : getInstructions()) {
99 // We are not interested in the "TargetOpcode" namespace.
100 if (Inst->Namespace != "TargetOpcode") {
101 InstNamespace = Inst->Namespace;
102 break;
103 }
104 }
105 }
106
107 return InstNamespace;
108}
109
110StringRef CodeGenTarget::getRegNamespace() const {
111 auto &RegClasses = RegBank->getRegClasses();
112 return RegClasses.size() > 0 ? RegClasses.front().Namespace : "";
113}
114
115const Record *CodeGenTarget::getInstructionSet() const {
116 return TargetRec->getValueAsDef(FieldName: "InstructionSet");
117}
118
119bool CodeGenTarget::getAllowRegisterRenaming() const {
120 return TargetRec->getValueAsBit(FieldName: "AllowRegisterRenaming");
121}
122
123bool CodeGenTarget::getRegistersAreIntervals() const {
124 return TargetRec->getValueAsBit(FieldName: "RegistersAreIntervals");
125}
126
127/// getAsmParser - Return the AssemblyParser definition for this target.
128///
129const Record *CodeGenTarget::getAsmParser() const {
130 std::vector<const Record *> LI =
131 TargetRec->getValueAsListOfDefs(FieldName: "AssemblyParsers");
132 if (AsmParserNum >= LI.size())
133 PrintFatalError(Msg: "Target does not have an AsmParser #" +
134 Twine(AsmParserNum) + "!");
135 return LI[AsmParserNum];
136}
137
138/// getAsmParserVariant - Return the AssemblyParserVariant definition for
139/// this target.
140///
141const Record *CodeGenTarget::getAsmParserVariant(unsigned Idx) const {
142 std::vector<const Record *> LI =
143 TargetRec->getValueAsListOfDefs(FieldName: "AssemblyParserVariants");
144 if (Idx >= LI.size())
145 PrintFatalError(Msg: "Target does not have an AsmParserVariant #" + Twine(Idx) +
146 "!");
147 return LI[Idx];
148}
149
150/// getAsmParserVariantCount - Return the AssemblyParserVariant definition
151/// available for this target.
152///
153unsigned CodeGenTarget::getAsmParserVariantCount() const {
154 return TargetRec->getValueAsListOfDefs(FieldName: "AssemblyParserVariants").size();
155}
156
157/// getAsmWriter - Return the AssemblyWriter definition for this target.
158///
159const Record *CodeGenTarget::getAsmWriter() const {
160 std::vector<const Record *> LI =
161 TargetRec->getValueAsListOfDefs(FieldName: "AssemblyWriters");
162 if (AsmWriterNum >= LI.size())
163 PrintFatalError(Msg: "Target does not have an AsmWriter #" +
164 Twine(AsmWriterNum) + "!");
165 return LI[AsmWriterNum];
166}
167
168CodeGenRegBank &CodeGenTarget::getRegBank() const {
169 if (!RegBank)
170 RegBank = std::make_unique<CodeGenRegBank>(args: Records, args: getHwModes(),
171 args: getRegistersAreIntervals());
172 return *RegBank;
173}
174
175/// getRegisterByName - If there is a register with the specific AsmName,
176/// return it.
177const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
178 return getRegBank().getRegistersByName().lookup(Key: Name);
179}
180
181const CodeGenRegisterClass &
182CodeGenTarget::getRegisterClass(const Record *R, ArrayRef<SMLoc> Loc) const {
183 return *getRegBank().getRegClass(R, Loc);
184}
185
186std::vector<ValueTypeByHwMode>
187CodeGenTarget::getRegisterVTs(const Record *R) const {
188 const CodeGenRegister *Reg = getRegBank().getReg(R);
189 std::vector<ValueTypeByHwMode> Result;
190 for (const auto &RC : getRegBank().getRegClasses()) {
191 if (RC.contains(Reg)) {
192 ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
193 llvm::append_range(C&: Result, R&: InVTs);
194 }
195 }
196
197 // Remove duplicates.
198 llvm::sort(C&: Result);
199 Result.erase(first: llvm::unique(R&: Result), last: Result.end());
200 return Result;
201}
202
203void CodeGenTarget::ReadLegalValueTypes() const {
204 for (const auto &RC : getRegBank().getRegClasses())
205 llvm::append_range(C&: LegalValueTypes, R: RC.VTs);
206
207 // Remove duplicates.
208 llvm::sort(C&: LegalValueTypes);
209 LegalValueTypes.erase(CS: llvm::unique(R&: LegalValueTypes), CE: LegalValueTypes.end());
210}
211
212const Record *CodeGenTarget::getInitValueAsRegClass(
213 const Init *V, bool AssumeRegClassByHwModeIsDefault) const {
214 const Record *RegClassLike = getInitValueAsRegClassLike(V);
215 if (!RegClassLike || RegClassLike->isSubClassOf(Name: "RegisterClass"))
216 return RegClassLike;
217
218 // FIXME: We should figure out the hwmode and dispatch. But this interface
219 // is broken, we should be returning a register class. The expected uses
220 // will use the same RegBanks in all modes.
221 if (AssumeRegClassByHwModeIsDefault &&
222 RegClassLike->isSubClassOf(Name: "RegClassByHwMode")) {
223 const HwModeSelect &ModeSelect = getHwModes().getHwModeSelect(R: RegClassLike);
224 if (ModeSelect.Items.empty())
225 return nullptr;
226 return ModeSelect.Items.front().second;
227 }
228
229 return nullptr;
230}
231
232const Record *CodeGenTarget::getInitValueAsRegClassLike(const Init *V) const {
233 const DefInit *VDefInit = dyn_cast<DefInit>(Val: V);
234 if (!VDefInit)
235 return nullptr;
236 return getAsRegClassLike(V: VDefInit->getDef());
237}
238
239const Record *CodeGenTarget::getAsRegClassLike(const Record *Rec) const {
240 if (Rec->isSubClassOf(Name: "RegisterOperand"))
241 return Rec->getValueAsDef(FieldName: "RegClass");
242
243 return Rec->isSubClassOf(Name: "RegisterClassLike") ? Rec : nullptr;
244}
245
246CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
247 if (!SchedModels)
248 SchedModels = std::make_unique<CodeGenSchedModels>(args: Records, args: *this);
249 return *SchedModels;
250}
251
252void CodeGenTarget::ReadInstructions() const {
253 ArrayRef<const Record *> Insts =
254 Records.getAllDerivedDefinitions(ClassName: "Instruction");
255 if (Insts.size() <= 2)
256 PrintFatalError(Msg: "No 'Instruction' subclasses defined!");
257
258 // Parse the instructions defined in the .td file.
259 for (const Record *R : Insts) {
260 auto [II, _] =
261 InstructionMap.try_emplace(Key: R, Args: std::make_unique<CodeGenInstruction>(args&: R));
262 HasVariableLengthEncodings |= II->second->isVariableLengthEncoding();
263 }
264}
265
266static const CodeGenInstruction *GetInstByName(
267 StringRef Name,
268 const DenseMap<const Record *, std::unique_ptr<CodeGenInstruction>> &Insts,
269 const RecordKeeper &Records) {
270 const Record *Rec = Records.getDef(Name);
271
272 const auto I = Insts.find(Val: Rec);
273 if (!Rec || I == Insts.end())
274 PrintFatalError(Msg: "Could not find '" + Name + "' instruction!");
275 return I->second.get();
276}
277
278static const char *FixedInstrs[] = {
279#define HANDLE_TARGET_OPCODE(OPC) #OPC,
280#include "llvm/Support/TargetOpcodes.def"
281};
282
283unsigned CodeGenTarget::getNumFixedInstructions() {
284 return std::size(FixedInstrs);
285}
286
287/// Return all of the instructions defined by the target, ordered by
288/// their enum value.
289void CodeGenTarget::ComputeInstrsByEnum() const {
290 const auto &InstMap = getInstructionMap();
291 for (const char *Name : FixedInstrs) {
292 const CodeGenInstruction *Instr = GetInstByName(Name, Insts: InstMap, Records);
293 assert(Instr && "Missing target independent instruction");
294 assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
295 InstrsByEnum.push_back(x: Instr);
296 }
297 unsigned EndOfPredefines = InstrsByEnum.size();
298 assert(EndOfPredefines == getNumFixedInstructions() &&
299 "Missing generic opcode");
300
301 [[maybe_unused]] unsigned SkippedInsts = 0;
302
303 for (const auto &[_, CGIUp] : InstMap) {
304 const CodeGenInstruction *CGI = CGIUp.get();
305 if (CGI->Namespace != "TargetOpcode") {
306
307 if (CGI->TheDef->isSubClassOf(
308 Name: "TargetSpecializedStandardPseudoInstruction")) {
309 ++SkippedInsts;
310 continue;
311 }
312
313 InstrsByEnum.push_back(x: CGI);
314 NumPseudoInstructions += CGI->TheDef->getValueAsBit(FieldName: "isPseudo");
315 }
316 }
317
318 assert(InstrsByEnum.size() + SkippedInsts == InstMap.size() &&
319 "Missing predefined instr");
320
321 // All of the instructions are now in random order based on the map iteration.
322 llvm::sort(
323 Start: InstrsByEnum.begin() + EndOfPredefines, End: InstrsByEnum.end(),
324 Comp: [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
325 const Record &D1 = *Rec1->TheDef;
326 const Record &D2 = *Rec2->TheDef;
327 // Sort all pseudo instructions before non-pseudo ones, and sort by name
328 // within.
329 return std::tuple(!Rec1->isPseudo, D1.getName()) <
330 std::tuple(!Rec2->isPseudo, D2.getName());
331 });
332
333 // Assign an enum value to each instruction according to the sorted order.
334 for (const auto &[Idx, Inst] : enumerate(First&: InstrsByEnum))
335 Inst->EnumVal = Idx;
336}
337
338/// isLittleEndianEncoding - Return whether this target encodes its instruction
339/// in little-endian format, i.e. bits laid out in the order [0..n]
340///
341bool CodeGenTarget::isLittleEndianEncoding() const {
342 return getInstructionSet()->getValueAsBit(FieldName: "isLittleEndianEncoding");
343}
344
345/// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
346/// encodings, reverse the bit order of all instructions.
347void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
348 if (!isLittleEndianEncoding())
349 return;
350
351 for (const Record *R :
352 Records.getAllDerivedDefinitions(ClassName: "InstructionEncoding")) {
353 if (R->getValueAsString(FieldName: "Namespace") == "TargetOpcode" ||
354 R->getValueAsBit(FieldName: "isPseudo"))
355 continue;
356
357 const BitsInit *BI = R->getValueAsBitsInit(FieldName: "Inst");
358
359 unsigned numBits = BI->getNumBits();
360
361 SmallVector<const Init *, 16> NewBits(numBits);
362
363 for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
364 unsigned bitSwapIdx = numBits - bit - 1;
365 const Init *OrigBit = BI->getBit(Bit: bit);
366 const Init *BitSwap = BI->getBit(Bit: bitSwapIdx);
367 NewBits[bit] = BitSwap;
368 NewBits[bitSwapIdx] = OrigBit;
369 }
370 if (numBits % 2) {
371 unsigned middle = (numBits + 1) / 2;
372 NewBits[middle] = BI->getBit(Bit: middle);
373 }
374
375 RecordKeeper &MutableRC = const_cast<RecordKeeper &>(Records);
376 const BitsInit *NewBI = BitsInit::get(RK&: MutableRC, Range: NewBits);
377
378 // Update the bits in reversed order so that emitters will get the correct
379 // endianness.
380 // FIXME: Eliminate mutation of TG records by creating a helper function
381 // to reverse bits and maintain a cache instead of mutating records.
382 Record *MutableR = const_cast<Record *>(R);
383 MutableR->getValue(Name: "Inst")->setValue(NewBI);
384 }
385}
386
387/// guessInstructionProperties - Return true if it's OK to guess instruction
388/// properties instead of raising an error.
389///
390/// This is configurable as a temporary migration aid. It will eventually be
391/// permanently false.
392bool CodeGenTarget::guessInstructionProperties() const {
393 return getInstructionSet()->getValueAsBit(FieldName: "guessInstructionProperties");
394}
395
396//===----------------------------------------------------------------------===//
397// ComplexPattern implementation
398//
399ComplexPattern::ComplexPattern(const Record *R) {
400 Ty = R->getValueAsDef(FieldName: "Ty");
401 NumOperands = R->getValueAsInt(FieldName: "NumOperands");
402 SelectFunc = R->getValueAsString(FieldName: "SelectFunc").str();
403 RootNodes = R->getValueAsListOfDefs(FieldName: "RootNodes");
404
405 // FIXME: This is a hack to statically increase the priority of patterns which
406 // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
407 // possible pattern match we'll need to dynamically calculate the complexity
408 // of all patterns a dag can potentially map to.
409 int64_t RawComplexity = R->getValueAsInt(FieldName: "Complexity");
410 if (RawComplexity == -1)
411 Complexity = NumOperands * 3;
412 else
413 Complexity = RawComplexity;
414
415 // FIXME: Why is this different from parseSDPatternOperatorProperties?
416 // Parse the properties.
417 Properties = 0;
418 for (const Record *Prop : R->getValueAsListOfDefs(FieldName: "Properties")) {
419 if (Prop->getName() == "SDNPHasChain") {
420 Properties |= 1 << SDNPHasChain;
421 } else if (Prop->getName() == "SDNPOptInGlue") {
422 Properties |= 1 << SDNPOptInGlue;
423 } else if (Prop->getName() == "SDNPMayStore") {
424 Properties |= 1 << SDNPMayStore;
425 } else if (Prop->getName() == "SDNPMayLoad") {
426 Properties |= 1 << SDNPMayLoad;
427 } else if (Prop->getName() == "SDNPSideEffect") {
428 Properties |= 1 << SDNPSideEffect;
429 } else if (Prop->getName() == "SDNPMemOperand") {
430 Properties |= 1 << SDNPMemOperand;
431 } else if (Prop->getName() == "SDNPVariadic") {
432 Properties |= 1 << SDNPVariadic;
433 } else {
434 PrintFatalError(ErrorLoc: R->getLoc(),
435 Msg: "Unsupported SD Node property '" + Prop->getName() +
436 "' on ComplexPattern '" + R->getName() + "'!");
437 }
438 }
439
440 WantsRoot = R->getValueAsBit(FieldName: "WantsRoot");
441 WantsParent = R->getValueAsBit(FieldName: "WantsParent");
442}
443