42864f54f3af2a6e014a44c4188271db5b975a63
[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 "CodeGenIntrinsics.h"
19 #include "Record.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CommandLine.h"
22 #include <set>
23 #include <algorithm>
24 using namespace llvm;
25
26 static cl::opt<unsigned>
27 AsmWriterNum("asmwriternum", cl::init(0),
28              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
29
30 /// getValueType - Return the MCV::ValueType that the specified TableGen record
31 /// corresponds to.
32 MVT::ValueType llvm::getValueType(Record *Rec) {
33   return (MVT::ValueType)Rec->getValueAsInt("Value");
34 }
35
36 std::string llvm::getName(MVT::ValueType T) {
37   switch (T) {
38   case MVT::Other: return "UNKNOWN";
39   case MVT::i1:    return "i1";
40   case MVT::i8:    return "i8";
41   case MVT::i16:   return "i16";
42   case MVT::i32:   return "i32";
43   case MVT::i64:   return "i64";
44   case MVT::i128:  return "i128";
45   case MVT::f32:   return "f32";
46   case MVT::f64:   return "f64";
47   case MVT::f80:   return "f80";
48   case MVT::f128:  return "f128";
49   case MVT::Flag:  return "Flag";
50   case MVT::isVoid:return "void";
51   case MVT::v8i8:  return "v8i8";
52   case MVT::v4i16: return "v4i16";
53   case MVT::v2i32: return "v2i32";
54   case MVT::v16i8: return "v16i8";
55   case MVT::v8i16: return "v8i16";
56   case MVT::v4i32: return "v4i32";
57   case MVT::v2i64: return "v2i64";
58   case MVT::v2f32: return "v2f32";
59   case MVT::v4f32: return "v4f32";
60   case MVT::v2f64: return "v2f64";
61   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
62   }
63 }
64
65 std::string llvm::getEnumName(MVT::ValueType T) {
66   switch (T) {
67   case MVT::Other: return "Other";
68   case MVT::i1:    return "i1";
69   case MVT::i8:    return "i8";
70   case MVT::i16:   return "i16";
71   case MVT::i32:   return "i32";
72   case MVT::i64:   return "i64";
73   case MVT::i128:  return "i128";
74   case MVT::f32:   return "f32";
75   case MVT::f64:   return "f64";
76   case MVT::f80:   return "f80";
77   case MVT::f128:  return "f128";
78   case MVT::Flag:  return "Flag";
79   case MVT::isVoid:return "isVoid";
80   case MVT::v8i8:  return "v8i8";
81   case MVT::v4i16: return "v4i16";
82   case MVT::v2i32: return "v2i32";
83   case MVT::v16i8: return "v16i8";
84   case MVT::v8i16: return "v8i16";
85   case MVT::v4i32: return "v4i32";
86   case MVT::v2i64: return "v2i64";
87   case MVT::v2f32: return "v2f32";
88   case MVT::v4f32: return "v4f32";
89   case MVT::v2f64: return "v2f64";
90   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
91   }
92 }
93
94
95 std::ostream &llvm::operator<<(std::ostream &OS, MVT::ValueType T) {
96   return OS << getName(T);
97 }
98
99
100 /// getTarget - Return the current instance of the Target class.
101 ///
102 CodeGenTarget::CodeGenTarget() : PointerType(MVT::Other) {
103   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
104   if (Targets.size() == 0)
105     throw std::string("ERROR: No 'Target' subclasses defined!");
106   if (Targets.size() != 1)
107     throw std::string("ERROR: Multiple subclasses of Target defined!");
108   TargetRec = Targets[0];
109
110   // Read in all of the CalleeSavedRegisters.
111   CalleeSavedRegisters =TargetRec->getValueAsListOfDefs("CalleeSavedRegisters");
112   PointerType = getValueType(TargetRec->getValueAsDef("PointerType"));
113 }
114
115
116 const std::string &CodeGenTarget::getName() const {
117   return TargetRec->getName();
118 }
119
120 Record *CodeGenTarget::getInstructionSet() const {
121   return TargetRec->getValueAsDef("InstructionSet");
122 }
123
124 /// getAsmWriter - Return the AssemblyWriter definition for this target.
125 ///
126 Record *CodeGenTarget::getAsmWriter() const {
127   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
128   if (AsmWriterNum >= LI.size())
129     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
130   return LI[AsmWriterNum];
131 }
132
133 void CodeGenTarget::ReadRegisters() const {
134   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
135   if (Regs.empty())
136     throw std::string("No 'Register' subclasses defined!");
137
138   Registers.reserve(Regs.size());
139   Registers.assign(Regs.begin(), Regs.end());
140 }
141
142 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
143   DeclaredSpillSize = R->getValueAsInt("SpillSize");
144   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
145 }
146
147 const std::string &CodeGenRegister::getName() const {
148   return TheDef->getName();
149 }
150
151 void CodeGenTarget::ReadRegisterClasses() const {
152   std::vector<Record*> RegClasses =
153     Records.getAllDerivedDefinitions("RegisterClass");
154   if (RegClasses.empty())
155     throw std::string("No 'RegisterClass' subclasses defined!");
156
157   RegisterClasses.reserve(RegClasses.size());
158   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
159 }
160
161 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
162   // Rename anonymous register classes.
163   if (R->getName().size() > 9 && R->getName()[9] == '.') {
164     static unsigned AnonCounter = 0;
165     R->setName("AnonRegClass_"+utostr(AnonCounter++));
166   } 
167   
168   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
169   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
170     Record *Type = TypeList[i];
171     if (!Type->isSubClassOf("ValueType"))
172       throw "RegTypes list member '" + Type->getName() +
173         "' does not derive from the ValueType class!";
174     VTs.push_back(getValueType(Type));
175   }
176   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
177   
178   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
179   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
180     Record *Reg = RegList[i];
181     if (!Reg->isSubClassOf("Register"))
182       throw "Register Class member '" + Reg->getName() +
183             "' does not derive from the Register class!";
184     Elements.push_back(Reg);
185   }
186   
187   // Allow targets to override the size in bits of the RegisterClass.
188   unsigned Size = R->getValueAsInt("Size");
189
190   Namespace = R->getValueAsString("Namespace");
191   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
192   SpillAlignment = R->getValueAsInt("Alignment");
193   MethodBodies = R->getValueAsCode("MethodBodies");
194   MethodProtos = R->getValueAsCode("MethodProtos");
195 }
196
197 const std::string &CodeGenRegisterClass::getName() const {
198   return TheDef->getName();
199 }
200
201 void CodeGenTarget::ReadLegalValueTypes() const {
202   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
203   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
204     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
205       LegalValueTypes.push_back(RCs[i].VTs[ri]);
206   
207   // Remove duplicates.
208   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
209   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
210                                     LegalValueTypes.end()),
211                         LegalValueTypes.end());
212 }
213
214
215 void CodeGenTarget::ReadInstructions() const {
216   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
217   if (Insts.size() <= 2)
218     throw std::string("No 'Instruction' subclasses defined!");
219
220   // Parse the instructions defined in the .td file.
221   std::string InstFormatName =
222     getAsmWriter()->getValueAsString("InstFormatName");
223
224   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
225     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
226     Instructions.insert(std::make_pair(Insts[i]->getName(),
227                                        CodeGenInstruction(Insts[i], AsmStr)));
228   }
229 }
230
231 /// getInstructionsByEnumValue - Return all of the instructions defined by the
232 /// target, ordered by their enum value.
233 void CodeGenTarget::
234 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
235                                                  &NumberedInstructions) {
236   std::map<std::string, CodeGenInstruction>::const_iterator I;
237   I = getInstructions().find("PHI");
238   if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
239   const CodeGenInstruction *PHI = &I->second;
240   
241   I = getInstructions().find("INLINEASM");
242   if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
243   const CodeGenInstruction *INLINEASM = &I->second;
244   
245   // Print out the rest of the instructions now.
246   NumberedInstructions.push_back(PHI);
247   NumberedInstructions.push_back(INLINEASM);
248   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
249     if (&II->second != PHI &&&II->second != INLINEASM)
250       NumberedInstructions.push_back(&II->second);
251 }
252
253
254 /// isLittleEndianEncoding - Return whether this target encodes its instruction
255 /// in little-endian format, i.e. bits laid out in the order [0..n]
256 ///
257 bool CodeGenTarget::isLittleEndianEncoding() const {
258   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
259 }
260
261 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
262   : TheDef(R), AsmString(AsmStr) {
263   Name      = R->getValueAsString("Name");
264   Namespace = R->getValueAsString("Namespace");
265
266   isReturn     = R->getValueAsBit("isReturn");
267   isBranch     = R->getValueAsBit("isBranch");
268   isBarrier    = R->getValueAsBit("isBarrier");
269   isCall       = R->getValueAsBit("isCall");
270   isLoad       = R->getValueAsBit("isLoad");
271   isStore      = R->getValueAsBit("isStore");
272   isTwoAddress = R->getValueAsBit("isTwoAddress");
273   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
274   isCommutable = R->getValueAsBit("isCommutable");
275   isTerminator = R->getValueAsBit("isTerminator");
276   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
277   usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
278   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
279   noResults    = R->getValueAsBit("noResults");
280   hasVariableNumberOfOperands = false;
281   
282   DagInit *DI;
283   try {
284     DI = R->getValueAsDag("OperandList");
285   } catch (...) {
286     // Error getting operand list, just ignore it (sparcv9).
287     AsmString.clear();
288     OperandList.clear();
289     return;
290   }
291
292   unsigned MIOperandNo = 0;
293   std::set<std::string> OperandNames;
294   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
295     DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
296     if (!Arg)
297       throw "Illegal operand for the '" + R->getName() + "' instruction!";
298
299     Record *Rec = Arg->getDef();
300     std::string PrintMethod = "printOperand";
301     unsigned NumOps = 1;
302     DagInit *MIOpInfo = 0;
303     if (Rec->isSubClassOf("Operand")) {
304       PrintMethod = Rec->getValueAsString("PrintMethod");
305       NumOps = Rec->getValueAsInt("NumMIOperands");
306       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
307     } else if (Rec->getName() == "variable_ops") {
308       hasVariableNumberOfOperands = true;
309       continue;
310     } else if (!Rec->isSubClassOf("RegisterClass"))
311       throw "Unknown operand class '" + Rec->getName() +
312             "' in instruction '" + R->getName() + "' instruction!";
313
314     // Check that the operand has a name and that it's unique.
315     if (DI->getArgName(i).empty())
316       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
317         " has no name!";
318     if (!OperandNames.insert(DI->getArgName(i)).second)
319       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
320         " has the same name as a previous operand!";
321     
322     OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, 
323                                       MIOperandNo, NumOps, MIOpInfo));
324     MIOperandNo += NumOps;
325   }
326 }
327
328
329
330 /// getOperandNamed - Return the index of the operand with the specified
331 /// non-empty name.  If the instruction does not have an operand with the
332 /// specified name, throw an exception.
333 ///
334 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
335   assert(!Name.empty() && "Cannot search for operand with no name!");
336   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
337     if (OperandList[i].Name == Name) return i;
338   throw "Instruction '" + TheDef->getName() +
339         "' does not have an operand named '$" + Name + "'!";
340 }
341
342 //===----------------------------------------------------------------------===//
343 // ComplexPattern implementation
344 //
345 ComplexPattern::ComplexPattern(Record *R) {
346   Ty          = ::getValueType(R->getValueAsDef("Ty"));
347   NumOperands = R->getValueAsInt("NumOperands");
348   SelectFunc  = R->getValueAsString("SelectFunc");
349   RootNodes   = R->getValueAsListOfDefs("RootNodes");
350 }
351
352 //===----------------------------------------------------------------------===//
353 // CodeGenIntrinsic Implementation
354 //===----------------------------------------------------------------------===//
355
356 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
357   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
358   return std::vector<CodeGenIntrinsic>(I.begin(), I.end());
359 }
360
361 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
362   TheDef = R;
363   std::string DefName = R->getName();
364   ModRef = WriteMem;
365   
366   if (DefName.size() <= 4 || 
367       std::string(DefName.begin(), DefName.begin()+4) != "int_")
368     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
369   EnumName = std::string(DefName.begin()+4, DefName.end());
370   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
371     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
372   TargetPrefix   = R->getValueAsString("TargetPrefix");
373   Name = R->getValueAsString("LLVMName");
374   if (Name == "") {
375     // If an explicit name isn't specified, derive one from the DefName.
376     Name = "llvm.";
377     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
378       if (EnumName[i] == '_')
379         Name += '.';
380       else
381         Name += EnumName[i];
382   } else {
383     // Verify it starts with "llvm.".
384     if (Name.size() <= 5 || 
385         std::string(Name.begin(), Name.begin()+5) != "llvm.")
386       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
387   }
388   
389   // If TargetPrefix is specified, make sure that Name starts with
390   // "llvm.<targetprefix>.".
391   if (!TargetPrefix.empty()) {
392     if (Name.size() < 6+TargetPrefix.size() ||
393         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
394         != (TargetPrefix+"."))
395       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
396         TargetPrefix + ".'!";
397   }
398   
399   // Parse the list of argument types.
400   ListInit *TypeList = R->getValueAsListInit("Types");
401   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
402     DefInit *DI = dynamic_cast<DefInit*>(TypeList->getElement(i));
403     assert(DI && "Invalid list type!");
404     Record *TyEl = DI->getDef();
405     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
406     ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
407     
408     ArgVTs.push_back(getValueType(TyEl->getValueAsDef("VT")));
409     ArgTypeDefs.push_back(TyEl);
410   }
411   if (ArgTypes.size() == 0)
412     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
413   
414   // Parse the intrinsic properties.
415   ListInit *PropList = R->getValueAsListInit("Properties");
416   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
417     DefInit *DI = dynamic_cast<DefInit*>(PropList->getElement(i));
418     assert(DI && "Invalid list type!");
419     Record *Property = DI->getDef();
420     assert(Property->isSubClassOf("IntrinsicProperty") &&
421            "Expected a property!");
422     
423     if (Property->getName() == "InstrNoMem")
424       ModRef = NoMem;
425     else if (Property->getName() == "InstrReadArgMem")
426       ModRef = ReadArgMem;
427     else if (Property->getName() == "IntrReadMem")
428       ModRef = ReadMem;
429     else if (Property->getName() == "InstrWriteArgMem")
430       ModRef = WriteArgMem;
431     else if (Property->getName() == "IntrWriteMem")
432       ModRef = WriteMem;
433     else
434       assert(0 && "Unknown property!");
435   }
436 }