1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting a description of the target
11 // instruction set for the code generator.
13 //===----------------------------------------------------------------------===//
16 #include "CodeGenDAGPatterns.h"
17 #include "CodeGenSchedule.h"
18 #include "CodeGenTarget.h"
19 #include "SequenceToOffsetTable.h"
20 #include "TableGenBackends.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
24 #include "llvm/TableGen/TableGenBackend.h"
32 class InstrInfoEmitter {
33 RecordKeeper &Records;
34 CodeGenDAGPatterns CDP;
35 const CodeGenSchedModels &SchedModels;
38 InstrInfoEmitter(RecordKeeper &R):
39 Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
41 // run - Output the instruction set description.
42 void run(raw_ostream &OS);
45 void emitEnums(raw_ostream &OS);
47 typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
49 /// The keys of this map are maps which have OpName enum values as their keys
50 /// and instruction operand indices as their values. The values of this map
51 /// are lists of instruction names.
52 typedef std::map<std::map<unsigned, unsigned>,
53 std::vector<std::string> > OpNameMapTy;
54 typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
55 void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
57 std::map<std::vector<Record*>, unsigned> &EL,
58 const OperandInfoMapTy &OpInfo,
60 void emitOperandTypesEnum(raw_ostream &OS, const CodeGenTarget &Target);
61 void initOperandMapData(
62 const std::vector<const CodeGenInstruction *> &NumberedInstructions,
63 const std::string &Namespace,
64 std::map<std::string, unsigned> &Operands,
65 OpNameMapTy &OperandMap);
66 void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
67 const std::vector<const CodeGenInstruction*> &NumberedInstructions);
69 // Operand information.
70 void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
71 std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
73 } // End anonymous namespace
75 static void PrintDefList(const std::vector<Record*> &Uses,
76 unsigned Num, raw_ostream &OS) {
77 OS << "static const uint16_t ImplicitList" << Num << "[] = { ";
78 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
79 OS << getQualifiedName(Uses[i]) << ", ";
83 //===----------------------------------------------------------------------===//
84 // Operand Info Emission.
85 //===----------------------------------------------------------------------===//
87 std::vector<std::string>
88 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
89 std::vector<std::string> Result;
91 for (auto &Op : Inst.Operands) {
92 // Handle aggregate operands and normal operands the same way by expanding
93 // either case into a list of operands for this op.
94 std::vector<CGIOperandList::OperandInfo> OperandList;
96 // This might be a multiple operand thing. Targets like X86 have
97 // registers in their multi-operand operands. It may also be an anonymous
98 // operand, which has a single operand, but no declared class for the
100 DagInit *MIOI = Op.MIOperandInfo;
102 if (!MIOI || MIOI->getNumArgs() == 0) {
103 // Single, anonymous, operand.
104 OperandList.push_back(Op);
106 for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) {
107 OperandList.push_back(Op);
109 Record *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
110 OperandList.back().Rec = OpR;
114 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
115 Record *OpR = OperandList[j].Rec;
118 if (OpR->isSubClassOf("RegisterOperand"))
119 OpR = OpR->getValueAsDef("RegClass");
120 if (OpR->isSubClassOf("RegisterClass"))
121 Res += getQualifiedName(OpR) + "RegClassID, ";
122 else if (OpR->isSubClassOf("PointerLikeRegClass"))
123 Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
125 // -1 means the operand does not have a fixed register class.
128 // Fill in applicable flags.
131 // Ptr value whose register class is resolved via callback.
132 if (OpR->isSubClassOf("PointerLikeRegClass"))
133 Res += "|(1<<MCOI::LookupPtrRegClass)";
135 // Predicate operands. Check to see if the original unexpanded operand
136 // was of type PredicateOp.
137 if (Op.Rec->isSubClassOf("PredicateOp"))
138 Res += "|(1<<MCOI::Predicate)";
140 // Optional def operands. Check to see if the original unexpanded operand
141 // was of type OptionalDefOperand.
142 if (Op.Rec->isSubClassOf("OptionalDefOperand"))
143 Res += "|(1<<MCOI::OptionalDef)";
145 // Fill in operand type.
147 assert(!Op.OperandType.empty() && "Invalid operand type.");
148 Res += Op.OperandType;
150 // Fill in constraint info.
153 const CGIOperandList::ConstraintInfo &Constraint =
155 if (Constraint.isNone())
157 else if (Constraint.isEarlyClobber())
158 Res += "(1 << MCOI::EARLY_CLOBBER)";
160 assert(Constraint.isTied());
161 Res += "((" + utostr(Constraint.getTiedOperand()) +
162 " << 16) | (1 << MCOI::TIED_TO))";
165 Result.push_back(Res);
172 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
173 OperandInfoMapTy &OperandInfoIDs) {
174 // ID #0 is for no operand info.
175 unsigned OperandListNum = 0;
176 OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
179 const CodeGenTarget &Target = CDP.getTargetInfo();
180 for (const CodeGenInstruction *Inst : Target.instructions()) {
181 std::vector<std::string> OperandInfo = GetOperandInfo(*Inst);
182 unsigned &N = OperandInfoIDs[OperandInfo];
183 if (N != 0) continue;
185 N = ++OperandListNum;
186 OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
187 for (const std::string &Info : OperandInfo)
188 OS << "{ " << Info << " }, ";
194 /// Initialize data structures for generating operand name mappings.
196 /// \param Operands [out] A map used to generate the OpName enum with operand
197 /// names as its keys and operand enum values as its values.
198 /// \param OperandMap [out] A map for representing the operand name mappings for
199 /// each instructions. This is used to generate the OperandMap table as
200 /// well as the getNamedOperandIdx() function.
201 void InstrInfoEmitter::initOperandMapData(
202 const std::vector<const CodeGenInstruction *> &NumberedInstructions,
203 const std::string &Namespace,
204 std::map<std::string, unsigned> &Operands,
205 OpNameMapTy &OperandMap) {
207 unsigned NumOperands = 0;
208 for (const CodeGenInstruction *Inst : NumberedInstructions) {
209 if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
211 std::map<unsigned, unsigned> OpList;
212 for (const auto &Info : Inst->Operands) {
213 StrUintMapIter I = Operands.find(Info.Name);
215 if (I == Operands.end()) {
216 I = Operands.insert(Operands.begin(),
217 std::pair<std::string, unsigned>(Info.Name, NumOperands++));
219 OpList[I->second] = Info.MIOperandNo;
221 OperandMap[OpList].push_back(Namespace + "::" + Inst->TheDef->getName());
225 /// Generate a table and function for looking up the indices of operands by
228 /// This code generates:
229 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
230 /// for each operand name.
231 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
233 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
234 /// for looking up the operand index for an instruction, given a value from
236 void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
237 const CodeGenTarget &Target,
238 const std::vector<const CodeGenInstruction*> &NumberedInstructions) {
240 const std::string &Namespace = Target.getInstNamespace();
241 std::string OpNameNS = "OpName";
242 // Map of operand names to their enumeration value. This will be used to
243 // generate the OpName enum.
244 std::map<std::string, unsigned> Operands;
245 OpNameMapTy OperandMap;
247 initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
249 OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
250 OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
251 OS << "namespace llvm {";
252 OS << "namespace " << Namespace << " {\n";
253 OS << "namespace " << OpNameNS << " { \n";
255 for (const auto &Op : Operands)
256 OS << " " << Op.first << " = " << Op.second << ",\n";
258 OS << "OPERAND_LAST";
260 OS << "} // End namespace OpName\n";
261 OS << "} // End namespace " << Namespace << "\n";
262 OS << "} // End namespace llvm\n";
263 OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n";
265 OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
266 OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
267 OS << "namespace llvm {";
268 OS << "namespace " << Namespace << " {\n";
269 OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
270 if (!Operands.empty()) {
271 OS << " static const int16_t OperandMap [][" << Operands.size()
273 for (const auto &Entry : OperandMap) {
274 const std::map<unsigned, unsigned> &OpList = Entry.first;
277 // Emit a row of the OperandMap table
278 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
279 OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
285 OS << " switch(Opcode) {\n";
286 unsigned TableIndex = 0;
287 for (const auto &Entry : OperandMap) {
288 for (const std::string &Name : Entry.second)
289 OS << " case " << Name << ":\n";
291 OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
293 OS << " default: return -1;\n";
296 // There are no operands, so no need to emit anything
297 OS << " return -1;\n";
300 OS << "} // End namespace " << Namespace << "\n";
301 OS << "} // End namespace llvm\n";
302 OS << "#endif //GET_INSTRINFO_NAMED_OPS\n";
306 /// Generate an enum for all the operand types for this target, under the
307 /// llvm::TargetNamespace::OpTypes namespace.
308 /// Operand types are all definitions derived of the Operand Target.td class.
309 void InstrInfoEmitter::emitOperandTypesEnum(raw_ostream &OS,
310 const CodeGenTarget &Target) {
312 const std::string &Namespace = Target.getInstNamespace();
313 std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");
315 OS << "\n#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
316 OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
317 OS << "namespace llvm {";
318 OS << "namespace " << Namespace << " {\n";
319 OS << "namespace OpTypes { \n";
320 OS << "enum OperandType {\n";
322 unsigned EnumVal = 0;
323 for (const Record *Op : Operands) {
324 if (!Op->isAnonymous())
325 OS << " " << Op->getName() << " = " << EnumVal << ",\n";
329 OS << " OPERAND_TYPE_LIST_END" << "\n};\n";
330 OS << "} // End namespace OpTypes\n";
331 OS << "} // End namespace " << Namespace << "\n";
332 OS << "} // End namespace llvm\n";
333 OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
336 //===----------------------------------------------------------------------===//
338 //===----------------------------------------------------------------------===//
340 // run - Emit the main instruction description records for the target...
341 void InstrInfoEmitter::run(raw_ostream &OS) {
342 emitSourceFileHeader("Target Instruction Enum Values", OS);
345 emitSourceFileHeader("Target Instruction Descriptors", OS);
347 OS << "\n#ifdef GET_INSTRINFO_MC_DESC\n";
348 OS << "#undef GET_INSTRINFO_MC_DESC\n";
350 OS << "namespace llvm {\n\n";
352 CodeGenTarget &Target = CDP.getTargetInfo();
353 const std::string &TargetName = Target.getName();
354 Record *InstrInfo = Target.getInstructionSet();
356 // Keep track of all of the def lists we have emitted already.
357 std::map<std::vector<Record*>, unsigned> EmittedLists;
358 unsigned ListNumber = 0;
360 // Emit all of the instruction's implicit uses and defs.
361 for (const CodeGenInstruction *II : Target.instructions()) {
362 Record *Inst = II->TheDef;
363 std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
365 unsigned &IL = EmittedLists[Uses];
366 if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
368 std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
370 unsigned &IL = EmittedLists[Defs];
371 if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
375 OperandInfoMapTy OperandInfoIDs;
377 // Emit all of the operand info records.
378 EmitOperandInfo(OS, OperandInfoIDs);
380 // Emit all of the MCInstrDesc records in their ENUM ordering.
382 OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
383 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
384 Target.getInstructionsByEnumValue();
386 SequenceToOffsetTable<std::string> InstrNames;
388 for (const CodeGenInstruction *Inst : NumberedInstructions) {
389 // Keep a list of the instruction names.
390 InstrNames.add(Inst->TheDef->getName());
391 // Emit the record into the table.
392 emitRecord(*Inst, Num++, InstrInfo, EmittedLists, OperandInfoIDs, OS);
396 // Emit the array of instruction names.
398 OS << "extern const char " << TargetName << "InstrNameData[] = {\n";
399 InstrNames.emit(OS, printChar);
402 OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
404 for (const CodeGenInstruction *Inst : NumberedInstructions) {
405 // Newline every eight entries.
408 OS << InstrNames.get(Inst->TheDef->getName()) << "U, ";
414 // MCInstrInfo initialization routine.
415 OS << "static inline void Init" << TargetName
416 << "MCInstrInfo(MCInstrInfo *II) {\n";
417 OS << " II->InitMCInstrInfo(" << TargetName << "Insts, "
418 << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
419 << NumberedInstructions.size() << ");\n}\n\n";
421 OS << "} // End llvm namespace \n";
423 OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
425 // Create a TargetInstrInfo subclass to hide the MC layer initialization.
426 OS << "\n#ifdef GET_INSTRINFO_HEADER\n";
427 OS << "#undef GET_INSTRINFO_HEADER\n";
429 std::string ClassName = TargetName + "GenInstrInfo";
430 OS << "namespace llvm {\n";
431 OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
432 << " explicit " << ClassName << "(int SO = -1, int DO = -1);\n"
433 << " virtual ~" << ClassName << "();\n"
435 OS << "} // End llvm namespace \n";
437 OS << "#endif // GET_INSTRINFO_HEADER\n\n";
439 OS << "\n#ifdef GET_INSTRINFO_CTOR_DTOR\n";
440 OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
442 OS << "namespace llvm {\n";
443 OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
444 OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
445 OS << "extern const char " << TargetName << "InstrNameData[];\n";
446 OS << ClassName << "::" << ClassName << "(int SO, int DO)\n"
447 << " : TargetInstrInfo(SO, DO) {\n"
448 << " InitMCInstrInfo(" << TargetName << "Insts, "
449 << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
450 << NumberedInstructions.size() << ");\n}\n"
451 << ClassName << "::~" << ClassName << "() {}\n";
452 OS << "} // End llvm namespace \n";
454 OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
456 emitOperandNameMappings(OS, Target, NumberedInstructions);
458 emitOperandTypesEnum(OS, Target);
461 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
463 std::map<std::vector<Record*>, unsigned> &EmittedLists,
464 const OperandInfoMapTy &OpInfo,
467 if (!Inst.Operands.empty())
468 // Each logical operand can be multiple MI operands.
469 MinOperands = Inst.Operands.back().MIOperandNo +
470 Inst.Operands.back().MINumOperands;
473 OS << Num << ",\t" << MinOperands << ",\t"
474 << Inst.Operands.NumDefs << ",\t"
475 << SchedModels.getSchedClassIdx(Inst) << ",\t"
476 << Inst.TheDef->getValueAsInt("Size") << ",\t0";
478 // Emit all of the target indepedent flags...
479 if (Inst.isPseudo) OS << "|(1<<MCID::Pseudo)";
480 if (Inst.isReturn) OS << "|(1<<MCID::Return)";
481 if (Inst.isBranch) OS << "|(1<<MCID::Branch)";
482 if (Inst.isIndirectBranch) OS << "|(1<<MCID::IndirectBranch)";
483 if (Inst.isCompare) OS << "|(1<<MCID::Compare)";
484 if (Inst.isMoveImm) OS << "|(1<<MCID::MoveImm)";
485 if (Inst.isBitcast) OS << "|(1<<MCID::Bitcast)";
486 if (Inst.isSelect) OS << "|(1<<MCID::Select)";
487 if (Inst.isBarrier) OS << "|(1<<MCID::Barrier)";
488 if (Inst.hasDelaySlot) OS << "|(1<<MCID::DelaySlot)";
489 if (Inst.isCall) OS << "|(1<<MCID::Call)";
490 if (Inst.canFoldAsLoad) OS << "|(1<<MCID::FoldableAsLoad)";
491 if (Inst.mayLoad) OS << "|(1<<MCID::MayLoad)";
492 if (Inst.mayStore) OS << "|(1<<MCID::MayStore)";
493 if (Inst.isPredicable) OS << "|(1<<MCID::Predicable)";
494 if (Inst.isConvertibleToThreeAddress) OS << "|(1<<MCID::ConvertibleTo3Addr)";
495 if (Inst.isCommutable) OS << "|(1<<MCID::Commutable)";
496 if (Inst.isTerminator) OS << "|(1<<MCID::Terminator)";
497 if (Inst.isReMaterializable) OS << "|(1<<MCID::Rematerializable)";
498 if (Inst.isNotDuplicable) OS << "|(1<<MCID::NotDuplicable)";
499 if (Inst.Operands.hasOptionalDef) OS << "|(1<<MCID::HasOptionalDef)";
500 if (Inst.usesCustomInserter) OS << "|(1<<MCID::UsesCustomInserter)";
501 if (Inst.hasPostISelHook) OS << "|(1<<MCID::HasPostISelHook)";
502 if (Inst.Operands.isVariadic)OS << "|(1<<MCID::Variadic)";
503 if (Inst.hasSideEffects) OS << "|(1<<MCID::UnmodeledSideEffects)";
504 if (Inst.isAsCheapAsAMove) OS << "|(1<<MCID::CheapAsAMove)";
505 if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<MCID::ExtraSrcRegAllocReq)";
506 if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<MCID::ExtraDefRegAllocReq)";
508 // Emit all of the target-specific flags...
509 BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
511 PrintFatalError("no TSFlags?");
513 for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
514 if (BitInit *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
515 Value |= uint64_t(Bit->getValue()) << i;
517 PrintFatalError("Invalid TSFlags bit in " + Inst.TheDef->getName());
523 // Emit the implicit uses and defs lists...
524 std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
528 OS << "ImplicitList" << EmittedLists[UseList] << ", ";
530 std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
534 OS << "ImplicitList" << EmittedLists[DefList] << ", ";
536 // Emit the operand info.
537 std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
538 if (OperandInfo.empty())
541 OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
543 CodeGenTarget &Target = CDP.getTargetInfo();
544 if (Inst.HasComplexDeprecationPredicate)
545 // Emit a function pointer to the complex predicate method.
547 << ",&get" << Inst.DeprecatedReason << "DeprecationInfo";
548 else if (!Inst.DeprecatedReason.empty())
549 // Emit the Subtarget feature.
550 OS << "," << Target.getInstNamespace() << "::" << Inst.DeprecatedReason
553 // Instruction isn't deprecated.
556 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
559 // emitEnums - Print out enum values for all of the instructions.
560 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
562 OS << "\n#ifdef GET_INSTRINFO_ENUM\n";
563 OS << "#undef GET_INSTRINFO_ENUM\n";
565 OS << "namespace llvm {\n\n";
567 CodeGenTarget Target(Records);
569 // We must emit the PHI opcode first...
570 std::string Namespace = Target.getInstNamespace();
572 if (Namespace.empty()) {
573 fprintf(stderr, "No instructions defined!\n");
577 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
578 Target.getInstructionsByEnumValue();
580 OS << "namespace " << Namespace << " {\n";
583 for (const CodeGenInstruction *Inst : NumberedInstructions)
584 OS << " " << Inst->TheDef->getName() << "\t= " << Num++ << ",\n";
585 OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
587 OS << "namespace Sched {\n";
590 for (const auto &Class : SchedModels.explicit_classes())
591 OS << " " << Class.Name << "\t= " << Num++ << ",\n";
592 OS << " SCHED_LIST_END = " << SchedModels.numInstrSchedClasses() << "\n";
594 OS << "} // End llvm namespace \n";
596 OS << "#endif // GET_INSTRINFO_ENUM\n\n";
601 void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
602 InstrInfoEmitter(RK).run(OS);
603 EmitMapTable(RK, OS);
606 } // End llvm namespace