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 initOperandMapData(
61 const std::vector<const CodeGenInstruction *> NumberedInstructions,
62 const std::string &Namespace,
63 std::map<std::string, unsigned> &Operands,
64 OpNameMapTy &OperandMap);
65 void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
66 const std::vector<const CodeGenInstruction*> &NumberedInstructions);
68 // Operand information.
69 void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
70 std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
72 } // End anonymous namespace
74 static void PrintDefList(const std::vector<Record*> &Uses,
75 unsigned Num, raw_ostream &OS) {
76 OS << "static const uint16_t ImplicitList" << Num << "[] = { ";
77 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
78 OS << getQualifiedName(Uses[i]) << ", ";
82 //===----------------------------------------------------------------------===//
83 // Operand Info Emission.
84 //===----------------------------------------------------------------------===//
86 std::vector<std::string>
87 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
88 std::vector<std::string> Result;
90 for (unsigned i = 0, e = Inst.Operands.size(); i != e; ++i) {
91 // Handle aggregate operands and normal operands the same way by expanding
92 // either case into a list of operands for this op.
93 std::vector<CGIOperandList::OperandInfo> OperandList;
95 // This might be a multiple operand thing. Targets like X86 have
96 // registers in their multi-operand operands. It may also be an anonymous
97 // operand, which has a single operand, but no declared class for the
99 DagInit *MIOI = Inst.Operands[i].MIOperandInfo;
101 if (!MIOI || MIOI->getNumArgs() == 0) {
102 // Single, anonymous, operand.
103 OperandList.push_back(Inst.Operands[i]);
105 for (unsigned j = 0, e = Inst.Operands[i].MINumOperands; j != e; ++j) {
106 OperandList.push_back(Inst.Operands[i]);
108 Record *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
109 OperandList.back().Rec = OpR;
113 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
114 Record *OpR = OperandList[j].Rec;
117 if (OpR->isSubClassOf("RegisterOperand"))
118 OpR = OpR->getValueAsDef("RegClass");
119 if (OpR->isSubClassOf("RegisterClass"))
120 Res += getQualifiedName(OpR) + "RegClassID, ";
121 else if (OpR->isSubClassOf("PointerLikeRegClass"))
122 Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
124 // -1 means the operand does not have a fixed register class.
127 // Fill in applicable flags.
130 // Ptr value whose register class is resolved via callback.
131 if (OpR->isSubClassOf("PointerLikeRegClass"))
132 Res += "|(1<<MCOI::LookupPtrRegClass)";
134 // Predicate operands. Check to see if the original unexpanded operand
135 // was of type PredicateOperand.
136 if (Inst.Operands[i].Rec->isSubClassOf("PredicateOperand"))
137 Res += "|(1<<MCOI::Predicate)";
139 // Optional def operands. Check to see if the original unexpanded operand
140 // was of type OptionalDefOperand.
141 if (Inst.Operands[i].Rec->isSubClassOf("OptionalDefOperand"))
142 Res += "|(1<<MCOI::OptionalDef)";
144 // Fill in operand type.
146 assert(!Inst.Operands[i].OperandType.empty() && "Invalid operand type.");
147 Res += Inst.Operands[i].OperandType;
149 // Fill in constraint info.
152 const CGIOperandList::ConstraintInfo &Constraint =
153 Inst.Operands[i].Constraints[j];
154 if (Constraint.isNone())
156 else if (Constraint.isEarlyClobber())
157 Res += "(1 << MCOI::EARLY_CLOBBER)";
159 assert(Constraint.isTied());
160 Res += "((" + utostr(Constraint.getTiedOperand()) +
161 " << 16) | (1 << MCOI::TIED_TO))";
164 Result.push_back(Res);
171 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
172 OperandInfoMapTy &OperandInfoIDs) {
173 // ID #0 is for no operand info.
174 unsigned OperandListNum = 0;
175 OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
178 const CodeGenTarget &Target = CDP.getTargetInfo();
179 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
180 E = Target.inst_end(); II != E; ++II) {
181 std::vector<std::string> OperandInfo = GetOperandInfo(**II);
182 unsigned &N = OperandInfoIDs[OperandInfo];
183 if (N != 0) continue;
185 N = ++OperandListNum;
186 OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
187 for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
188 OS << "{ " << OperandInfo[i] << " }, ";
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 (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
209 const CodeGenInstruction *Inst = NumberedInstructions[i];
210 if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable")) {
213 std::map<unsigned, unsigned> OpList;
214 for (unsigned j = 0, je = Inst->Operands.size(); j != je; ++j) {
215 const CGIOperandList::OperandInfo &Info = Inst->Operands[j];
216 StrUintMapIter I = Operands.find(Info.Name);
218 if (I == Operands.end()) {
219 I = Operands.insert(Operands.begin(),
220 std::pair<std::string, unsigned>(Info.Name, NumOperands++));
222 OpList[I->second] = Info.MIOperandNo;
224 OperandMap[OpList].push_back(Namespace + "::" + Inst->TheDef->getName());
228 /// Generate a table and function for looking up the indices of operands by
231 /// This code generates:
232 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
233 /// for each operand name.
234 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
236 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
237 /// for looking up the operand index for an instruction, given a value from
239 void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
240 const CodeGenTarget &Target,
241 const std::vector<const CodeGenInstruction*> &NumberedInstructions) {
243 const std::string &Namespace = Target.getInstNamespace();
244 std::string OpNameNS = "OpName";
245 // Map of operand names to their enumeration value. This will be used to
246 // generate the OpName enum.
247 std::map<std::string, unsigned> Operands;
248 OpNameMapTy OperandMap;
250 initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
252 OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
253 OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
254 OS << "namespace llvm {";
255 OS << "namespace " << Namespace << " {\n";
256 OS << "namespace " << OpNameNS << " { \n";
258 for (StrUintMapIter i = Operands.begin(), e = Operands.end(); i != e; ++i)
259 OS << " " << i->first << " = " << i->second << ",\n";
261 OS << "OPERAND_LAST";
263 OS << "} // End namespace OpName\n";
264 OS << "} // End namespace " << Namespace << "\n";
265 OS << "} // End namespace llvm\n";
266 OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n";
268 OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
269 OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
270 OS << "namespace llvm {";
271 OS << "namespace " << Namespace << " {\n";
272 OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
273 OS << " static const int16_t OperandMap []["<< Operands.size() << "] = {\n";
274 for (OpNameMapTy::iterator i = OperandMap.begin(), e = OperandMap.end();
276 const std::map<unsigned, unsigned> &OpList = i->first;
279 // Emit a row of the OperandMap table
280 for (unsigned ii = 0, ie = Operands.size(); ii != ie; ++ii)
281 OS << (OpList.count(ii) == 0 ? -1 : (int)OpList.find(ii)->second) << ", ";
287 OS << " switch(Opcode) {\n";
288 unsigned TableIndex = 0;
289 for (OpNameMapTy::iterator i = OperandMap.begin(), e = OperandMap.end();
291 std::vector<std::string> &OpcodeList = i->second;
293 for (unsigned ii = 0, ie = OpcodeList.size(); ii != ie; ++ii)
294 OS << " case " << OpcodeList[ii] << ":\n";
296 OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
298 OS << " default: return -1;\n";
301 OS << "} // End namespace " << Namespace << "\n";
302 OS << "} // End namespace llvm\n";
303 OS << "#endif //GET_INSTRINFO_NAMED_OPS\n";
307 //===----------------------------------------------------------------------===//
309 //===----------------------------------------------------------------------===//
311 // run - Emit the main instruction description records for the target...
312 void InstrInfoEmitter::run(raw_ostream &OS) {
313 emitSourceFileHeader("Target Instruction Enum Values", OS);
316 emitSourceFileHeader("Target Instruction Descriptors", OS);
318 OS << "\n#ifdef GET_INSTRINFO_MC_DESC\n";
319 OS << "#undef GET_INSTRINFO_MC_DESC\n";
321 OS << "namespace llvm {\n\n";
323 CodeGenTarget &Target = CDP.getTargetInfo();
324 const std::string &TargetName = Target.getName();
325 Record *InstrInfo = Target.getInstructionSet();
327 // Keep track of all of the def lists we have emitted already.
328 std::map<std::vector<Record*>, unsigned> EmittedLists;
329 unsigned ListNumber = 0;
331 // Emit all of the instruction's implicit uses and defs.
332 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
333 E = Target.inst_end(); II != E; ++II) {
334 Record *Inst = (*II)->TheDef;
335 std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
337 unsigned &IL = EmittedLists[Uses];
338 if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
340 std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
342 unsigned &IL = EmittedLists[Defs];
343 if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
347 OperandInfoMapTy OperandInfoIDs;
349 // Emit all of the operand info records.
350 EmitOperandInfo(OS, OperandInfoIDs);
352 // Emit all of the MCInstrDesc records in their ENUM ordering.
354 OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
355 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
356 Target.getInstructionsByEnumValue();
358 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
359 emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
363 // Build an array of instruction names
364 SequenceToOffsetTable<std::string> InstrNames;
365 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
366 const CodeGenInstruction *Instr = NumberedInstructions[i];
367 InstrNames.add(Instr->TheDef->getName());
371 OS << "extern const char " << TargetName << "InstrNameData[] = {\n";
372 InstrNames.emit(OS, printChar);
375 OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
376 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
379 const CodeGenInstruction *Instr = NumberedInstructions[i];
380 OS << InstrNames.get(Instr->TheDef->getName()) << "U, ";
385 // MCInstrInfo initialization routine.
386 OS << "static inline void Init" << TargetName
387 << "MCInstrInfo(MCInstrInfo *II) {\n";
388 OS << " II->InitMCInstrInfo(" << TargetName << "Insts, "
389 << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
390 << NumberedInstructions.size() << ");\n}\n\n";
392 OS << "} // End llvm namespace \n";
394 OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
396 // Create a TargetInstrInfo subclass to hide the MC layer initialization.
397 OS << "\n#ifdef GET_INSTRINFO_HEADER\n";
398 OS << "#undef GET_INSTRINFO_HEADER\n";
400 std::string ClassName = TargetName + "GenInstrInfo";
401 OS << "namespace llvm {\n";
402 OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
403 << " explicit " << ClassName << "(int SO = -1, int DO = -1);\n"
405 OS << "} // End llvm namespace \n";
407 OS << "#endif // GET_INSTRINFO_HEADER\n\n";
409 OS << "\n#ifdef GET_INSTRINFO_CTOR\n";
410 OS << "#undef GET_INSTRINFO_CTOR\n";
412 OS << "namespace llvm {\n";
413 OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
414 OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
415 OS << "extern const char " << TargetName << "InstrNameData[];\n";
416 OS << ClassName << "::" << ClassName << "(int SO, int DO)\n"
417 << " : TargetInstrInfo(SO, DO) {\n"
418 << " InitMCInstrInfo(" << TargetName << "Insts, "
419 << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
420 << NumberedInstructions.size() << ");\n}\n";
421 OS << "} // End llvm namespace \n";
423 OS << "#endif // GET_INSTRINFO_CTOR\n\n";
425 emitOperandNameMappings(OS, Target, NumberedInstructions);
428 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
430 std::map<std::vector<Record*>, unsigned> &EmittedLists,
431 const OperandInfoMapTy &OpInfo,
434 if (!Inst.Operands.empty())
435 // Each logical operand can be multiple MI operands.
436 MinOperands = Inst.Operands.back().MIOperandNo +
437 Inst.Operands.back().MINumOperands;
440 OS << Num << ",\t" << MinOperands << ",\t"
441 << Inst.Operands.NumDefs << ",\t"
442 << SchedModels.getSchedClassIdx(Inst) << ",\t"
443 << Inst.TheDef->getValueAsInt("Size") << ",\t0";
445 // Emit all of the target indepedent flags...
446 if (Inst.isPseudo) OS << "|(1<<MCID::Pseudo)";
447 if (Inst.isReturn) OS << "|(1<<MCID::Return)";
448 if (Inst.isBranch) OS << "|(1<<MCID::Branch)";
449 if (Inst.isIndirectBranch) OS << "|(1<<MCID::IndirectBranch)";
450 if (Inst.isCompare) OS << "|(1<<MCID::Compare)";
451 if (Inst.isMoveImm) OS << "|(1<<MCID::MoveImm)";
452 if (Inst.isBitcast) OS << "|(1<<MCID::Bitcast)";
453 if (Inst.isSelect) OS << "|(1<<MCID::Select)";
454 if (Inst.isBarrier) OS << "|(1<<MCID::Barrier)";
455 if (Inst.hasDelaySlot) OS << "|(1<<MCID::DelaySlot)";
456 if (Inst.isCall) OS << "|(1<<MCID::Call)";
457 if (Inst.canFoldAsLoad) OS << "|(1<<MCID::FoldableAsLoad)";
458 if (Inst.mayLoad) OS << "|(1<<MCID::MayLoad)";
459 if (Inst.mayStore) OS << "|(1<<MCID::MayStore)";
460 if (Inst.isPredicable) OS << "|(1<<MCID::Predicable)";
461 if (Inst.isConvertibleToThreeAddress) OS << "|(1<<MCID::ConvertibleTo3Addr)";
462 if (Inst.isCommutable) OS << "|(1<<MCID::Commutable)";
463 if (Inst.isTerminator) OS << "|(1<<MCID::Terminator)";
464 if (Inst.isReMaterializable) OS << "|(1<<MCID::Rematerializable)";
465 if (Inst.isNotDuplicable) OS << "|(1<<MCID::NotDuplicable)";
466 if (Inst.Operands.hasOptionalDef) OS << "|(1<<MCID::HasOptionalDef)";
467 if (Inst.usesCustomInserter) OS << "|(1<<MCID::UsesCustomInserter)";
468 if (Inst.hasPostISelHook) OS << "|(1<<MCID::HasPostISelHook)";
469 if (Inst.Operands.isVariadic)OS << "|(1<<MCID::Variadic)";
470 if (Inst.hasSideEffects) OS << "|(1<<MCID::UnmodeledSideEffects)";
471 if (Inst.isAsCheapAsAMove) OS << "|(1<<MCID::CheapAsAMove)";
472 if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<MCID::ExtraSrcRegAllocReq)";
473 if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<MCID::ExtraDefRegAllocReq)";
475 // Emit all of the target-specific flags...
476 BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
478 PrintFatalError("no TSFlags?");
480 for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
481 if (BitInit *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
482 Value |= uint64_t(Bit->getValue()) << i;
484 PrintFatalError("Invalid TSFlags bit in " + Inst.TheDef->getName());
490 // Emit the implicit uses and defs lists...
491 std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
495 OS << "ImplicitList" << EmittedLists[UseList] << ", ";
497 std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
501 OS << "ImplicitList" << EmittedLists[DefList] << ", ";
503 // Emit the operand info.
504 std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
505 if (OperandInfo.empty())
508 OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
510 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
513 // emitEnums - Print out enum values for all of the instructions.
514 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
516 OS << "\n#ifdef GET_INSTRINFO_ENUM\n";
517 OS << "#undef GET_INSTRINFO_ENUM\n";
519 OS << "namespace llvm {\n\n";
521 CodeGenTarget Target(Records);
523 // We must emit the PHI opcode first...
524 std::string Namespace = Target.getInstNamespace();
526 if (Namespace.empty()) {
527 fprintf(stderr, "No instructions defined!\n");
531 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
532 Target.getInstructionsByEnumValue();
534 OS << "namespace " << Namespace << " {\n";
536 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
537 OS << " " << NumberedInstructions[i]->TheDef->getName()
538 << "\t= " << i << ",\n";
540 OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
542 OS << "} // End llvm namespace \n";
544 OS << "#endif // GET_INSTRINFO_ENUM\n\n";
549 void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
550 InstrInfoEmitter(RK).run(OS);
551 EmitMapTable(RK, OS);
554 } // End llvm namespace