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