InstrInfoEmitter.cpp revision d45eddd214061bf12ad1e6b86497a41725e61d75
1//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend is responsible for emitting a description of the target
11// instruction set for the code generator.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstrInfoEmitter.h"
16#include "CodeGenTarget.h"
17#include "llvm/Target/TargetInstrInfo.h"
18#include "Record.h"
19#include <algorithm>
20using namespace llvm;
21
22// runEnums - Print out enum values for all of the instructions.
23void InstrInfoEmitter::runEnums(std::ostream &OS) {
24  EmitSourceFileHeader("Target Instruction Enum Values", OS);
25  OS << "namespace llvm {\n\n";
26
27  CodeGenTarget Target;
28
29  // We must emit the PHI opcode first...
30  std::string Namespace;
31  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
32       E = Target.inst_end(); II != E; ++II) {
33    if (II->second.Namespace != "TargetInstrInfo") {
34      Namespace = II->second.Namespace;
35      break;
36    }
37  }
38
39  if (Namespace.empty()) {
40    cerr << "No instructions defined!\n";
41    exit(1);
42  }
43
44  std::vector<const CodeGenInstruction*> NumberedInstructions;
45  Target.getInstructionsByEnumValue(NumberedInstructions);
46
47  OS << "namespace " << Namespace << " {\n";
48  OS << "  enum {\n";
49  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
50    OS << "    " << NumberedInstructions[i]->TheDef->getName()
51       << "\t= " << i << ",\n";
52  }
53  OS << "    INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
54  OS << "  };\n}\n";
55  OS << "} // End llvm namespace \n";
56}
57
58void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
59                                    unsigned Num, std::ostream &OS) const {
60  OS << "static const unsigned ImplicitList" << Num << "[] = { ";
61  for (unsigned i = 0, e = Uses.size(); i != e; ++i)
62    OS << getQualifiedName(Uses[i]) << ", ";
63  OS << "0 };\n";
64}
65
66std::vector<std::string>
67InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
68  std::vector<std::string> Result;
69
70  for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
71    // Handle aggregate operands and normal operands the same way by expanding
72    // either case into a list of operands for this op.
73    std::vector<CodeGenInstruction::OperandInfo> OperandList;
74
75    // This might be a multiple operand thing.  Targets like X86 have
76    // registers in their multi-operand operands.  It may also be an anonymous
77    // operand, which has a single operand, but no declared class for the
78    // operand.
79    DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
80
81    if (!MIOI || MIOI->getNumArgs() == 0) {
82      // Single, anonymous, operand.
83      OperandList.push_back(Inst.OperandList[i]);
84    } else {
85      for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
86        OperandList.push_back(Inst.OperandList[i]);
87
88        Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
89        OperandList.back().Rec = OpR;
90      }
91    }
92
93    for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
94      Record *OpR = OperandList[j].Rec;
95      std::string Res;
96
97      if (OpR->isSubClassOf("RegisterClass"))
98        Res += getQualifiedName(OpR) + "RegClassID, ";
99      else
100        Res += "0, ";
101      // Fill in applicable flags.
102      Res += "0";
103
104      // Ptr value whose register class is resolved via callback.
105      if (OpR->getName() == "ptr_rc")
106        Res += "|M_LOOK_UP_PTR_REG_CLASS";
107
108      // Predicate operands.  Check to see if the original unexpanded operand
109      // was of type PredicateOperand.
110      if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
111        Res += "|M_PREDICATE_OPERAND";
112
113      // Fill in constraint info.
114      Res += ", " + Inst.OperandList[i].Constraints[j];
115      Result.push_back(Res);
116    }
117  }
118
119  return Result;
120}
121
122
123// run - Emit the main instruction description records for the target...
124void InstrInfoEmitter::run(std::ostream &OS) {
125  GatherItinClasses();
126
127  EmitSourceFileHeader("Target Instruction Descriptors", OS);
128  OS << "namespace llvm {\n\n";
129
130  CodeGenTarget Target;
131  const std::string &TargetName = Target.getName();
132  Record *InstrInfo = Target.getInstructionSet();
133
134  // Keep track of all of the def lists we have emitted already.
135  std::map<std::vector<Record*>, unsigned> EmittedLists;
136  unsigned ListNumber = 0;
137
138  // Emit all of the instruction's implicit uses and defs.
139  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
140         E = Target.inst_end(); II != E; ++II) {
141    Record *Inst = II->second.TheDef;
142    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
143    if (!Uses.empty()) {
144      unsigned &IL = EmittedLists[Uses];
145      if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
146    }
147    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
148    if (!Defs.empty()) {
149      unsigned &IL = EmittedLists[Defs];
150      if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
151    }
152  }
153
154  std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;
155  unsigned OperandListNum = 0;
156  OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;
157
158  // Emit all of the operand info records.
159  OS << "\n";
160  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
161       E = Target.inst_end(); II != E; ++II) {
162    std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
163    unsigned &N = OperandInfosEmitted[OperandInfo];
164    if (N == 0) {
165      N = ++OperandListNum;
166      OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
167      for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
168        OS << "{ " << OperandInfo[i] << " }, ";
169      OS << "};\n";
170    }
171  }
172
173  // Emit all of the TargetInstrDescriptor records in their ENUM ordering.
174  //
175  OS << "\nstatic const TargetInstrDescriptor " << TargetName
176     << "Insts[] = {\n";
177  std::vector<const CodeGenInstruction*> NumberedInstructions;
178  Target.getInstructionsByEnumValue(NumberedInstructions);
179
180  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
181    emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
182               OperandInfosEmitted, OS);
183  OS << "};\n";
184  OS << "} // End llvm namespace \n";
185}
186
187void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
188                                  Record *InstrInfo,
189                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
190                           std::map<std::vector<std::string>, unsigned> &OpInfo,
191                                  std::ostream &OS) {
192  int MinOperands;
193  if (!Inst.OperandList.empty())
194    // Each logical operand can be multiple MI operands.
195    MinOperands = Inst.OperandList.back().MIOperandNo +
196                  Inst.OperandList.back().MINumOperands;
197  else
198    MinOperands = 0;
199
200  OS << "  { ";
201  OS << Num << ",\t" << MinOperands << ",\t\"";
202
203  if (Inst.Name.empty())
204    OS << Inst.TheDef->getName();
205  else
206    OS << Inst.Name;
207
208  unsigned ItinClass = !IsItineraries ? 0 :
209            ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());
210
211  OS << "\",\t" << ItinClass << ", 0";
212
213  // Try to determine (from the pattern), if the instruction is a store.
214  bool isStore = false;
215  if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
216    ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
217    if (LI && LI->getSize() > 0) {
218      DagInit *Dag = (DagInit *)LI->getElement(0);
219      DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
220      if (OpDef) {
221        Record *Operator = OpDef->getDef();
222        if (Operator->isSubClassOf("SDNode")) {
223          const std::string Opcode = Operator->getValueAsString("Opcode");
224          if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
225            isStore = true;
226        }
227      }
228    }
229  }
230
231  // Emit all of the target indepedent flags...
232  if (Inst.isReturn)     OS << "|M_RET_FLAG";
233  if (Inst.isBranch)     OS << "|M_BRANCH_FLAG";
234  if (Inst.isBarrier)    OS << "|M_BARRIER_FLAG";
235  if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
236  if (Inst.isCall)       OS << "|M_CALL_FLAG";
237  if (Inst.isLoad)       OS << "|M_LOAD_FLAG";
238  if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
239  if (Inst.isPredicable) OS << "|M_PREDICABLE";
240  if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
241  if (Inst.isCommutable) OS << "|M_COMMUTABLE";
242  if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
243  if (Inst.isReMaterializable) OS << "|M_REMATERIALIZIBLE";
244  if (Inst.clobbersPred) OS << "|M_CLOBBERS_PRED";
245  if (Inst.isNotDuplicable) OS << "|M_NOT_DUPLICABLE";
246  if (Inst.usesCustomDAGSchedInserter)
247    OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
248  if (Inst.hasVariableNumberOfOperands)
249    OS << "|M_VARIABLE_OPS";
250  OS << ", 0";
251
252  // Emit all of the target-specific flags...
253  ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
254  ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
255  if (LI->getSize() != Shift->getSize())
256    throw "Lengths of " + InstrInfo->getName() +
257          ":(TargetInfoFields, TargetInfoPositions) must be equal!";
258
259  for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
260    emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
261                     dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
262
263  OS << ", ";
264
265  // Emit the implicit uses and defs lists...
266  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
267  if (UseList.empty())
268    OS << "NULL, ";
269  else
270    OS << "ImplicitList" << EmittedLists[UseList] << ", ";
271
272  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
273  if (DefList.empty())
274    OS << "NULL, ";
275  else
276    OS << "ImplicitList" << EmittedLists[DefList] << ", ";
277
278  // Emit the operand info.
279  std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
280  if (OperandInfo.empty())
281    OS << "0";
282  else
283    OS << "OperandInfo" << OpInfo[OperandInfo];
284
285  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
286}
287
288struct LessRecord {
289  bool operator()(const Record *Rec1, const Record *Rec2) const {
290    return Rec1->getName() < Rec2->getName();
291  }
292};
293void InstrInfoEmitter::GatherItinClasses() {
294  std::vector<Record*> DefList =
295                          Records.getAllDerivedDefinitions("InstrItinClass");
296  IsItineraries = !DefList.empty();
297
298  if (!IsItineraries) return;
299
300  std::sort(DefList.begin(), DefList.end(), LessRecord());
301
302  for (unsigned i = 0, N = DefList.size(); i < N; i++) {
303    Record *Def = DefList[i];
304    ItinClassMap[Def->getName()] = i;
305  }
306}
307
308unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
309  return ItinClassMap[ItinName];
310}
311
312void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
313                                        IntInit *ShiftInt, std::ostream &OS) {
314  if (Val == 0 || ShiftInt == 0)
315    throw std::string("Illegal value or shift amount in TargetInfo*!");
316  RecordVal *RV = R->getValue(Val->getValue());
317  int Shift = ShiftInt->getValue();
318
319  if (RV == 0 || RV->getValue() == 0) {
320    // This isn't an error if this is a builtin instruction.
321    if (R->getName() != "PHI" &&
322        R->getName() != "INLINEASM" &&
323        R->getName() != "LABEL")
324      throw R->getName() + " doesn't have a field named '" +
325            Val->getValue() + "'!";
326    return;
327  }
328
329  Init *Value = RV->getValue();
330  if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
331    if (BI->getValue()) OS << "|(1<<" << Shift << ")";
332    return;
333  } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
334    // Convert the Bits to an integer to print...
335    Init *I = BI->convertInitializerTo(new IntRecTy());
336    if (I)
337      if (IntInit *II = dynamic_cast<IntInit*>(I)) {
338        if (II->getValue()) {
339          if (Shift)
340            OS << "|(" << II->getValue() << "<<" << Shift << ")";
341          else
342            OS << "|" << II->getValue();
343        }
344        return;
345      }
346
347  } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
348    if (II->getValue()) {
349      if (Shift)
350        OS << "|(" << II->getValue() << "<<" << Shift << ")";
351      else
352        OS << II->getValue();
353    }
354    return;
355  }
356
357  cerr << "Unhandled initializer: " << *Val << "\n";
358  throw "In record '" + R->getName() + "' for TSFlag emission.";
359}
360
361