xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/InstrInfoEmitter.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenDAGPatterns.h"
15 #include "CodeGenInstruction.h"
16 #include "CodeGenSchedule.h"
17 #include "CodeGenTarget.h"
18 #include "PredicateExpander.h"
19 #include "SequenceToOffsetTable.h"
20 #include "TableGenBackends.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/TableGen/Error.h"
26 #include "llvm/TableGen/Record.h"
27 #include "llvm/TableGen/TableGenBackend.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <map>
31 #include <string>
32 #include <utility>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 namespace {
38 
39 class InstrInfoEmitter {
40   RecordKeeper &Records;
41   CodeGenDAGPatterns CDP;
42   const CodeGenSchedModels &SchedModels;
43 
44 public:
45   InstrInfoEmitter(RecordKeeper &R):
46     Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
47 
48   // run - Output the instruction set description.
49   void run(raw_ostream &OS);
50 
51 private:
52   void emitEnums(raw_ostream &OS);
53 
54   typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
55 
56   /// The keys of this map are maps which have OpName enum values as their keys
57   /// and instruction operand indices as their values.  The values of this map
58   /// are lists of instruction names.
59   typedef std::map<std::map<unsigned, unsigned>,
60                    std::vector<std::string>> OpNameMapTy;
61   typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
62 
63   /// Generate member functions in the target-specific GenInstrInfo class.
64   ///
65   /// This method is used to custom expand TIIPredicate definitions.
66   /// See file llvm/Target/TargetInstPredicates.td for a description of what is
67   /// a TIIPredicate and how to use it.
68   void emitTIIHelperMethods(raw_ostream &OS, StringRef TargetName,
69                             bool ExpandDefinition = true);
70 
71   /// Expand TIIPredicate definitions to functions that accept a const MCInst
72   /// reference.
73   void emitMCIIHelperMethods(raw_ostream &OS, StringRef TargetName);
74   void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
75                   Record *InstrInfo,
76                   std::map<std::vector<Record*>, unsigned> &EL,
77                   const OperandInfoMapTy &OpInfo,
78                   raw_ostream &OS);
79   void emitOperandTypeMappings(
80       raw_ostream &OS, const CodeGenTarget &Target,
81       ArrayRef<const CodeGenInstruction *> NumberedInstructions);
82   void initOperandMapData(
83             ArrayRef<const CodeGenInstruction *> NumberedInstructions,
84             StringRef Namespace,
85             std::map<std::string, unsigned> &Operands,
86             OpNameMapTy &OperandMap);
87   void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
88             ArrayRef<const CodeGenInstruction*> NumberedInstructions);
89 
90   // Operand information.
91   void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
92   std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
93 };
94 
95 } // end anonymous namespace
96 
97 static void PrintDefList(const std::vector<Record*> &Uses,
98                          unsigned Num, raw_ostream &OS) {
99   OS << "static const MCPhysReg ImplicitList" << Num << "[] = { ";
100   for (Record *U : Uses)
101     OS << getQualifiedName(U) << ", ";
102   OS << "0 };\n";
103 }
104 
105 //===----------------------------------------------------------------------===//
106 // Operand Info Emission.
107 //===----------------------------------------------------------------------===//
108 
109 std::vector<std::string>
110 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
111   std::vector<std::string> Result;
112 
113   for (auto &Op : Inst.Operands) {
114     // Handle aggregate operands and normal operands the same way by expanding
115     // either case into a list of operands for this op.
116     std::vector<CGIOperandList::OperandInfo> OperandList;
117 
118     // This might be a multiple operand thing.  Targets like X86 have
119     // registers in their multi-operand operands.  It may also be an anonymous
120     // operand, which has a single operand, but no declared class for the
121     // operand.
122     DagInit *MIOI = Op.MIOperandInfo;
123 
124     if (!MIOI || MIOI->getNumArgs() == 0) {
125       // Single, anonymous, operand.
126       OperandList.push_back(Op);
127     } else {
128       for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) {
129         OperandList.push_back(Op);
130 
131         auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
132         OperandList.back().Rec = OpR;
133       }
134     }
135 
136     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
137       Record *OpR = OperandList[j].Rec;
138       std::string Res;
139 
140       if (OpR->isSubClassOf("RegisterOperand"))
141         OpR = OpR->getValueAsDef("RegClass");
142       if (OpR->isSubClassOf("RegisterClass"))
143         Res += getQualifiedName(OpR) + "RegClassID, ";
144       else if (OpR->isSubClassOf("PointerLikeRegClass"))
145         Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
146       else
147         // -1 means the operand does not have a fixed register class.
148         Res += "-1, ";
149 
150       // Fill in applicable flags.
151       Res += "0";
152 
153       // Ptr value whose register class is resolved via callback.
154       if (OpR->isSubClassOf("PointerLikeRegClass"))
155         Res += "|(1<<MCOI::LookupPtrRegClass)";
156 
157       // Predicate operands.  Check to see if the original unexpanded operand
158       // was of type PredicateOp.
159       if (Op.Rec->isSubClassOf("PredicateOp"))
160         Res += "|(1<<MCOI::Predicate)";
161 
162       // Optional def operands.  Check to see if the original unexpanded operand
163       // was of type OptionalDefOperand.
164       if (Op.Rec->isSubClassOf("OptionalDefOperand"))
165         Res += "|(1<<MCOI::OptionalDef)";
166 
167       // Branch target operands.  Check to see if the original unexpanded
168       // operand was of type BranchTargetOperand.
169       if (Op.Rec->isSubClassOf("BranchTargetOperand"))
170         Res += "|(1<<MCOI::BranchTarget)";
171 
172       // Fill in operand type.
173       Res += ", ";
174       assert(!Op.OperandType.empty() && "Invalid operand type.");
175       Res += Op.OperandType;
176 
177       // Fill in constraint info.
178       Res += ", ";
179 
180       const CGIOperandList::ConstraintInfo &Constraint =
181         Op.Constraints[j];
182       if (Constraint.isNone())
183         Res += "0";
184       else if (Constraint.isEarlyClobber())
185         Res += "MCOI_EARLY_CLOBBER";
186       else {
187         assert(Constraint.isTied());
188         Res += "MCOI_TIED_TO(" + utostr(Constraint.getTiedOperand()) + ")";
189       }
190 
191       Result.push_back(Res);
192     }
193   }
194 
195   return Result;
196 }
197 
198 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
199                                        OperandInfoMapTy &OperandInfoIDs) {
200   // ID #0 is for no operand info.
201   unsigned OperandListNum = 0;
202   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
203 
204   OS << "\n";
205   const CodeGenTarget &Target = CDP.getTargetInfo();
206   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
207     std::vector<std::string> OperandInfo = GetOperandInfo(*Inst);
208     unsigned &N = OperandInfoIDs[OperandInfo];
209     if (N != 0) continue;
210 
211     N = ++OperandListNum;
212     OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
213     for (const std::string &Info : OperandInfo)
214       OS << "{ " << Info << " }, ";
215     OS << "};\n";
216   }
217 }
218 
219 /// Initialize data structures for generating operand name mappings.
220 ///
221 /// \param Operands [out] A map used to generate the OpName enum with operand
222 ///        names as its keys and operand enum values as its values.
223 /// \param OperandMap [out] A map for representing the operand name mappings for
224 ///        each instructions.  This is used to generate the OperandMap table as
225 ///        well as the getNamedOperandIdx() function.
226 void InstrInfoEmitter::initOperandMapData(
227         ArrayRef<const CodeGenInstruction *> NumberedInstructions,
228         StringRef Namespace,
229         std::map<std::string, unsigned> &Operands,
230         OpNameMapTy &OperandMap) {
231   unsigned NumOperands = 0;
232   for (const CodeGenInstruction *Inst : NumberedInstructions) {
233     if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
234       continue;
235     std::map<unsigned, unsigned> OpList;
236     for (const auto &Info : Inst->Operands) {
237       StrUintMapIter I = Operands.find(Info.Name);
238 
239       if (I == Operands.end()) {
240         I = Operands.insert(Operands.begin(),
241                     std::pair<std::string, unsigned>(Info.Name, NumOperands++));
242       }
243       OpList[I->second] = Info.MIOperandNo;
244     }
245     OperandMap[OpList].push_back(Namespace.str() + "::" +
246                                  Inst->TheDef->getName().str());
247   }
248 }
249 
250 /// Generate a table and function for looking up the indices of operands by
251 /// name.
252 ///
253 /// This code generates:
254 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
255 ///   for each operand name.
256 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
257 ///   operand indices.
258 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
259 ///   for looking up the operand index for an instruction, given a value from
260 ///   OpName enum
261 void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
262            const CodeGenTarget &Target,
263            ArrayRef<const CodeGenInstruction*> NumberedInstructions) {
264   StringRef Namespace = Target.getInstNamespace();
265   std::string OpNameNS = "OpName";
266   // Map of operand names to their enumeration value.  This will be used to
267   // generate the OpName enum.
268   std::map<std::string, unsigned> Operands;
269   OpNameMapTy OperandMap;
270 
271   initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
272 
273   OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
274   OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
275   OS << "namespace llvm {\n";
276   OS << "namespace " << Namespace << " {\n";
277   OS << "namespace " << OpNameNS << " {\n";
278   OS << "enum {\n";
279   for (const auto &Op : Operands)
280     OS << "  " << Op.first << " = " << Op.second << ",\n";
281 
282   OS << "  OPERAND_LAST";
283   OS << "\n};\n";
284   OS << "} // end namespace OpName\n";
285   OS << "} // end namespace " << Namespace << "\n";
286   OS << "} // end namespace llvm\n";
287   OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n";
288 
289   OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
290   OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
291   OS << "namespace llvm {\n";
292   OS << "namespace " << Namespace << " {\n";
293   OS << "LLVM_READONLY\n";
294   OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
295   if (!Operands.empty()) {
296     OS << "  static const int16_t OperandMap [][" << Operands.size()
297        << "] = {\n";
298     for (const auto &Entry : OperandMap) {
299       const std::map<unsigned, unsigned> &OpList = Entry.first;
300       OS << "{";
301 
302       // Emit a row of the OperandMap table
303       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
304         OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
305 
306       OS << "},\n";
307     }
308     OS << "};\n";
309 
310     OS << "  switch(Opcode) {\n";
311     unsigned TableIndex = 0;
312     for (const auto &Entry : OperandMap) {
313       for (const std::string &Name : Entry.second)
314         OS << "  case " << Name << ":\n";
315 
316       OS << "    return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
317     }
318     OS << "  default: return -1;\n";
319     OS << "  }\n";
320   } else {
321     // There are no operands, so no need to emit anything
322     OS << "  return -1;\n";
323   }
324   OS << "}\n";
325   OS << "} // end namespace " << Namespace << "\n";
326   OS << "} // end namespace llvm\n";
327   OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n";
328 }
329 
330 /// Generate an enum for all the operand types for this target, under the
331 /// llvm::TargetNamespace::OpTypes namespace.
332 /// Operand types are all definitions derived of the Operand Target.td class.
333 void InstrInfoEmitter::emitOperandTypeMappings(
334     raw_ostream &OS, const CodeGenTarget &Target,
335     ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
336 
337   StringRef Namespace = Target.getInstNamespace();
338   std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");
339   std::vector<Record *> RegisterOperands =
340       Records.getAllDerivedDefinitions("RegisterOperand");
341   std::vector<Record *> RegisterClasses =
342       Records.getAllDerivedDefinitions("RegisterClass");
343 
344   OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
345   OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
346   OS << "namespace llvm {\n";
347   OS << "namespace " << Namespace << " {\n";
348   OS << "namespace OpTypes {\n";
349   OS << "enum OperandType {\n";
350 
351   unsigned EnumVal = 0;
352   for (const std::vector<Record *> *RecordsToAdd :
353        {&Operands, &RegisterOperands, &RegisterClasses}) {
354     for (const Record *Op : *RecordsToAdd) {
355       if (!Op->isAnonymous())
356         OS << "  " << Op->getName() << " = " << EnumVal << ",\n";
357       ++EnumVal;
358     }
359   }
360 
361   OS << "  OPERAND_TYPE_LIST_END" << "\n};\n";
362   OS << "} // end namespace OpTypes\n";
363   OS << "} // end namespace " << Namespace << "\n";
364   OS << "} // end namespace llvm\n";
365   OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n";
366 
367   OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n";
368   OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n";
369   OS << "namespace llvm {\n";
370   OS << "namespace " << Namespace << " {\n";
371   OS << "LLVM_READONLY\n";
372   OS << "static int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n";
373   // TODO: Factor out duplicate operand lists to compress the tables.
374   if (!NumberedInstructions.empty()) {
375     std::vector<int> OperandOffsets;
376     std::vector<Record *> OperandRecords;
377     int CurrentOffset = 0;
378     for (const CodeGenInstruction *Inst : NumberedInstructions) {
379       OperandOffsets.push_back(CurrentOffset);
380       for (const auto &Op : Inst->Operands) {
381         const DagInit *MIOI = Op.MIOperandInfo;
382         if (!MIOI || MIOI->getNumArgs() == 0) {
383           // Single, anonymous, operand.
384           OperandRecords.push_back(Op.Rec);
385           ++CurrentOffset;
386         } else {
387           for (Init *Arg : MIOI->getArgs()) {
388             OperandRecords.push_back(cast<DefInit>(Arg)->getDef());
389             ++CurrentOffset;
390           }
391         }
392       }
393     }
394 
395     // Emit the table of offsets (indexes) into the operand type table.
396     // Size the unsigned integer offset to save space.
397     assert(OperandRecords.size() <= UINT32_MAX &&
398            "Too many operands for offset table");
399     OS << ((OperandRecords.size() <= UINT16_MAX) ? "  const uint16_t"
400                                                  : "  const uint32_t");
401     OS << " Offsets[] = {\n";
402     for (int I = 0, E = OperandOffsets.size(); I != E; ++I)
403       OS << "    " << OperandOffsets[I] << ",\n";
404     OS << "  };\n";
405 
406     // Add an entry for the end so that we don't need to special case it below.
407     OperandOffsets.push_back(OperandRecords.size());
408 
409     // Emit the actual operand types in a flat table.
410     // Size the signed integer operand type to save space.
411     assert(EnumVal <= INT16_MAX &&
412            "Too many operand types for operand types table");
413     OS << ((EnumVal <= INT8_MAX) ? "  const int8_t" : "  const int16_t");
414     OS << " OpcodeOperandTypes[] = {\n    ";
415     for (int I = 0, E = OperandRecords.size(), CurOffset = 1; I != E; ++I) {
416       // We print each Opcode's operands in its own row.
417       if (I == OperandOffsets[CurOffset]) {
418         OS << "\n    ";
419         // If there are empty rows, mark them with an empty comment.
420         while (OperandOffsets[++CurOffset] == I)
421           OS << "/**/\n    ";
422       }
423       Record *OpR = OperandRecords[I];
424       if ((OpR->isSubClassOf("Operand") ||
425            OpR->isSubClassOf("RegisterOperand") ||
426            OpR->isSubClassOf("RegisterClass")) &&
427           !OpR->isAnonymous())
428         OS << "OpTypes::" << OpR->getName();
429       else
430         OS << -1;
431       OS << ", ";
432     }
433     OS << "\n  };\n";
434 
435     OS << "  return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n";
436   } else {
437     OS << "  llvm_unreachable(\"No instructions defined\");\n";
438   }
439   OS << "}\n";
440   OS << "} // end namespace " << Namespace << "\n";
441   OS << "} // end namespace llvm\n";
442   OS << "#endif // GET_INSTRINFO_OPERAND_TYPE\n\n";
443 }
444 
445 void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS,
446                                              StringRef TargetName) {
447   RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
448   if (TIIPredicates.empty())
449     return;
450 
451   OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n";
452   OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n";
453 
454   OS << "namespace llvm {\n";
455   OS << "class MCInst;\n\n";
456 
457   OS << "namespace " << TargetName << "_MC {\n\n";
458 
459   for (const Record *Rec : TIIPredicates) {
460     OS << "bool " << Rec->getValueAsString("FunctionName")
461         << "(const MCInst &MI);\n";
462   }
463 
464   OS << "\n} // end namespace " << TargetName << "_MC\n";
465   OS << "} // end namespace llvm\n\n";
466 
467   OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n";
468 
469   OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n";
470   OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n";
471 
472   OS << "namespace llvm {\n";
473   OS << "namespace " << TargetName << "_MC {\n\n";
474 
475   PredicateExpander PE(TargetName);
476   PE.setExpandForMC(true);
477 
478   for (const Record *Rec : TIIPredicates) {
479     OS << "bool " << Rec->getValueAsString("FunctionName");
480     OS << "(const MCInst &MI) {\n";
481 
482     OS.indent(PE.getIndentLevel() * 2);
483     PE.expandStatement(OS, Rec->getValueAsDef("Body"));
484     OS << "\n}\n\n";
485   }
486 
487   OS << "} // end namespace " << TargetName << "_MC\n";
488   OS << "} // end namespace llvm\n\n";
489 
490   OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n";
491 }
492 
493 void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS,
494                                             StringRef TargetName,
495                                             bool ExpandDefinition) {
496   RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
497   if (TIIPredicates.empty())
498     return;
499 
500   PredicateExpander PE(TargetName);
501   PE.setExpandForMC(false);
502 
503   for (const Record *Rec : TIIPredicates) {
504     OS << (ExpandDefinition ? "" : "static ") << "bool ";
505     if (ExpandDefinition)
506       OS << TargetName << "InstrInfo::";
507     OS << Rec->getValueAsString("FunctionName");
508     OS << "(const MachineInstr &MI)";
509     if (!ExpandDefinition) {
510       OS << ";\n";
511       continue;
512     }
513 
514     OS << " {\n";
515     OS.indent(PE.getIndentLevel() * 2);
516     PE.expandStatement(OS, Rec->getValueAsDef("Body"));
517     OS << "\n}\n\n";
518   }
519 }
520 
521 //===----------------------------------------------------------------------===//
522 // Main Output.
523 //===----------------------------------------------------------------------===//
524 
525 // run - Emit the main instruction description records for the target...
526 void InstrInfoEmitter::run(raw_ostream &OS) {
527   emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS);
528   emitEnums(OS);
529 
530   OS << "#ifdef GET_INSTRINFO_MC_DESC\n";
531   OS << "#undef GET_INSTRINFO_MC_DESC\n";
532 
533   OS << "namespace llvm {\n\n";
534 
535   CodeGenTarget &Target = CDP.getTargetInfo();
536   const std::string &TargetName = std::string(Target.getName());
537   Record *InstrInfo = Target.getInstructionSet();
538 
539   // Keep track of all of the def lists we have emitted already.
540   std::map<std::vector<Record*>, unsigned> EmittedLists;
541   unsigned ListNumber = 0;
542 
543   // Emit all of the instruction's implicit uses and defs.
544   Records.startTimer("Emit uses/defs");
545   for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) {
546     Record *Inst = II->TheDef;
547     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
548     if (!Uses.empty()) {
549       unsigned &IL = EmittedLists[Uses];
550       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
551     }
552     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
553     if (!Defs.empty()) {
554       unsigned &IL = EmittedLists[Defs];
555       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
556     }
557   }
558 
559   OperandInfoMapTy OperandInfoIDs;
560 
561   // Emit all of the operand info records.
562   Records.startTimer("Emit operand info");
563   EmitOperandInfo(OS, OperandInfoIDs);
564 
565   // Emit all of the MCInstrDesc records in their ENUM ordering.
566   //
567   Records.startTimer("Emit InstrDesc records");
568   OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
569   ArrayRef<const CodeGenInstruction*> NumberedInstructions =
570     Target.getInstructionsByEnumValue();
571 
572   SequenceToOffsetTable<std::string> InstrNames;
573   unsigned Num = 0;
574   for (const CodeGenInstruction *Inst : NumberedInstructions) {
575     // Keep a list of the instruction names.
576     InstrNames.add(std::string(Inst->TheDef->getName()));
577     // Emit the record into the table.
578     emitRecord(*Inst, Num++, InstrInfo, EmittedLists, OperandInfoIDs, OS);
579   }
580   OS << "};\n\n";
581 
582   // Emit the array of instruction names.
583   Records.startTimer("Emit instruction names");
584   InstrNames.layout();
585   InstrNames.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
586                                           "InstrNameData[]");
587 
588   OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
589   Num = 0;
590   for (const CodeGenInstruction *Inst : NumberedInstructions) {
591     // Newline every eight entries.
592     if (Num % 8 == 0)
593       OS << "\n    ";
594     OS << InstrNames.get(std::string(Inst->TheDef->getName())) << "U, ";
595     ++Num;
596   }
597   OS << "\n};\n\n";
598 
599   bool HasDeprecationFeatures =
600       llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
601         return !Inst->HasComplexDeprecationPredicate &&
602                !Inst->DeprecatedReason.empty();
603       });
604   if (HasDeprecationFeatures) {
605     OS << "extern const uint8_t " << TargetName
606        << "InstrDeprecationFeatures[] = {";
607     Num = 0;
608     for (const CodeGenInstruction *Inst : NumberedInstructions) {
609       if (Num % 8 == 0)
610         OS << "\n    ";
611       if (!Inst->HasComplexDeprecationPredicate &&
612           !Inst->DeprecatedReason.empty())
613         OS << Target.getInstNamespace() << "::" << Inst->DeprecatedReason
614            << ", ";
615       else
616         OS << "uint8_t(-1), ";
617       ++Num;
618     }
619     OS << "\n};\n\n";
620   }
621 
622   bool HasComplexDeprecationInfos =
623       llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
624         return Inst->HasComplexDeprecationPredicate;
625       });
626   if (HasComplexDeprecationInfos) {
627     OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
628        << "InstrComplexDeprecationInfos[] = {";
629     Num = 0;
630     for (const CodeGenInstruction *Inst : NumberedInstructions) {
631       if (Num % 8 == 0)
632         OS << "\n    ";
633       if (Inst->HasComplexDeprecationPredicate)
634         // Emit a function pointer to the complex predicate method.
635         OS << "&get" << Inst->DeprecatedReason << "DeprecationInfo, ";
636       else
637         OS << "nullptr, ";
638       ++Num;
639     }
640     OS << "\n};\n\n";
641   }
642 
643   // MCInstrInfo initialization routine.
644   Records.startTimer("Emit initialization routine");
645   OS << "static inline void Init" << TargetName
646      << "MCInstrInfo(MCInstrInfo *II) {\n";
647   OS << "  II->InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
648      << "InstrNameIndices, " << TargetName << "InstrNameData, ";
649   if (HasDeprecationFeatures)
650     OS << TargetName << "InstrDeprecationFeatures, ";
651   else
652     OS << "nullptr, ";
653   if (HasComplexDeprecationInfos)
654     OS << TargetName << "InstrComplexDeprecationInfos, ";
655   else
656     OS << "nullptr, ";
657   OS << NumberedInstructions.size() << ");\n}\n\n";
658 
659   OS << "} // end namespace llvm\n";
660 
661   OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
662 
663   // Create a TargetInstrInfo subclass to hide the MC layer initialization.
664   OS << "#ifdef GET_INSTRINFO_HEADER\n";
665   OS << "#undef GET_INSTRINFO_HEADER\n";
666 
667   std::string ClassName = TargetName + "GenInstrInfo";
668   OS << "namespace llvm {\n";
669   OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
670      << "  explicit " << ClassName
671      << "(int CFSetupOpcode = -1, int CFDestroyOpcode = -1, int CatchRetOpcode = -1, int ReturnOpcode = -1);\n"
672      << "  ~" << ClassName << "() override = default;\n";
673 
674 
675   OS << "\n};\n} // end namespace llvm\n";
676 
677   OS << "#endif // GET_INSTRINFO_HEADER\n\n";
678 
679   OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n";
680   OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n";
681   emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */false);
682   OS << "\n";
683   OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n";
684 
685   OS << "#ifdef GET_INSTRINFO_HELPERS\n";
686   OS << "#undef GET_INSTRINFO_HELPERS\n\n";
687   emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */true);
688   OS << "#endif // GET_INSTRINFO_HELPERS\n\n";
689 
690   OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n";
691   OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
692 
693   OS << "namespace llvm {\n";
694   OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
695   OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
696   OS << "extern const char " << TargetName << "InstrNameData[];\n";
697   if (HasDeprecationFeatures)
698     OS << "extern const uint8_t " << TargetName
699        << "InstrDeprecationFeatures[];\n";
700   if (HasComplexDeprecationInfos)
701     OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
702        << "InstrComplexDeprecationInfos[];\n";
703   OS << ClassName << "::" << ClassName
704      << "(int CFSetupOpcode, int CFDestroyOpcode, int CatchRetOpcode, int "
705         "ReturnOpcode)\n"
706      << "  : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, "
707         "ReturnOpcode) {\n"
708      << "  InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
709      << "InstrNameIndices, " << TargetName << "InstrNameData, ";
710   if (HasDeprecationFeatures)
711     OS << TargetName << "InstrDeprecationFeatures, ";
712   else
713     OS << "nullptr, ";
714   if (HasComplexDeprecationInfos)
715     OS << TargetName << "InstrComplexDeprecationInfos, ";
716   else
717     OS << "nullptr, ";
718   OS << NumberedInstructions.size() << ");\n}\n";
719   OS << "} // end namespace llvm\n";
720 
721   OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
722 
723   Records.startTimer("Emit operand name mappings");
724   emitOperandNameMappings(OS, Target, NumberedInstructions);
725 
726   Records.startTimer("Emit operand type mappings");
727   emitOperandTypeMappings(OS, Target, NumberedInstructions);
728 
729   Records.startTimer("Emit helper methods");
730   emitMCIIHelperMethods(OS, TargetName);
731 }
732 
733 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
734                                   Record *InstrInfo,
735                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
736                                   const OperandInfoMapTy &OpInfo,
737                                   raw_ostream &OS) {
738   int MinOperands = 0;
739   if (!Inst.Operands.empty())
740     // Each logical operand can be multiple MI operands.
741     MinOperands = Inst.Operands.back().MIOperandNo +
742                   Inst.Operands.back().MINumOperands;
743 
744   OS << "  { ";
745   OS << Num << ",\t" << MinOperands << ",\t"
746      << Inst.Operands.NumDefs << ",\t"
747      << Inst.TheDef->getValueAsInt("Size") << ",\t"
748      << SchedModels.getSchedClassIdx(Inst) << ",\t0";
749 
750   CodeGenTarget &Target = CDP.getTargetInfo();
751 
752   // Emit all of the target independent flags...
753   if (Inst.isPreISelOpcode)    OS << "|(1ULL<<MCID::PreISelOpcode)";
754   if (Inst.isPseudo)           OS << "|(1ULL<<MCID::Pseudo)";
755   if (Inst.isReturn)           OS << "|(1ULL<<MCID::Return)";
756   if (Inst.isEHScopeReturn)    OS << "|(1ULL<<MCID::EHScopeReturn)";
757   if (Inst.isBranch)           OS << "|(1ULL<<MCID::Branch)";
758   if (Inst.isIndirectBranch)   OS << "|(1ULL<<MCID::IndirectBranch)";
759   if (Inst.isCompare)          OS << "|(1ULL<<MCID::Compare)";
760   if (Inst.isMoveImm)          OS << "|(1ULL<<MCID::MoveImm)";
761   if (Inst.isMoveReg)          OS << "|(1ULL<<MCID::MoveReg)";
762   if (Inst.isBitcast)          OS << "|(1ULL<<MCID::Bitcast)";
763   if (Inst.isAdd)              OS << "|(1ULL<<MCID::Add)";
764   if (Inst.isTrap)             OS << "|(1ULL<<MCID::Trap)";
765   if (Inst.isSelect)           OS << "|(1ULL<<MCID::Select)";
766   if (Inst.isBarrier)          OS << "|(1ULL<<MCID::Barrier)";
767   if (Inst.hasDelaySlot)       OS << "|(1ULL<<MCID::DelaySlot)";
768   if (Inst.isCall)             OS << "|(1ULL<<MCID::Call)";
769   if (Inst.canFoldAsLoad)      OS << "|(1ULL<<MCID::FoldableAsLoad)";
770   if (Inst.mayLoad)            OS << "|(1ULL<<MCID::MayLoad)";
771   if (Inst.mayStore)           OS << "|(1ULL<<MCID::MayStore)";
772   if (Inst.mayRaiseFPException) OS << "|(1ULL<<MCID::MayRaiseFPException)";
773   if (Inst.isPredicable)       OS << "|(1ULL<<MCID::Predicable)";
774   if (Inst.isConvertibleToThreeAddress) OS << "|(1ULL<<MCID::ConvertibleTo3Addr)";
775   if (Inst.isCommutable)       OS << "|(1ULL<<MCID::Commutable)";
776   if (Inst.isTerminator)       OS << "|(1ULL<<MCID::Terminator)";
777   if (Inst.isReMaterializable) OS << "|(1ULL<<MCID::Rematerializable)";
778   if (Inst.isNotDuplicable)    OS << "|(1ULL<<MCID::NotDuplicable)";
779   if (Inst.Operands.hasOptionalDef) OS << "|(1ULL<<MCID::HasOptionalDef)";
780   if (Inst.usesCustomInserter) OS << "|(1ULL<<MCID::UsesCustomInserter)";
781   if (Inst.hasPostISelHook)    OS << "|(1ULL<<MCID::HasPostISelHook)";
782   if (Inst.Operands.isVariadic)OS << "|(1ULL<<MCID::Variadic)";
783   if (Inst.hasSideEffects)     OS << "|(1ULL<<MCID::UnmodeledSideEffects)";
784   if (Inst.isAsCheapAsAMove)   OS << "|(1ULL<<MCID::CheapAsAMove)";
785   if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq)
786     OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)";
787   if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq)
788     OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)";
789   if (Inst.isRegSequence) OS << "|(1ULL<<MCID::RegSequence)";
790   if (Inst.isExtractSubreg) OS << "|(1ULL<<MCID::ExtractSubreg)";
791   if (Inst.isInsertSubreg) OS << "|(1ULL<<MCID::InsertSubreg)";
792   if (Inst.isConvergent) OS << "|(1ULL<<MCID::Convergent)";
793   if (Inst.variadicOpsAreDefs) OS << "|(1ULL<<MCID::VariadicOpsAreDefs)";
794   if (Inst.isAuthenticated) OS << "|(1ULL<<MCID::Authenticated)";
795 
796   // Emit all of the target-specific flags...
797   BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
798   if (!TSF)
799     PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?");
800   uint64_t Value = 0;
801   for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
802     if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
803       Value |= uint64_t(Bit->getValue()) << i;
804     else
805       PrintFatalError(Inst.TheDef->getLoc(),
806                       "Invalid TSFlags bit in " + Inst.TheDef->getName());
807   }
808   OS << ", 0x";
809   OS.write_hex(Value);
810   OS << "ULL, ";
811 
812   // Emit the implicit uses and defs lists...
813   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
814   if (UseList.empty())
815     OS << "nullptr, ";
816   else
817     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
818 
819   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
820   if (DefList.empty())
821     OS << "nullptr, ";
822   else
823     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
824 
825   // Emit the operand info.
826   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
827   if (OperandInfo.empty())
828     OS << "nullptr";
829   else
830     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
831 
832   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
833 }
834 
835 // emitEnums - Print out enum values for all of the instructions.
836 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
837   OS << "#ifdef GET_INSTRINFO_ENUM\n";
838   OS << "#undef GET_INSTRINFO_ENUM\n";
839 
840   OS << "namespace llvm {\n\n";
841 
842   const CodeGenTarget &Target = CDP.getTargetInfo();
843 
844   // We must emit the PHI opcode first...
845   StringRef Namespace = Target.getInstNamespace();
846 
847   if (Namespace.empty())
848     PrintFatalError("No instructions defined!");
849 
850   OS << "namespace " << Namespace << " {\n";
851   OS << "  enum {\n";
852   unsigned Num = 0;
853   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue())
854     OS << "    " << Inst->TheDef->getName() << "\t= " << Num++ << ",\n";
855   OS << "    INSTRUCTION_LIST_END = " << Num << "\n";
856   OS << "  };\n\n";
857   OS << "} // end namespace " << Namespace << "\n";
858   OS << "} // end namespace llvm\n";
859   OS << "#endif // GET_INSTRINFO_ENUM\n\n";
860 
861   OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n";
862   OS << "#undef GET_INSTRINFO_SCHED_ENUM\n";
863   OS << "namespace llvm {\n\n";
864   OS << "namespace " << Namespace << " {\n";
865   OS << "namespace Sched {\n";
866   OS << "  enum {\n";
867   Num = 0;
868   for (const auto &Class : SchedModels.explicit_classes())
869     OS << "    " << Class.Name << "\t= " << Num++ << ",\n";
870   OS << "    SCHED_LIST_END = " << Num << "\n";
871   OS << "  };\n";
872   OS << "} // end namespace Sched\n";
873   OS << "} // end namespace " << Namespace << "\n";
874   OS << "} // end namespace llvm\n";
875 
876   OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n";
877 }
878 
879 namespace llvm {
880 
881 void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
882   RK.startTimer("Analyze DAG patterns");
883   InstrInfoEmitter(RK).run(OS);
884   RK.startTimer("Emit map table");
885   EmitMapTable(RK, OS);
886 }
887 
888 } // end namespace llvm
889