CodeGenTarget.cpp revision 341825
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 "CodeGenDAGPatterns.h"
19#include "CodeGenIntrinsics.h"
20#include "CodeGenSchedule.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/TableGen/Error.h"
25#include "llvm/TableGen/Record.h"
26#include <algorithm>
27using namespace llvm;
28
29cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
30cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
31
32static cl::opt<unsigned>
33    AsmParserNum("asmparsernum", cl::init(0),
34                 cl::desc("Make -gen-asm-parser emit assembly parser #N"),
35                 cl::cat(AsmParserCat));
36
37static cl::opt<unsigned>
38    AsmWriterNum("asmwriternum", cl::init(0),
39                 cl::desc("Make -gen-asm-writer emit assembly writer #N"),
40                 cl::cat(AsmWriterCat));
41
42/// getValueType - Return the MVT::SimpleValueType that the specified TableGen
43/// record corresponds to.
44MVT::SimpleValueType llvm::getValueType(Record *Rec) {
45  return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
46}
47
48StringRef llvm::getName(MVT::SimpleValueType T) {
49  switch (T) {
50  case MVT::Other:   return "UNKNOWN";
51  case MVT::iPTR:    return "TLI.getPointerTy()";
52  case MVT::iPTRAny: return "TLI.getPointerTy()";
53  default: return getEnumName(T);
54  }
55}
56
57StringRef llvm::getEnumName(MVT::SimpleValueType T) {
58  switch (T) {
59  case MVT::Other:    return "MVT::Other";
60  case MVT::i1:       return "MVT::i1";
61  case MVT::i8:       return "MVT::i8";
62  case MVT::i16:      return "MVT::i16";
63  case MVT::i32:      return "MVT::i32";
64  case MVT::i64:      return "MVT::i64";
65  case MVT::i128:     return "MVT::i128";
66  case MVT::Any:      return "MVT::Any";
67  case MVT::iAny:     return "MVT::iAny";
68  case MVT::fAny:     return "MVT::fAny";
69  case MVT::vAny:     return "MVT::vAny";
70  case MVT::f16:      return "MVT::f16";
71  case MVT::f32:      return "MVT::f32";
72  case MVT::f64:      return "MVT::f64";
73  case MVT::f80:      return "MVT::f80";
74  case MVT::f128:     return "MVT::f128";
75  case MVT::ppcf128:  return "MVT::ppcf128";
76  case MVT::x86mmx:   return "MVT::x86mmx";
77  case MVT::Glue:     return "MVT::Glue";
78  case MVT::isVoid:   return "MVT::isVoid";
79  case MVT::v1i1:     return "MVT::v1i1";
80  case MVT::v2i1:     return "MVT::v2i1";
81  case MVT::v4i1:     return "MVT::v4i1";
82  case MVT::v8i1:     return "MVT::v8i1";
83  case MVT::v16i1:    return "MVT::v16i1";
84  case MVT::v32i1:    return "MVT::v32i1";
85  case MVT::v64i1:    return "MVT::v64i1";
86  case MVT::v128i1:   return "MVT::v128i1";
87  case MVT::v512i1:   return "MVT::v512i1";
88  case MVT::v1024i1:  return "MVT::v1024i1";
89  case MVT::v1i8:     return "MVT::v1i8";
90  case MVT::v2i8:     return "MVT::v2i8";
91  case MVT::v4i8:     return "MVT::v4i8";
92  case MVT::v8i8:     return "MVT::v8i8";
93  case MVT::v16i8:    return "MVT::v16i8";
94  case MVT::v32i8:    return "MVT::v32i8";
95  case MVT::v64i8:    return "MVT::v64i8";
96  case MVT::v128i8:   return "MVT::v128i8";
97  case MVT::v256i8:   return "MVT::v256i8";
98  case MVT::v1i16:    return "MVT::v1i16";
99  case MVT::v2i16:    return "MVT::v2i16";
100  case MVT::v4i16:    return "MVT::v4i16";
101  case MVT::v8i16:    return "MVT::v8i16";
102  case MVT::v16i16:   return "MVT::v16i16";
103  case MVT::v32i16:   return "MVT::v32i16";
104  case MVT::v64i16:   return "MVT::v64i16";
105  case MVT::v128i16:  return "MVT::v128i16";
106  case MVT::v1i32:    return "MVT::v1i32";
107  case MVT::v2i32:    return "MVT::v2i32";
108  case MVT::v4i32:    return "MVT::v4i32";
109  case MVT::v8i32:    return "MVT::v8i32";
110  case MVT::v16i32:   return "MVT::v16i32";
111  case MVT::v32i32:   return "MVT::v32i32";
112  case MVT::v64i32:   return "MVT::v64i32";
113  case MVT::v1i64:    return "MVT::v1i64";
114  case MVT::v2i64:    return "MVT::v2i64";
115  case MVT::v4i64:    return "MVT::v4i64";
116  case MVT::v8i64:    return "MVT::v8i64";
117  case MVT::v16i64:   return "MVT::v16i64";
118  case MVT::v32i64:   return "MVT::v32i64";
119  case MVT::v1i128:   return "MVT::v1i128";
120  case MVT::v2f16:    return "MVT::v2f16";
121  case MVT::v4f16:    return "MVT::v4f16";
122  case MVT::v8f16:    return "MVT::v8f16";
123  case MVT::v1f32:    return "MVT::v1f32";
124  case MVT::v2f32:    return "MVT::v2f32";
125  case MVT::v4f32:    return "MVT::v4f32";
126  case MVT::v8f32:    return "MVT::v8f32";
127  case MVT::v16f32:   return "MVT::v16f32";
128  case MVT::v1f64:    return "MVT::v1f64";
129  case MVT::v2f64:    return "MVT::v2f64";
130  case MVT::v4f64:    return "MVT::v4f64";
131  case MVT::v8f64:    return "MVT::v8f64";
132  case MVT::nxv1i1:   return "MVT::nxv1i1";
133  case MVT::nxv2i1:   return "MVT::nxv2i1";
134  case MVT::nxv4i1:   return "MVT::nxv4i1";
135  case MVT::nxv8i1:   return "MVT::nxv8i1";
136  case MVT::nxv16i1:  return "MVT::nxv16i1";
137  case MVT::nxv32i1:  return "MVT::nxv32i1";
138  case MVT::nxv1i8:   return "MVT::nxv1i8";
139  case MVT::nxv2i8:   return "MVT::nxv2i8";
140  case MVT::nxv4i8:   return "MVT::nxv4i8";
141  case MVT::nxv8i8:   return "MVT::nxv8i8";
142  case MVT::nxv16i8:  return "MVT::nxv16i8";
143  case MVT::nxv32i8:  return "MVT::nxv32i8";
144  case MVT::nxv1i16:  return "MVT::nxv1i16";
145  case MVT::nxv2i16:  return "MVT::nxv2i16";
146  case MVT::nxv4i16:  return "MVT::nxv4i16";
147  case MVT::nxv8i16:  return "MVT::nxv8i16";
148  case MVT::nxv16i16: return "MVT::nxv16i16";
149  case MVT::nxv32i16: return "MVT::nxv32i16";
150  case MVT::nxv1i32:  return "MVT::nxv1i32";
151  case MVT::nxv2i32:  return "MVT::nxv2i32";
152  case MVT::nxv4i32:  return "MVT::nxv4i32";
153  case MVT::nxv8i32:  return "MVT::nxv8i32";
154  case MVT::nxv16i32: return "MVT::nxv16i32";
155  case MVT::nxv1i64:  return "MVT::nxv1i64";
156  case MVT::nxv2i64:  return "MVT::nxv2i64";
157  case MVT::nxv4i64:  return "MVT::nxv4i64";
158  case MVT::nxv8i64:  return "MVT::nxv8i64";
159  case MVT::nxv16i64: return "MVT::nxv16i64";
160  case MVT::nxv2f16:  return "MVT::nxv2f16";
161  case MVT::nxv4f16:  return "MVT::nxv4f16";
162  case MVT::nxv8f16:  return "MVT::nxv8f16";
163  case MVT::nxv1f32:  return "MVT::nxv1f32";
164  case MVT::nxv2f32:  return "MVT::nxv2f32";
165  case MVT::nxv4f32:  return "MVT::nxv4f32";
166  case MVT::nxv8f32:  return "MVT::nxv8f32";
167  case MVT::nxv16f32: return "MVT::nxv16f32";
168  case MVT::nxv1f64:  return "MVT::nxv1f64";
169  case MVT::nxv2f64:  return "MVT::nxv2f64";
170  case MVT::nxv4f64:  return "MVT::nxv4f64";
171  case MVT::nxv8f64:  return "MVT::nxv8f64";
172  case MVT::token:    return "MVT::token";
173  case MVT::Metadata: return "MVT::Metadata";
174  case MVT::iPTR:     return "MVT::iPTR";
175  case MVT::iPTRAny:  return "MVT::iPTRAny";
176  case MVT::Untyped:  return "MVT::Untyped";
177  case MVT::ExceptRef: return "MVT::ExceptRef";
178  default: llvm_unreachable("ILLEGAL VALUE TYPE!");
179  }
180}
181
182/// getQualifiedName - Return the name of the specified record, with a
183/// namespace qualifier if the record contains one.
184///
185std::string llvm::getQualifiedName(const Record *R) {
186  std::string Namespace;
187  if (R->getValue("Namespace"))
188     Namespace = R->getValueAsString("Namespace");
189  if (Namespace.empty()) return R->getName();
190  return Namespace + "::" + R->getName().str();
191}
192
193
194/// getTarget - Return the current instance of the Target class.
195///
196CodeGenTarget::CodeGenTarget(RecordKeeper &records)
197  : Records(records), CGH(records) {
198  std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
199  if (Targets.size() == 0)
200    PrintFatalError("ERROR: No 'Target' subclasses defined!");
201  if (Targets.size() != 1)
202    PrintFatalError("ERROR: Multiple subclasses of Target defined!");
203  TargetRec = Targets[0];
204}
205
206CodeGenTarget::~CodeGenTarget() {
207}
208
209const StringRef CodeGenTarget::getName() const {
210  return TargetRec->getName();
211}
212
213StringRef CodeGenTarget::getInstNamespace() const {
214  for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
215    // Make sure not to pick up "TargetOpcode" by accidentally getting
216    // the namespace off the PHI instruction or something.
217    if (Inst->Namespace != "TargetOpcode")
218      return Inst->Namespace;
219  }
220
221  return "";
222}
223
224Record *CodeGenTarget::getInstructionSet() const {
225  return TargetRec->getValueAsDef("InstructionSet");
226}
227
228bool CodeGenTarget::getAllowRegisterRenaming() const {
229  return TargetRec->getValueAsInt("AllowRegisterRenaming");
230}
231
232/// getAsmParser - Return the AssemblyParser definition for this target.
233///
234Record *CodeGenTarget::getAsmParser() const {
235  std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
236  if (AsmParserNum >= LI.size())
237    PrintFatalError("Target does not have an AsmParser #" +
238                    Twine(AsmParserNum) + "!");
239  return LI[AsmParserNum];
240}
241
242/// getAsmParserVariant - Return the AssmblyParserVariant definition for
243/// this target.
244///
245Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
246  std::vector<Record*> LI =
247    TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
248  if (i >= LI.size())
249    PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
250                    "!");
251  return LI[i];
252}
253
254/// getAsmParserVariantCount - Return the AssmblyParserVariant definition
255/// available for this target.
256///
257unsigned CodeGenTarget::getAsmParserVariantCount() const {
258  std::vector<Record*> LI =
259    TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
260  return LI.size();
261}
262
263/// getAsmWriter - Return the AssemblyWriter definition for this target.
264///
265Record *CodeGenTarget::getAsmWriter() const {
266  std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
267  if (AsmWriterNum >= LI.size())
268    PrintFatalError("Target does not have an AsmWriter #" +
269                    Twine(AsmWriterNum) + "!");
270  return LI[AsmWriterNum];
271}
272
273CodeGenRegBank &CodeGenTarget::getRegBank() const {
274  if (!RegBank)
275    RegBank = llvm::make_unique<CodeGenRegBank>(Records, getHwModes());
276  return *RegBank;
277}
278
279void CodeGenTarget::ReadRegAltNameIndices() const {
280  RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
281  llvm::sort(RegAltNameIndices.begin(), RegAltNameIndices.end(), LessRecord());
282}
283
284/// getRegisterByName - If there is a register with the specific AsmName,
285/// return it.
286const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
287  const StringMap<CodeGenRegister*> &Regs = getRegBank().getRegistersByName();
288  StringMap<CodeGenRegister*>::const_iterator I = Regs.find(Name);
289  if (I == Regs.end())
290    return nullptr;
291  return I->second;
292}
293
294std::vector<ValueTypeByHwMode> CodeGenTarget::getRegisterVTs(Record *R)
295      const {
296  const CodeGenRegister *Reg = getRegBank().getReg(R);
297  std::vector<ValueTypeByHwMode> Result;
298  for (const auto &RC : getRegBank().getRegClasses()) {
299    if (RC.contains(Reg)) {
300      ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
301      Result.insert(Result.end(), InVTs.begin(), InVTs.end());
302    }
303  }
304
305  // Remove duplicates.
306  llvm::sort(Result.begin(), Result.end());
307  Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
308  return Result;
309}
310
311
312void CodeGenTarget::ReadLegalValueTypes() const {
313  for (const auto &RC : getRegBank().getRegClasses())
314    LegalValueTypes.insert(LegalValueTypes.end(), RC.VTs.begin(), RC.VTs.end());
315
316  // Remove duplicates.
317  llvm::sort(LegalValueTypes.begin(), LegalValueTypes.end());
318  LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
319                                    LegalValueTypes.end()),
320                        LegalValueTypes.end());
321}
322
323CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
324  if (!SchedModels)
325    SchedModels = llvm::make_unique<CodeGenSchedModels>(Records, *this);
326  return *SchedModels;
327}
328
329void CodeGenTarget::ReadInstructions() const {
330  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
331  if (Insts.size() <= 2)
332    PrintFatalError("No 'Instruction' subclasses defined!");
333
334  // Parse the instructions defined in the .td file.
335  for (unsigned i = 0, e = Insts.size(); i != e; ++i)
336    Instructions[Insts[i]] = llvm::make_unique<CodeGenInstruction>(Insts[i]);
337}
338
339static const CodeGenInstruction *
340GetInstByName(const char *Name,
341              const DenseMap<const Record*,
342                             std::unique_ptr<CodeGenInstruction>> &Insts,
343              RecordKeeper &Records) {
344  const Record *Rec = Records.getDef(Name);
345
346  const auto I = Insts.find(Rec);
347  if (!Rec || I == Insts.end())
348    PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
349  return I->second.get();
350}
351
352static const char *const FixedInstrs[] = {
353#define HANDLE_TARGET_OPCODE(OPC) #OPC,
354#include "llvm/Support/TargetOpcodes.def"
355    nullptr};
356
357unsigned CodeGenTarget::getNumFixedInstructions() {
358  return array_lengthof(FixedInstrs) - 1;
359}
360
361/// Return all of the instructions defined by the target, ordered by
362/// their enum value.
363void CodeGenTarget::ComputeInstrsByEnum() const {
364  const auto &Insts = getInstructions();
365  for (const char *const *p = FixedInstrs; *p; ++p) {
366    const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
367    assert(Instr && "Missing target independent instruction");
368    assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
369    InstrsByEnum.push_back(Instr);
370  }
371  unsigned EndOfPredefines = InstrsByEnum.size();
372  assert(EndOfPredefines == getNumFixedInstructions() &&
373         "Missing generic opcode");
374
375  for (const auto &I : Insts) {
376    const CodeGenInstruction *CGI = I.second.get();
377    if (CGI->Namespace != "TargetOpcode") {
378      InstrsByEnum.push_back(CGI);
379      if (CGI->TheDef->getValueAsBit("isPseudo"))
380        ++NumPseudoInstructions;
381    }
382  }
383
384  assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
385
386  // All of the instructions are now in random order based on the map iteration.
387  llvm::sort(
388      InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
389      [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
390        const auto &D1 = *Rec1->TheDef;
391        const auto &D2 = *Rec2->TheDef;
392        return std::make_tuple(!D1.getValueAsBit("isPseudo"), D1.getName()) <
393               std::make_tuple(!D2.getValueAsBit("isPseudo"), D2.getName());
394      });
395}
396
397
398/// isLittleEndianEncoding - Return whether this target encodes its instruction
399/// in little-endian format, i.e. bits laid out in the order [0..n]
400///
401bool CodeGenTarget::isLittleEndianEncoding() const {
402  return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
403}
404
405/// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
406/// encodings, reverse the bit order of all instructions.
407void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
408  if (!isLittleEndianEncoding())
409    return;
410
411  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
412  for (Record *R : Insts) {
413    if (R->getValueAsString("Namespace") == "TargetOpcode" ||
414        R->getValueAsBit("isPseudo"))
415      continue;
416
417    BitsInit *BI = R->getValueAsBitsInit("Inst");
418
419    unsigned numBits = BI->getNumBits();
420
421    SmallVector<Init *, 16> NewBits(numBits);
422
423    for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
424      unsigned bitSwapIdx = numBits - bit - 1;
425      Init *OrigBit = BI->getBit(bit);
426      Init *BitSwap = BI->getBit(bitSwapIdx);
427      NewBits[bit]        = BitSwap;
428      NewBits[bitSwapIdx] = OrigBit;
429    }
430    if (numBits % 2) {
431      unsigned middle = (numBits + 1) / 2;
432      NewBits[middle] = BI->getBit(middle);
433    }
434
435    BitsInit *NewBI = BitsInit::get(NewBits);
436
437    // Update the bits in reversed order so that emitInstrOpBits will get the
438    // correct endianness.
439    R->getValue("Inst")->setValue(NewBI);
440  }
441}
442
443/// guessInstructionProperties - Return true if it's OK to guess instruction
444/// properties instead of raising an error.
445///
446/// This is configurable as a temporary migration aid. It will eventually be
447/// permanently false.
448bool CodeGenTarget::guessInstructionProperties() const {
449  return getInstructionSet()->getValueAsBit("guessInstructionProperties");
450}
451
452//===----------------------------------------------------------------------===//
453// ComplexPattern implementation
454//
455ComplexPattern::ComplexPattern(Record *R) {
456  Ty          = ::getValueType(R->getValueAsDef("Ty"));
457  NumOperands = R->getValueAsInt("NumOperands");
458  SelectFunc  = R->getValueAsString("SelectFunc");
459  RootNodes   = R->getValueAsListOfDefs("RootNodes");
460
461  // FIXME: This is a hack to statically increase the priority of patterns which
462  // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
463  // possible pattern match we'll need to dynamically calculate the complexity
464  // of all patterns a dag can potentially map to.
465  int64_t RawComplexity = R->getValueAsInt("Complexity");
466  if (RawComplexity == -1)
467    Complexity = NumOperands * 3;
468  else
469    Complexity = RawComplexity;
470
471  // FIXME: Why is this different from parseSDPatternOperatorProperties?
472  // Parse the properties.
473  Properties = 0;
474  std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
475  for (unsigned i = 0, e = PropList.size(); i != e; ++i)
476    if (PropList[i]->getName() == "SDNPHasChain") {
477      Properties |= 1 << SDNPHasChain;
478    } else if (PropList[i]->getName() == "SDNPOptInGlue") {
479      Properties |= 1 << SDNPOptInGlue;
480    } else if (PropList[i]->getName() == "SDNPMayStore") {
481      Properties |= 1 << SDNPMayStore;
482    } else if (PropList[i]->getName() == "SDNPMayLoad") {
483      Properties |= 1 << SDNPMayLoad;
484    } else if (PropList[i]->getName() == "SDNPSideEffect") {
485      Properties |= 1 << SDNPSideEffect;
486    } else if (PropList[i]->getName() == "SDNPMemOperand") {
487      Properties |= 1 << SDNPMemOperand;
488    } else if (PropList[i]->getName() == "SDNPVariadic") {
489      Properties |= 1 << SDNPVariadic;
490    } else if (PropList[i]->getName() == "SDNPWantRoot") {
491      Properties |= 1 << SDNPWantRoot;
492    } else if (PropList[i]->getName() == "SDNPWantParent") {
493      Properties |= 1 << SDNPWantParent;
494    } else {
495      PrintFatalError("Unsupported SD Node property '" +
496                      PropList[i]->getName() + "' on ComplexPattern '" +
497                      R->getName() + "'!");
498    }
499}
500
501//===----------------------------------------------------------------------===//
502// CodeGenIntrinsic Implementation
503//===----------------------------------------------------------------------===//
504
505CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC,
506                                             bool TargetOnly) {
507  std::vector<Record*> Defs = RC.getAllDerivedDefinitions("Intrinsic");
508
509  Intrinsics.reserve(Defs.size());
510
511  for (unsigned I = 0, e = Defs.size(); I != e; ++I) {
512    bool isTarget = Defs[I]->getValueAsBit("isTarget");
513    if (isTarget == TargetOnly)
514      Intrinsics.push_back(CodeGenIntrinsic(Defs[I]));
515  }
516  llvm::sort(Intrinsics.begin(), Intrinsics.end(),
517             [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
518               return std::tie(LHS.TargetPrefix, LHS.Name) <
519                      std::tie(RHS.TargetPrefix, RHS.Name);
520             });
521  Targets.push_back({"", 0, 0});
522  for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
523    if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
524      Targets.back().Count = I - Targets.back().Offset;
525      Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
526    }
527  Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
528}
529
530CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
531  TheDef = R;
532  std::string DefName = R->getName();
533  ModRef = ReadWriteMem;
534  Properties = 0;
535  isOverloaded = false;
536  isCommutative = false;
537  canThrow = false;
538  isNoReturn = false;
539  isNoDuplicate = false;
540  isConvergent = false;
541  isSpeculatable = false;
542  hasSideEffects = false;
543
544  if (DefName.size() <= 4 ||
545      std::string(DefName.begin(), DefName.begin() + 4) != "int_")
546    PrintFatalError("Intrinsic '" + DefName + "' does not start with 'int_'!");
547
548  EnumName = std::string(DefName.begin()+4, DefName.end());
549
550  if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
551    GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
552  if (R->getValue("MSBuiltinName"))   // Ignore a missing MSBuiltinName field.
553    MSBuiltinName = R->getValueAsString("MSBuiltinName");
554
555  TargetPrefix = R->getValueAsString("TargetPrefix");
556  Name = R->getValueAsString("LLVMName");
557
558  if (Name == "") {
559    // If an explicit name isn't specified, derive one from the DefName.
560    Name = "llvm.";
561
562    for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
563      Name += (EnumName[i] == '_') ? '.' : EnumName[i];
564  } else {
565    // Verify it starts with "llvm.".
566    if (Name.size() <= 5 ||
567        std::string(Name.begin(), Name.begin() + 5) != "llvm.")
568      PrintFatalError("Intrinsic '" + DefName + "'s name does not start with 'llvm.'!");
569  }
570
571  // If TargetPrefix is specified, make sure that Name starts with
572  // "llvm.<targetprefix>.".
573  if (!TargetPrefix.empty()) {
574    if (Name.size() < 6+TargetPrefix.size() ||
575        std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
576        != (TargetPrefix + "."))
577      PrintFatalError("Intrinsic '" + DefName + "' does not start with 'llvm." +
578        TargetPrefix + ".'!");
579  }
580
581  // Parse the list of return types.
582  std::vector<MVT::SimpleValueType> OverloadedVTs;
583  ListInit *TypeList = R->getValueAsListInit("RetTypes");
584  for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
585    Record *TyEl = TypeList->getElementAsRecord(i);
586    assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
587    MVT::SimpleValueType VT;
588    if (TyEl->isSubClassOf("LLVMMatchType")) {
589      unsigned MatchTy = TyEl->getValueAsInt("Number");
590      assert(MatchTy < OverloadedVTs.size() &&
591             "Invalid matching number!");
592      VT = OverloadedVTs[MatchTy];
593      // It only makes sense to use the extended and truncated vector element
594      // variants with iAny types; otherwise, if the intrinsic is not
595      // overloaded, all the types can be specified directly.
596      assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
597               !TyEl->isSubClassOf("LLVMTruncatedType")) ||
598              VT == MVT::iAny || VT == MVT::vAny) &&
599             "Expected iAny or vAny type");
600    } else {
601      VT = getValueType(TyEl->getValueAsDef("VT"));
602    }
603    if (MVT(VT).isOverloaded()) {
604      OverloadedVTs.push_back(VT);
605      isOverloaded = true;
606    }
607
608    // Reject invalid types.
609    if (VT == MVT::isVoid)
610      PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
611
612    IS.RetVTs.push_back(VT);
613    IS.RetTypeDefs.push_back(TyEl);
614  }
615
616  // Parse the list of parameter types.
617  TypeList = R->getValueAsListInit("ParamTypes");
618  for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
619    Record *TyEl = TypeList->getElementAsRecord(i);
620    assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
621    MVT::SimpleValueType VT;
622    if (TyEl->isSubClassOf("LLVMMatchType")) {
623      unsigned MatchTy = TyEl->getValueAsInt("Number");
624      if (MatchTy >= OverloadedVTs.size()) {
625        PrintError(R->getLoc(),
626                   "Parameter #" + Twine(i) + " has out of bounds matching "
627                   "number " + Twine(MatchTy));
628        PrintFatalError(Twine("ParamTypes is ") + TypeList->getAsString());
629      }
630      VT = OverloadedVTs[MatchTy];
631      // It only makes sense to use the extended and truncated vector element
632      // variants with iAny types; otherwise, if the intrinsic is not
633      // overloaded, all the types can be specified directly.
634      assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
635               !TyEl->isSubClassOf("LLVMTruncatedType") &&
636               !TyEl->isSubClassOf("LLVMVectorSameWidth")) ||
637              VT == MVT::iAny || VT == MVT::vAny) &&
638             "Expected iAny or vAny type");
639    } else
640      VT = getValueType(TyEl->getValueAsDef("VT"));
641
642    if (MVT(VT).isOverloaded()) {
643      OverloadedVTs.push_back(VT);
644      isOverloaded = true;
645    }
646
647    // Reject invalid types.
648    if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
649      PrintFatalError("Intrinsic '" + DefName + " has void in result type list!");
650
651    IS.ParamVTs.push_back(VT);
652    IS.ParamTypeDefs.push_back(TyEl);
653  }
654
655  // Parse the intrinsic properties.
656  ListInit *PropList = R->getValueAsListInit("IntrProperties");
657  for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
658    Record *Property = PropList->getElementAsRecord(i);
659    assert(Property->isSubClassOf("IntrinsicProperty") &&
660           "Expected a property!");
661
662    if (Property->getName() == "IntrNoMem")
663      ModRef = NoMem;
664    else if (Property->getName() == "IntrReadMem")
665      ModRef = ModRefBehavior(ModRef & ~MR_Mod);
666    else if (Property->getName() == "IntrWriteMem")
667      ModRef = ModRefBehavior(ModRef & ~MR_Ref);
668    else if (Property->getName() == "IntrArgMemOnly")
669      ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem);
670    else if (Property->getName() == "IntrInaccessibleMemOnly")
671      ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem);
672    else if (Property->getName() == "IntrInaccessibleMemOrArgMemOnly")
673      ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem |
674                              MR_InaccessibleMem);
675    else if (Property->getName() == "Commutative")
676      isCommutative = true;
677    else if (Property->getName() == "Throws")
678      canThrow = true;
679    else if (Property->getName() == "IntrNoDuplicate")
680      isNoDuplicate = true;
681    else if (Property->getName() == "IntrConvergent")
682      isConvergent = true;
683    else if (Property->getName() == "IntrNoReturn")
684      isNoReturn = true;
685    else if (Property->getName() == "IntrSpeculatable")
686      isSpeculatable = true;
687    else if (Property->getName() == "IntrHasSideEffects")
688      hasSideEffects = true;
689    else if (Property->isSubClassOf("NoCapture")) {
690      unsigned ArgNo = Property->getValueAsInt("ArgNo");
691      ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
692    } else if (Property->isSubClassOf("Returned")) {
693      unsigned ArgNo = Property->getValueAsInt("ArgNo");
694      ArgumentAttributes.push_back(std::make_pair(ArgNo, Returned));
695    } else if (Property->isSubClassOf("ReadOnly")) {
696      unsigned ArgNo = Property->getValueAsInt("ArgNo");
697      ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadOnly));
698    } else if (Property->isSubClassOf("WriteOnly")) {
699      unsigned ArgNo = Property->getValueAsInt("ArgNo");
700      ArgumentAttributes.push_back(std::make_pair(ArgNo, WriteOnly));
701    } else if (Property->isSubClassOf("ReadNone")) {
702      unsigned ArgNo = Property->getValueAsInt("ArgNo");
703      ArgumentAttributes.push_back(std::make_pair(ArgNo, ReadNone));
704    } else
705      llvm_unreachable("Unknown property!");
706  }
707
708  // Also record the SDPatternOperator Properties.
709  Properties = parseSDPatternOperatorProperties(R);
710
711  // Sort the argument attributes for later benefit.
712  llvm::sort(ArgumentAttributes.begin(), ArgumentAttributes.end());
713}
714
715