[Frontend] Remove unused includes (NFC) (#116927)
[llvm-project.git] / llvm / utils / TableGen / InstrInfoEmitter.cpp
blob8c0e27215a736232a2f4ef8edf303dd05be830b0
1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. --*- 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 tablegen backend is responsible for emitting a description of the target
10 // instruction set for the code generator.
12 //===----------------------------------------------------------------------===//
14 #include "Basic/SequenceToOffsetTable.h"
15 #include "Common/CodeGenDAGPatterns.h"
16 #include "Common/CodeGenInstruction.h"
17 #include "Common/CodeGenSchedule.h"
18 #include "Common/CodeGenTarget.h"
19 #include "Common/PredicateExpander.h"
20 #include "Common/SubtargetFeatureInfo.h"
21 #include "Common/Types.h"
22 #include "TableGenBackends.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/TableGen/Error.h"
30 #include "llvm/TableGen/Record.h"
31 #include "llvm/TableGen/TGTimer.h"
32 #include "llvm/TableGen/TableGenBackend.h"
33 #include <cassert>
34 #include <cstdint>
35 #include <iterator>
36 #include <map>
37 #include <string>
38 #include <utility>
39 #include <vector>
41 using namespace llvm;
43 cl::OptionCategory InstrInfoEmitterCat("Options for -gen-instr-info");
44 static cl::opt<bool> ExpandMIOperandInfo(
45 "instr-info-expand-mi-operand-info",
46 cl::desc("Expand operand's MIOperandInfo DAG into suboperands"),
47 cl::cat(InstrInfoEmitterCat), cl::init(true));
49 namespace {
51 class InstrInfoEmitter {
52 const RecordKeeper &Records;
53 const CodeGenDAGPatterns CDP;
54 const CodeGenSchedModels &SchedModels;
56 public:
57 InstrInfoEmitter(const RecordKeeper &R)
58 : Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
60 // run - Output the instruction set description.
61 void run(raw_ostream &OS);
63 private:
64 void emitEnums(raw_ostream &OS);
66 typedef std::vector<std::string> OperandInfoTy;
67 typedef std::vector<OperandInfoTy> OperandInfoListTy;
68 typedef std::map<OperandInfoTy, unsigned> OperandInfoMapTy;
70 /// The keys of this map are maps which have OpName enum values as their keys
71 /// and instruction operand indices as their values. The values of this map
72 /// are lists of instruction names.
73 typedef std::map<std::map<unsigned, unsigned>, std::vector<std::string>>
74 OpNameMapTy;
75 typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
77 /// Generate member functions in the target-specific GenInstrInfo class.
78 ///
79 /// This method is used to custom expand TIIPredicate definitions.
80 /// See file llvm/Target/TargetInstPredicates.td for a description of what is
81 /// a TIIPredicate and how to use it.
82 void emitTIIHelperMethods(raw_ostream &OS, StringRef TargetName,
83 bool ExpandDefinition = true);
85 /// Expand TIIPredicate definitions to functions that accept a const MCInst
86 /// reference.
87 void emitMCIIHelperMethods(raw_ostream &OS, StringRef TargetName);
89 /// Write verifyInstructionPredicates methods.
90 void emitFeatureVerifier(raw_ostream &OS, const CodeGenTarget &Target);
91 void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
92 const Record *InstrInfo,
93 std::map<std::vector<const Record *>, unsigned> &EL,
94 const OperandInfoMapTy &OperandInfo, raw_ostream &OS);
95 void emitOperandTypeMappings(
96 raw_ostream &OS, const CodeGenTarget &Target,
97 ArrayRef<const CodeGenInstruction *> NumberedInstructions);
98 void
99 initOperandMapData(ArrayRef<const CodeGenInstruction *> NumberedInstructions,
100 StringRef Namespace,
101 std::map<std::string, unsigned> &Operands,
102 OpNameMapTy &OperandMap);
103 void emitOperandNameMappings(
104 raw_ostream &OS, const CodeGenTarget &Target,
105 ArrayRef<const CodeGenInstruction *> NumberedInstructions);
107 void emitLogicalOperandSizeMappings(
108 raw_ostream &OS, StringRef Namespace,
109 ArrayRef<const CodeGenInstruction *> NumberedInstructions);
110 void emitLogicalOperandTypeMappings(
111 raw_ostream &OS, StringRef Namespace,
112 ArrayRef<const CodeGenInstruction *> NumberedInstructions);
114 // Operand information.
115 unsigned CollectOperandInfo(OperandInfoListTy &OperandInfoList,
116 OperandInfoMapTy &OperandInfoMap);
117 void EmitOperandInfo(raw_ostream &OS, OperandInfoListTy &OperandInfoList);
118 OperandInfoTy GetOperandInfo(const CodeGenInstruction &Inst);
121 } // end anonymous namespace
123 //===----------------------------------------------------------------------===//
124 // Operand Info Emission.
125 //===----------------------------------------------------------------------===//
127 InstrInfoEmitter::OperandInfoTy
128 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
129 OperandInfoTy Result;
131 for (auto &Op : Inst.Operands) {
132 // Handle aggregate operands and normal operands the same way by expanding
133 // either case into a list of operands for this op.
134 std::vector<CGIOperandList::OperandInfo> OperandList;
136 // This might be a multiple operand thing. Targets like X86 have
137 // registers in their multi-operand operands. It may also be an anonymous
138 // operand, which has a single operand, but no declared class for the
139 // operand.
140 const DagInit *MIOI = Op.MIOperandInfo;
142 if (!MIOI || MIOI->getNumArgs() == 0) {
143 // Single, anonymous, operand.
144 OperandList.push_back(Op);
145 } else {
146 for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) {
147 OperandList.push_back(Op);
149 auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
150 OperandList.back().Rec = OpR;
154 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
155 const Record *OpR = OperandList[j].Rec;
156 std::string Res;
158 if (OpR->isSubClassOf("RegisterOperand"))
159 OpR = OpR->getValueAsDef("RegClass");
160 if (OpR->isSubClassOf("RegisterClass"))
161 Res += getQualifiedName(OpR) + "RegClassID, ";
162 else if (OpR->isSubClassOf("PointerLikeRegClass"))
163 Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
164 else
165 // -1 means the operand does not have a fixed register class.
166 Res += "-1, ";
168 // Fill in applicable flags.
169 Res += "0";
171 // Ptr value whose register class is resolved via callback.
172 if (OpR->isSubClassOf("PointerLikeRegClass"))
173 Res += "|(1<<MCOI::LookupPtrRegClass)";
175 // Predicate operands. Check to see if the original unexpanded operand
176 // was of type PredicateOp.
177 if (Op.Rec->isSubClassOf("PredicateOp"))
178 Res += "|(1<<MCOI::Predicate)";
180 // Optional def operands. Check to see if the original unexpanded operand
181 // was of type OptionalDefOperand.
182 if (Op.Rec->isSubClassOf("OptionalDefOperand"))
183 Res += "|(1<<MCOI::OptionalDef)";
185 // Branch target operands. Check to see if the original unexpanded
186 // operand was of type BranchTargetOperand.
187 if (Op.Rec->isSubClassOf("BranchTargetOperand"))
188 Res += "|(1<<MCOI::BranchTarget)";
190 // Fill in operand type.
191 Res += ", ";
192 assert(!Op.OperandType.empty() && "Invalid operand type.");
193 Res += Op.OperandType;
195 // Fill in constraint info.
196 Res += ", ";
198 const CGIOperandList::ConstraintInfo &Constraint = Op.Constraints[j];
199 if (Constraint.isNone())
200 Res += "0";
201 else if (Constraint.isEarlyClobber())
202 Res += "MCOI_EARLY_CLOBBER";
203 else {
204 assert(Constraint.isTied());
205 Res += "MCOI_TIED_TO(" + utostr(Constraint.getTiedOperand()) + ")";
208 Result.push_back(Res);
212 return Result;
215 unsigned
216 InstrInfoEmitter::CollectOperandInfo(OperandInfoListTy &OperandInfoList,
217 OperandInfoMapTy &OperandInfoMap) {
218 const CodeGenTarget &Target = CDP.getTargetInfo();
219 unsigned Offset = 0;
220 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
221 OperandInfoTy OperandInfo = GetOperandInfo(*Inst);
222 if (OperandInfoMap.insert({OperandInfo, Offset}).second) {
223 OperandInfoList.push_back(OperandInfo);
224 Offset += OperandInfo.size();
227 return Offset;
230 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
231 OperandInfoListTy &OperandInfoList) {
232 unsigned Offset = 0;
233 for (auto &OperandInfo : OperandInfoList) {
234 OS << " /* " << Offset << " */";
235 for (auto &Info : OperandInfo)
236 OS << " { " << Info << " },";
237 OS << '\n';
238 Offset += OperandInfo.size();
242 /// Initialize data structures for generating operand name mappings.
244 /// \param Operands [out] A map used to generate the OpName enum with operand
245 /// names as its keys and operand enum values as its values.
246 /// \param OperandMap [out] A map for representing the operand name mappings for
247 /// each instructions. This is used to generate the OperandMap table as
248 /// well as the getNamedOperandIdx() function.
249 void InstrInfoEmitter::initOperandMapData(
250 ArrayRef<const CodeGenInstruction *> NumberedInstructions,
251 StringRef Namespace, std::map<std::string, unsigned> &Operands,
252 OpNameMapTy &OperandMap) {
253 unsigned NumOperands = 0;
254 for (const CodeGenInstruction *Inst : NumberedInstructions) {
255 if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
256 continue;
257 std::map<unsigned, unsigned> OpList;
258 for (const auto &Info : Inst->Operands) {
259 StrUintMapIter I = Operands.find(Info.Name);
261 if (I == Operands.end()) {
262 I = Operands.insert(Operands.begin(), std::pair<std::string, unsigned>(
263 Info.Name, NumOperands++));
265 OpList[I->second] = Info.MIOperandNo;
267 OperandMap[OpList].push_back(Namespace.str() +
268 "::" + Inst->TheDef->getName().str());
272 /// Generate a table and function for looking up the indices of operands by
273 /// name.
275 /// This code generates:
276 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
277 /// for each operand name.
278 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
279 /// operand indices.
280 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
281 /// for looking up the operand index for an instruction, given a value from
282 /// OpName enum
283 void InstrInfoEmitter::emitOperandNameMappings(
284 raw_ostream &OS, const CodeGenTarget &Target,
285 ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
286 StringRef Namespace = Target.getInstNamespace();
287 std::string OpNameNS = "OpName";
288 // Map of operand names to their enumeration value. This will be used to
289 // generate the OpName enum.
290 std::map<std::string, unsigned> Operands;
291 OpNameMapTy OperandMap;
293 initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
295 OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
296 OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
297 OS << "namespace llvm {\n";
298 OS << "namespace " << Namespace << " {\n";
299 OS << "namespace " << OpNameNS << " {\n";
300 OS << "enum {\n";
301 for (const auto &Op : Operands)
302 OS << " " << Op.first << " = " << Op.second << ",\n";
304 OS << " OPERAND_LAST";
305 OS << "\n};\n";
306 OS << "} // end namespace OpName\n";
307 OS << "} // end namespace " << Namespace << "\n";
308 OS << "} // end namespace llvm\n";
309 OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n";
311 OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
312 OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
313 OS << "namespace llvm {\n";
314 OS << "namespace " << Namespace << " {\n";
315 OS << "LLVM_READONLY\n";
316 OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
317 if (!Operands.empty()) {
318 OS << " static const int16_t OperandMap [][" << Operands.size()
319 << "] = {\n";
320 for (const auto &Entry : OperandMap) {
321 const std::map<unsigned, unsigned> &OpList = Entry.first;
322 OS << "{";
324 // Emit a row of the OperandMap table
325 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
326 OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
328 OS << "},\n";
330 OS << "};\n";
332 OS << " switch(Opcode) {\n";
333 unsigned TableIndex = 0;
334 for (const auto &Entry : OperandMap) {
335 for (const std::string &Name : Entry.second)
336 OS << " case " << Name << ":\n";
338 OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
340 OS << " default: return -1;\n";
341 OS << " }\n";
342 } else {
343 // There are no operands, so no need to emit anything
344 OS << " return -1;\n";
346 OS << "}\n";
347 OS << "} // end namespace " << Namespace << "\n";
348 OS << "} // end namespace llvm\n";
349 OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n";
352 /// Generate an enum for all the operand types for this target, under the
353 /// llvm::TargetNamespace::OpTypes namespace.
354 /// Operand types are all definitions derived of the Operand Target.td class.
355 void InstrInfoEmitter::emitOperandTypeMappings(
356 raw_ostream &OS, const CodeGenTarget &Target,
357 ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
359 StringRef Namespace = Target.getInstNamespace();
360 ArrayRef<const Record *> Operands =
361 Records.getAllDerivedDefinitions("Operand");
362 ArrayRef<const Record *> RegisterOperands =
363 Records.getAllDerivedDefinitions("RegisterOperand");
364 ArrayRef<const Record *> RegisterClasses =
365 Records.getAllDerivedDefinitions("RegisterClass");
367 OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
368 OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
369 OS << "namespace llvm {\n";
370 OS << "namespace " << Namespace << " {\n";
371 OS << "namespace OpTypes {\n";
372 OS << "enum OperandType {\n";
374 unsigned EnumVal = 0;
375 for (ArrayRef<const Record *> RecordsToAdd :
376 {Operands, RegisterOperands, RegisterClasses}) {
377 for (const Record *Op : RecordsToAdd) {
378 if (!Op->isAnonymous())
379 OS << " " << Op->getName() << " = " << EnumVal << ",\n";
380 ++EnumVal;
384 OS << " OPERAND_TYPE_LIST_END"
385 << "\n};\n";
386 OS << "} // end namespace OpTypes\n";
387 OS << "} // end namespace " << Namespace << "\n";
388 OS << "} // end namespace llvm\n";
389 OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n";
391 OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n";
392 OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n";
393 OS << "namespace llvm {\n";
394 OS << "namespace " << Namespace << " {\n";
395 OS << "LLVM_READONLY\n";
396 OS << "static int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n";
397 auto getInstrName = [&](int I) -> StringRef {
398 return NumberedInstructions[I]->TheDef->getName();
400 // TODO: Factor out duplicate operand lists to compress the tables.
401 if (!NumberedInstructions.empty()) {
402 std::vector<int> OperandOffsets;
403 std::vector<const Record *> OperandRecords;
404 int CurrentOffset = 0;
405 for (const CodeGenInstruction *Inst : NumberedInstructions) {
406 OperandOffsets.push_back(CurrentOffset);
407 for (const auto &Op : Inst->Operands) {
408 const DagInit *MIOI = Op.MIOperandInfo;
409 if (!ExpandMIOperandInfo || !MIOI || MIOI->getNumArgs() == 0) {
410 // Single, anonymous, operand.
411 OperandRecords.push_back(Op.Rec);
412 ++CurrentOffset;
413 } else {
414 for (const Init *Arg : MIOI->getArgs()) {
415 OperandRecords.push_back(cast<DefInit>(Arg)->getDef());
416 ++CurrentOffset;
422 // Emit the table of offsets (indexes) into the operand type table.
423 // Size the unsigned integer offset to save space.
424 assert(OperandRecords.size() <= UINT32_MAX &&
425 "Too many operands for offset table");
426 OS << " static const " << getMinimalTypeForRange(OperandRecords.size());
427 OS << " Offsets[] = {\n";
428 for (int I = 0, E = OperandOffsets.size(); I != E; ++I) {
429 OS << " /* " << getInstrName(I) << " */\n";
430 OS << " " << OperandOffsets[I] << ",\n";
432 OS << " };\n";
434 // Add an entry for the end so that we don't need to special case it below.
435 OperandOffsets.push_back(OperandRecords.size());
437 // Emit the actual operand types in a flat table.
438 // Size the signed integer operand type to save space.
439 assert(EnumVal <= INT16_MAX &&
440 "Too many operand types for operand types table");
441 OS << "\n using namespace OpTypes;\n";
442 OS << " static";
443 OS << ((EnumVal <= INT8_MAX) ? " const int8_t" : " const int16_t");
444 OS << " OpcodeOperandTypes[] = {\n ";
445 for (int I = 0, E = OperandRecords.size(), CurOffset = 0; I != E; ++I) {
446 // We print each Opcode's operands in its own row.
447 if (I == OperandOffsets[CurOffset]) {
448 OS << "\n /* " << getInstrName(CurOffset) << " */\n ";
449 while (OperandOffsets[++CurOffset] == I)
450 OS << "/* " << getInstrName(CurOffset) << " */\n ";
452 const Record *OpR = OperandRecords[I];
453 if ((OpR->isSubClassOf("Operand") ||
454 OpR->isSubClassOf("RegisterOperand") ||
455 OpR->isSubClassOf("RegisterClass")) &&
456 !OpR->isAnonymous())
457 OS << OpR->getName();
458 else
459 OS << -1;
460 OS << ", ";
462 OS << "\n };\n";
464 OS << " return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n";
465 } else {
466 OS << " llvm_unreachable(\"No instructions defined\");\n";
468 OS << "}\n";
469 OS << "} // end namespace " << Namespace << "\n";
470 OS << "} // end namespace llvm\n";
471 OS << "#endif // GET_INSTRINFO_OPERAND_TYPE\n\n";
473 OS << "#ifdef GET_INSTRINFO_MEM_OPERAND_SIZE\n";
474 OS << "#undef GET_INSTRINFO_MEM_OPERAND_SIZE\n";
475 OS << "namespace llvm {\n";
476 OS << "namespace " << Namespace << " {\n";
477 OS << "LLVM_READONLY\n";
478 OS << "static int getMemOperandSize(int OpType) {\n";
479 OS << " switch (OpType) {\n";
480 std::map<int, SmallVector<StringRef, 0>> SizeToOperandName;
481 for (const Record *Op : Operands) {
482 if (!Op->isSubClassOf("X86MemOperand"))
483 continue;
484 if (int Size = Op->getValueAsInt("Size"))
485 SizeToOperandName[Size].push_back(Op->getName());
487 OS << " default: return 0;\n";
488 for (const auto &KV : SizeToOperandName) {
489 for (const StringRef &OperandName : KV.second)
490 OS << " case OpTypes::" << OperandName << ":\n";
491 OS << " return " << KV.first << ";\n\n";
493 OS << " }\n}\n";
494 OS << "} // end namespace " << Namespace << "\n";
495 OS << "} // end namespace llvm\n";
496 OS << "#endif // GET_INSTRINFO_MEM_OPERAND_SIZE\n\n";
499 void InstrInfoEmitter::emitLogicalOperandSizeMappings(
500 raw_ostream &OS, StringRef Namespace,
501 ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
502 std::map<std::vector<unsigned>, unsigned> LogicalOpSizeMap;
504 std::map<unsigned, std::vector<std::string>> InstMap;
506 size_t LogicalOpListSize = 0U;
507 std::vector<unsigned> LogicalOpList;
508 for (const auto *Inst : NumberedInstructions) {
509 if (!Inst->TheDef->getValueAsBit("UseLogicalOperandMappings"))
510 continue;
512 LogicalOpList.clear();
513 llvm::transform(Inst->Operands, std::back_inserter(LogicalOpList),
514 [](const CGIOperandList::OperandInfo &Op) -> unsigned {
515 auto *MIOI = Op.MIOperandInfo;
516 if (!MIOI || MIOI->getNumArgs() == 0)
517 return 1;
518 return MIOI->getNumArgs();
520 LogicalOpListSize = std::max(LogicalOpList.size(), LogicalOpListSize);
522 auto I =
523 LogicalOpSizeMap.insert({LogicalOpList, LogicalOpSizeMap.size()}).first;
524 InstMap[I->second].push_back(
525 (Namespace + "::" + Inst->TheDef->getName()).str());
528 OS << "#ifdef GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n";
529 OS << "#undef GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n";
530 OS << "namespace llvm {\n";
531 OS << "namespace " << Namespace << " {\n";
532 OS << "LLVM_READONLY static unsigned\n";
533 OS << "getLogicalOperandSize(uint16_t Opcode, uint16_t LogicalOpIdx) {\n";
534 if (!InstMap.empty()) {
535 std::vector<const std::vector<unsigned> *> LogicalOpSizeList(
536 LogicalOpSizeMap.size());
537 for (auto &P : LogicalOpSizeMap) {
538 LogicalOpSizeList[P.second] = &P.first;
540 OS << " static const unsigned SizeMap[][" << LogicalOpListSize
541 << "] = {\n";
542 for (auto &R : LogicalOpSizeList) {
543 const auto &Row = *R;
544 OS << " {";
545 int i;
546 for (i = 0; i < static_cast<int>(Row.size()); ++i) {
547 OS << Row[i] << ", ";
549 for (; i < static_cast<int>(LogicalOpListSize); ++i) {
550 OS << "0, ";
552 OS << "}, ";
553 OS << "\n";
555 OS << " };\n";
557 OS << " switch (Opcode) {\n";
558 OS << " default: return LogicalOpIdx;\n";
559 for (auto &P : InstMap) {
560 auto OpMapIdx = P.first;
561 const auto &Insts = P.second;
562 for (const auto &Inst : Insts) {
563 OS << " case " << Inst << ":\n";
565 OS << " return SizeMap[" << OpMapIdx << "][LogicalOpIdx];\n";
567 OS << " }\n";
568 } else {
569 OS << " return LogicalOpIdx;\n";
571 OS << "}\n";
573 OS << "LLVM_READONLY static inline unsigned\n";
574 OS << "getLogicalOperandIdx(uint16_t Opcode, uint16_t LogicalOpIdx) {\n";
575 OS << " auto S = 0U;\n";
576 OS << " for (auto i = 0U; i < LogicalOpIdx; ++i)\n";
577 OS << " S += getLogicalOperandSize(Opcode, i);\n";
578 OS << " return S;\n";
579 OS << "}\n";
581 OS << "} // end namespace " << Namespace << "\n";
582 OS << "} // end namespace llvm\n";
583 OS << "#endif // GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n\n";
586 void InstrInfoEmitter::emitLogicalOperandTypeMappings(
587 raw_ostream &OS, StringRef Namespace,
588 ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
589 std::map<std::vector<std::string>, unsigned> LogicalOpTypeMap;
591 std::map<unsigned, std::vector<std::string>> InstMap;
593 size_t OpTypeListSize = 0U;
594 std::vector<std::string> LogicalOpTypeList;
595 for (const auto *Inst : NumberedInstructions) {
596 if (!Inst->TheDef->getValueAsBit("UseLogicalOperandMappings"))
597 continue;
599 LogicalOpTypeList.clear();
600 for (const auto &Op : Inst->Operands) {
601 auto *OpR = Op.Rec;
602 if ((OpR->isSubClassOf("Operand") ||
603 OpR->isSubClassOf("RegisterOperand") ||
604 OpR->isSubClassOf("RegisterClass")) &&
605 !OpR->isAnonymous()) {
606 LogicalOpTypeList.push_back(
607 (Namespace + "::OpTypes::" + Op.Rec->getName()).str());
608 } else {
609 LogicalOpTypeList.push_back("-1");
612 OpTypeListSize = std::max(LogicalOpTypeList.size(), OpTypeListSize);
614 auto I =
615 LogicalOpTypeMap.insert({LogicalOpTypeList, LogicalOpTypeMap.size()})
616 .first;
617 InstMap[I->second].push_back(
618 (Namespace + "::" + Inst->TheDef->getName()).str());
621 OS << "#ifdef GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n";
622 OS << "#undef GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n";
623 OS << "namespace llvm {\n";
624 OS << "namespace " << Namespace << " {\n";
625 OS << "LLVM_READONLY static int\n";
626 OS << "getLogicalOperandType(uint16_t Opcode, uint16_t LogicalOpIdx) {\n";
627 if (!InstMap.empty()) {
628 std::vector<const std::vector<std::string> *> LogicalOpTypeList(
629 LogicalOpTypeMap.size());
630 for (auto &P : LogicalOpTypeMap) {
631 LogicalOpTypeList[P.second] = &P.first;
633 OS << " static const int TypeMap[][" << OpTypeListSize << "] = {\n";
634 for (int r = 0, rs = LogicalOpTypeList.size(); r < rs; ++r) {
635 const auto &Row = *LogicalOpTypeList[r];
636 OS << " {";
637 int i, s = Row.size();
638 for (i = 0; i < s; ++i) {
639 if (i > 0)
640 OS << ", ";
641 OS << Row[i];
643 for (; i < static_cast<int>(OpTypeListSize); ++i) {
644 if (i > 0)
645 OS << ", ";
646 OS << "-1";
648 OS << "}";
649 if (r != rs - 1)
650 OS << ",";
651 OS << "\n";
653 OS << " };\n";
655 OS << " switch (Opcode) {\n";
656 OS << " default: return -1;\n";
657 for (auto &P : InstMap) {
658 auto OpMapIdx = P.first;
659 const auto &Insts = P.second;
660 for (const auto &Inst : Insts) {
661 OS << " case " << Inst << ":\n";
663 OS << " return TypeMap[" << OpMapIdx << "][LogicalOpIdx];\n";
665 OS << " }\n";
666 } else {
667 OS << " return -1;\n";
669 OS << "}\n";
670 OS << "} // end namespace " << Namespace << "\n";
671 OS << "} // end namespace llvm\n";
672 OS << "#endif // GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n\n";
675 void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS,
676 StringRef TargetName) {
677 ArrayRef<const Record *> TIIPredicates =
678 Records.getAllDerivedDefinitions("TIIPredicate");
680 OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n";
681 OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n";
683 OS << "namespace llvm {\n";
684 OS << "class MCInst;\n";
685 OS << "class FeatureBitset;\n\n";
687 OS << "namespace " << TargetName << "_MC {\n\n";
689 for (const Record *Rec : TIIPredicates) {
690 OS << "bool " << Rec->getValueAsString("FunctionName")
691 << "(const MCInst &MI);\n";
694 OS << "void verifyInstructionPredicates(unsigned Opcode, const FeatureBitset "
695 "&Features);\n";
697 OS << "\n} // end namespace " << TargetName << "_MC\n";
698 OS << "} // end namespace llvm\n\n";
700 OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n";
702 OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n";
703 OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n";
705 OS << "namespace llvm {\n";
706 OS << "namespace " << TargetName << "_MC {\n\n";
708 PredicateExpander PE(TargetName);
709 PE.setExpandForMC(true);
711 for (const Record *Rec : TIIPredicates) {
712 OS << "bool " << Rec->getValueAsString("FunctionName");
713 OS << "(const MCInst &MI) {\n";
715 OS << PE.getIndent();
716 PE.expandStatement(OS, Rec->getValueAsDef("Body"));
717 OS << "\n}\n\n";
720 OS << "} // end namespace " << TargetName << "_MC\n";
721 OS << "} // end namespace llvm\n\n";
723 OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n\n";
726 static std::string
727 getNameForFeatureBitset(ArrayRef<const Record *> FeatureBitset) {
728 std::string Name = "CEFBS";
729 for (const Record *Feature : FeatureBitset)
730 Name += ("_" + Feature->getName()).str();
731 return Name;
734 void InstrInfoEmitter::emitFeatureVerifier(raw_ostream &OS,
735 const CodeGenTarget &Target) {
736 const auto &All = SubtargetFeatureInfo::getAll(Records);
737 SubtargetFeatureInfoMap SubtargetFeatures;
738 SubtargetFeatures.insert(All.begin(), All.end());
740 OS << "#if (defined(ENABLE_INSTR_PREDICATE_VERIFIER) && !defined(NDEBUG)) "
741 << "||\\\n"
742 << " defined(GET_AVAILABLE_OPCODE_CHECKER)\n"
743 << "#define GET_COMPUTE_FEATURES\n"
744 << "#endif\n";
745 OS << "#ifdef GET_COMPUTE_FEATURES\n"
746 << "#undef GET_COMPUTE_FEATURES\n"
747 << "namespace llvm {\n"
748 << "namespace " << Target.getName() << "_MC {\n\n";
750 // Emit the subtarget feature enumeration.
751 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
752 OS);
753 // Emit the available features compute function.
754 OS << "inline ";
755 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
756 Target.getName(), "", "computeAvailableFeatures", SubtargetFeatures, OS);
758 std::vector<std::vector<const Record *>> FeatureBitsets;
759 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
760 FeatureBitsets.emplace_back();
761 for (const Record *Predicate :
762 Inst->TheDef->getValueAsListOfDefs("Predicates")) {
763 const auto &I = SubtargetFeatures.find(Predicate);
764 if (I != SubtargetFeatures.end())
765 FeatureBitsets.back().push_back(I->second.TheDef);
769 llvm::sort(FeatureBitsets, [&](ArrayRef<const Record *> A,
770 ArrayRef<const Record *> B) {
771 if (A.size() < B.size())
772 return true;
773 if (A.size() > B.size())
774 return false;
775 for (auto Pair : zip(A, B)) {
776 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
777 return true;
778 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
779 return false;
781 return false;
783 FeatureBitsets.erase(llvm::unique(FeatureBitsets), FeatureBitsets.end());
784 OS << "inline FeatureBitset computeRequiredFeatures(unsigned Opcode) {\n"
785 << " enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
786 << " CEFBS_None,\n";
787 for (const auto &FeatureBitset : FeatureBitsets) {
788 if (FeatureBitset.empty())
789 continue;
790 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
792 OS << " };\n\n"
793 << " static constexpr FeatureBitset FeatureBitsets[] = {\n"
794 << " {}, // CEFBS_None\n";
795 for (const auto &FeatureBitset : FeatureBitsets) {
796 if (FeatureBitset.empty())
797 continue;
798 OS << " {";
799 for (const auto &Feature : FeatureBitset) {
800 const auto &I = SubtargetFeatures.find(Feature);
801 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
802 OS << I->second.getEnumBitName() << ", ";
804 OS << "},\n";
806 OS << " };\n"
807 << " static constexpr " << getMinimalTypeForRange(FeatureBitsets.size())
808 << " RequiredFeaturesRefs[] = {\n";
809 unsigned InstIdx = 0;
810 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
811 OS << " CEFBS";
812 unsigned NumPredicates = 0;
813 for (const Record *Predicate :
814 Inst->TheDef->getValueAsListOfDefs("Predicates")) {
815 const auto &I = SubtargetFeatures.find(Predicate);
816 if (I != SubtargetFeatures.end()) {
817 OS << '_' << I->second.TheDef->getName();
818 NumPredicates++;
821 if (!NumPredicates)
822 OS << "_None";
823 OS << ", // " << Inst->TheDef->getName() << " = " << InstIdx << "\n";
824 InstIdx++;
826 OS << " };\n\n"
827 << " assert(Opcode < " << InstIdx << ");\n"
828 << " return FeatureBitsets[RequiredFeaturesRefs[Opcode]];\n"
829 << "}\n\n";
831 OS << "} // end namespace " << Target.getName() << "_MC\n"
832 << "} // end namespace llvm\n"
833 << "#endif // GET_COMPUTE_FEATURES\n\n";
835 OS << "#ifdef GET_AVAILABLE_OPCODE_CHECKER\n"
836 << "#undef GET_AVAILABLE_OPCODE_CHECKER\n"
837 << "namespace llvm {\n"
838 << "namespace " << Target.getName() << "_MC {\n";
839 OS << "bool isOpcodeAvailable("
840 << "unsigned Opcode, const FeatureBitset &Features) {\n"
841 << " FeatureBitset AvailableFeatures = "
842 << "computeAvailableFeatures(Features);\n"
843 << " FeatureBitset RequiredFeatures = "
844 << "computeRequiredFeatures(Opcode);\n"
845 << " FeatureBitset MissingFeatures =\n"
846 << " (AvailableFeatures & RequiredFeatures) ^\n"
847 << " RequiredFeatures;\n"
848 << " return !MissingFeatures.any();\n"
849 << "}\n";
850 OS << "} // end namespace " << Target.getName() << "_MC\n"
851 << "} // end namespace llvm\n"
852 << "#endif // GET_AVAILABLE_OPCODE_CHECKER\n\n";
854 OS << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n"
855 << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n"
856 << "#include <sstream>\n\n";
858 OS << "namespace llvm {\n";
859 OS << "namespace " << Target.getName() << "_MC {\n\n";
861 // Emit the name table for error messages.
862 OS << "#ifndef NDEBUG\n";
863 SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, OS);
864 OS << "#endif // NDEBUG\n\n";
866 // Emit the predicate verifier.
867 OS << "void verifyInstructionPredicates(\n"
868 << " unsigned Opcode, const FeatureBitset &Features) {\n"
869 << "#ifndef NDEBUG\n";
870 OS << " FeatureBitset AvailableFeatures = "
871 "computeAvailableFeatures(Features);\n";
872 OS << " FeatureBitset RequiredFeatures = "
873 << "computeRequiredFeatures(Opcode);\n";
874 OS << " FeatureBitset MissingFeatures =\n"
875 << " (AvailableFeatures & RequiredFeatures) ^\n"
876 << " RequiredFeatures;\n"
877 << " if (MissingFeatures.any()) {\n"
878 << " std::ostringstream Msg;\n"
879 << " Msg << \"Attempting to emit \" << &" << Target.getName()
880 << "InstrNameData[" << Target.getName() << "InstrNameIndices[Opcode]]\n"
881 << " << \" instruction but the \";\n"
882 << " for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)\n"
883 << " if (MissingFeatures.test(i))\n"
884 << " Msg << SubtargetFeatureNames[i] << \" \";\n"
885 << " Msg << \"predicate(s) are not met\";\n"
886 << " report_fatal_error(Msg.str().c_str());\n"
887 << " }\n"
888 << "#endif // NDEBUG\n";
889 OS << "}\n";
890 OS << "} // end namespace " << Target.getName() << "_MC\n";
891 OS << "} // end namespace llvm\n";
892 OS << "#endif // ENABLE_INSTR_PREDICATE_VERIFIER\n\n";
895 void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS,
896 StringRef TargetName,
897 bool ExpandDefinition) {
898 ArrayRef<const Record *> TIIPredicates =
899 Records.getAllDerivedDefinitions("TIIPredicate");
900 if (TIIPredicates.empty())
901 return;
903 PredicateExpander PE(TargetName);
904 PE.setExpandForMC(false);
906 for (const Record *Rec : TIIPredicates) {
907 OS << (ExpandDefinition ? "" : "static ") << "bool ";
908 if (ExpandDefinition)
909 OS << TargetName << "InstrInfo::";
910 OS << Rec->getValueAsString("FunctionName");
911 OS << "(const MachineInstr &MI)";
912 if (!ExpandDefinition) {
913 OS << ";\n";
914 continue;
917 OS << " {\n";
918 OS << PE.getIndent();
919 PE.expandStatement(OS, Rec->getValueAsDef("Body"));
920 OS << "\n}\n\n";
924 //===----------------------------------------------------------------------===//
925 // Main Output.
926 //===----------------------------------------------------------------------===//
928 // run - Emit the main instruction description records for the target...
929 void InstrInfoEmitter::run(raw_ostream &OS) {
930 emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS);
931 emitEnums(OS);
933 const CodeGenTarget &Target = CDP.getTargetInfo();
934 const std::string &TargetName = std::string(Target.getName());
935 const Record *InstrInfo = Target.getInstructionSet();
937 // Collect all of the operand info records.
938 TGTimer &Timer = Records.getTimer();
939 Timer.startTimer("Collect operand info");
940 OperandInfoListTy OperandInfoList;
941 OperandInfoMapTy OperandInfoMap;
942 unsigned OperandInfoSize =
943 CollectOperandInfo(OperandInfoList, OperandInfoMap);
945 // Collect all of the instruction's implicit uses and defs.
946 Timer.startTimer("Collect uses/defs");
947 std::map<std::vector<const Record *>, unsigned> EmittedLists;
948 std::vector<std::vector<const Record *>> ImplicitLists;
949 unsigned ImplicitListSize = 0;
950 for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) {
951 std::vector<const Record *> ImplicitOps = II->ImplicitUses;
952 llvm::append_range(ImplicitOps, II->ImplicitDefs);
953 if (EmittedLists.insert({ImplicitOps, ImplicitListSize}).second) {
954 ImplicitLists.push_back(ImplicitOps);
955 ImplicitListSize += ImplicitOps.size();
959 ArrayRef<const CodeGenInstruction *> NumberedInstructions =
960 Target.getInstructionsByEnumValue();
961 OS << "#if defined(GET_INSTRINFO_MC_DESC) || "
962 "defined(GET_INSTRINFO_CTOR_DTOR)\n";
963 OS << "namespace llvm {\n\n";
965 OS << "struct " << TargetName << "InstrTable {\n";
966 OS << " MCInstrDesc Insts[" << NumberedInstructions.size() << "];\n";
967 OS << " static_assert(alignof(MCInstrDesc) >= alignof(MCOperandInfo), "
968 "\"Unwanted padding between Insts and OperandInfo\");\n";
969 OS << " MCOperandInfo OperandInfo[" << OperandInfoSize << "];\n";
970 OS << " static_assert(alignof(MCOperandInfo) >= alignof(MCPhysReg), "
971 "\"Unwanted padding between OperandInfo and ImplicitOps\");\n";
972 OS << " MCPhysReg ImplicitOps[" << std::max(ImplicitListSize, 1U) << "];\n";
973 OS << "};\n\n";
975 OS << "} // end namespace llvm\n";
976 OS << "#endif // defined(GET_INSTRINFO_MC_DESC) || "
977 "defined(GET_INSTRINFO_CTOR_DTOR)\n\n";
979 OS << "#ifdef GET_INSTRINFO_MC_DESC\n";
980 OS << "#undef GET_INSTRINFO_MC_DESC\n";
981 OS << "namespace llvm {\n\n";
983 // Emit all of the MCInstrDesc records in reverse ENUM ordering.
984 Timer.startTimer("Emit InstrDesc records");
985 OS << "static_assert(sizeof(MCOperandInfo) % sizeof(MCPhysReg) == 0);\n";
986 OS << "static constexpr unsigned " << TargetName << "ImpOpBase = sizeof "
987 << TargetName << "InstrTable::OperandInfo / (sizeof(MCPhysReg));\n\n";
989 OS << "extern const " << TargetName << "InstrTable " << TargetName
990 << "Descs = {\n {\n";
991 SequenceToOffsetTable<std::string> InstrNames;
992 unsigned Num = NumberedInstructions.size();
993 for (const CodeGenInstruction *Inst : reverse(NumberedInstructions)) {
994 // Keep a list of the instruction names.
995 InstrNames.add(std::string(Inst->TheDef->getName()));
996 // Emit the record into the table.
997 emitRecord(*Inst, --Num, InstrInfo, EmittedLists, OperandInfoMap, OS);
1000 OS << " }, {\n";
1002 // Emit all of the operand info records.
1003 Timer.startTimer("Emit operand info");
1004 EmitOperandInfo(OS, OperandInfoList);
1006 OS << " }, {\n";
1008 // Emit all of the instruction's implicit uses and defs.
1009 Timer.startTimer("Emit uses/defs");
1010 for (auto &List : ImplicitLists) {
1011 OS << " /* " << EmittedLists[List] << " */";
1012 for (auto &Reg : List)
1013 OS << ' ' << getQualifiedName(Reg) << ',';
1014 OS << '\n';
1017 OS << " }\n};\n\n";
1019 // Emit the array of instruction names.
1020 Timer.startTimer("Emit instruction names");
1021 InstrNames.layout();
1022 InstrNames.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
1023 "InstrNameData[]");
1025 OS << "extern const unsigned " << TargetName << "InstrNameIndices[] = {";
1026 Num = 0;
1027 for (const CodeGenInstruction *Inst : NumberedInstructions) {
1028 // Newline every eight entries.
1029 if (Num % 8 == 0)
1030 OS << "\n ";
1031 OS << InstrNames.get(std::string(Inst->TheDef->getName())) << "U, ";
1032 ++Num;
1034 OS << "\n};\n\n";
1036 bool HasDeprecationFeatures =
1037 llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
1038 return !Inst->HasComplexDeprecationPredicate &&
1039 !Inst->DeprecatedReason.empty();
1041 if (HasDeprecationFeatures) {
1042 OS << "extern const uint8_t " << TargetName
1043 << "InstrDeprecationFeatures[] = {";
1044 Num = 0;
1045 for (const CodeGenInstruction *Inst : NumberedInstructions) {
1046 if (Num % 8 == 0)
1047 OS << "\n ";
1048 if (!Inst->HasComplexDeprecationPredicate &&
1049 !Inst->DeprecatedReason.empty())
1050 OS << Target.getInstNamespace() << "::" << Inst->DeprecatedReason
1051 << ", ";
1052 else
1053 OS << "uint8_t(-1), ";
1054 ++Num;
1056 OS << "\n};\n\n";
1059 bool HasComplexDeprecationInfos =
1060 llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
1061 return Inst->HasComplexDeprecationPredicate;
1063 if (HasComplexDeprecationInfos) {
1064 OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
1065 << "InstrComplexDeprecationInfos[] = {";
1066 Num = 0;
1067 for (const CodeGenInstruction *Inst : NumberedInstructions) {
1068 if (Num % 8 == 0)
1069 OS << "\n ";
1070 if (Inst->HasComplexDeprecationPredicate)
1071 // Emit a function pointer to the complex predicate method.
1072 OS << "&get" << Inst->DeprecatedReason << "DeprecationInfo, ";
1073 else
1074 OS << "nullptr, ";
1075 ++Num;
1077 OS << "\n};\n\n";
1080 // MCInstrInfo initialization routine.
1081 Timer.startTimer("Emit initialization routine");
1082 OS << "static inline void Init" << TargetName
1083 << "MCInstrInfo(MCInstrInfo *II) {\n";
1084 OS << " II->InitMCInstrInfo(" << TargetName << "Descs.Insts, " << TargetName
1085 << "InstrNameIndices, " << TargetName << "InstrNameData, ";
1086 if (HasDeprecationFeatures)
1087 OS << TargetName << "InstrDeprecationFeatures, ";
1088 else
1089 OS << "nullptr, ";
1090 if (HasComplexDeprecationInfos)
1091 OS << TargetName << "InstrComplexDeprecationInfos, ";
1092 else
1093 OS << "nullptr, ";
1094 OS << NumberedInstructions.size() << ");\n}\n\n";
1096 OS << "} // end namespace llvm\n";
1098 OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
1100 // Create a TargetInstrInfo subclass to hide the MC layer initialization.
1101 OS << "#ifdef GET_INSTRINFO_HEADER\n";
1102 OS << "#undef GET_INSTRINFO_HEADER\n";
1104 std::string ClassName = TargetName + "GenInstrInfo";
1105 OS << "namespace llvm {\n";
1106 OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
1107 << " explicit " << ClassName
1108 << "(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u, "
1109 "unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u);\n"
1110 << " ~" << ClassName << "() override = default;\n";
1112 OS << "\n};\n} // end namespace llvm\n";
1114 OS << "#endif // GET_INSTRINFO_HEADER\n\n";
1116 OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n";
1117 OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n";
1118 emitTIIHelperMethods(OS, TargetName, /* ExpandDefinition = */ false);
1119 OS << "\n";
1120 OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n";
1122 OS << "#ifdef GET_INSTRINFO_HELPERS\n";
1123 OS << "#undef GET_INSTRINFO_HELPERS\n\n";
1124 emitTIIHelperMethods(OS, TargetName, /* ExpandDefinition = */ true);
1125 OS << "#endif // GET_INSTRINFO_HELPERS\n\n";
1127 OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n";
1128 OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
1130 OS << "namespace llvm {\n";
1131 OS << "extern const " << TargetName << "InstrTable " << TargetName
1132 << "Descs;\n";
1133 OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
1134 OS << "extern const char " << TargetName << "InstrNameData[];\n";
1135 if (HasDeprecationFeatures)
1136 OS << "extern const uint8_t " << TargetName
1137 << "InstrDeprecationFeatures[];\n";
1138 if (HasComplexDeprecationInfos)
1139 OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
1140 << "InstrComplexDeprecationInfos[];\n";
1141 OS << ClassName << "::" << ClassName
1142 << "(unsigned CFSetupOpcode, unsigned CFDestroyOpcode, unsigned "
1143 "CatchRetOpcode, unsigned ReturnOpcode)\n"
1144 << " : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, "
1145 "ReturnOpcode) {\n"
1146 << " InitMCInstrInfo(" << TargetName << "Descs.Insts, " << TargetName
1147 << "InstrNameIndices, " << TargetName << "InstrNameData, ";
1148 if (HasDeprecationFeatures)
1149 OS << TargetName << "InstrDeprecationFeatures, ";
1150 else
1151 OS << "nullptr, ";
1152 if (HasComplexDeprecationInfos)
1153 OS << TargetName << "InstrComplexDeprecationInfos, ";
1154 else
1155 OS << "nullptr, ";
1156 OS << NumberedInstructions.size() << ");\n}\n";
1157 OS << "} // end namespace llvm\n";
1159 OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
1161 Timer.startTimer("Emit operand name mappings");
1162 emitOperandNameMappings(OS, Target, NumberedInstructions);
1164 Timer.startTimer("Emit operand type mappings");
1165 emitOperandTypeMappings(OS, Target, NumberedInstructions);
1167 Timer.startTimer("Emit logical operand size mappings");
1168 emitLogicalOperandSizeMappings(OS, TargetName, NumberedInstructions);
1170 Timer.startTimer("Emit logical operand type mappings");
1171 emitLogicalOperandTypeMappings(OS, TargetName, NumberedInstructions);
1173 Timer.startTimer("Emit helper methods");
1174 emitMCIIHelperMethods(OS, TargetName);
1176 Timer.startTimer("Emit verifier methods");
1177 emitFeatureVerifier(OS, Target);
1180 void InstrInfoEmitter::emitRecord(
1181 const CodeGenInstruction &Inst, unsigned Num, const Record *InstrInfo,
1182 std::map<std::vector<const Record *>, unsigned> &EmittedLists,
1183 const OperandInfoMapTy &OperandInfoMap, raw_ostream &OS) {
1184 int MinOperands = 0;
1185 if (!Inst.Operands.empty())
1186 // Each logical operand can be multiple MI operands.
1187 MinOperands =
1188 Inst.Operands.back().MIOperandNo + Inst.Operands.back().MINumOperands;
1189 // Even the logical output operand may be multiple MI operands.
1190 int DefOperands = 0;
1191 if (Inst.Operands.NumDefs) {
1192 auto &Opnd = Inst.Operands[Inst.Operands.NumDefs - 1];
1193 DefOperands = Opnd.MIOperandNo + Opnd.MINumOperands;
1196 OS << " { ";
1197 OS << Num << ",\t" << MinOperands << ",\t" << DefOperands << ",\t"
1198 << Inst.TheDef->getValueAsInt("Size") << ",\t"
1199 << SchedModels.getSchedClassIdx(Inst) << ",\t";
1201 const CodeGenTarget &Target = CDP.getTargetInfo();
1203 // Emit the implicit use/def list...
1204 OS << Inst.ImplicitUses.size() << ",\t" << Inst.ImplicitDefs.size() << ",\t";
1205 std::vector<const Record *> ImplicitOps = Inst.ImplicitUses;
1206 llvm::append_range(ImplicitOps, Inst.ImplicitDefs);
1207 OS << Target.getName() << "ImpOpBase + " << EmittedLists[ImplicitOps]
1208 << ",\t";
1210 // Emit the operand info offset.
1211 OperandInfoTy OperandInfo = GetOperandInfo(Inst);
1212 OS << OperandInfoMap.find(OperandInfo)->second << ",\t0";
1214 // Emit all of the target independent flags...
1215 if (Inst.isPreISelOpcode)
1216 OS << "|(1ULL<<MCID::PreISelOpcode)";
1217 if (Inst.isPseudo)
1218 OS << "|(1ULL<<MCID::Pseudo)";
1219 if (Inst.isMeta)
1220 OS << "|(1ULL<<MCID::Meta)";
1221 if (Inst.isReturn)
1222 OS << "|(1ULL<<MCID::Return)";
1223 if (Inst.isEHScopeReturn)
1224 OS << "|(1ULL<<MCID::EHScopeReturn)";
1225 if (Inst.isBranch)
1226 OS << "|(1ULL<<MCID::Branch)";
1227 if (Inst.isIndirectBranch)
1228 OS << "|(1ULL<<MCID::IndirectBranch)";
1229 if (Inst.isCompare)
1230 OS << "|(1ULL<<MCID::Compare)";
1231 if (Inst.isMoveImm)
1232 OS << "|(1ULL<<MCID::MoveImm)";
1233 if (Inst.isMoveReg)
1234 OS << "|(1ULL<<MCID::MoveReg)";
1235 if (Inst.isBitcast)
1236 OS << "|(1ULL<<MCID::Bitcast)";
1237 if (Inst.isAdd)
1238 OS << "|(1ULL<<MCID::Add)";
1239 if (Inst.isTrap)
1240 OS << "|(1ULL<<MCID::Trap)";
1241 if (Inst.isSelect)
1242 OS << "|(1ULL<<MCID::Select)";
1243 if (Inst.isBarrier)
1244 OS << "|(1ULL<<MCID::Barrier)";
1245 if (Inst.hasDelaySlot)
1246 OS << "|(1ULL<<MCID::DelaySlot)";
1247 if (Inst.isCall)
1248 OS << "|(1ULL<<MCID::Call)";
1249 if (Inst.canFoldAsLoad)
1250 OS << "|(1ULL<<MCID::FoldableAsLoad)";
1251 if (Inst.mayLoad)
1252 OS << "|(1ULL<<MCID::MayLoad)";
1253 if (Inst.mayStore)
1254 OS << "|(1ULL<<MCID::MayStore)";
1255 if (Inst.mayRaiseFPException)
1256 OS << "|(1ULL<<MCID::MayRaiseFPException)";
1257 if (Inst.isPredicable)
1258 OS << "|(1ULL<<MCID::Predicable)";
1259 if (Inst.isConvertibleToThreeAddress)
1260 OS << "|(1ULL<<MCID::ConvertibleTo3Addr)";
1261 if (Inst.isCommutable)
1262 OS << "|(1ULL<<MCID::Commutable)";
1263 if (Inst.isTerminator)
1264 OS << "|(1ULL<<MCID::Terminator)";
1265 if (Inst.isReMaterializable)
1266 OS << "|(1ULL<<MCID::Rematerializable)";
1267 if (Inst.isNotDuplicable)
1268 OS << "|(1ULL<<MCID::NotDuplicable)";
1269 if (Inst.Operands.hasOptionalDef)
1270 OS << "|(1ULL<<MCID::HasOptionalDef)";
1271 if (Inst.usesCustomInserter)
1272 OS << "|(1ULL<<MCID::UsesCustomInserter)";
1273 if (Inst.hasPostISelHook)
1274 OS << "|(1ULL<<MCID::HasPostISelHook)";
1275 if (Inst.Operands.isVariadic)
1276 OS << "|(1ULL<<MCID::Variadic)";
1277 if (Inst.hasSideEffects)
1278 OS << "|(1ULL<<MCID::UnmodeledSideEffects)";
1279 if (Inst.isAsCheapAsAMove)
1280 OS << "|(1ULL<<MCID::CheapAsAMove)";
1281 if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq)
1282 OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)";
1283 if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq)
1284 OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)";
1285 if (Inst.isRegSequence)
1286 OS << "|(1ULL<<MCID::RegSequence)";
1287 if (Inst.isExtractSubreg)
1288 OS << "|(1ULL<<MCID::ExtractSubreg)";
1289 if (Inst.isInsertSubreg)
1290 OS << "|(1ULL<<MCID::InsertSubreg)";
1291 if (Inst.isConvergent)
1292 OS << "|(1ULL<<MCID::Convergent)";
1293 if (Inst.variadicOpsAreDefs)
1294 OS << "|(1ULL<<MCID::VariadicOpsAreDefs)";
1295 if (Inst.isAuthenticated)
1296 OS << "|(1ULL<<MCID::Authenticated)";
1298 // Emit all of the target-specific flags...
1299 const BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
1300 if (!TSF)
1301 PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?");
1302 uint64_t Value = 0;
1303 for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
1304 if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
1305 Value |= uint64_t(Bit->getValue()) << i;
1306 else
1307 PrintFatalError(Inst.TheDef->getLoc(),
1308 "Invalid TSFlags bit in " + Inst.TheDef->getName());
1310 OS << ", 0x";
1311 OS.write_hex(Value);
1312 OS << "ULL";
1314 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
1317 // emitEnums - Print out enum values for all of the instructions.
1318 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
1319 OS << "#ifdef GET_INSTRINFO_ENUM\n";
1320 OS << "#undef GET_INSTRINFO_ENUM\n";
1322 OS << "namespace llvm {\n\n";
1324 const CodeGenTarget &Target = CDP.getTargetInfo();
1326 // We must emit the PHI opcode first...
1327 StringRef Namespace = Target.getInstNamespace();
1329 if (Namespace.empty())
1330 PrintFatalError("No instructions defined!");
1332 OS << "namespace " << Namespace << " {\n";
1333 OS << " enum {\n";
1334 unsigned Num = 0;
1335 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue())
1336 OS << " " << Inst->TheDef->getName()
1337 << "\t= " << (Num = Target.getInstrIntValue(Inst->TheDef)) << ",\n";
1338 OS << " INSTRUCTION_LIST_END = " << Num + 1 << "\n";
1339 OS << " };\n\n";
1340 OS << "} // end namespace " << Namespace << "\n";
1341 OS << "} // end namespace llvm\n";
1342 OS << "#endif // GET_INSTRINFO_ENUM\n\n";
1344 OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n";
1345 OS << "#undef GET_INSTRINFO_SCHED_ENUM\n";
1346 OS << "namespace llvm {\n\n";
1347 OS << "namespace " << Namespace << " {\n";
1348 OS << "namespace Sched {\n";
1349 OS << " enum {\n";
1350 Num = 0;
1351 for (const auto &Class : SchedModels.explicit_classes())
1352 OS << " " << Class.Name << "\t= " << Num++ << ",\n";
1353 OS << " SCHED_LIST_END = " << Num << "\n";
1354 OS << " };\n";
1355 OS << "} // end namespace Sched\n";
1356 OS << "} // end namespace " << Namespace << "\n";
1357 OS << "} // end namespace llvm\n";
1359 OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n";
1362 static void EmitInstrInfo(const RecordKeeper &Records, raw_ostream &OS) {
1363 TGTimer &Timer = Records.getTimer();
1364 Timer.startTimer("Analyze DAG patterns");
1365 InstrInfoEmitter(Records).run(OS);
1366 Timer.startTimer("Emit map table");
1367 EmitMapTable(Records, OS);
1370 static TableGen::Emitter::Opt X("gen-instr-info", EmitInstrInfo,
1371 "Generate instruction descriptions");