Rename COPY_TO_SUBCLASS to COPY_TO_REGCLASS, and generalize
[oota-llvm.git] / utils / TableGen / InstrInfoEmitter.cpp
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 <algorithm>
19 #include <iostream>
20 using namespace llvm;
21
22 static void PrintDefList(const std::vector<Record*> &Uses,
23                          unsigned Num, std::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
30 static void PrintBarriers(std::vector<Record*> &Barriers,
31                           unsigned Num, std::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
42 struct RecordNameComparator {
43   bool operator()(const Record *Rec1, const Record *Rec2) const {
44     return Rec1->getName() < Rec2->getName();
45   }
46 };
47
48 void InstrInfoEmitter::GatherItinClasses() {
49   std::vector<Record*> DefList =
50   Records.getAllDerivedDefinitions("InstrItinClass");
51   std::sort(DefList.begin(), DefList.end(), RecordNameComparator());
52   
53   for (unsigned i = 0, N = DefList.size(); i < N; i++)
54     ItinClassMap[DefList[i]->getName()] = i;
55 }  
56
57 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
58   return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
59 }
60
61 //===----------------------------------------------------------------------===//
62 // Operand Info Emission.
63 //===----------------------------------------------------------------------===//
64
65 std::vector<std::string>
66 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
67   std::vector<std::string> Result;
68   
69   for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
70     // Handle aggregate operands and normal operands the same way by expanding
71     // either case into a list of operands for this op.
72     std::vector<CodeGenInstruction::OperandInfo> OperandList;
73
74     // This might be a multiple operand thing.  Targets like X86 have
75     // registers in their multi-operand operands.  It may also be an anonymous
76     // operand, which has a single operand, but no declared class for the
77     // operand.
78     DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
79     
80     if (!MIOI || MIOI->getNumArgs() == 0) {
81       // Single, anonymous, operand.
82       OperandList.push_back(Inst.OperandList[i]);
83     } else {
84       for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
85         OperandList.push_back(Inst.OperandList[i]);
86
87         Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
88         OperandList.back().Rec = OpR;
89       }
90     }
91
92     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
93       Record *OpR = OperandList[j].Rec;
94       std::string Res;
95       
96       if (OpR->isSubClassOf("RegisterClass"))
97         Res += getQualifiedName(OpR) + "RegClassID, ";
98       else
99         Res += "0, ";
100       // Fill in applicable flags.
101       Res += "0";
102         
103       // Ptr value whose register class is resolved via callback.
104       if (OpR->getName() == "ptr_rc")
105         Res += "|(1<<TOI::LookupPtrRegClass)";
106
107       // Predicate operands.  Check to see if the original unexpanded operand
108       // was of type PredicateOperand.
109       if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
110         Res += "|(1<<TOI::Predicate)";
111         
112       // Optional def operands.  Check to see if the original unexpanded operand
113       // was of type OptionalDefOperand.
114       if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
115         Res += "|(1<<TOI::OptionalDef)";
116
117       // Fill in constraint info.
118       Res += ", " + Inst.OperandList[i].Constraints[j];
119       Result.push_back(Res);
120     }
121   }
122
123   return Result;
124 }
125
126 void InstrInfoEmitter::EmitOperandInfo(std::ostream &OS, 
127                                        OperandInfoMapTy &OperandInfoIDs) {
128   // ID #0 is for no operand info.
129   unsigned OperandListNum = 0;
130   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
131   
132   OS << "\n";
133   const CodeGenTarget &Target = CDP.getTargetInfo();
134   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
135        E = Target.inst_end(); II != E; ++II) {
136     std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
137     unsigned &N = OperandInfoIDs[OperandInfo];
138     if (N != 0) continue;
139     
140     N = ++OperandListNum;
141     OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
142     for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
143       OS << "{ " << OperandInfo[i] << " }, ";
144     OS << "};\n";
145   }
146 }
147
148 void InstrInfoEmitter::DetectRegisterClassBarriers(std::vector<Record*> &Defs,
149                                   const std::vector<CodeGenRegisterClass> &RCs,
150                                   std::vector<Record*> &Barriers) {
151   std::set<Record*> DefSet;
152   unsigned NumDefs = Defs.size();
153   for (unsigned i = 0; i < NumDefs; ++i)
154     DefSet.insert(Defs[i]);
155
156   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
157     const CodeGenRegisterClass &RC = RCs[i];
158     unsigned NumRegs = RC.Elements.size();
159     if (NumRegs > NumDefs)
160       continue; // Can't possibly clobber this RC.
161
162     bool Clobber = true;
163     for (unsigned j = 0; j < NumRegs; ++j) {
164       Record *Reg = RC.Elements[j];
165       if (!DefSet.count(Reg)) {
166         Clobber = false;
167         break;
168       }
169     }
170     if (Clobber)
171       Barriers.push_back(RC.TheDef);
172   }
173 }
174
175 //===----------------------------------------------------------------------===//
176 // Main Output.
177 //===----------------------------------------------------------------------===//
178
179 // run - Emit the main instruction description records for the target...
180 void InstrInfoEmitter::run(std::ostream &OS) {
181   GatherItinClasses();
182
183   EmitSourceFileHeader("Target Instruction Descriptors", OS);
184   OS << "namespace llvm {\n\n";
185
186   CodeGenTarget &Target = CDP.getTargetInfo();
187   const std::string &TargetName = Target.getName();
188   Record *InstrInfo = Target.getInstructionSet();
189   const std::vector<CodeGenRegisterClass> &RCs = Target.getRegisterClasses();
190
191   // Keep track of all of the def lists we have emitted already.
192   std::map<std::vector<Record*>, unsigned> EmittedLists;
193   unsigned ListNumber = 0;
194   std::map<std::vector<Record*>, unsigned> EmittedBarriers;
195   unsigned BarrierNumber = 0;
196   std::map<Record*, unsigned> BarriersMap;
197  
198   // Emit all of the instruction's implicit uses and defs.
199   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
200          E = Target.inst_end(); II != E; ++II) {
201     Record *Inst = II->second.TheDef;
202     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
203     if (!Uses.empty()) {
204       unsigned &IL = EmittedLists[Uses];
205       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
206     }
207     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
208     if (!Defs.empty()) {
209       std::vector<Record*> RCBarriers;
210       DetectRegisterClassBarriers(Defs, RCs, RCBarriers);
211       if (!RCBarriers.empty()) {
212         unsigned &IB = EmittedBarriers[RCBarriers];
213         if (!IB) PrintBarriers(RCBarriers, IB = ++BarrierNumber, OS);
214         BarriersMap.insert(std::make_pair(Inst, IB));
215       }
216
217       unsigned &IL = EmittedLists[Defs];
218       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
219     }
220   }
221
222   OperandInfoMapTy OperandInfoIDs;
223   
224   // Emit all of the operand info records.
225   EmitOperandInfo(OS, OperandInfoIDs);
226   
227   // Emit all of the TargetInstrDesc records in their ENUM ordering.
228   //
229   OS << "\nstatic const TargetInstrDesc " << TargetName
230      << "Insts[] = {\n";
231   std::vector<const CodeGenInstruction*> NumberedInstructions;
232   Target.getInstructionsByEnumValue(NumberedInstructions);
233
234   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
235     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
236                BarriersMap, OperandInfoIDs, OS);
237   OS << "};\n";
238   OS << "} // End llvm namespace \n";
239 }
240
241 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
242                                   Record *InstrInfo,
243                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
244                                   std::map<Record*, unsigned> &BarriersMap,
245                                   const OperandInfoMapTy &OpInfo,
246                                   std::ostream &OS) {
247   int MinOperands = 0;
248   if (!Inst.OperandList.empty())
249     // Each logical operand can be multiple MI operands.
250     MinOperands = Inst.OperandList.back().MIOperandNo +
251                   Inst.OperandList.back().MINumOperands;
252
253   OS << "  { ";
254   OS << Num << ",\t" << MinOperands << ",\t"
255      << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
256      << ",\t\"" << Inst.TheDef->getName() << "\", 0";
257
258   // Emit all of the target indepedent flags...
259   if (Inst.isReturn)           OS << "|(1<<TID::Return)";
260   if (Inst.isBranch)           OS << "|(1<<TID::Branch)";
261   if (Inst.isIndirectBranch)   OS << "|(1<<TID::IndirectBranch)";
262   if (Inst.isBarrier)          OS << "|(1<<TID::Barrier)";
263   if (Inst.hasDelaySlot)       OS << "|(1<<TID::DelaySlot)";
264   if (Inst.isCall)             OS << "|(1<<TID::Call)";
265   if (Inst.canFoldAsLoad)      OS << "|(1<<TID::FoldableAsLoad)";
266   if (Inst.mayLoad)            OS << "|(1<<TID::MayLoad)";
267   if (Inst.mayStore)           OS << "|(1<<TID::MayStore)";
268   if (Inst.isPredicable)       OS << "|(1<<TID::Predicable)";
269   if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
270   if (Inst.isCommutable)       OS << "|(1<<TID::Commutable)";
271   if (Inst.isTerminator)       OS << "|(1<<TID::Terminator)";
272   if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
273   if (Inst.isNotDuplicable)    OS << "|(1<<TID::NotDuplicable)";
274   if (Inst.hasOptionalDef)     OS << "|(1<<TID::HasOptionalDef)";
275   if (Inst.usesCustomDAGSchedInserter)
276     OS << "|(1<<TID::UsesCustomDAGSchedInserter)";
277   if (Inst.isVariadic)         OS << "|(1<<TID::Variadic)";
278   if (Inst.hasSideEffects)     OS << "|(1<<TID::UnmodeledSideEffects)";
279   if (Inst.isAsCheapAsAMove)   OS << "|(1<<TID::CheapAsAMove)";
280   OS << ", 0";
281
282   // Emit all of the target-specific flags...
283   ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
284   ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
285   if (LI->getSize() != Shift->getSize())
286     throw "Lengths of " + InstrInfo->getName() +
287           ":(TargetInfoFields, TargetInfoPositions) must be equal!";
288
289   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
290     emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
291                      dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
292
293   OS << ", ";
294
295   // Emit the implicit uses and defs lists...
296   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
297   if (UseList.empty())
298     OS << "NULL, ";
299   else
300     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
301
302   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
303   if (DefList.empty())
304     OS << "NULL, ";
305   else
306     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
307
308   std::map<Record*, unsigned>::iterator BI = BarriersMap.find(Inst.TheDef);
309   if (BI == BarriersMap.end())
310     OS << "NULL, ";
311   else
312     OS << "Barriers" << BI->second << ", ";
313
314   // Emit the operand info.
315   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
316   if (OperandInfo.empty())
317     OS << "0";
318   else
319     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
320   
321   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
322 }
323
324
325 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
326                                         IntInit *ShiftInt, std::ostream &OS) {
327   if (Val == 0 || ShiftInt == 0)
328     throw std::string("Illegal value or shift amount in TargetInfo*!");
329   RecordVal *RV = R->getValue(Val->getValue());
330   int Shift = ShiftInt->getValue();
331
332   if (RV == 0 || RV->getValue() == 0) {
333     // This isn't an error if this is a builtin instruction.
334     if (R->getName() != "PHI" &&
335         R->getName() != "INLINEASM" &&
336         R->getName() != "DBG_LABEL" &&
337         R->getName() != "EH_LABEL" &&
338         R->getName() != "GC_LABEL" &&
339         R->getName() != "DECLARE" &&
340         R->getName() != "EXTRACT_SUBREG" &&
341         R->getName() != "INSERT_SUBREG" &&
342         R->getName() != "IMPLICIT_DEF" &&
343         R->getName() != "SUBREG_TO_REG" &&
344         R->getName() != "COPY_TO_REGCLASS")
345       throw R->getName() + " doesn't have a field named '" + 
346             Val->getValue() + "'!";
347     return;
348   }
349
350   Init *Value = RV->getValue();
351   if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
352     if (BI->getValue()) OS << "|(1<<" << Shift << ")";
353     return;
354   } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
355     // Convert the Bits to an integer to print...
356     Init *I = BI->convertInitializerTo(new IntRecTy());
357     if (I)
358       if (IntInit *II = dynamic_cast<IntInit*>(I)) {
359         if (II->getValue()) {
360           if (Shift)
361             OS << "|(" << II->getValue() << "<<" << Shift << ")";
362           else
363             OS << "|" << II->getValue();
364         }
365         return;
366       }
367
368   } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
369     if (II->getValue()) {
370       if (Shift)
371         OS << "|(" << II->getValue() << "<<" << Shift << ")";
372       else
373         OS << II->getValue();
374     }
375     return;
376   }
377
378   std::cerr << "Unhandled initializer: " << *Val << "\n";
379   throw "In record '" + R->getName() + "' for TSFlag emission.";
380 }
381