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