source: parabix-LLVM/CodeGenTarget.cpp.pytemplate @ 4014

Last change on this file since 4014 was 3853, checked in by cameron, 5 years ago

Also generate CodeGenTarget?.cpp for TableGen?

File size: 20.0 KB
Line 
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 abort on error conditions.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CodeGenTarget.h"
18#include "CodeGenIntrinsics.h"
19#include "CodeGenSchedule.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/TableGen/Error.h"
24#include "llvm/TableGen/Record.h"
25#include <algorithm>
26using namespace llvm;
27
28static cl::opt<unsigned>
29AsmParserNum("asmparsernum", cl::init(0),
30             cl::desc("Make -gen-asm-parser emit assembly parser #N"));
31
32static cl::opt<unsigned>
33AsmWriterNum("asmwriternum", cl::init(0),
34             cl::desc("Make -gen-asm-writer emit assembly writer #N"));
35
36/// getValueType - Return the MVT::SimpleValueType that the specified TableGen
37/// record corresponds to.
38MVT::SimpleValueType llvm::getValueType(Record *Rec) {
39  return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
40}
41
42std::string llvm::getName(MVT::SimpleValueType T) {
43  switch (T) {
44  case MVT::Other:   return "UNKNOWN";
45  case MVT::iPTR:    return "TLI.getPointerTy()";
46  case MVT::iPTRAny: return "TLI.getPointerTy()";
47  default: return getEnumName(T);
48  }
49}
50
51std::string llvm::getEnumName(MVT::SimpleValueType T) {
52  switch (T) {
53  case MVT::Other:    return "MVT::Other";
54${int_type_enum_strings}
55  case MVT::iAny:     return "MVT::iAny";
56  case MVT::fAny:     return "MVT::fAny";
57  case MVT::vAny:     return "MVT::vAny";
58  case MVT::f16:      return "MVT::f16";
59  case MVT::f32:      return "MVT::f32";
60  case MVT::f64:      return "MVT::f64";
61  case MVT::f80:      return "MVT::f80";
62  case MVT::f128:     return "MVT::f128";
63  case MVT::ppcf128:  return "MVT::ppcf128";
64  case MVT::x86mmx:   return "MVT::x86mmx";
65  case MVT::Glue:     return "MVT::Glue";
66  case MVT::isVoid:   return "MVT::isVoid";
67${int_vector_value_enum_strings}
68${float_vector_value_enum_strings}
69  case MVT::Metadata: return "MVT::Metadata";
70  case MVT::iPTR:     return "MVT::iPTR";
71  case MVT::iPTRAny:  return "MVT::iPTRAny";
72  case MVT::Untyped:  return "MVT::Untyped";
73  default: llvm_unreachable("ILLEGAL VALUE TYPE!");
74  }
75}
76
77/// getQualifiedName - Return the name of the specified record, with a
78/// namespace qualifier if the record contains one.
79///
80std::string llvm::getQualifiedName(const Record *R) {
81  std::string Namespace;
82  if (R->getValue("Namespace"))
83     Namespace = R->getValueAsString("Namespace");
84  if (Namespace.empty()) return R->getName();
85  return Namespace + "::" + R->getName();
86}
87
88
89/// getTarget - Return the current instance of the Target class.
90///
91CodeGenTarget::CodeGenTarget(RecordKeeper &records)
92  : Records(records), RegBank(nullptr), SchedModels(nullptr) {
93  std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
94  if (Targets.size() == 0)
95    PrintFatalError("ERROR: No 'Target' subclasses defined!");
96  if (Targets.size() != 1)
97    PrintFatalError("ERROR: Multiple subclasses of Target defined!");
98  TargetRec = Targets[0];
99}
100
101CodeGenTarget::~CodeGenTarget() {
102  DeleteContainerSeconds(Instructions);
103  delete RegBank;
104  delete SchedModels;
105}
106
107const std::string &CodeGenTarget::getName() const {
108  return TargetRec->getName();
109}
110
111std::string CodeGenTarget::getInstNamespace() const {
112  for (inst_iterator i = inst_begin(), e = inst_end(); i != e; ++i) {
113    // Make sure not to pick up "TargetOpcode" by accidentally getting
114    // the namespace off the PHI instruction or something.
115    if ((*i)->Namespace != "TargetOpcode")
116      return (*i)->Namespace;
117  }
118
119  return "";
120}
121
122Record *CodeGenTarget::getInstructionSet() const {
123  return TargetRec->getValueAsDef("InstructionSet");
124}
125
126
127/// getAsmParser - Return the AssemblyParser definition for this target.
128///
129Record *CodeGenTarget::getAsmParser() const {
130  std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
131  if (AsmParserNum >= LI.size())
132    PrintFatalError("Target does not have an AsmParser #" +
133                    Twine(AsmParserNum) + "!");
134  return LI[AsmParserNum];
135}
136
137/// getAsmParserVariant - Return the AssmblyParserVariant definition for
138/// this target.
139///
140Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
141  std::vector<Record*> LI =
142    TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
143  if (i >= LI.size())
144    PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
145                    "!");
146  return LI[i];
147}
148
149/// getAsmParserVariantCount - Return the AssmblyParserVariant definition
150/// available for this target.
151///
152unsigned CodeGenTarget::getAsmParserVariantCount() const {
153  std::vector<Record*> LI =
154    TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
155  return LI.size();
156}
157
158/// getAsmWriter - Return the AssemblyWriter definition for this target.
159///
160Record *CodeGenTarget::getAsmWriter() const {
161  std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
162  if (AsmWriterNum >= LI.size())
163    PrintFatalError("Target does not have an AsmWriter #" +
164                    Twine(AsmWriterNum) + "!");
165  return LI[AsmWriterNum];
166}
167
168CodeGenRegBank &CodeGenTarget::getRegBank() const {
169  if (!RegBank)
170    RegBank = new CodeGenRegBank(Records);
171  return *RegBank;
172}
173
174void CodeGenTarget::ReadRegAltNameIndices() const {
175  RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
176  std::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
177}
178
179/// getRegisterByName - If there is a register with the specific AsmName,
180/// return it.
181const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
182  const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
183  StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
184  if (I == Regs.end())
185    return nullptr;
186  return I->second;
187}
188
189std::vector<MVT::SimpleValueType> CodeGenTarget::
190getRegisterVTs(Record *R) const {
191  const CodeGenRegister *Reg = getRegBank().getReg(R);
192  std::vector<MVT::SimpleValueType> Result;
193  ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
194  for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
195    const CodeGenRegisterClass &RC = *RCs[i];
196    if (RC.contains(Reg)) {
197      ArrayRef<MVT::SimpleValueType> InVTs = RC.getValueTypes();
198      Result.insert(Result.end(), InVTs.begin(), InVTs.end());
199    }
200  }
201
202  // Remove duplicates.
203  array_pod_sort(Result.begin(), Result.end());
204  Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
205  return Result;
206}
207
208
209void CodeGenTarget::ReadLegalValueTypes() const {
210  ArrayRef<CodeGenRegisterClass*> RCs = getRegBank().getRegClasses();
211  for (unsigned i = 0, e = RCs.size(); i != e; ++i)
212    for (unsigned ri = 0, re = RCs[i]->VTs.size(); ri != re; ++ri)
213      LegalValueTypes.push_back(RCs[i]->VTs[ri]);
214
215  // Remove duplicates.
216  std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
217  LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
218                                    LegalValueTypes.end()),
219                        LegalValueTypes.end());
220}
221
222CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
223  if (!SchedModels)
224    SchedModels = new CodeGenSchedModels(Records, *this);
225  return *SchedModels;
226}
227
228void CodeGenTarget::ReadInstructions() const {
229  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
230  if (Insts.size() <= 2)
231    PrintFatalError("No 'Instruction' subclasses defined!");
232
233  // Parse the instructions defined in the .td file.
234  for (unsigned i = 0, e = Insts.size(); i != e; ++i)
235    Instructions[Insts[i]] = new CodeGenInstruction(Insts[i]);
236}
237
238static const CodeGenInstruction *
239GetInstByName(const char *Name,
240              const DenseMap<const Record*, CodeGenInstruction*> &Insts,
241              RecordKeeper &Records) {
242  const Record *Rec = Records.getDef(Name);
243
244  DenseMap<const Record*, CodeGenInstruction*>::const_iterator
245    I = Insts.find(Rec);
246  if (!Rec || I == Insts.end())
247    PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
248  return I->second;
249}
250
251/// \brief Return all of the instructions defined by the target, ordered by
252/// their enum value.
253void CodeGenTarget::ComputeInstrsByEnum() const {
254  // The ordering here must match the ordering in TargetOpcodes.h.
255  static const char *const FixedInstrs[] = {
256      "PHI",          "INLINEASM",     "CFI_INSTRUCTION",  "EH_LABEL",
257      "GC_LABEL",     "KILL",          "EXTRACT_SUBREG",   "INSERT_SUBREG",
258      "IMPLICIT_DEF", "SUBREG_TO_REG", "COPY_TO_REGCLASS", "DBG_VALUE",
259      "REG_SEQUENCE", "COPY",          "BUNDLE",           "LIFETIME_START",
260      "LIFETIME_END", "STACKMAP",      "PATCHPOINT",       nullptr};
261  const DenseMap<const Record*, CodeGenInstruction*> &Insts = getInstructions();
262  for (const char *const *p = FixedInstrs; *p; ++p) {
263    const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
264    assert(Instr && "Missing target independent instruction");
265    assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
266    InstrsByEnum.push_back(Instr);
267  }
268  unsigned EndOfPredefines = InstrsByEnum.size();
269
270  for (DenseMap<const Record*, CodeGenInstruction*>::const_iterator
271       I = Insts.begin(), E = Insts.end(); I != E; ++I) {
272    const CodeGenInstruction *CGI = I->second;
273    if (CGI->Namespace != "TargetOpcode")
274      InstrsByEnum.push_back(CGI);
275  }
276
277  assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
278
279  // All of the instructions are now in random order based on the map iteration.
280  // Sort them by name.
281  std::sort(InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
282            [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
283    return Rec1->TheDef->getName() < Rec2->TheDef->getName();
284  });
285}
286
287
288/// isLittleEndianEncoding - Return whether this target encodes its instruction
289/// in little-endian format, i.e. bits laid out in the order [0..n]
290///
291bool CodeGenTarget::isLittleEndianEncoding() const {
292  return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
293}
294
295/// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
296/// encodings, reverse the bit order of all instructions.
297void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
298  if (!isLittleEndianEncoding())
299    return;
300
301  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
302  for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
303       I != E; ++I) {
304    Record *R = *I;
305    if (R->getValueAsString("Namespace") == "TargetOpcode" ||
306        R->getValueAsBit("isPseudo"))
307      continue;
308
309    BitsInit *BI = R->getValueAsBitsInit("Inst");
310
311    unsigned numBits = BI->getNumBits();
312 
313    SmallVector<Init *, 16> NewBits(numBits);
314 
315    for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
316      unsigned bitSwapIdx = numBits - bit - 1;
317      Init *OrigBit = BI->getBit(bit);
318      Init *BitSwap = BI->getBit(bitSwapIdx);
319      NewBits[bit]        = BitSwap;
320      NewBits[bitSwapIdx] = OrigBit;
321    }
322    if (numBits % 2) {
323      unsigned middle = (numBits + 1) / 2;
324      NewBits[middle] = BI->getBit(middle);
325    }
326
327    BitsInit *NewBI = BitsInit::get(NewBits);
328
329    // Update the bits in reversed order so that emitInstrOpBits will get the
330    // correct endianness.
331    R->getValue("Inst")->setValue(NewBI);
332  }
333}
334
335/// guessInstructionProperties - Return true if it's OK to guess instruction
336/// properties instead of raising an error.
337///
338/// This is configurable as a temporary migration aid. It will eventually be
339/// permanently false.
340bool CodeGenTarget::guessInstructionProperties() const {
341  return getInstructionSet()->getValueAsBit("guessInstructionProperties");
342}
343
344//===----------------------------------------------------------------------===//
345// ComplexPattern implementation
346//
347ComplexPattern::ComplexPattern(Record *R) {
348  Ty          = ::getValueType(R->getValueAsDef("Ty"));
349  NumOperands = R->getValueAsInt("NumOperands");
350  SelectFunc  = R->getValueAsString("SelectFunc");
351  RootNodes   = R->getValueAsListOfDefs("RootNodes");
352
353  // Parse the properties.
354  Properties = 0;
355  std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
356  for (unsigned i = 0, e = PropList.size(); i != e; ++i)
357    if (PropList[i]->getName() == "SDNPHasChain") {
358      Properties |= 1 << SDNPHasChain;
359    } else if (PropList[i]->getName() == "SDNPOptInGlue") {
360      Properties |= 1 << SDNPOptInGlue;
361    } else if (PropList[i]->getName() == "SDNPMayStore") {
362      Properties |= 1 << SDNPMayStore;
363    } else if (PropList[i]->getName() == "SDNPMayLoad") {
364      Properties |= 1 << SDNPMayLoad;
365    } else if (PropList[i]->getName() == "SDNPSideEffect") {
366      Properties |= 1 << SDNPSideEffect;
367    } else if (PropList[i]->getName() == "SDNPMemOperand") {
368      Properties |= 1 << SDNPMemOperand;
369    } else if (PropList[i]->getName() == "SDNPVariadic") {
370      Properties |= 1 << SDNPVariadic;
371    } else if (PropList[i]->getName() == "SDNPWantRoot") {
372      Properties |= 1 << SDNPWantRoot;
373    } else if (PropList[i]->getName() == "SDNPWantParent") {
374      Properties |= 1 << SDNPWantParent;
375    } else {
376      errs() << "Unsupported SD Node property '" << PropList[i]->getName()
377             << "' on ComplexPattern '" << R->getName() << "'!\n";
378      exit(1);
379    }
380}
381
382//===----------------------------------------------------------------------===//
383// CodeGenIntrinsic Implementation
384//===----------------------------------------------------------------------===//
385
386std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC,
387                                                   bool TargetOnly) {
388  std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
389
390  std::vector<CodeGenIntrinsic> Result;
391
392  for (unsigned i = 0, e = I.size(); i != e; ++i) {
393    bool isTarget = I[i]->getValueAsBit("isTarget");
394    if (isTarget == TargetOnly)
395      Result.push_back(CodeGenIntrinsic(I[i]));
396  }
397  return Result;
398}
399
400CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
401  TheDef = R;
402  std::string DefName = R->getName();
403  ModRef = ReadWriteMem;
404  isOverloaded = false;
405  isCommutative = false;
406  canThrow = false;
407  isNoReturn = false;
408  isNoDuplicate = false;
409
410  if (DefName.size() <= 4 ||
411      std::string(DefName.begin(), DefName.begin() + 4) != "int_")
412    PrintFatalError("Intrinsic '" + DefName + "' does not start with 'int_'!");
413
414  EnumName = std::string(DefName.begin()+4, DefName.end());
415
416  if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
417    GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
418
419  TargetPrefix = R->getValueAsString("TargetPrefix");
420  Name = R->getValueAsString("LLVMName");
421
422  if (Name == "") {
423    // If an explicit name isn't specified, derive one from the DefName.
424    Name = "llvm.";
425
426    for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
427      Name += (EnumName[i] == '_') ? '.' : EnumName[i];
428  } else {
429    // Verify it starts with "llvm.".
430    if (Name.size() <= 5 ||
431        std::string(Name.begin(), Name.begin() + 5) != "llvm.")
432      PrintFatalError("Intrinsic '" + DefName + "'s name does not start with 'llvm.'!");
433  }
434
435  // If TargetPrefix is specified, make sure that Name starts with
436  // "llvm.<targetprefix>.".
437  if (!TargetPrefix.empty()) {
438    if (Name.size() < 6+TargetPrefix.size() ||
439        std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
440        != (TargetPrefix + "."))
441      PrintFatalError("Intrinsic '" + DefName + "' does not start with 'llvm." +
442        TargetPrefix + ".'!");
443  }
444
445  // Parse the list of return types.
446  std::vector<MVT::SimpleValueType> OverloadedVTs;
447  ListInit *TypeList = R->getValueAsListInit("RetTypes");
448  for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
449    Record *TyEl = TypeList->getElementAsRecord(i);
450    assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
451    MVT::SimpleValueType VT;
452    if (TyEl->isSubClassOf("LLVMMatchType")) {
453      unsigned MatchTy = TyEl->getValueAsInt("Number");
454      assert(MatchTy < OverloadedVTs.size() &&
455             "Invalid matching number!");
456      VT = OverloadedVTs[MatchTy];
457      // It only makes sense to use the extended and truncated vector element
458      // variants with iAny types; otherwise, if the intrinsic is not
459      // overloaded, all the types can be specified directly.
460      assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
461               !TyEl->isSubClassOf("LLVMTruncatedType")) ||
462              VT == MVT::iAny || VT == MVT::vAny) &&
463             "Expected iAny or vAny type");
464    } else {
465      VT = getValueType(TyEl->getValueAsDef("VT"));
466    }
467    if (MVT(VT).isOverloaded()) {
468      OverloadedVTs.push_back(VT);
469      isOverloaded = true;
470    }
471
472    // Reject invalid types.
473    if (VT == MVT::isVoid)
474      PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
475
476    IS.RetVTs.push_back(VT);
477    IS.RetTypeDefs.push_back(TyEl);
478  }
479
480  // Parse the list of parameter types.
481  TypeList = R->getValueAsListInit("ParamTypes");
482  for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
483    Record *TyEl = TypeList->getElementAsRecord(i);
484    assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
485    MVT::SimpleValueType VT;
486    if (TyEl->isSubClassOf("LLVMMatchType")) {
487      unsigned MatchTy = TyEl->getValueAsInt("Number");
488      assert(MatchTy < OverloadedVTs.size() &&
489             "Invalid matching number!");
490      VT = OverloadedVTs[MatchTy];
491      // It only makes sense to use the extended and truncated vector element
492      // variants with iAny types; otherwise, if the intrinsic is not
493      // overloaded, all the types can be specified directly.
494      assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
495               !TyEl->isSubClassOf("LLVMTruncatedType")) ||
496              VT == MVT::iAny || VT == MVT::vAny) &&
497             "Expected iAny or vAny type");
498    } else
499      VT = getValueType(TyEl->getValueAsDef("VT"));
500
501    if (MVT(VT).isOverloaded()) {
502      OverloadedVTs.push_back(VT);
503      isOverloaded = true;
504    }
505
506    // Reject invalid types.
507    if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
508      PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
509
510    IS.ParamVTs.push_back(VT);
511    IS.ParamTypeDefs.push_back(TyEl);
512  }
513
514  // Parse the intrinsic properties.
515  ListInit *PropList = R->getValueAsListInit("Properties");
516  for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
517    Record *Property = PropList->getElementAsRecord(i);
518    assert(Property->isSubClassOf("IntrinsicProperty") &&
519           "Expected a property!");
520
521    if (Property->getName() == "IntrNoMem")
522      ModRef = NoMem;
523    else if (Property->getName() == "IntrReadArgMem")
524      ModRef = ReadArgMem;
525    else if (Property->getName() == "IntrReadMem")
526      ModRef = ReadMem;
527    else if (Property->getName() == "IntrReadWriteArgMem")
528      ModRef = ReadWriteArgMem;
529    else if (Property->getName() == "Commutative")
530      isCommutative = true;
531    else if (Property->getName() == "Throws")
532      canThrow = true;
533    else if (Property->getName() == "IntrNoDuplicate")
534      isNoDuplicate = true;
535    else if (Property->getName() == "IntrNoReturn")
536      isNoReturn = true;
537    else if (Property->isSubClassOf("NoCapture")) {
538      unsigned ArgNo = Property->getValueAsInt("ArgNo");
539      ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
540    } else if (Property->isSubClassOf("ReadOnly")) {
541      unsigned ArgNo = Property->getValueAsInt("ArgNo");
542      ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadOnly));
543    } else if (Property->isSubClassOf("ReadNone")) {
544      unsigned ArgNo = Property->getValueAsInt("ArgNo");
545      ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadNone));
546    } else
547      llvm_unreachable("Unknown property!");
548  }
549
550  // Sort the argument attributes for later benefit.
551  std::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
552}
Note: See TracBrowser for help on using the repository browser.