CodeGenTarget.cpp revision 87c8a8f304d1ee72829086ce2c41a8fa3813ba6a
1//===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
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 class wraps 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 "llvm/Support/Streams.h"
23#include <algorithm>
24using namespace llvm;
25
26static cl::opt<unsigned>
27AsmWriterNum("asmwriternum", cl::init(0),
28             cl::desc("Make -gen-asm-writer emit assembly writer #N"));
29
30/// getValueType - Return the MVT::SimpleValueType that the specified TableGen
31/// record corresponds to.
32MVT::SimpleValueType llvm::getValueType(Record *Rec) {
33  return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
34}
35
36std::string llvm::getName(MVT::SimpleValueType T) {
37  switch (T) {
38  case MVT::Other: return "UNKNOWN";
39  case MVT::i1:    return "MVT::i1";
40  case MVT::i8:    return "MVT::i8";
41  case MVT::i16:   return "MVT::i16";
42  case MVT::i32:   return "MVT::i32";
43  case MVT::i64:   return "MVT::i64";
44  case MVT::i128:  return "MVT::i128";
45  case MVT::iAny:  return "MVT::iAny";
46  case MVT::fAny:  return "MVT::fAny";
47  case MVT::f32:   return "MVT::f32";
48  case MVT::f64:   return "MVT::f64";
49  case MVT::f80:   return "MVT::f80";
50  case MVT::f128:  return "MVT::f128";
51  case MVT::ppcf128:  return "MVT::ppcf128";
52  case MVT::Flag:  return "MVT::Flag";
53  case MVT::isVoid:return "MVT::isVoid";
54  case MVT::v2i8:  return "MVT::v2i8";
55  case MVT::v4i8:  return "MVT::v4i8";
56  case MVT::v2i16: return "MVT::v2i16";
57  case MVT::v8i8:  return "MVT::v8i8";
58  case MVT::v4i16: return "MVT::v4i16";
59  case MVT::v2i32: return "MVT::v2i32";
60  case MVT::v1i64: return "MVT::v1i64";
61  case MVT::v16i8: return "MVT::v16i8";
62  case MVT::v8i16: return "MVT::v8i16";
63  case MVT::v4i32: return "MVT::v4i32";
64  case MVT::v2i64: return "MVT::v2i64";
65  case MVT::v2f32: return "MVT::v2f32";
66  case MVT::v4f32: return "MVT::v4f32";
67  case MVT::v2f64: return "MVT::v2f64";
68  case MVT::v3i32: return "MVT::v3i32";
69  case MVT::v3f32: return "MVT::v3f32";
70  case MVT::iPTR:  return "TLI.getPointerTy()";
71  case MVT::iPTRAny:  return "TLI.getPointerTy()";
72  default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
73  }
74}
75
76std::string llvm::getEnumName(MVT::SimpleValueType T) {
77  switch (T) {
78  case MVT::Other: return "MVT::Other";
79  case MVT::i1:    return "MVT::i1";
80  case MVT::i8:    return "MVT::i8";
81  case MVT::i16:   return "MVT::i16";
82  case MVT::i32:   return "MVT::i32";
83  case MVT::i64:   return "MVT::i64";
84  case MVT::i128:  return "MVT::i128";
85  case MVT::iAny:  return "MVT::iAny";
86  case MVT::fAny:  return "MVT::fAny";
87  case MVT::f32:   return "MVT::f32";
88  case MVT::f64:   return "MVT::f64";
89  case MVT::f80:   return "MVT::f80";
90  case MVT::f128:  return "MVT::f128";
91  case MVT::ppcf128:  return "MVT::ppcf128";
92  case MVT::Flag:  return "MVT::Flag";
93  case MVT::isVoid:return "MVT::isVoid";
94  case MVT::v2i8:  return "MVT::v2i8";
95  case MVT::v4i8:  return "MVT::v4i8";
96  case MVT::v2i16: return "MVT::v2i16";
97  case MVT::v8i8:  return "MVT::v8i8";
98  case MVT::v4i16: return "MVT::v4i16";
99  case MVT::v2i32: return "MVT::v2i32";
100  case MVT::v1i64: return "MVT::v1i64";
101  case MVT::v16i8: return "MVT::v16i8";
102  case MVT::v8i16: return "MVT::v8i16";
103  case MVT::v4i32: return "MVT::v4i32";
104  case MVT::v2i64: return "MVT::v2i64";
105  case MVT::v2f32: return "MVT::v2f32";
106  case MVT::v4f32: return "MVT::v4f32";
107  case MVT::v2f64: return "MVT::v2f64";
108  case MVT::v3i32: return "MVT::v3i32";
109  case MVT::v3f32: return "MVT::v3f32";
110  case MVT::iPTR:  return "MVT::iPTR";
111  case MVT::iPTRAny:  return "MVT::iPTRAny";
112  default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
113  }
114}
115
116/// getQualifiedName - Return the name of the specified record, with a
117/// namespace qualifier if the record contains one.
118///
119std::string llvm::getQualifiedName(const Record *R) {
120  std::string Namespace = R->getValueAsString("Namespace");
121  if (Namespace.empty()) return R->getName();
122  return Namespace + "::" + R->getName();
123}
124
125
126
127
128/// getTarget - Return the current instance of the Target class.
129///
130CodeGenTarget::CodeGenTarget() {
131  std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
132  if (Targets.size() == 0)
133    throw std::string("ERROR: No 'Target' subclasses defined!");
134  if (Targets.size() != 1)
135    throw std::string("ERROR: Multiple subclasses of Target defined!");
136  TargetRec = Targets[0];
137}
138
139
140const std::string &CodeGenTarget::getName() const {
141  return TargetRec->getName();
142}
143
144std::string CodeGenTarget::getInstNamespace() const {
145  std::string InstNS;
146
147  for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
148    InstNS = i->second.Namespace;
149
150    // Make sure not to pick up "TargetInstrInfo" by accidentally getting
151    // the namespace off the PHI instruction or something.
152    if (InstNS != "TargetInstrInfo")
153      break;
154  }
155
156  return InstNS;
157}
158
159Record *CodeGenTarget::getInstructionSet() const {
160  return TargetRec->getValueAsDef("InstructionSet");
161}
162
163/// getAsmWriter - Return the AssemblyWriter definition for this target.
164///
165Record *CodeGenTarget::getAsmWriter() const {
166  std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
167  if (AsmWriterNum >= LI.size())
168    throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
169  return LI[AsmWriterNum];
170}
171
172void CodeGenTarget::ReadRegisters() const {
173  std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
174  if (Regs.empty())
175    throw std::string("No 'Register' subclasses defined!");
176
177  Registers.reserve(Regs.size());
178  Registers.assign(Regs.begin(), Regs.end());
179}
180
181CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
182  DeclaredSpillSize = R->getValueAsInt("SpillSize");
183  DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
184}
185
186const std::string &CodeGenRegister::getName() const {
187  return TheDef->getName();
188}
189
190void CodeGenTarget::ReadRegisterClasses() const {
191  std::vector<Record*> RegClasses =
192    Records.getAllDerivedDefinitions("RegisterClass");
193  if (RegClasses.empty())
194    throw std::string("No 'RegisterClass' subclasses defined!");
195
196  RegisterClasses.reserve(RegClasses.size());
197  RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
198}
199
200std::vector<unsigned char> CodeGenTarget::getRegisterVTs(Record *R) const {
201  std::vector<unsigned char> Result;
202  const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
203  for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
204    const CodeGenRegisterClass &RC = RegisterClasses[i];
205    for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
206      if (R == RC.Elements[ei]) {
207        const std::vector<MVT::SimpleValueType> &InVTs = RC.getValueTypes();
208        for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
209          Result.push_back(InVTs[i]);
210      }
211    }
212  }
213  return Result;
214}
215
216
217CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
218  // Rename anonymous register classes.
219  if (R->getName().size() > 9 && R->getName()[9] == '.') {
220    static unsigned AnonCounter = 0;
221    R->setName("AnonRegClass_"+utostr(AnonCounter++));
222  }
223
224  std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
225  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
226    Record *Type = TypeList[i];
227    if (!Type->isSubClassOf("ValueType"))
228      throw "RegTypes list member '" + Type->getName() +
229        "' does not derive from the ValueType class!";
230    VTs.push_back(getValueType(Type));
231  }
232  assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
233
234  std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
235  for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
236    Record *Reg = RegList[i];
237    if (!Reg->isSubClassOf("Register"))
238      throw "Register Class member '" + Reg->getName() +
239            "' does not derive from the Register class!";
240    Elements.push_back(Reg);
241  }
242
243  std::vector<Record*> SubRegClassList =
244                        R->getValueAsListOfDefs("SubRegClassList");
245  for (unsigned i = 0, e = SubRegClassList.size(); i != e; ++i) {
246    Record *SubRegClass = SubRegClassList[i];
247    if (!SubRegClass->isSubClassOf("RegisterClass"))
248      throw "Register Class member '" + SubRegClass->getName() +
249            "' does not derive from the RegisterClass class!";
250    SubRegClasses.push_back(SubRegClass);
251  }
252
253  // Allow targets to override the size in bits of the RegisterClass.
254  unsigned Size = R->getValueAsInt("Size");
255
256  Namespace = R->getValueAsString("Namespace");
257  SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
258  SpillAlignment = R->getValueAsInt("Alignment");
259  CopyCost = R->getValueAsInt("CopyCost");
260  MethodBodies = R->getValueAsCode("MethodBodies");
261  MethodProtos = R->getValueAsCode("MethodProtos");
262}
263
264const std::string &CodeGenRegisterClass::getName() const {
265  return TheDef->getName();
266}
267
268void CodeGenTarget::ReadLegalValueTypes() const {
269  const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
270  for (unsigned i = 0, e = RCs.size(); i != e; ++i)
271    for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
272      LegalValueTypes.push_back(RCs[i].VTs[ri]);
273
274  // Remove duplicates.
275  std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
276  LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
277                                    LegalValueTypes.end()),
278                        LegalValueTypes.end());
279}
280
281
282void CodeGenTarget::ReadInstructions() const {
283  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
284  if (Insts.size() <= 2)
285    throw std::string("No 'Instruction' subclasses defined!");
286
287  // Parse the instructions defined in the .td file.
288  std::string InstFormatName =
289    getAsmWriter()->getValueAsString("InstFormatName");
290
291  for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
292    std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
293    Instructions.insert(std::make_pair(Insts[i]->getName(),
294                                       CodeGenInstruction(Insts[i], AsmStr)));
295  }
296}
297
298/// getInstructionsByEnumValue - Return all of the instructions defined by the
299/// target, ordered by their enum value.
300void CodeGenTarget::
301getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
302                                                 &NumberedInstructions) {
303  std::map<std::string, CodeGenInstruction>::const_iterator I;
304  I = getInstructions().find("PHI");
305  if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
306  const CodeGenInstruction *PHI = &I->second;
307
308  I = getInstructions().find("INLINEASM");
309  if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
310  const CodeGenInstruction *INLINEASM = &I->second;
311
312  I = getInstructions().find("DBG_LABEL");
313  if (I == Instructions.end()) throw "Could not find 'DBG_LABEL' instruction!";
314  const CodeGenInstruction *DBG_LABEL = &I->second;
315
316  I = getInstructions().find("EH_LABEL");
317  if (I == Instructions.end()) throw "Could not find 'EH_LABEL' instruction!";
318  const CodeGenInstruction *EH_LABEL = &I->second;
319
320  I = getInstructions().find("GC_LABEL");
321  if (I == Instructions.end()) throw "Could not find 'GC_LABEL' instruction!";
322  const CodeGenInstruction *GC_LABEL = &I->second;
323
324  I = getInstructions().find("DECLARE");
325  if (I == Instructions.end()) throw "Could not find 'DECLARE' instruction!";
326  const CodeGenInstruction *DECLARE = &I->second;
327
328  I = getInstructions().find("EXTRACT_SUBREG");
329  if (I == Instructions.end())
330    throw "Could not find 'EXTRACT_SUBREG' instruction!";
331  const CodeGenInstruction *EXTRACT_SUBREG = &I->second;
332
333  I = getInstructions().find("INSERT_SUBREG");
334  if (I == Instructions.end())
335    throw "Could not find 'INSERT_SUBREG' instruction!";
336  const CodeGenInstruction *INSERT_SUBREG = &I->second;
337
338  I = getInstructions().find("IMPLICIT_DEF");
339  if (I == Instructions.end())
340    throw "Could not find 'IMPLICIT_DEF' instruction!";
341  const CodeGenInstruction *IMPLICIT_DEF = &I->second;
342
343  I = getInstructions().find("SUBREG_TO_REG");
344  if (I == Instructions.end())
345    throw "Could not find 'SUBREG_TO_REG' instruction!";
346  const CodeGenInstruction *SUBREG_TO_REG = &I->second;
347
348  // Print out the rest of the instructions now.
349  NumberedInstructions.push_back(PHI);
350  NumberedInstructions.push_back(INLINEASM);
351  NumberedInstructions.push_back(DBG_LABEL);
352  NumberedInstructions.push_back(EH_LABEL);
353  NumberedInstructions.push_back(GC_LABEL);
354  NumberedInstructions.push_back(DECLARE);
355  NumberedInstructions.push_back(EXTRACT_SUBREG);
356  NumberedInstructions.push_back(INSERT_SUBREG);
357  NumberedInstructions.push_back(IMPLICIT_DEF);
358  NumberedInstructions.push_back(SUBREG_TO_REG);
359  for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
360    if (&II->second != PHI &&
361        &II->second != INLINEASM &&
362        &II->second != DBG_LABEL &&
363        &II->second != EH_LABEL &&
364        &II->second != GC_LABEL &&
365        &II->second != DECLARE &&
366        &II->second != EXTRACT_SUBREG &&
367        &II->second != INSERT_SUBREG &&
368        &II->second != IMPLICIT_DEF &&
369        &II->second != SUBREG_TO_REG)
370      NumberedInstructions.push_back(&II->second);
371}
372
373
374/// isLittleEndianEncoding - Return whether this target encodes its instruction
375/// in little-endian format, i.e. bits laid out in the order [0..n]
376///
377bool CodeGenTarget::isLittleEndianEncoding() const {
378  return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
379}
380
381//===----------------------------------------------------------------------===//
382// ComplexPattern implementation
383//
384ComplexPattern::ComplexPattern(Record *R) {
385  Ty          = ::getValueType(R->getValueAsDef("Ty"));
386  NumOperands = R->getValueAsInt("NumOperands");
387  SelectFunc  = R->getValueAsString("SelectFunc");
388  RootNodes   = R->getValueAsListOfDefs("RootNodes");
389
390  // Parse the properties.
391  Properties = 0;
392  std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
393  for (unsigned i = 0, e = PropList.size(); i != e; ++i)
394    if (PropList[i]->getName() == "SDNPHasChain") {
395      Properties |= 1 << SDNPHasChain;
396    } else if (PropList[i]->getName() == "SDNPOptInFlag") {
397      Properties |= 1 << SDNPOptInFlag;
398    } else if (PropList[i]->getName() == "SDNPMayStore") {
399      Properties |= 1 << SDNPMayStore;
400    } else if (PropList[i]->getName() == "SDNPMayLoad") {
401      Properties |= 1 << SDNPMayLoad;
402    } else if (PropList[i]->getName() == "SDNPSideEffect") {
403      Properties |= 1 << SDNPSideEffect;
404    } else if (PropList[i]->getName() == "SDNPMemOperand") {
405      Properties |= 1 << SDNPMemOperand;
406    } else {
407      cerr << "Unsupported SD Node property '" << PropList[i]->getName()
408           << "' on ComplexPattern '" << R->getName() << "'!\n";
409      exit(1);
410    }
411
412  // Parse the attributes.
413  Attributes = 0;
414  PropList = R->getValueAsListOfDefs("Attributes");
415  for (unsigned i = 0, e = PropList.size(); i != e; ++i)
416    if (PropList[i]->getName() == "CPAttrParentAsRoot") {
417      Attributes |= 1 << CPAttrParentAsRoot;
418    } else {
419      cerr << "Unsupported pattern attribute '" << PropList[i]->getName()
420           << "' on ComplexPattern '" << R->getName() << "'!\n";
421      exit(1);
422    }
423}
424
425//===----------------------------------------------------------------------===//
426// CodeGenIntrinsic Implementation
427//===----------------------------------------------------------------------===//
428
429std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
430  std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
431
432  std::vector<CodeGenIntrinsic> Result;
433
434  for (unsigned i = 0, e = I.size(); i != e; ++i)
435    Result.push_back(CodeGenIntrinsic(I[i]));
436  return Result;
437}
438
439CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
440  TheDef = R;
441  std::string DefName = R->getName();
442  ModRef = WriteMem;
443  isOverloaded = false;
444  isCommutative = false;
445
446  if (DefName.size() <= 4 ||
447      std::string(DefName.begin(), DefName.begin() + 4) != "int_")
448    throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
449
450  EnumName = std::string(DefName.begin()+4, DefName.end());
451
452  if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
453    GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
454
455  TargetPrefix = R->getValueAsString("TargetPrefix");
456  Name = R->getValueAsString("LLVMName");
457
458  if (Name == "") {
459    // If an explicit name isn't specified, derive one from the DefName.
460    Name = "llvm.";
461
462    for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
463      Name += (EnumName[i] == '_') ? '.' : EnumName[i];
464  } else {
465    // Verify it starts with "llvm.".
466    if (Name.size() <= 5 ||
467        std::string(Name.begin(), Name.begin() + 5) != "llvm.")
468      throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
469  }
470
471  // If TargetPrefix is specified, make sure that Name starts with
472  // "llvm.<targetprefix>.".
473  if (!TargetPrefix.empty()) {
474    if (Name.size() < 6+TargetPrefix.size() ||
475        std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
476        != (TargetPrefix + "."))
477      throw "Intrinsic '" + DefName + "' does not start with 'llvm." +
478        TargetPrefix + ".'!";
479  }
480
481  // Parse the list of return types.
482  ListInit *TypeList = R->getValueAsListInit("RetTypes");
483  for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
484    Record *TyEl = TypeList->getElementAsRecord(i);
485    assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
486    MVT::SimpleValueType VT = getValueType(TyEl->getValueAsDef("VT"));
487    isOverloaded |= VT == MVT::iAny || VT == MVT::fAny || VT == MVT::iPTRAny;
488    IS.RetVTs.push_back(VT);
489    IS.RetTypeDefs.push_back(TyEl);
490  }
491
492  if (IS.RetVTs.size() == 0)
493    throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
494
495  // Parse the list of parameter types.
496  TypeList = R->getValueAsListInit("ParamTypes");
497  for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
498    Record *TyEl = TypeList->getElementAsRecord(i);
499    assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
500    MVT::SimpleValueType VT = getValueType(TyEl->getValueAsDef("VT"));
501    isOverloaded |= VT == MVT::iAny || VT == MVT::fAny || VT == MVT::iPTRAny;
502    IS.ParamVTs.push_back(VT);
503    IS.ParamTypeDefs.push_back(TyEl);
504  }
505
506  // Parse the intrinsic properties.
507  ListInit *PropList = R->getValueAsListInit("Properties");
508  for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
509    Record *Property = PropList->getElementAsRecord(i);
510    assert(Property->isSubClassOf("IntrinsicProperty") &&
511           "Expected a property!");
512
513    if (Property->getName() == "IntrNoMem")
514      ModRef = NoMem;
515    else if (Property->getName() == "IntrReadArgMem")
516      ModRef = ReadArgMem;
517    else if (Property->getName() == "IntrReadMem")
518      ModRef = ReadMem;
519    else if (Property->getName() == "IntrWriteArgMem")
520      ModRef = WriteArgMem;
521    else if (Property->getName() == "IntrWriteMem")
522      ModRef = WriteMem;
523    else if (Property->getName() == "Commutative")
524      isCommutative = true;
525    else
526      assert(0 && "Unknown property!");
527  }
528}
529