Home | History | Annotate | Line # | Download | only in TableGen
      1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This class wraps target description classes used by the various code
     10 // generation TableGen backends.  This makes it easier to access the data and
     11 // provides a single place that needs to check it for validity.  All of these
     12 // classes abort on error conditions.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "CodeGenTarget.h"
     17 #include "CodeGenDAGPatterns.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/Support/Timer.h"
     24 #include "llvm/TableGen/Error.h"
     25 #include "llvm/TableGen/Record.h"
     26 #include "llvm/TableGen/TableGenBackend.h"
     27 #include <algorithm>
     28 using namespace llvm;
     29 
     30 cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
     31 cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
     32 
     33 static cl::opt<unsigned>
     34     AsmParserNum("asmparsernum", cl::init(0),
     35                  cl::desc("Make -gen-asm-parser emit assembly parser #N"),
     36                  cl::cat(AsmParserCat));
     37 
     38 static cl::opt<unsigned>
     39     AsmWriterNum("asmwriternum", cl::init(0),
     40                  cl::desc("Make -gen-asm-writer emit assembly writer #N"),
     41                  cl::cat(AsmWriterCat));
     42 
     43 /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
     44 /// record corresponds to.
     45 MVT::SimpleValueType llvm::getValueType(Record *Rec) {
     46   return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
     47 }
     48 
     49 StringRef llvm::getName(MVT::SimpleValueType T) {
     50   switch (T) {
     51   case MVT::Other:   return "UNKNOWN";
     52   case MVT::iPTR:    return "TLI.getPointerTy()";
     53   case MVT::iPTRAny: return "TLI.getPointerTy()";
     54   default: return getEnumName(T);
     55   }
     56 }
     57 
     58 StringRef llvm::getEnumName(MVT::SimpleValueType T) {
     59   switch (T) {
     60   case MVT::Other:    return "MVT::Other";
     61   case MVT::i1:       return "MVT::i1";
     62   case MVT::i8:       return "MVT::i8";
     63   case MVT::i16:      return "MVT::i16";
     64   case MVT::i32:      return "MVT::i32";
     65   case MVT::i64:      return "MVT::i64";
     66   case MVT::i128:     return "MVT::i128";
     67   case MVT::Any:      return "MVT::Any";
     68   case MVT::iAny:     return "MVT::iAny";
     69   case MVT::fAny:     return "MVT::fAny";
     70   case MVT::vAny:     return "MVT::vAny";
     71   case MVT::f16:      return "MVT::f16";
     72   case MVT::bf16:     return "MVT::bf16";
     73   case MVT::f32:      return "MVT::f32";
     74   case MVT::f64:      return "MVT::f64";
     75   case MVT::f80:      return "MVT::f80";
     76   case MVT::f128:     return "MVT::f128";
     77   case MVT::ppcf128:  return "MVT::ppcf128";
     78   case MVT::x86mmx:   return "MVT::x86mmx";
     79   case MVT::x86amx:   return "MVT::x86amx";
     80   case MVT::Glue:     return "MVT::Glue";
     81   case MVT::isVoid:   return "MVT::isVoid";
     82   case MVT::v1i1:     return "MVT::v1i1";
     83   case MVT::v2i1:     return "MVT::v2i1";
     84   case MVT::v4i1:     return "MVT::v4i1";
     85   case MVT::v8i1:     return "MVT::v8i1";
     86   case MVT::v16i1:    return "MVT::v16i1";
     87   case MVT::v32i1:    return "MVT::v32i1";
     88   case MVT::v64i1:    return "MVT::v64i1";
     89   case MVT::v128i1:   return "MVT::v128i1";
     90   case MVT::v256i1:   return "MVT::v256i1";
     91   case MVT::v512i1:   return "MVT::v512i1";
     92   case MVT::v1024i1:  return "MVT::v1024i1";
     93   case MVT::v1i8:     return "MVT::v1i8";
     94   case MVT::v2i8:     return "MVT::v2i8";
     95   case MVT::v4i8:     return "MVT::v4i8";
     96   case MVT::v8i8:     return "MVT::v8i8";
     97   case MVT::v16i8:    return "MVT::v16i8";
     98   case MVT::v32i8:    return "MVT::v32i8";
     99   case MVT::v64i8:    return "MVT::v64i8";
    100   case MVT::v128i8:   return "MVT::v128i8";
    101   case MVT::v256i8:   return "MVT::v256i8";
    102   case MVT::v1i16:    return "MVT::v1i16";
    103   case MVT::v2i16:    return "MVT::v2i16";
    104   case MVT::v3i16:    return "MVT::v3i16";
    105   case MVT::v4i16:    return "MVT::v4i16";
    106   case MVT::v8i16:    return "MVT::v8i16";
    107   case MVT::v16i16:   return "MVT::v16i16";
    108   case MVT::v32i16:   return "MVT::v32i16";
    109   case MVT::v64i16:   return "MVT::v64i16";
    110   case MVT::v128i16:  return "MVT::v128i16";
    111   case MVT::v1i32:    return "MVT::v1i32";
    112   case MVT::v2i32:    return "MVT::v2i32";
    113   case MVT::v3i32:    return "MVT::v3i32";
    114   case MVT::v4i32:    return "MVT::v4i32";
    115   case MVT::v5i32:    return "MVT::v5i32";
    116   case MVT::v8i32:    return "MVT::v8i32";
    117   case MVT::v16i32:   return "MVT::v16i32";
    118   case MVT::v32i32:   return "MVT::v32i32";
    119   case MVT::v64i32:   return "MVT::v64i32";
    120   case MVT::v128i32:  return "MVT::v128i32";
    121   case MVT::v256i32:  return "MVT::v256i32";
    122   case MVT::v512i32:  return "MVT::v512i32";
    123   case MVT::v1024i32: return "MVT::v1024i32";
    124   case MVT::v2048i32: return "MVT::v2048i32";
    125   case MVT::v1i64:    return "MVT::v1i64";
    126   case MVT::v2i64:    return "MVT::v2i64";
    127   case MVT::v4i64:    return "MVT::v4i64";
    128   case MVT::v8i64:    return "MVT::v8i64";
    129   case MVT::v16i64:   return "MVT::v16i64";
    130   case MVT::v32i64:   return "MVT::v32i64";
    131   case MVT::v64i64:   return "MVT::v64i64";
    132   case MVT::v128i64:  return "MVT::v128i64";
    133   case MVT::v256i64:  return "MVT::v256i64";
    134   case MVT::v1i128:   return "MVT::v1i128";
    135   case MVT::v2f16:    return "MVT::v2f16";
    136   case MVT::v3f16:    return "MVT::v3f16";
    137   case MVT::v4f16:    return "MVT::v4f16";
    138   case MVT::v8f16:    return "MVT::v8f16";
    139   case MVT::v16f16:   return "MVT::v16f16";
    140   case MVT::v32f16:   return "MVT::v32f16";
    141   case MVT::v64f16:   return "MVT::v64f16";
    142   case MVT::v128f16:  return "MVT::v128f16";
    143   case MVT::v2bf16:   return "MVT::v2bf16";
    144   case MVT::v3bf16:   return "MVT::v3bf16";
    145   case MVT::v4bf16:   return "MVT::v4bf16";
    146   case MVT::v8bf16:   return "MVT::v8bf16";
    147   case MVT::v16bf16:  return "MVT::v16bf16";
    148   case MVT::v32bf16:  return "MVT::v32bf16";
    149   case MVT::v64bf16:  return "MVT::v64bf16";
    150   case MVT::v128bf16: return "MVT::v128bf16";
    151   case MVT::v1f32:    return "MVT::v1f32";
    152   case MVT::v2f32:    return "MVT::v2f32";
    153   case MVT::v3f32:    return "MVT::v3f32";
    154   case MVT::v4f32:    return "MVT::v4f32";
    155   case MVT::v5f32:    return "MVT::v5f32";
    156   case MVT::v8f32:    return "MVT::v8f32";
    157   case MVT::v16f32:   return "MVT::v16f32";
    158   case MVT::v32f32:   return "MVT::v32f32";
    159   case MVT::v64f32:   return "MVT::v64f32";
    160   case MVT::v128f32:  return "MVT::v128f32";
    161   case MVT::v256f32:  return "MVT::v256f32";
    162   case MVT::v512f32:  return "MVT::v512f32";
    163   case MVT::v1024f32: return "MVT::v1024f32";
    164   case MVT::v2048f32: return "MVT::v2048f32";
    165   case MVT::v1f64:    return "MVT::v1f64";
    166   case MVT::v2f64:    return "MVT::v2f64";
    167   case MVT::v4f64:    return "MVT::v4f64";
    168   case MVT::v8f64:    return "MVT::v8f64";
    169   case MVT::v16f64:   return "MVT::v16f64";
    170   case MVT::v32f64:   return "MVT::v32f64";
    171   case MVT::v64f64:   return "MVT::v64f64";
    172   case MVT::v128f64:  return "MVT::v128f64";
    173   case MVT::v256f64:  return "MVT::v256f64";
    174   case MVT::nxv1i1:   return "MVT::nxv1i1";
    175   case MVT::nxv2i1:   return "MVT::nxv2i1";
    176   case MVT::nxv4i1:   return "MVT::nxv4i1";
    177   case MVT::nxv8i1:   return "MVT::nxv8i1";
    178   case MVT::nxv16i1:  return "MVT::nxv16i1";
    179   case MVT::nxv32i1:  return "MVT::nxv32i1";
    180   case MVT::nxv64i1:  return "MVT::nxv64i1";
    181   case MVT::nxv1i8:   return "MVT::nxv1i8";
    182   case MVT::nxv2i8:   return "MVT::nxv2i8";
    183   case MVT::nxv4i8:   return "MVT::nxv4i8";
    184   case MVT::nxv8i8:   return "MVT::nxv8i8";
    185   case MVT::nxv16i8:  return "MVT::nxv16i8";
    186   case MVT::nxv32i8:  return "MVT::nxv32i8";
    187   case MVT::nxv64i8:  return "MVT::nxv64i8";
    188   case MVT::nxv1i16:  return "MVT::nxv1i16";
    189   case MVT::nxv2i16:  return "MVT::nxv2i16";
    190   case MVT::nxv4i16:  return "MVT::nxv4i16";
    191   case MVT::nxv8i16:  return "MVT::nxv8i16";
    192   case MVT::nxv16i16: return "MVT::nxv16i16";
    193   case MVT::nxv32i16: return "MVT::nxv32i16";
    194   case MVT::nxv1i32:  return "MVT::nxv1i32";
    195   case MVT::nxv2i32:  return "MVT::nxv2i32";
    196   case MVT::nxv4i32:  return "MVT::nxv4i32";
    197   case MVT::nxv8i32:  return "MVT::nxv8i32";
    198   case MVT::nxv16i32: return "MVT::nxv16i32";
    199   case MVT::nxv32i32: return "MVT::nxv32i32";
    200   case MVT::nxv1i64:  return "MVT::nxv1i64";
    201   case MVT::nxv2i64:  return "MVT::nxv2i64";
    202   case MVT::nxv4i64:  return "MVT::nxv4i64";
    203   case MVT::nxv8i64:  return "MVT::nxv8i64";
    204   case MVT::nxv16i64: return "MVT::nxv16i64";
    205   case MVT::nxv32i64: return "MVT::nxv32i64";
    206   case MVT::nxv1f16:  return "MVT::nxv1f16";
    207   case MVT::nxv2f16:  return "MVT::nxv2f16";
    208   case MVT::nxv4f16:  return "MVT::nxv4f16";
    209   case MVT::nxv8f16:  return "MVT::nxv8f16";
    210   case MVT::nxv16f16: return "MVT::nxv16f16";
    211   case MVT::nxv32f16: return "MVT::nxv32f16";
    212   case MVT::nxv2bf16:  return "MVT::nxv2bf16";
    213   case MVT::nxv4bf16:  return "MVT::nxv4bf16";
    214   case MVT::nxv8bf16:  return "MVT::nxv8bf16";
    215   case MVT::nxv1f32:   return "MVT::nxv1f32";
    216   case MVT::nxv2f32:   return "MVT::nxv2f32";
    217   case MVT::nxv4f32:   return "MVT::nxv4f32";
    218   case MVT::nxv8f32:   return "MVT::nxv8f32";
    219   case MVT::nxv16f32:  return "MVT::nxv16f32";
    220   case MVT::nxv1f64:   return "MVT::nxv1f64";
    221   case MVT::nxv2f64:   return "MVT::nxv2f64";
    222   case MVT::nxv4f64:   return "MVT::nxv4f64";
    223   case MVT::nxv8f64:   return "MVT::nxv8f64";
    224   case MVT::token:     return "MVT::token";
    225   case MVT::Metadata:  return "MVT::Metadata";
    226   case MVT::iPTR:      return "MVT::iPTR";
    227   case MVT::iPTRAny:   return "MVT::iPTRAny";
    228   case MVT::Untyped:   return "MVT::Untyped";
    229   case MVT::funcref:   return "MVT::funcref";
    230   case MVT::externref: return "MVT::externref";
    231   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
    232   }
    233 }
    234 
    235 /// getQualifiedName - Return the name of the specified record, with a
    236 /// namespace qualifier if the record contains one.
    237 ///
    238 std::string llvm::getQualifiedName(const Record *R) {
    239   std::string Namespace;
    240   if (R->getValue("Namespace"))
    241     Namespace = std::string(R->getValueAsString("Namespace"));
    242   if (Namespace.empty())
    243     return std::string(R->getName());
    244   return Namespace + "::" + R->getName().str();
    245 }
    246 
    247 
    248 /// getTarget - Return the current instance of the Target class.
    249 ///
    250 CodeGenTarget::CodeGenTarget(RecordKeeper &records)
    251   : Records(records), CGH(records) {
    252   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
    253   if (Targets.size() == 0)
    254     PrintFatalError("No 'Target' subclasses defined!");
    255   if (Targets.size() != 1)
    256     PrintFatalError("Multiple subclasses of Target defined!");
    257   TargetRec = Targets[0];
    258 }
    259 
    260 CodeGenTarget::~CodeGenTarget() {
    261 }
    262 
    263 StringRef CodeGenTarget::getName() const { return TargetRec->getName(); }
    264 
    265 /// getInstNamespace - Find and return the target machine's instruction
    266 /// namespace. The namespace is cached because it is requested multiple times.
    267 StringRef CodeGenTarget::getInstNamespace() const {
    268   if (InstNamespace.empty()) {
    269     for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
    270       // We are not interested in the "TargetOpcode" namespace.
    271       if (Inst->Namespace != "TargetOpcode") {
    272         InstNamespace = Inst->Namespace;
    273         break;
    274       }
    275     }
    276   }
    277 
    278   return InstNamespace;
    279 }
    280 
    281 StringRef CodeGenTarget::getRegNamespace() const {
    282   auto &RegClasses = RegBank->getRegClasses();
    283   return RegClasses.size() > 0 ? RegClasses.front().Namespace : "";
    284 }
    285 
    286 Record *CodeGenTarget::getInstructionSet() const {
    287   return TargetRec->getValueAsDef("InstructionSet");
    288 }
    289 
    290 bool CodeGenTarget::getAllowRegisterRenaming() const {
    291   return TargetRec->getValueAsInt("AllowRegisterRenaming");
    292 }
    293 
    294 /// getAsmParser - Return the AssemblyParser definition for this target.
    295 ///
    296 Record *CodeGenTarget::getAsmParser() const {
    297   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
    298   if (AsmParserNum >= LI.size())
    299     PrintFatalError("Target does not have an AsmParser #" +
    300                     Twine(AsmParserNum) + "!");
    301   return LI[AsmParserNum];
    302 }
    303 
    304 /// getAsmParserVariant - Return the AssemblyParserVariant definition for
    305 /// this target.
    306 ///
    307 Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
    308   std::vector<Record*> LI =
    309     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
    310   if (i >= LI.size())
    311     PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
    312                     "!");
    313   return LI[i];
    314 }
    315 
    316 /// getAsmParserVariantCount - Return the AssemblyParserVariant definition
    317 /// available for this target.
    318 ///
    319 unsigned CodeGenTarget::getAsmParserVariantCount() const {
    320   std::vector<Record*> LI =
    321     TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
    322   return LI.size();
    323 }
    324 
    325 /// getAsmWriter - Return the AssemblyWriter definition for this target.
    326 ///
    327 Record *CodeGenTarget::getAsmWriter() const {
    328   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
    329   if (AsmWriterNum >= LI.size())
    330     PrintFatalError("Target does not have an AsmWriter #" +
    331                     Twine(AsmWriterNum) + "!");
    332   return LI[AsmWriterNum];
    333 }
    334 
    335 CodeGenRegBank &CodeGenTarget::getRegBank() const {
    336   if (!RegBank)
    337     RegBank = std::make_unique<CodeGenRegBank>(Records, getHwModes());
    338   return *RegBank;
    339 }
    340 
    341 Optional<CodeGenRegisterClass *>
    342 CodeGenTarget::getSuperRegForSubReg(const ValueTypeByHwMode &ValueTy,
    343                                     CodeGenRegBank &RegBank,
    344                                     const CodeGenSubRegIndex *SubIdx,
    345                                     bool MustBeAllocatable) const {
    346   std::vector<CodeGenRegisterClass *> Candidates;
    347   auto &RegClasses = RegBank.getRegClasses();
    348 
    349   // Try to find a register class which supports ValueTy, and also contains
    350   // SubIdx.
    351   for (CodeGenRegisterClass &RC : RegClasses) {
    352     // Is there a subclass of this class which contains this subregister index?
    353     CodeGenRegisterClass *SubClassWithSubReg = RC.getSubClassWithSubReg(SubIdx);
    354     if (!SubClassWithSubReg)
    355       continue;
    356 
    357     // We have a class. Check if it supports this value type.
    358     if (!llvm::is_contained(SubClassWithSubReg->VTs, ValueTy))
    359       continue;
    360 
    361     // If necessary, check that it is allocatable.
    362     if (MustBeAllocatable && !SubClassWithSubReg->Allocatable)
    363       continue;
    364 
    365     // We have a register class which supports both the value type and
    366     // subregister index. Remember it.
    367     Candidates.push_back(SubClassWithSubReg);
    368   }
    369 
    370   // If we didn't find anything, we're done.
    371   if (Candidates.empty())
    372     return None;
    373 
    374   // Find and return the largest of our candidate classes.
    375   llvm::stable_sort(Candidates, [&](const CodeGenRegisterClass *A,
    376                                     const CodeGenRegisterClass *B) {
    377     if (A->getMembers().size() > B->getMembers().size())
    378       return true;
    379 
    380     if (A->getMembers().size() < B->getMembers().size())
    381       return false;
    382 
    383     // Order by name as a tie-breaker.
    384     return StringRef(A->getName()) < B->getName();
    385   });
    386 
    387   return Candidates[0];
    388 }
    389 
    390 void CodeGenTarget::ReadRegAltNameIndices() const {
    391   RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
    392   llvm::sort(RegAltNameIndices, LessRecord());
    393 }
    394 
    395 /// getRegisterByName - If there is a register with the specific AsmName,
    396 /// return it.
    397 const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
    398   return getRegBank().getRegistersByName().lookup(Name);
    399 }
    400 
    401 std::vector<ValueTypeByHwMode> CodeGenTarget::getRegisterVTs(Record *R)
    402       const {
    403   const CodeGenRegister *Reg = getRegBank().getReg(R);
    404   std::vector<ValueTypeByHwMode> Result;
    405   for (const auto &RC : getRegBank().getRegClasses()) {
    406     if (RC.contains(Reg)) {
    407       ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
    408       llvm::append_range(Result, InVTs);
    409     }
    410   }
    411 
    412   // Remove duplicates.
    413   llvm::sort(Result);
    414   Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
    415   return Result;
    416 }
    417 
    418 
    419 void CodeGenTarget::ReadLegalValueTypes() const {
    420   for (const auto &RC : getRegBank().getRegClasses())
    421     llvm::append_range(LegalValueTypes, RC.VTs);
    422 
    423   // Remove duplicates.
    424   llvm::sort(LegalValueTypes);
    425   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
    426                                     LegalValueTypes.end()),
    427                         LegalValueTypes.end());
    428 }
    429 
    430 CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
    431   if (!SchedModels)
    432     SchedModels = std::make_unique<CodeGenSchedModels>(Records, *this);
    433   return *SchedModels;
    434 }
    435 
    436 void CodeGenTarget::ReadInstructions() const {
    437   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
    438   if (Insts.size() <= 2)
    439     PrintFatalError("No 'Instruction' subclasses defined!");
    440 
    441   // Parse the instructions defined in the .td file.
    442   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
    443     Instructions[Insts[i]] = std::make_unique<CodeGenInstruction>(Insts[i]);
    444 }
    445 
    446 static const CodeGenInstruction *
    447 GetInstByName(const char *Name,
    448               const DenseMap<const Record*,
    449                              std::unique_ptr<CodeGenInstruction>> &Insts,
    450               RecordKeeper &Records) {
    451   const Record *Rec = Records.getDef(Name);
    452 
    453   const auto I = Insts.find(Rec);
    454   if (!Rec || I == Insts.end())
    455     PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
    456   return I->second.get();
    457 }
    458 
    459 static const char *const FixedInstrs[] = {
    460 #define HANDLE_TARGET_OPCODE(OPC) #OPC,
    461 #include "llvm/Support/TargetOpcodes.def"
    462     nullptr};
    463 
    464 unsigned CodeGenTarget::getNumFixedInstructions() {
    465   return array_lengthof(FixedInstrs) - 1;
    466 }
    467 
    468 /// Return all of the instructions defined by the target, ordered by
    469 /// their enum value.
    470 void CodeGenTarget::ComputeInstrsByEnum() const {
    471   const auto &Insts = getInstructions();
    472   for (const char *const *p = FixedInstrs; *p; ++p) {
    473     const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
    474     assert(Instr && "Missing target independent instruction");
    475     assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
    476     InstrsByEnum.push_back(Instr);
    477   }
    478   unsigned EndOfPredefines = InstrsByEnum.size();
    479   assert(EndOfPredefines == getNumFixedInstructions() &&
    480          "Missing generic opcode");
    481 
    482   for (const auto &I : Insts) {
    483     const CodeGenInstruction *CGI = I.second.get();
    484     if (CGI->Namespace != "TargetOpcode") {
    485       InstrsByEnum.push_back(CGI);
    486       if (CGI->TheDef->getValueAsBit("isPseudo"))
    487         ++NumPseudoInstructions;
    488     }
    489   }
    490 
    491   assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
    492 
    493   // All of the instructions are now in random order based on the map iteration.
    494   llvm::sort(
    495       InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
    496       [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
    497         const auto &D1 = *Rec1->TheDef;
    498         const auto &D2 = *Rec2->TheDef;
    499         return std::make_tuple(!D1.getValueAsBit("isPseudo"), D1.getName()) <
    500                std::make_tuple(!D2.getValueAsBit("isPseudo"), D2.getName());
    501       });
    502 }
    503 
    504 
    505 /// isLittleEndianEncoding - Return whether this target encodes its instruction
    506 /// in little-endian format, i.e. bits laid out in the order [0..n]
    507 ///
    508 bool CodeGenTarget::isLittleEndianEncoding() const {
    509   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
    510 }
    511 
    512 /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
    513 /// encodings, reverse the bit order of all instructions.
    514 void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
    515   if (!isLittleEndianEncoding())
    516     return;
    517 
    518   std::vector<Record *> Insts =
    519       Records.getAllDerivedDefinitions("InstructionEncoding");
    520   for (Record *R : Insts) {
    521     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
    522         R->getValueAsBit("isPseudo"))
    523       continue;
    524 
    525     BitsInit *BI = R->getValueAsBitsInit("Inst");
    526 
    527     unsigned numBits = BI->getNumBits();
    528 
    529     SmallVector<Init *, 16> NewBits(numBits);
    530 
    531     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
    532       unsigned bitSwapIdx = numBits - bit - 1;
    533       Init *OrigBit = BI->getBit(bit);
    534       Init *BitSwap = BI->getBit(bitSwapIdx);
    535       NewBits[bit]        = BitSwap;
    536       NewBits[bitSwapIdx] = OrigBit;
    537     }
    538     if (numBits % 2) {
    539       unsigned middle = (numBits + 1) / 2;
    540       NewBits[middle] = BI->getBit(middle);
    541     }
    542 
    543     BitsInit *NewBI = BitsInit::get(NewBits);
    544 
    545     // Update the bits in reversed order so that emitInstrOpBits will get the
    546     // correct endianness.
    547     R->getValue("Inst")->setValue(NewBI);
    548   }
    549 }
    550 
    551 /// guessInstructionProperties - Return true if it's OK to guess instruction
    552 /// properties instead of raising an error.
    553 ///
    554 /// This is configurable as a temporary migration aid. It will eventually be
    555 /// permanently false.
    556 bool CodeGenTarget::guessInstructionProperties() const {
    557   return getInstructionSet()->getValueAsBit("guessInstructionProperties");
    558 }
    559 
    560 //===----------------------------------------------------------------------===//
    561 // ComplexPattern implementation
    562 //
    563 ComplexPattern::ComplexPattern(Record *R) {
    564   Ty          = ::getValueType(R->getValueAsDef("Ty"));
    565   NumOperands = R->getValueAsInt("NumOperands");
    566   SelectFunc = std::string(R->getValueAsString("SelectFunc"));
    567   RootNodes   = R->getValueAsListOfDefs("RootNodes");
    568 
    569   // FIXME: This is a hack to statically increase the priority of patterns which
    570   // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
    571   // possible pattern match we'll need to dynamically calculate the complexity
    572   // of all patterns a dag can potentially map to.
    573   int64_t RawComplexity = R->getValueAsInt("Complexity");
    574   if (RawComplexity == -1)
    575     Complexity = NumOperands * 3;
    576   else
    577     Complexity = RawComplexity;
    578 
    579   // FIXME: Why is this different from parseSDPatternOperatorProperties?
    580   // Parse the properties.
    581   Properties = 0;
    582   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
    583   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
    584     if (PropList[i]->getName() == "SDNPHasChain") {
    585       Properties |= 1 << SDNPHasChain;
    586     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
    587       Properties |= 1 << SDNPOptInGlue;
    588     } else if (PropList[i]->getName() == "SDNPMayStore") {
    589       Properties |= 1 << SDNPMayStore;
    590     } else if (PropList[i]->getName() == "SDNPMayLoad") {
    591       Properties |= 1 << SDNPMayLoad;
    592     } else if (PropList[i]->getName() == "SDNPSideEffect") {
    593       Properties |= 1 << SDNPSideEffect;
    594     } else if (PropList[i]->getName() == "SDNPMemOperand") {
    595       Properties |= 1 << SDNPMemOperand;
    596     } else if (PropList[i]->getName() == "SDNPVariadic") {
    597       Properties |= 1 << SDNPVariadic;
    598     } else if (PropList[i]->getName() == "SDNPWantRoot") {
    599       Properties |= 1 << SDNPWantRoot;
    600     } else if (PropList[i]->getName() == "SDNPWantParent") {
    601       Properties |= 1 << SDNPWantParent;
    602     } else {
    603       PrintFatalError(R->getLoc(), "Unsupported SD Node property '" +
    604                                        PropList[i]->getName() +
    605                                        "' on ComplexPattern '" + R->getName() +
    606                                        "'!");
    607     }
    608 }
    609 
    610 //===----------------------------------------------------------------------===//
    611 // CodeGenIntrinsic Implementation
    612 //===----------------------------------------------------------------------===//
    613 
    614 CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC) {
    615   std::vector<Record *> IntrProperties =
    616       RC.getAllDerivedDefinitions("IntrinsicProperty");
    617 
    618   std::vector<Record *> DefaultProperties;
    619   for (Record *Rec : IntrProperties)
    620     if (Rec->getValueAsBit("IsDefault"))
    621       DefaultProperties.push_back(Rec);
    622 
    623   std::vector<Record *> Defs = RC.getAllDerivedDefinitions("Intrinsic");
    624   Intrinsics.reserve(Defs.size());
    625 
    626   for (unsigned I = 0, e = Defs.size(); I != e; ++I)
    627     Intrinsics.push_back(CodeGenIntrinsic(Defs[I], DefaultProperties));
    628 
    629   llvm::sort(Intrinsics,
    630              [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
    631                return std::tie(LHS.TargetPrefix, LHS.Name) <
    632                       std::tie(RHS.TargetPrefix, RHS.Name);
    633              });
    634   Targets.push_back({"", 0, 0});
    635   for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
    636     if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
    637       Targets.back().Count = I - Targets.back().Offset;
    638       Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
    639     }
    640   Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
    641 }
    642 
    643 CodeGenIntrinsic::CodeGenIntrinsic(Record *R,
    644                                    std::vector<Record *> DefaultProperties) {
    645   TheDef = R;
    646   std::string DefName = std::string(R->getName());
    647   ArrayRef<SMLoc> DefLoc = R->getLoc();
    648   ModRef = ReadWriteMem;
    649   Properties = 0;
    650   isOverloaded = false;
    651   isCommutative = false;
    652   canThrow = false;
    653   isNoReturn = false;
    654   isNoSync = false;
    655   isNoFree = false;
    656   isWillReturn = false;
    657   isCold = false;
    658   isNoDuplicate = false;
    659   isNoMerge = false;
    660   isConvergent = false;
    661   isSpeculatable = false;
    662   hasSideEffects = false;
    663 
    664   if (DefName.size() <= 4 ||
    665       std::string(DefName.begin(), DefName.begin() + 4) != "int_")
    666     PrintFatalError(DefLoc,
    667                     "Intrinsic '" + DefName + "' does not start with 'int_'!");
    668 
    669   EnumName = std::string(DefName.begin()+4, DefName.end());
    670 
    671   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
    672     GCCBuiltinName = std::string(R->getValueAsString("GCCBuiltinName"));
    673   if (R->getValue("MSBuiltinName"))   // Ignore a missing MSBuiltinName field.
    674     MSBuiltinName = std::string(R->getValueAsString("MSBuiltinName"));
    675 
    676   TargetPrefix = std::string(R->getValueAsString("TargetPrefix"));
    677   Name = std::string(R->getValueAsString("LLVMName"));
    678 
    679   if (Name == "") {
    680     // If an explicit name isn't specified, derive one from the DefName.
    681     Name = "llvm.";
    682 
    683     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
    684       Name += (EnumName[i] == '_') ? '.' : EnumName[i];
    685   } else {
    686     // Verify it starts with "llvm.".
    687     if (Name.size() <= 5 ||
    688         std::string(Name.begin(), Name.begin() + 5) != "llvm.")
    689       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
    690                                   "'s name does not start with 'llvm.'!");
    691   }
    692 
    693   // If TargetPrefix is specified, make sure that Name starts with
    694   // "llvm.<targetprefix>.".
    695   if (!TargetPrefix.empty()) {
    696     if (Name.size() < 6+TargetPrefix.size() ||
    697         std::string(Name.begin() + 5, Name.begin() + 6 + TargetPrefix.size())
    698         != (TargetPrefix + "."))
    699       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
    700                                   "' does not start with 'llvm." +
    701                                   TargetPrefix + ".'!");
    702   }
    703 
    704   ListInit *RetTypes = R->getValueAsListInit("RetTypes");
    705   ListInit *ParamTypes = R->getValueAsListInit("ParamTypes");
    706 
    707   // First collate a list of overloaded types.
    708   std::vector<MVT::SimpleValueType> OverloadedVTs;
    709   for (ListInit *TypeList : {RetTypes, ParamTypes}) {
    710     for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
    711       Record *TyEl = TypeList->getElementAsRecord(i);
    712       assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
    713 
    714       if (TyEl->isSubClassOf("LLVMMatchType"))
    715         continue;
    716 
    717       MVT::SimpleValueType VT = getValueType(TyEl->getValueAsDef("VT"));
    718       if (MVT(VT).isOverloaded()) {
    719         OverloadedVTs.push_back(VT);
    720         isOverloaded = true;
    721       }
    722     }
    723   }
    724 
    725   // Parse the list of return types.
    726   ListInit *TypeList = RetTypes;
    727   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
    728     Record *TyEl = TypeList->getElementAsRecord(i);
    729     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
    730     MVT::SimpleValueType VT;
    731     if (TyEl->isSubClassOf("LLVMMatchType")) {
    732       unsigned MatchTy = TyEl->getValueAsInt("Number");
    733       assert(MatchTy < OverloadedVTs.size() &&
    734              "Invalid matching number!");
    735       VT = OverloadedVTs[MatchTy];
    736       // It only makes sense to use the extended and truncated vector element
    737       // variants with iAny types; otherwise, if the intrinsic is not
    738       // overloaded, all the types can be specified directly.
    739       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
    740                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
    741               VT == MVT::iAny || VT == MVT::vAny) &&
    742              "Expected iAny or vAny type");
    743     } else {
    744       VT = getValueType(TyEl->getValueAsDef("VT"));
    745     }
    746 
    747     // Reject invalid types.
    748     if (VT == MVT::isVoid)
    749       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
    750                                   " has void in result type list!");
    751 
    752     IS.RetVTs.push_back(VT);
    753     IS.RetTypeDefs.push_back(TyEl);
    754   }
    755 
    756   // Parse the list of parameter types.
    757   TypeList = ParamTypes;
    758   for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
    759     Record *TyEl = TypeList->getElementAsRecord(i);
    760     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
    761     MVT::SimpleValueType VT;
    762     if (TyEl->isSubClassOf("LLVMMatchType")) {
    763       unsigned MatchTy = TyEl->getValueAsInt("Number");
    764       if (MatchTy >= OverloadedVTs.size()) {
    765         PrintError(R->getLoc(),
    766                    "Parameter #" + Twine(i) + " has out of bounds matching "
    767                    "number " + Twine(MatchTy));
    768         PrintFatalError(DefLoc,
    769                         Twine("ParamTypes is ") + TypeList->getAsString());
    770       }
    771       VT = OverloadedVTs[MatchTy];
    772       // It only makes sense to use the extended and truncated vector element
    773       // variants with iAny types; otherwise, if the intrinsic is not
    774       // overloaded, all the types can be specified directly.
    775       assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
    776                !TyEl->isSubClassOf("LLVMTruncatedType")) ||
    777               VT == MVT::iAny || VT == MVT::vAny) &&
    778              "Expected iAny or vAny type");
    779     } else
    780       VT = getValueType(TyEl->getValueAsDef("VT"));
    781 
    782     // Reject invalid types.
    783     if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
    784       PrintFatalError(DefLoc, "Intrinsic '" + DefName +
    785                                   " has void in result type list!");
    786 
    787     IS.ParamVTs.push_back(VT);
    788     IS.ParamTypeDefs.push_back(TyEl);
    789   }
    790 
    791   // Parse the intrinsic properties.
    792   ListInit *PropList = R->getValueAsListInit("IntrProperties");
    793   for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
    794     Record *Property = PropList->getElementAsRecord(i);
    795     assert(Property->isSubClassOf("IntrinsicProperty") &&
    796            "Expected a property!");
    797 
    798     setProperty(Property);
    799   }
    800 
    801   // Set default properties to true.
    802   setDefaultProperties(R, DefaultProperties);
    803 
    804   // Also record the SDPatternOperator Properties.
    805   Properties = parseSDPatternOperatorProperties(R);
    806 
    807   // Sort the argument attributes for later benefit.
    808   llvm::sort(ArgumentAttributes);
    809 }
    810 
    811 void CodeGenIntrinsic::setDefaultProperties(
    812     Record *R, std::vector<Record *> DefaultProperties) {
    813   // opt-out of using default attributes.
    814   if (R->getValueAsBit("DisableDefaultAttributes"))
    815     return;
    816 
    817   for (Record *Rec : DefaultProperties)
    818     setProperty(Rec);
    819 }
    820 
    821 void CodeGenIntrinsic::setProperty(Record *R) {
    822   if (R->getName() == "IntrNoMem")
    823     ModRef = NoMem;
    824   else if (R->getName() == "IntrReadMem") {
    825     if (!(ModRef & MR_Ref))
    826       PrintFatalError(TheDef->getLoc(),
    827                       Twine("IntrReadMem cannot be used after IntrNoMem or "
    828                             "IntrWriteMem. Default is ReadWrite"));
    829     ModRef = ModRefBehavior(ModRef & ~MR_Mod);
    830   } else if (R->getName() == "IntrWriteMem") {
    831     if (!(ModRef & MR_Mod))
    832       PrintFatalError(TheDef->getLoc(),
    833                       Twine("IntrWriteMem cannot be used after IntrNoMem or "
    834                             "IntrReadMem. Default is ReadWrite"));
    835     ModRef = ModRefBehavior(ModRef & ~MR_Ref);
    836   } else if (R->getName() == "IntrArgMemOnly")
    837     ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem);
    838   else if (R->getName() == "IntrInaccessibleMemOnly")
    839     ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_InaccessibleMem);
    840   else if (R->getName() == "IntrInaccessibleMemOrArgMemOnly")
    841     ModRef = ModRefBehavior((ModRef & ~MR_Anywhere) | MR_ArgMem |
    842                             MR_InaccessibleMem);
    843   else if (R->getName() == "Commutative")
    844     isCommutative = true;
    845   else if (R->getName() == "Throws")
    846     canThrow = true;
    847   else if (R->getName() == "IntrNoDuplicate")
    848     isNoDuplicate = true;
    849   else if (R->getName() == "IntrNoMerge")
    850     isNoMerge = true;
    851   else if (R->getName() == "IntrConvergent")
    852     isConvergent = true;
    853   else if (R->getName() == "IntrNoReturn")
    854     isNoReturn = true;
    855   else if (R->getName() == "IntrNoSync")
    856     isNoSync = true;
    857   else if (R->getName() == "IntrNoFree")
    858     isNoFree = true;
    859   else if (R->getName() == "IntrWillReturn")
    860     isWillReturn = !isNoReturn;
    861   else if (R->getName() == "IntrCold")
    862     isCold = true;
    863   else if (R->getName() == "IntrSpeculatable")
    864     isSpeculatable = true;
    865   else if (R->getName() == "IntrHasSideEffects")
    866     hasSideEffects = true;
    867   else if (R->isSubClassOf("NoCapture")) {
    868     unsigned ArgNo = R->getValueAsInt("ArgNo");
    869     ArgumentAttributes.emplace_back(ArgNo, NoCapture, 0);
    870   } else if (R->isSubClassOf("NoAlias")) {
    871     unsigned ArgNo = R->getValueAsInt("ArgNo");
    872     ArgumentAttributes.emplace_back(ArgNo, NoAlias, 0);
    873   } else if (R->isSubClassOf("NoUndef")) {
    874     unsigned ArgNo = R->getValueAsInt("ArgNo");
    875     ArgumentAttributes.emplace_back(ArgNo, NoUndef, 0);
    876   } else if (R->isSubClassOf("Returned")) {
    877     unsigned ArgNo = R->getValueAsInt("ArgNo");
    878     ArgumentAttributes.emplace_back(ArgNo, Returned, 0);
    879   } else if (R->isSubClassOf("ReadOnly")) {
    880     unsigned ArgNo = R->getValueAsInt("ArgNo");
    881     ArgumentAttributes.emplace_back(ArgNo, ReadOnly, 0);
    882   } else if (R->isSubClassOf("WriteOnly")) {
    883     unsigned ArgNo = R->getValueAsInt("ArgNo");
    884     ArgumentAttributes.emplace_back(ArgNo, WriteOnly, 0);
    885   } else if (R->isSubClassOf("ReadNone")) {
    886     unsigned ArgNo = R->getValueAsInt("ArgNo");
    887     ArgumentAttributes.emplace_back(ArgNo, ReadNone, 0);
    888   } else if (R->isSubClassOf("ImmArg")) {
    889     unsigned ArgNo = R->getValueAsInt("ArgNo");
    890     ArgumentAttributes.emplace_back(ArgNo, ImmArg, 0);
    891   } else if (R->isSubClassOf("Align")) {
    892     unsigned ArgNo = R->getValueAsInt("ArgNo");
    893     uint64_t Align = R->getValueAsInt("Align");
    894     ArgumentAttributes.emplace_back(ArgNo, Alignment, Align);
    895   } else
    896     llvm_unreachable("Unknown property!");
    897 }
    898 
    899 bool CodeGenIntrinsic::isParamAPointer(unsigned ParamIdx) const {
    900   if (ParamIdx >= IS.ParamVTs.size())
    901     return false;
    902   MVT ParamType = MVT(IS.ParamVTs[ParamIdx]);
    903   return ParamType == MVT::iPTR || ParamType == MVT::iPTRAny;
    904 }
    905 
    906 bool CodeGenIntrinsic::isParamImmArg(unsigned ParamIdx) const {
    907   // Convert argument index to attribute index starting from `FirstArgIndex`.
    908   ArgAttribute Val{ParamIdx + 1, ImmArg, 0};
    909   return std::binary_search(ArgumentAttributes.begin(),
    910                             ArgumentAttributes.end(), Val);
    911 }
    912