Bug fix. Flag operand number may be calculated incorrectly.
[oota-llvm.git] / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===//
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 class wrap target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes throw exceptions on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "CodeGenTarget.h"
18 #include "Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/CommandLine.h"
21 #include <set>
22 #include <algorithm>
23 using namespace llvm;
24
25 static cl::opt<unsigned>
26 AsmWriterNum("asmwriternum", cl::init(0),
27              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
28
29 /// getValueType - Return the MCV::ValueType that the specified TableGen record
30 /// corresponds to.
31 MVT::ValueType llvm::getValueType(Record *Rec) {
32   return (MVT::ValueType)Rec->getValueAsInt("Value");
33 }
34
35 std::string llvm::getName(MVT::ValueType T) {
36   switch (T) {
37   case MVT::Other: return "UNKNOWN";
38   case MVT::i1:    return "i1";
39   case MVT::i8:    return "i8";
40   case MVT::i16:   return "i16";
41   case MVT::i32:   return "i32";
42   case MVT::i64:   return "i64";
43   case MVT::i128:  return "i128";
44   case MVT::f32:   return "f32";
45   case MVT::f64:   return "f64";
46   case MVT::f80:   return "f80";
47   case MVT::f128:  return "f128";
48   case MVT::Flag:  return "Flag";
49   case MVT::isVoid:return "void";
50   case MVT::v16i8: return "v16i8";
51   case MVT::v8i16: return "v8i16";
52   case MVT::v4i32: return "v4i32";
53   case MVT::v2i64: return "v2i64";
54   case MVT::v4f32: return "v4f32";
55   case MVT::v2f64: return "v2f64";
56   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
57   }
58 }
59
60 std::string llvm::getEnumName(MVT::ValueType T) {
61   switch (T) {
62   case MVT::Other: return "Other";
63   case MVT::i1:    return "i1";
64   case MVT::i8:    return "i8";
65   case MVT::i16:   return "i16";
66   case MVT::i32:   return "i32";
67   case MVT::i64:   return "i64";
68   case MVT::i128:  return "i128";
69   case MVT::f32:   return "f32";
70   case MVT::f64:   return "f64";
71   case MVT::f80:   return "f80";
72   case MVT::f128:  return "f128";
73   case MVT::Flag:  return "Flag";
74   case MVT::isVoid:return "isVoid";
75   case MVT::v16i8: return "v16i8";
76   case MVT::v8i16: return "v8i16";
77   case MVT::v4i32: return "v4i32";
78   case MVT::v2i64: return "v2i64";
79   case MVT::v4f32: return "v4f32";
80   case MVT::v2f64: return "v2f64";
81   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
82   }
83 }
84
85
86 std::ostream &llvm::operator<<(std::ostream &OS, MVT::ValueType T) {
87   return OS << getName(T);
88 }
89
90
91 /// getTarget - Return the current instance of the Target class.
92 ///
93 CodeGenTarget::CodeGenTarget() : PointerType(MVT::Other) {
94   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
95   if (Targets.size() == 0)
96     throw std::string("ERROR: No 'Target' subclasses defined!");
97   if (Targets.size() != 1)
98     throw std::string("ERROR: Multiple subclasses of Target defined!");
99   TargetRec = Targets[0];
100
101   // Read in all of the CalleeSavedRegisters.
102   CalleeSavedRegisters =TargetRec->getValueAsListOfDefs("CalleeSavedRegisters");
103   PointerType = getValueType(TargetRec->getValueAsDef("PointerType"));
104 }
105
106
107 const std::string &CodeGenTarget::getName() const {
108   return TargetRec->getName();
109 }
110
111 Record *CodeGenTarget::getInstructionSet() const {
112   return TargetRec->getValueAsDef("InstructionSet");
113 }
114
115 /// getAsmWriter - Return the AssemblyWriter definition for this target.
116 ///
117 Record *CodeGenTarget::getAsmWriter() const {
118   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
119   if (AsmWriterNum >= LI.size())
120     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
121   return LI[AsmWriterNum];
122 }
123
124 void CodeGenTarget::ReadRegisters() const {
125   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
126   if (Regs.empty())
127     throw std::string("No 'Register' subclasses defined!");
128
129   Registers.reserve(Regs.size());
130   Registers.assign(Regs.begin(), Regs.end());
131 }
132
133 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
134   DeclaredSpillSize = R->getValueAsInt("SpillSize");
135   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
136 }
137
138 const std::string &CodeGenRegister::getName() const {
139   return TheDef->getName();
140 }
141
142 void CodeGenTarget::ReadRegisterClasses() const {
143   std::vector<Record*> RegClasses =
144     Records.getAllDerivedDefinitions("RegisterClass");
145   if (RegClasses.empty())
146     throw std::string("No 'RegisterClass' subclasses defined!");
147
148   RegisterClasses.reserve(RegClasses.size());
149   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
150 }
151
152 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
153   // Rename anonymous register classes.
154   if (R->getName().size() > 9 && R->getName()[9] == '.') {
155     static unsigned AnonCounter = 0;
156     R->setName("AnonRegClass_"+utostr(AnonCounter++));
157   } 
158   
159   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
160   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
161     Record *Type = TypeList[i];
162     if (!Type->isSubClassOf("ValueType"))
163       throw "RegTypes list member '" + Type->getName() +
164         "' does not derive from the ValueType class!";
165     VTs.push_back(getValueType(Type));
166   }
167   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
168   
169   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
170   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
171     Record *Reg = RegList[i];
172     if (!Reg->isSubClassOf("Register"))
173       throw "Register Class member '" + Reg->getName() +
174             "' does not derive from the Register class!";
175     Elements.push_back(Reg);
176   }
177   
178   // Allow targets to override the size in bits of the RegisterClass.
179   unsigned Size = R->getValueAsInt("Size");
180
181   Namespace = R->getValueAsString("Namespace");
182   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
183   SpillAlignment = R->getValueAsInt("Alignment");
184   MethodBodies = R->getValueAsCode("MethodBodies");
185   MethodProtos = R->getValueAsCode("MethodProtos");
186 }
187
188 const std::string &CodeGenRegisterClass::getName() const {
189   return TheDef->getName();
190 }
191
192 void CodeGenTarget::ReadLegalValueTypes() const {
193   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
194   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
195     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
196       LegalValueTypes.push_back(RCs[i].VTs[ri]);
197   
198   // Remove duplicates.
199   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
200   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
201                                     LegalValueTypes.end()),
202                         LegalValueTypes.end());
203 }
204
205
206 void CodeGenTarget::ReadInstructions() const {
207   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
208
209   if (Insts.empty())
210     throw std::string("No 'Instruction' subclasses defined!");
211
212   std::string InstFormatName =
213     getAsmWriter()->getValueAsString("InstFormatName");
214
215   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
216     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
217     Instructions.insert(std::make_pair(Insts[i]->getName(),
218                                        CodeGenInstruction(Insts[i], AsmStr)));
219   }
220 }
221
222 /// getPHIInstruction - Return the designated PHI instruction.
223 ///
224 const CodeGenInstruction &CodeGenTarget::getPHIInstruction() const {
225   Record *PHI = getInstructionSet()->getValueAsDef("PHIInst");
226   std::map<std::string, CodeGenInstruction>::const_iterator I =
227     getInstructions().find(PHI->getName());
228   if (I == Instructions.end())
229     throw "Could not find PHI instruction named '" + PHI->getName() + "'!";
230   return I->second;
231 }
232
233 /// getInstructionsByEnumValue - Return all of the instructions defined by the
234 /// target, ordered by their enum value.
235 void CodeGenTarget::
236 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
237                                                  &NumberedInstructions) {
238
239   // Print out the rest of the instructions now.
240   unsigned i = 0;
241   const CodeGenInstruction *PHI = &getPHIInstruction();
242   NumberedInstructions.push_back(PHI);
243   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
244     if (&II->second != PHI)
245       NumberedInstructions.push_back(&II->second);
246 }
247
248
249 /// isLittleEndianEncoding - Return whether this target encodes its instruction
250 /// in little-endian format, i.e. bits laid out in the order [0..n]
251 ///
252 bool CodeGenTarget::isLittleEndianEncoding() const {
253   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
254 }
255
256 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
257   : TheDef(R), AsmString(AsmStr) {
258   Name      = R->getValueAsString("Name");
259   Namespace = R->getValueAsString("Namespace");
260
261   isReturn     = R->getValueAsBit("isReturn");
262   isBranch     = R->getValueAsBit("isBranch");
263   isBarrier    = R->getValueAsBit("isBarrier");
264   isCall       = R->getValueAsBit("isCall");
265   isLoad       = R->getValueAsBit("isLoad");
266   isStore      = R->getValueAsBit("isStore");
267   isTwoAddress = R->getValueAsBit("isTwoAddress");
268   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
269   isCommutable = R->getValueAsBit("isCommutable");
270   isTerminator = R->getValueAsBit("isTerminator");
271   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
272   usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
273   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
274   noResults    = R->getValueAsBit("noResults");
275   hasVariableNumberOfOperands = false;
276   
277   DagInit *DI;
278   try {
279     DI = R->getValueAsDag("OperandList");
280   } catch (...) {
281     // Error getting operand list, just ignore it (sparcv9).
282     AsmString.clear();
283     OperandList.clear();
284     return;
285   }
286
287   unsigned MIOperandNo = 0;
288   std::set<std::string> OperandNames;
289   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
290     DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
291     if (!Arg)
292       throw "Illegal operand for the '" + R->getName() + "' instruction!";
293
294     Record *Rec = Arg->getDef();
295     std::string PrintMethod = "printOperand";
296     unsigned NumOps = 1;
297     DagInit *MIOpInfo = 0;
298     if (Rec->isSubClassOf("Operand")) {
299       PrintMethod = Rec->getValueAsString("PrintMethod");
300       NumOps = Rec->getValueAsInt("NumMIOperands");
301       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
302     } else if (Rec->getName() == "variable_ops") {
303       hasVariableNumberOfOperands = true;
304       continue;
305     } else if (!Rec->isSubClassOf("RegisterClass"))
306       throw "Unknown operand class '" + Rec->getName() +
307             "' in instruction '" + R->getName() + "' instruction!";
308
309     // Check that the operand has a name and that it's unique.
310     if (DI->getArgName(i).empty())
311       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
312         " has no name!";
313     if (!OperandNames.insert(DI->getArgName(i)).second)
314       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
315         " has the same name as a previous operand!";
316     
317     OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, 
318                                       MIOperandNo, NumOps, MIOpInfo));
319     MIOperandNo += NumOps;
320   }
321 }
322
323
324
325 /// getOperandNamed - Return the index of the operand with the specified
326 /// non-empty name.  If the instruction does not have an operand with the
327 /// specified name, throw an exception.
328 ///
329 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
330   assert(!Name.empty() && "Cannot search for operand with no name!");
331   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
332     if (OperandList[i].Name == Name) return i;
333   throw "Instruction '" + TheDef->getName() +
334         "' does not have an operand named '$" + Name + "'!";
335 }
336
337 //===----------------------------------------------------------------------===//
338 // ComplexPattern implementation
339 //
340 ComplexPattern::ComplexPattern(Record *R) {
341   Ty          = ::getValueType(R->getValueAsDef("Ty"));
342   NumOperands = R->getValueAsInt("NumOperands");
343   SelectFunc  = R->getValueAsString("SelectFunc");
344   RootNodes   = R->getValueAsListOfDefs("RootNodes");
345 }
346