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