InstrInfoEmitter.cpp revision f523e476c2e199220306b367b7bd834978fb93d6
1//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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 "Record.h"
18#include "llvm/ADT/StringExtras.h"
19#include <algorithm>
20using namespace llvm;
21
22static void PrintDefList(const std::vector<Record*> &Uses,
23                         unsigned Num, raw_ostream &OS) {
24  OS << "static const unsigned ImplicitList" << Num << "[] = { ";
25  for (unsigned i = 0, e = Uses.size(); i != e; ++i)
26    OS << getQualifiedName(Uses[i]) << ", ";
27  OS << "0 };\n";
28}
29
30static void PrintBarriers(std::vector<Record*> &Barriers,
31                          unsigned Num, raw_ostream &OS) {
32  OS << "static const TargetRegisterClass* Barriers" << Num << "[] = { ";
33  for (unsigned i = 0, e = Barriers.size(); i != e; ++i)
34    OS << "&" << getQualifiedName(Barriers[i]) << "RegClass, ";
35  OS << "NULL };\n";
36}
37
38//===----------------------------------------------------------------------===//
39// Instruction Itinerary Information.
40//===----------------------------------------------------------------------===//
41
42void InstrInfoEmitter::GatherItinClasses() {
43  std::vector<Record*> DefList =
44  Records.getAllDerivedDefinitions("InstrItinClass");
45  std::sort(DefList.begin(), DefList.end(), LessRecord());
46
47  for (unsigned i = 0, N = DefList.size(); i < N; i++)
48    ItinClassMap[DefList[i]->getName()] = i;
49}
50
51unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
52  return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
53}
54
55//===----------------------------------------------------------------------===//
56// Operand Info Emission.
57//===----------------------------------------------------------------------===//
58
59std::vector<std::string>
60InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
61  std::vector<std::string> Result;
62
63  for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
64    // Handle aggregate operands and normal operands the same way by expanding
65    // either case into a list of operands for this op.
66    std::vector<CodeGenInstruction::OperandInfo> OperandList;
67
68    // This might be a multiple operand thing.  Targets like X86 have
69    // registers in their multi-operand operands.  It may also be an anonymous
70    // operand, which has a single operand, but no declared class for the
71    // operand.
72    DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
73
74    if (!MIOI || MIOI->getNumArgs() == 0) {
75      // Single, anonymous, operand.
76      OperandList.push_back(Inst.OperandList[i]);
77    } else {
78      for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
79        OperandList.push_back(Inst.OperandList[i]);
80
81        Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
82        OperandList.back().Rec = OpR;
83      }
84    }
85
86    for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
87      Record *OpR = OperandList[j].Rec;
88      std::string Res;
89
90      if (OpR->isSubClassOf("RegisterClass"))
91        Res += getQualifiedName(OpR) + "RegClassID, ";
92      else if (OpR->isSubClassOf("PointerLikeRegClass"))
93        Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
94      else
95        // -1 means the operand does not have a fixed register class.
96        Res += "-1, ";
97
98      // Fill in applicable flags.
99      Res += "0";
100
101      // Ptr value whose register class is resolved via callback.
102      if (OpR->isSubClassOf("PointerLikeRegClass"))
103        Res += "|(1<<TOI::LookupPtrRegClass)";
104
105      // Predicate operands.  Check to see if the original unexpanded operand
106      // was of type PredicateOperand.
107      if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
108        Res += "|(1<<TOI::Predicate)";
109
110      // Optional def operands.  Check to see if the original unexpanded operand
111      // was of type OptionalDefOperand.
112      if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
113        Res += "|(1<<TOI::OptionalDef)";
114
115      // Fill in constraint info.
116      Res += ", ";
117
118      const CodeGenInstruction::ConstraintInfo &Constraint =
119        Inst.OperandList[i].Constraints[j];
120      if (Constraint.isNone())
121        Res += "0";
122      else if (Constraint.isEarlyClobber())
123        Res += "(1 << TOI::EARLY_CLOBBER)";
124      else {
125        assert(Constraint.isTied());
126        Res += "((" + utostr(Constraint.getTiedOperand()) +
127                    " << 16) | (1 << TOI::TIED_TO))";
128      }
129
130      Result.push_back(Res);
131    }
132  }
133
134  return Result;
135}
136
137void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
138                                       OperandInfoMapTy &OperandInfoIDs) {
139  // ID #0 is for no operand info.
140  unsigned OperandListNum = 0;
141  OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
142
143  OS << "\n";
144  const CodeGenTarget &Target = CDP.getTargetInfo();
145  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
146       E = Target.inst_end(); II != E; ++II) {
147    std::vector<std::string> OperandInfo = GetOperandInfo(**II);
148    unsigned &N = OperandInfoIDs[OperandInfo];
149    if (N != 0) continue;
150
151    N = ++OperandListNum;
152    OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
153    for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
154      OS << "{ " << OperandInfo[i] << " }, ";
155    OS << "};\n";
156  }
157}
158
159void InstrInfoEmitter::DetectRegisterClassBarriers(std::vector<Record*> &Defs,
160                                  const std::vector<CodeGenRegisterClass> &RCs,
161                                  std::vector<Record*> &Barriers) {
162  std::set<Record*> DefSet;
163  unsigned NumDefs = Defs.size();
164  for (unsigned i = 0; i < NumDefs; ++i)
165    DefSet.insert(Defs[i]);
166
167  for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
168    const CodeGenRegisterClass &RC = RCs[i];
169    unsigned NumRegs = RC.Elements.size();
170    if (NumRegs > NumDefs)
171      continue; // Can't possibly clobber this RC.
172
173    bool Clobber = true;
174    for (unsigned j = 0; j < NumRegs; ++j) {
175      Record *Reg = RC.Elements[j];
176      if (!DefSet.count(Reg)) {
177        Clobber = false;
178        break;
179      }
180    }
181    if (Clobber)
182      Barriers.push_back(RC.TheDef);
183  }
184}
185
186//===----------------------------------------------------------------------===//
187// Main Output.
188//===----------------------------------------------------------------------===//
189
190// run - Emit the main instruction description records for the target...
191void InstrInfoEmitter::run(raw_ostream &OS) {
192  GatherItinClasses();
193
194  EmitSourceFileHeader("Target Instruction Descriptors", OS);
195  OS << "namespace llvm {\n\n";
196
197  CodeGenTarget &Target = CDP.getTargetInfo();
198  const std::string &TargetName = Target.getName();
199  Record *InstrInfo = Target.getInstructionSet();
200  const std::vector<CodeGenRegisterClass> &RCs = Target.getRegisterClasses();
201
202  // Keep track of all of the def lists we have emitted already.
203  std::map<std::vector<Record*>, unsigned> EmittedLists;
204  unsigned ListNumber = 0;
205  std::map<std::vector<Record*>, unsigned> EmittedBarriers;
206  unsigned BarrierNumber = 0;
207  std::map<Record*, unsigned> BarriersMap;
208
209  // Emit all of the instruction's implicit uses and defs.
210  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
211         E = Target.inst_end(); II != E; ++II) {
212    Record *Inst = (*II)->TheDef;
213    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
214    if (!Uses.empty()) {
215      unsigned &IL = EmittedLists[Uses];
216      if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
217    }
218    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
219    if (!Defs.empty()) {
220      std::vector<Record*> RCBarriers;
221      DetectRegisterClassBarriers(Defs, RCs, RCBarriers);
222      if (!RCBarriers.empty()) {
223        unsigned &IB = EmittedBarriers[RCBarriers];
224        if (!IB) PrintBarriers(RCBarriers, IB = ++BarrierNumber, OS);
225        BarriersMap.insert(std::make_pair(Inst, IB));
226      }
227
228      unsigned &IL = EmittedLists[Defs];
229      if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
230    }
231  }
232
233  OperandInfoMapTy OperandInfoIDs;
234
235  // Emit all of the operand info records.
236  EmitOperandInfo(OS, OperandInfoIDs);
237
238  // Emit all of the TargetInstrDesc records in their ENUM ordering.
239  //
240  OS << "\nstatic const TargetInstrDesc " << TargetName
241     << "Insts[] = {\n";
242  const std::vector<const CodeGenInstruction*> &NumberedInstructions =
243    Target.getInstructionsByEnumValue();
244
245  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
246    emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
247               BarriersMap, OperandInfoIDs, OS);
248  OS << "};\n";
249  OS << "} // End llvm namespace \n";
250}
251
252void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
253                                  Record *InstrInfo,
254                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
255                                  std::map<Record*, unsigned> &BarriersMap,
256                                  const OperandInfoMapTy &OpInfo,
257                                  raw_ostream &OS) {
258  int MinOperands = 0;
259  if (!Inst.OperandList.empty())
260    // Each logical operand can be multiple MI operands.
261    MinOperands = Inst.OperandList.back().MIOperandNo +
262                  Inst.OperandList.back().MINumOperands;
263
264  OS << "  { ";
265  OS << Num << ",\t" << MinOperands << ",\t"
266     << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
267     << ",\t\"" << Inst.TheDef->getName() << "\", 0";
268
269  // Emit all of the target indepedent flags...
270  if (Inst.isReturn)           OS << "|(1<<TID::Return)";
271  if (Inst.isBranch)           OS << "|(1<<TID::Branch)";
272  if (Inst.isIndirectBranch)   OS << "|(1<<TID::IndirectBranch)";
273  if (Inst.isCompare)          OS << "|(1<<TID::Compare)";
274  if (Inst.isBarrier)          OS << "|(1<<TID::Barrier)";
275  if (Inst.hasDelaySlot)       OS << "|(1<<TID::DelaySlot)";
276  if (Inst.isCall)             OS << "|(1<<TID::Call)";
277  if (Inst.canFoldAsLoad)      OS << "|(1<<TID::FoldableAsLoad)";
278  if (Inst.mayLoad)            OS << "|(1<<TID::MayLoad)";
279  if (Inst.mayStore)           OS << "|(1<<TID::MayStore)";
280  if (Inst.isPredicable)       OS << "|(1<<TID::Predicable)";
281  if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
282  if (Inst.isCommutable)       OS << "|(1<<TID::Commutable)";
283  if (Inst.isTerminator)       OS << "|(1<<TID::Terminator)";
284  if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
285  if (Inst.isNotDuplicable)    OS << "|(1<<TID::NotDuplicable)";
286  if (Inst.hasOptionalDef)     OS << "|(1<<TID::HasOptionalDef)";
287  if (Inst.usesCustomInserter) OS << "|(1<<TID::UsesCustomInserter)";
288  if (Inst.isVariadic)         OS << "|(1<<TID::Variadic)";
289  if (Inst.hasSideEffects)     OS << "|(1<<TID::UnmodeledSideEffects)";
290  if (Inst.isAsCheapAsAMove)   OS << "|(1<<TID::CheapAsAMove)";
291  if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<TID::ExtraSrcRegAllocReq)";
292  if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<TID::ExtraDefRegAllocReq)";
293
294  // Emit all of the target-specific flags...
295  BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
296  if (!TSF) throw "no TSFlags?";
297  uint64_t Value = 0;
298  for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
299    if (BitInit *Bit = dynamic_cast<BitInit*>(TSF->getBit(i)))
300      Value |= uint64_t(Bit->getValue()) << i;
301    else
302      throw "Invalid TSFlags bit in " + Inst.TheDef->getName();
303  }
304  OS << ", 0x";
305  OS.write_hex(Value);
306  OS << "ULL, ";
307
308  // Emit the implicit uses and defs lists...
309  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
310  if (UseList.empty())
311    OS << "NULL, ";
312  else
313    OS << "ImplicitList" << EmittedLists[UseList] << ", ";
314
315  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
316  if (DefList.empty())
317    OS << "NULL, ";
318  else
319    OS << "ImplicitList" << EmittedLists[DefList] << ", ";
320
321  std::map<Record*, unsigned>::iterator BI = BarriersMap.find(Inst.TheDef);
322  if (BI == BarriersMap.end())
323    OS << "NULL, ";
324  else
325    OS << "Barriers" << BI->second << ", ";
326
327  // Emit the operand info.
328  std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
329  if (OperandInfo.empty())
330    OS << "0";
331  else
332    OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
333
334  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
335}
336