1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. --*- C++ -*-===// 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 tablegen backend is responsible for emitting a description of the target 10 // instruction set for the code generator. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "Basic/SequenceToOffsetTable.h" 15 #include "Common/CodeGenDAGPatterns.h" 16 #include "Common/CodeGenInstruction.h" 17 #include "Common/CodeGenSchedule.h" 18 #include "Common/CodeGenTarget.h" 19 #include "Common/PredicateExpander.h" 20 #include "Common/SubtargetFeatureInfo.h" 21 #include "Common/Types.h" 22 #include "TableGenBackends.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/Support/Casting.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/TableGen/Error.h" 30 #include "llvm/TableGen/Record.h" 31 #include "llvm/TableGen/TGTimer.h" 32 #include "llvm/TableGen/TableGenBackend.h" 33 #include <cassert> 34 #include <cstdint> 35 #include <iterator> 36 #include <map> 37 #include <string> 38 #include <utility> 39 #include <vector> 40 41 using namespace llvm; 42 43 cl::OptionCategory InstrInfoEmitterCat("Options for -gen-instr-info"); 44 static cl::opt<bool> ExpandMIOperandInfo( 45 "instr-info-expand-mi-operand-info", 46 cl::desc("Expand operand's MIOperandInfo DAG into suboperands"), 47 cl::cat(InstrInfoEmitterCat), cl::init(true)); 48 49 namespace { 50 51 class InstrInfoEmitter { 52 const RecordKeeper &Records; 53 const CodeGenDAGPatterns CDP; 54 const CodeGenSchedModels &SchedModels; 55 56 public: 57 InstrInfoEmitter(const RecordKeeper &R) 58 : Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {} 59 60 // run - Output the instruction set description. 61 void run(raw_ostream &OS); 62 63 private: 64 void emitEnums(raw_ostream &OS); 65 66 typedef std::vector<std::string> OperandInfoTy; 67 typedef std::vector<OperandInfoTy> OperandInfoListTy; 68 typedef std::map<OperandInfoTy, unsigned> OperandInfoMapTy; 69 70 /// The keys of this map are maps which have OpName enum values as their keys 71 /// and instruction operand indices as their values. The values of this map 72 /// are lists of instruction names. 73 typedef std::map<std::map<unsigned, unsigned>, std::vector<std::string>> 74 OpNameMapTy; 75 typedef std::map<std::string, unsigned>::iterator StrUintMapIter; 76 77 /// Generate member functions in the target-specific GenInstrInfo class. 78 /// 79 /// This method is used to custom expand TIIPredicate definitions. 80 /// See file llvm/Target/TargetInstPredicates.td for a description of what is 81 /// a TIIPredicate and how to use it. 82 void emitTIIHelperMethods(raw_ostream &OS, StringRef TargetName, 83 bool ExpandDefinition = true); 84 85 /// Expand TIIPredicate definitions to functions that accept a const MCInst 86 /// reference. 87 void emitMCIIHelperMethods(raw_ostream &OS, StringRef TargetName); 88 89 /// Write verifyInstructionPredicates methods. 90 void emitFeatureVerifier(raw_ostream &OS, const CodeGenTarget &Target); 91 void emitRecord(const CodeGenInstruction &Inst, unsigned Num, 92 const Record *InstrInfo, 93 std::map<std::vector<const Record *>, unsigned> &EL, 94 const OperandInfoMapTy &OperandInfo, raw_ostream &OS); 95 void emitOperandTypeMappings( 96 raw_ostream &OS, const CodeGenTarget &Target, 97 ArrayRef<const CodeGenInstruction *> NumberedInstructions); 98 void 99 initOperandMapData(ArrayRef<const CodeGenInstruction *> NumberedInstructions, 100 StringRef Namespace, 101 std::map<std::string, unsigned> &Operands, 102 OpNameMapTy &OperandMap); 103 void emitOperandNameMappings( 104 raw_ostream &OS, const CodeGenTarget &Target, 105 ArrayRef<const CodeGenInstruction *> NumberedInstructions); 106 107 void emitLogicalOperandSizeMappings( 108 raw_ostream &OS, StringRef Namespace, 109 ArrayRef<const CodeGenInstruction *> NumberedInstructions); 110 void emitLogicalOperandTypeMappings( 111 raw_ostream &OS, StringRef Namespace, 112 ArrayRef<const CodeGenInstruction *> NumberedInstructions); 113 114 // Operand information. 115 unsigned CollectOperandInfo(OperandInfoListTy &OperandInfoList, 116 OperandInfoMapTy &OperandInfoMap); 117 void EmitOperandInfo(raw_ostream &OS, OperandInfoListTy &OperandInfoList); 118 OperandInfoTy GetOperandInfo(const CodeGenInstruction &Inst); 119 }; 120 121 } // end anonymous namespace 122 123 //===----------------------------------------------------------------------===// 124 // Operand Info Emission. 125 //===----------------------------------------------------------------------===// 126 127 InstrInfoEmitter::OperandInfoTy 128 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) { 129 OperandInfoTy Result; 130 131 for (auto &Op : Inst.Operands) { 132 // Handle aggregate operands and normal operands the same way by expanding 133 // either case into a list of operands for this op. 134 std::vector<CGIOperandList::OperandInfo> OperandList; 135 136 // This might be a multiple operand thing. Targets like X86 have 137 // registers in their multi-operand operands. It may also be an anonymous 138 // operand, which has a single operand, but no declared class for the 139 // operand. 140 const DagInit *MIOI = Op.MIOperandInfo; 141 142 if (!MIOI || MIOI->getNumArgs() == 0) { 143 // Single, anonymous, operand. 144 OperandList.push_back(Op); 145 } else { 146 for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) { 147 OperandList.push_back(Op); 148 149 auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef(); 150 OperandList.back().Rec = OpR; 151 } 152 } 153 154 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) { 155 const Record *OpR = OperandList[j].Rec; 156 std::string Res; 157 158 if (OpR->isSubClassOf("RegisterOperand")) 159 OpR = OpR->getValueAsDef("RegClass"); 160 if (OpR->isSubClassOf("RegisterClass")) 161 Res += getQualifiedName(OpR) + "RegClassID, "; 162 else if (OpR->isSubClassOf("PointerLikeRegClass")) 163 Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", "; 164 else 165 // -1 means the operand does not have a fixed register class. 166 Res += "-1, "; 167 168 // Fill in applicable flags. 169 Res += "0"; 170 171 // Ptr value whose register class is resolved via callback. 172 if (OpR->isSubClassOf("PointerLikeRegClass")) 173 Res += "|(1<<MCOI::LookupPtrRegClass)"; 174 175 // Predicate operands. Check to see if the original unexpanded operand 176 // was of type PredicateOp. 177 if (Op.Rec->isSubClassOf("PredicateOp")) 178 Res += "|(1<<MCOI::Predicate)"; 179 180 // Optional def operands. Check to see if the original unexpanded operand 181 // was of type OptionalDefOperand. 182 if (Op.Rec->isSubClassOf("OptionalDefOperand")) 183 Res += "|(1<<MCOI::OptionalDef)"; 184 185 // Branch target operands. Check to see if the original unexpanded 186 // operand was of type BranchTargetOperand. 187 if (Op.Rec->isSubClassOf("BranchTargetOperand")) 188 Res += "|(1<<MCOI::BranchTarget)"; 189 190 // Fill in operand type. 191 Res += ", "; 192 assert(!Op.OperandType.empty() && "Invalid operand type."); 193 Res += Op.OperandType; 194 195 // Fill in constraint info. 196 Res += ", "; 197 198 const CGIOperandList::ConstraintInfo &Constraint = Op.Constraints[j]; 199 if (Constraint.isNone()) 200 Res += "0"; 201 else if (Constraint.isEarlyClobber()) 202 Res += "MCOI_EARLY_CLOBBER"; 203 else { 204 assert(Constraint.isTied()); 205 Res += "MCOI_TIED_TO(" + utostr(Constraint.getTiedOperand()) + ")"; 206 } 207 208 Result.push_back(Res); 209 } 210 } 211 212 return Result; 213 } 214 215 unsigned 216 InstrInfoEmitter::CollectOperandInfo(OperandInfoListTy &OperandInfoList, 217 OperandInfoMapTy &OperandInfoMap) { 218 const CodeGenTarget &Target = CDP.getTargetInfo(); 219 unsigned Offset = 0; 220 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) { 221 OperandInfoTy OperandInfo = GetOperandInfo(*Inst); 222 if (OperandInfoMap.insert({OperandInfo, Offset}).second) { 223 OperandInfoList.push_back(OperandInfo); 224 Offset += OperandInfo.size(); 225 } 226 } 227 return Offset; 228 } 229 230 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS, 231 OperandInfoListTy &OperandInfoList) { 232 unsigned Offset = 0; 233 for (auto &OperandInfo : OperandInfoList) { 234 OS << " /* " << Offset << " */"; 235 for (auto &Info : OperandInfo) 236 OS << " { " << Info << " },"; 237 OS << '\n'; 238 Offset += OperandInfo.size(); 239 } 240 } 241 242 /// Initialize data structures for generating operand name mappings. 243 /// 244 /// \param Operands [out] A map used to generate the OpName enum with operand 245 /// names as its keys and operand enum values as its values. 246 /// \param OperandMap [out] A map for representing the operand name mappings for 247 /// each instructions. This is used to generate the OperandMap table as 248 /// well as the getNamedOperandIdx() function. 249 void InstrInfoEmitter::initOperandMapData( 250 ArrayRef<const CodeGenInstruction *> NumberedInstructions, 251 StringRef Namespace, std::map<std::string, unsigned> &Operands, 252 OpNameMapTy &OperandMap) { 253 unsigned NumOperands = 0; 254 for (const CodeGenInstruction *Inst : NumberedInstructions) { 255 if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable")) 256 continue; 257 std::map<unsigned, unsigned> OpList; 258 for (const auto &Info : Inst->Operands) { 259 StrUintMapIter I = Operands.find(Info.Name); 260 261 if (I == Operands.end()) { 262 I = Operands.insert(Operands.begin(), {Info.Name, NumOperands++}); 263 } 264 OpList[I->second] = Info.MIOperandNo; 265 } 266 OperandMap[OpList].push_back(Namespace.str() + 267 "::" + Inst->TheDef->getName().str()); 268 } 269 } 270 271 /// Generate a table and function for looking up the indices of operands by 272 /// name. 273 /// 274 /// This code generates: 275 /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry 276 /// for each operand name. 277 /// - A 2-dimensional table called OperandMap for mapping OpName enum values to 278 /// operand indices. 279 /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) 280 /// for looking up the operand index for an instruction, given a value from 281 /// OpName enum 282 void InstrInfoEmitter::emitOperandNameMappings( 283 raw_ostream &OS, const CodeGenTarget &Target, 284 ArrayRef<const CodeGenInstruction *> NumberedInstructions) { 285 StringRef Namespace = Target.getInstNamespace(); 286 // Map of operand names to their enumeration value. This will be used to 287 // generate the OpName enum. 288 std::map<std::string, unsigned> Operands; 289 OpNameMapTy OperandMap; 290 291 initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap); 292 293 OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n"; 294 OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n"; 295 OS << "namespace llvm::" << Namespace << "::OpName {\n"; 296 OS << "enum {\n"; 297 for (const auto &Op : Operands) 298 OS << " " << Op.first << " = " << Op.second << ",\n"; 299 300 OS << " OPERAND_LAST"; 301 OS << "\n};\n"; 302 OS << "} // end namespace llvm::" << Namespace << "::OpName\n"; 303 OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n"; 304 305 OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n"; 306 OS << "#undef GET_INSTRINFO_NAMED_OPS\n"; 307 OS << "namespace llvm::" << Namespace << " {\n"; 308 OS << "LLVM_READONLY\n"; 309 OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n"; 310 if (!Operands.empty()) { 311 OS << " static const int16_t OperandMap [][" << Operands.size() 312 << "] = {\n"; 313 for (const auto &Entry : OperandMap) { 314 const std::map<unsigned, unsigned> &OpList = Entry.first; 315 OS << "{"; 316 317 // Emit a row of the OperandMap table 318 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 319 OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", "; 320 321 OS << "},\n"; 322 } 323 OS << "};\n"; 324 325 OS << " switch(Opcode) {\n"; 326 unsigned TableIndex = 0; 327 for (const auto &Entry : OperandMap) { 328 for (const std::string &Name : Entry.second) 329 OS << " case " << Name << ":\n"; 330 331 OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n"; 332 } 333 OS << " default: return -1;\n"; 334 OS << " }\n"; 335 } else { 336 // There are no operands, so no need to emit anything 337 OS << " return -1;\n"; 338 } 339 OS << "}\n"; 340 OS << "} // end namespace llvm::" << Namespace << "\n"; 341 OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n"; 342 } 343 344 /// Generate an enum for all the operand types for this target, under the 345 /// llvm::TargetNamespace::OpTypes namespace. 346 /// Operand types are all definitions derived of the Operand Target.td class. 347 void InstrInfoEmitter::emitOperandTypeMappings( 348 raw_ostream &OS, const CodeGenTarget &Target, 349 ArrayRef<const CodeGenInstruction *> NumberedInstructions) { 350 351 StringRef Namespace = Target.getInstNamespace(); 352 ArrayRef<const Record *> Operands = 353 Records.getAllDerivedDefinitions("Operand"); 354 ArrayRef<const Record *> RegisterOperands = 355 Records.getAllDerivedDefinitions("RegisterOperand"); 356 ArrayRef<const Record *> RegisterClasses = 357 Records.getAllDerivedDefinitions("RegisterClass"); 358 359 OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n"; 360 OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n"; 361 OS << "namespace llvm::" << Namespace << "::OpTypes {\n"; 362 OS << "enum OperandType {\n"; 363 364 unsigned EnumVal = 0; 365 for (ArrayRef<const Record *> RecordsToAdd : 366 {Operands, RegisterOperands, RegisterClasses}) { 367 for (const Record *Op : RecordsToAdd) { 368 if (!Op->isAnonymous()) 369 OS << " " << Op->getName() << " = " << EnumVal << ",\n"; 370 ++EnumVal; 371 } 372 } 373 374 OS << " OPERAND_TYPE_LIST_END" 375 << "\n};\n"; 376 OS << "} // end namespace llvm::" << Namespace << "::OpTypes\n"; 377 OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n"; 378 379 OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n"; 380 OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n"; 381 OS << "namespace llvm::" << Namespace << " {\n"; 382 OS << "LLVM_READONLY\n"; 383 OS << "static int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n"; 384 auto getInstrName = [&](int I) -> StringRef { 385 return NumberedInstructions[I]->TheDef->getName(); 386 }; 387 // TODO: Factor out duplicate operand lists to compress the tables. 388 if (!NumberedInstructions.empty()) { 389 std::vector<int> OperandOffsets; 390 std::vector<const Record *> OperandRecords; 391 int CurrentOffset = 0; 392 for (const CodeGenInstruction *Inst : NumberedInstructions) { 393 OperandOffsets.push_back(CurrentOffset); 394 for (const auto &Op : Inst->Operands) { 395 const DagInit *MIOI = Op.MIOperandInfo; 396 if (!ExpandMIOperandInfo || !MIOI || MIOI->getNumArgs() == 0) { 397 // Single, anonymous, operand. 398 OperandRecords.push_back(Op.Rec); 399 ++CurrentOffset; 400 } else { 401 for (const Init *Arg : MIOI->getArgs()) { 402 OperandRecords.push_back(cast<DefInit>(Arg)->getDef()); 403 ++CurrentOffset; 404 } 405 } 406 } 407 } 408 409 // Emit the table of offsets (indexes) into the operand type table. 410 // Size the unsigned integer offset to save space. 411 assert(OperandRecords.size() <= UINT32_MAX && 412 "Too many operands for offset table"); 413 OS << " static const " << getMinimalTypeForRange(OperandRecords.size()); 414 OS << " Offsets[] = {\n"; 415 for (int I = 0, E = OperandOffsets.size(); I != E; ++I) { 416 OS << " /* " << getInstrName(I) << " */\n"; 417 OS << " " << OperandOffsets[I] << ",\n"; 418 } 419 OS << " };\n"; 420 421 // Add an entry for the end so that we don't need to special case it below. 422 OperandOffsets.push_back(OperandRecords.size()); 423 424 // Emit the actual operand types in a flat table. 425 // Size the signed integer operand type to save space. 426 assert(EnumVal <= INT16_MAX && 427 "Too many operand types for operand types table"); 428 OS << "\n using namespace OpTypes;\n"; 429 OS << " static"; 430 OS << ((EnumVal <= INT8_MAX) ? " const int8_t" : " const int16_t"); 431 OS << " OpcodeOperandTypes[] = {\n "; 432 for (int I = 0, E = OperandRecords.size(), CurOffset = 0; I != E; ++I) { 433 // We print each Opcode's operands in its own row. 434 if (I == OperandOffsets[CurOffset]) { 435 OS << "\n /* " << getInstrName(CurOffset) << " */\n "; 436 while (OperandOffsets[++CurOffset] == I) 437 OS << "/* " << getInstrName(CurOffset) << " */\n "; 438 } 439 const Record *OpR = OperandRecords[I]; 440 if ((OpR->isSubClassOf("Operand") || 441 OpR->isSubClassOf("RegisterOperand") || 442 OpR->isSubClassOf("RegisterClass")) && 443 !OpR->isAnonymous()) 444 OS << OpR->getName(); 445 else 446 OS << -1; 447 OS << ", "; 448 } 449 OS << "\n };\n"; 450 451 OS << " return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n"; 452 } else { 453 OS << " llvm_unreachable(\"No instructions defined\");\n"; 454 } 455 OS << "}\n"; 456 OS << "} // end namespace llvm::" << Namespace << "\n"; 457 OS << "#endif // GET_INSTRINFO_OPERAND_TYPE\n\n"; 458 459 OS << "#ifdef GET_INSTRINFO_MEM_OPERAND_SIZE\n"; 460 OS << "#undef GET_INSTRINFO_MEM_OPERAND_SIZE\n"; 461 OS << "namespace llvm::" << Namespace << " {\n"; 462 OS << "LLVM_READONLY\n"; 463 OS << "static int getMemOperandSize(int OpType) {\n"; 464 OS << " switch (OpType) {\n"; 465 std::map<int, SmallVector<StringRef, 0>> SizeToOperandName; 466 for (const Record *Op : Operands) { 467 if (!Op->isSubClassOf("X86MemOperand")) 468 continue; 469 if (int Size = Op->getValueAsInt("Size")) 470 SizeToOperandName[Size].push_back(Op->getName()); 471 } 472 OS << " default: return 0;\n"; 473 for (const auto &KV : SizeToOperandName) { 474 for (const StringRef &OperandName : KV.second) 475 OS << " case OpTypes::" << OperandName << ":\n"; 476 OS << " return " << KV.first << ";\n\n"; 477 } 478 OS << " }\n}\n"; 479 OS << "} // end namespace llvm::" << Namespace << "\n"; 480 OS << "#endif // GET_INSTRINFO_MEM_OPERAND_SIZE\n\n"; 481 } 482 483 void InstrInfoEmitter::emitLogicalOperandSizeMappings( 484 raw_ostream &OS, StringRef Namespace, 485 ArrayRef<const CodeGenInstruction *> NumberedInstructions) { 486 std::map<std::vector<unsigned>, unsigned> LogicalOpSizeMap; 487 488 std::map<unsigned, std::vector<std::string>> InstMap; 489 490 size_t LogicalOpListSize = 0U; 491 std::vector<unsigned> LogicalOpList; 492 for (const auto *Inst : NumberedInstructions) { 493 if (!Inst->TheDef->getValueAsBit("UseLogicalOperandMappings")) 494 continue; 495 496 LogicalOpList.clear(); 497 llvm::transform(Inst->Operands, std::back_inserter(LogicalOpList), 498 [](const CGIOperandList::OperandInfo &Op) -> unsigned { 499 auto *MIOI = Op.MIOperandInfo; 500 if (!MIOI || MIOI->getNumArgs() == 0) 501 return 1; 502 return MIOI->getNumArgs(); 503 }); 504 LogicalOpListSize = std::max(LogicalOpList.size(), LogicalOpListSize); 505 506 auto I = 507 LogicalOpSizeMap.insert({LogicalOpList, LogicalOpSizeMap.size()}).first; 508 InstMap[I->second].push_back( 509 (Namespace + "::" + Inst->TheDef->getName()).str()); 510 } 511 512 OS << "#ifdef GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n"; 513 OS << "#undef GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n"; 514 OS << "namespace llvm::" << Namespace << " {\n"; 515 OS << "LLVM_READONLY static unsigned\n"; 516 OS << "getLogicalOperandSize(uint16_t Opcode, uint16_t LogicalOpIdx) {\n"; 517 if (!InstMap.empty()) { 518 std::vector<const std::vector<unsigned> *> LogicalOpSizeList( 519 LogicalOpSizeMap.size()); 520 for (auto &P : LogicalOpSizeMap) { 521 LogicalOpSizeList[P.second] = &P.first; 522 } 523 OS << " static const unsigned SizeMap[][" << LogicalOpListSize 524 << "] = {\n"; 525 for (auto &R : LogicalOpSizeList) { 526 const auto &Row = *R; 527 OS << " {"; 528 int i; 529 for (i = 0; i < static_cast<int>(Row.size()); ++i) { 530 OS << Row[i] << ", "; 531 } 532 for (; i < static_cast<int>(LogicalOpListSize); ++i) { 533 OS << "0, "; 534 } 535 OS << "}, "; 536 OS << "\n"; 537 } 538 OS << " };\n"; 539 540 OS << " switch (Opcode) {\n"; 541 OS << " default: return LogicalOpIdx;\n"; 542 for (auto &P : InstMap) { 543 auto OpMapIdx = P.first; 544 const auto &Insts = P.second; 545 for (const auto &Inst : Insts) { 546 OS << " case " << Inst << ":\n"; 547 } 548 OS << " return SizeMap[" << OpMapIdx << "][LogicalOpIdx];\n"; 549 } 550 OS << " }\n"; 551 } else { 552 OS << " return LogicalOpIdx;\n"; 553 } 554 OS << "}\n"; 555 556 OS << "LLVM_READONLY static inline unsigned\n"; 557 OS << "getLogicalOperandIdx(uint16_t Opcode, uint16_t LogicalOpIdx) {\n"; 558 OS << " auto S = 0U;\n"; 559 OS << " for (auto i = 0U; i < LogicalOpIdx; ++i)\n"; 560 OS << " S += getLogicalOperandSize(Opcode, i);\n"; 561 OS << " return S;\n"; 562 OS << "}\n"; 563 564 OS << "} // end namespace llvm::" << Namespace << "\n"; 565 OS << "#endif // GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n\n"; 566 } 567 568 void InstrInfoEmitter::emitLogicalOperandTypeMappings( 569 raw_ostream &OS, StringRef Namespace, 570 ArrayRef<const CodeGenInstruction *> NumberedInstructions) { 571 std::map<std::vector<std::string>, unsigned> LogicalOpTypeMap; 572 573 std::map<unsigned, std::vector<std::string>> InstMap; 574 575 size_t OpTypeListSize = 0U; 576 std::vector<std::string> LogicalOpTypeList; 577 for (const auto *Inst : NumberedInstructions) { 578 if (!Inst->TheDef->getValueAsBit("UseLogicalOperandMappings")) 579 continue; 580 581 LogicalOpTypeList.clear(); 582 for (const auto &Op : Inst->Operands) { 583 auto *OpR = Op.Rec; 584 if ((OpR->isSubClassOf("Operand") || 585 OpR->isSubClassOf("RegisterOperand") || 586 OpR->isSubClassOf("RegisterClass")) && 587 !OpR->isAnonymous()) { 588 LogicalOpTypeList.push_back( 589 (Namespace + "::OpTypes::" + Op.Rec->getName()).str()); 590 } else { 591 LogicalOpTypeList.push_back("-1"); 592 } 593 } 594 OpTypeListSize = std::max(LogicalOpTypeList.size(), OpTypeListSize); 595 596 auto I = 597 LogicalOpTypeMap.insert({LogicalOpTypeList, LogicalOpTypeMap.size()}) 598 .first; 599 InstMap[I->second].push_back( 600 (Namespace + "::" + Inst->TheDef->getName()).str()); 601 } 602 603 OS << "#ifdef GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n"; 604 OS << "#undef GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n"; 605 OS << "namespace llvm::" << Namespace << " {\n"; 606 OS << "LLVM_READONLY static int\n"; 607 OS << "getLogicalOperandType(uint16_t Opcode, uint16_t LogicalOpIdx) {\n"; 608 if (!InstMap.empty()) { 609 std::vector<const std::vector<std::string> *> LogicalOpTypeList( 610 LogicalOpTypeMap.size()); 611 for (auto &P : LogicalOpTypeMap) { 612 LogicalOpTypeList[P.second] = &P.first; 613 } 614 OS << " static const int TypeMap[][" << OpTypeListSize << "] = {\n"; 615 for (int r = 0, rs = LogicalOpTypeList.size(); r < rs; ++r) { 616 const auto &Row = *LogicalOpTypeList[r]; 617 OS << " {"; 618 int i, s = Row.size(); 619 for (i = 0; i < s; ++i) { 620 if (i > 0) 621 OS << ", "; 622 OS << Row[i]; 623 } 624 for (; i < static_cast<int>(OpTypeListSize); ++i) { 625 if (i > 0) 626 OS << ", "; 627 OS << "-1"; 628 } 629 OS << "}"; 630 if (r != rs - 1) 631 OS << ","; 632 OS << "\n"; 633 } 634 OS << " };\n"; 635 636 OS << " switch (Opcode) {\n"; 637 OS << " default: return -1;\n"; 638 for (auto &P : InstMap) { 639 auto OpMapIdx = P.first; 640 const auto &Insts = P.second; 641 for (const auto &Inst : Insts) { 642 OS << " case " << Inst << ":\n"; 643 } 644 OS << " return TypeMap[" << OpMapIdx << "][LogicalOpIdx];\n"; 645 } 646 OS << " }\n"; 647 } else { 648 OS << " return -1;\n"; 649 } 650 OS << "}\n"; 651 OS << "} // end namespace llvm::" << Namespace << "\n"; 652 OS << "#endif // GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n\n"; 653 } 654 655 void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS, 656 StringRef TargetName) { 657 ArrayRef<const Record *> TIIPredicates = 658 Records.getAllDerivedDefinitions("TIIPredicate"); 659 660 OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n"; 661 OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n"; 662 663 OS << "namespace llvm {\n"; 664 OS << "class MCInst;\n"; 665 OS << "class FeatureBitset;\n\n"; 666 667 OS << "namespace " << TargetName << "_MC {\n\n"; 668 669 for (const Record *Rec : TIIPredicates) { 670 OS << "bool " << Rec->getValueAsString("FunctionName") 671 << "(const MCInst &MI);\n"; 672 } 673 674 OS << "void verifyInstructionPredicates(unsigned Opcode, const FeatureBitset " 675 "&Features);\n"; 676 677 OS << "\n} // end namespace " << TargetName << "_MC\n"; 678 OS << "} // end namespace llvm\n\n"; 679 680 OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n"; 681 682 OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n"; 683 OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n"; 684 685 OS << "namespace llvm::" << TargetName << "_MC {\n"; 686 687 PredicateExpander PE(TargetName); 688 PE.setExpandForMC(true); 689 690 for (const Record *Rec : TIIPredicates) { 691 OS << "bool " << Rec->getValueAsString("FunctionName"); 692 OS << "(const MCInst &MI) {\n"; 693 694 OS << PE.getIndent(); 695 PE.expandStatement(OS, Rec->getValueAsDef("Body")); 696 OS << "\n}\n\n"; 697 } 698 699 OS << "} // end namespace llvm::" << TargetName << "_MC\n"; 700 701 OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n\n"; 702 } 703 704 static std::string 705 getNameForFeatureBitset(ArrayRef<const Record *> FeatureBitset) { 706 std::string Name = "CEFBS"; 707 for (const Record *Feature : FeatureBitset) 708 Name += ("_" + Feature->getName()).str(); 709 return Name; 710 } 711 712 void InstrInfoEmitter::emitFeatureVerifier(raw_ostream &OS, 713 const CodeGenTarget &Target) { 714 const auto &All = SubtargetFeatureInfo::getAll(Records); 715 SubtargetFeatureInfoMap SubtargetFeatures; 716 SubtargetFeatures.insert(All.begin(), All.end()); 717 718 OS << "#if (defined(ENABLE_INSTR_PREDICATE_VERIFIER) && !defined(NDEBUG)) " 719 << "||\\\n" 720 << " defined(GET_AVAILABLE_OPCODE_CHECKER)\n" 721 << "#define GET_COMPUTE_FEATURES\n" 722 << "#endif\n"; 723 OS << "#ifdef GET_COMPUTE_FEATURES\n" 724 << "#undef GET_COMPUTE_FEATURES\n" 725 << "namespace llvm::" << Target.getName() << "_MC {\n"; 726 727 // Emit the subtarget feature enumeration. 728 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures, 729 OS); 730 // Emit the available features compute function. 731 OS << "inline "; 732 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures( 733 Target.getName(), "", "computeAvailableFeatures", SubtargetFeatures, OS); 734 735 std::vector<std::vector<const Record *>> FeatureBitsets; 736 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) { 737 FeatureBitsets.emplace_back(); 738 for (const Record *Predicate : 739 Inst->TheDef->getValueAsListOfDefs("Predicates")) { 740 const auto &I = SubtargetFeatures.find(Predicate); 741 if (I != SubtargetFeatures.end()) 742 FeatureBitsets.back().push_back(I->second.TheDef); 743 } 744 } 745 746 llvm::sort(FeatureBitsets, [&](ArrayRef<const Record *> A, 747 ArrayRef<const Record *> B) { 748 if (A.size() < B.size()) 749 return true; 750 if (A.size() > B.size()) 751 return false; 752 for (auto Pair : zip(A, B)) { 753 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName()) 754 return true; 755 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName()) 756 return false; 757 } 758 return false; 759 }); 760 FeatureBitsets.erase(llvm::unique(FeatureBitsets), FeatureBitsets.end()); 761 OS << "inline FeatureBitset computeRequiredFeatures(unsigned Opcode) {\n" 762 << " enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n" 763 << " CEFBS_None,\n"; 764 for (const auto &FeatureBitset : FeatureBitsets) { 765 if (FeatureBitset.empty()) 766 continue; 767 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n"; 768 } 769 OS << " };\n\n" 770 << " static constexpr FeatureBitset FeatureBitsets[] = {\n" 771 << " {}, // CEFBS_None\n"; 772 for (const auto &FeatureBitset : FeatureBitsets) { 773 if (FeatureBitset.empty()) 774 continue; 775 OS << " {"; 776 for (const auto &Feature : FeatureBitset) { 777 const auto &I = SubtargetFeatures.find(Feature); 778 assert(I != SubtargetFeatures.end() && "Didn't import predicate?"); 779 OS << I->second.getEnumBitName() << ", "; 780 } 781 OS << "},\n"; 782 } 783 OS << " };\n" 784 << " static constexpr " << getMinimalTypeForRange(FeatureBitsets.size()) 785 << " RequiredFeaturesRefs[] = {\n"; 786 unsigned InstIdx = 0; 787 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) { 788 OS << " CEFBS"; 789 unsigned NumPredicates = 0; 790 for (const Record *Predicate : 791 Inst->TheDef->getValueAsListOfDefs("Predicates")) { 792 const auto &I = SubtargetFeatures.find(Predicate); 793 if (I != SubtargetFeatures.end()) { 794 OS << '_' << I->second.TheDef->getName(); 795 NumPredicates++; 796 } 797 } 798 if (!NumPredicates) 799 OS << "_None"; 800 OS << ", // " << Inst->TheDef->getName() << " = " << InstIdx << "\n"; 801 InstIdx++; 802 } 803 OS << " };\n\n" 804 << " assert(Opcode < " << InstIdx << ");\n" 805 << " return FeatureBitsets[RequiredFeaturesRefs[Opcode]];\n" 806 << "}\n\n"; 807 808 OS << "} // end namespace llvm::" << Target.getName() << "_MC\n" 809 << "#endif // GET_COMPUTE_FEATURES\n\n"; 810 811 OS << "#ifdef GET_AVAILABLE_OPCODE_CHECKER\n" 812 << "#undef GET_AVAILABLE_OPCODE_CHECKER\n" 813 << "namespace llvm::" << Target.getName() << "_MC {\n"; 814 OS << "bool isOpcodeAvailable(" 815 << "unsigned Opcode, const FeatureBitset &Features) {\n" 816 << " FeatureBitset AvailableFeatures = " 817 << "computeAvailableFeatures(Features);\n" 818 << " FeatureBitset RequiredFeatures = " 819 << "computeRequiredFeatures(Opcode);\n" 820 << " FeatureBitset MissingFeatures =\n" 821 << " (AvailableFeatures & RequiredFeatures) ^\n" 822 << " RequiredFeatures;\n" 823 << " return !MissingFeatures.any();\n" 824 << "}\n"; 825 OS << "} // end namespace llvm::" << Target.getName() << "_MC\n" 826 << "#endif // GET_AVAILABLE_OPCODE_CHECKER\n\n"; 827 828 OS << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n" 829 << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n" 830 << "#include <sstream>\n\n"; 831 832 OS << "namespace llvm::" << Target.getName() << "_MC {\n"; 833 834 // Emit the name table for error messages. 835 OS << "#ifndef NDEBUG\n"; 836 SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, OS); 837 OS << "#endif // NDEBUG\n\n"; 838 839 // Emit the predicate verifier. 840 OS << "void verifyInstructionPredicates(\n" 841 << " unsigned Opcode, const FeatureBitset &Features) {\n" 842 << "#ifndef NDEBUG\n"; 843 OS << " FeatureBitset AvailableFeatures = " 844 "computeAvailableFeatures(Features);\n"; 845 OS << " FeatureBitset RequiredFeatures = " 846 << "computeRequiredFeatures(Opcode);\n"; 847 OS << " FeatureBitset MissingFeatures =\n" 848 << " (AvailableFeatures & RequiredFeatures) ^\n" 849 << " RequiredFeatures;\n" 850 << " if (MissingFeatures.any()) {\n" 851 << " std::ostringstream Msg;\n" 852 << " Msg << \"Attempting to emit \" << &" << Target.getName() 853 << "InstrNameData[" << Target.getName() << "InstrNameIndices[Opcode]]\n" 854 << " << \" instruction but the \";\n" 855 << " for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)\n" 856 << " if (MissingFeatures.test(i))\n" 857 << " Msg << SubtargetFeatureNames[i] << \" \";\n" 858 << " Msg << \"predicate(s) are not met\";\n" 859 << " report_fatal_error(Msg.str().c_str());\n" 860 << " }\n" 861 << "#endif // NDEBUG\n"; 862 OS << "}\n"; 863 OS << "} // end namespace llvm::" << Target.getName() << "_MC\n"; 864 OS << "#endif // ENABLE_INSTR_PREDICATE_VERIFIER\n\n"; 865 } 866 867 void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS, 868 StringRef TargetName, 869 bool ExpandDefinition) { 870 ArrayRef<const Record *> TIIPredicates = 871 Records.getAllDerivedDefinitions("TIIPredicate"); 872 if (TIIPredicates.empty()) 873 return; 874 875 PredicateExpander PE(TargetName); 876 PE.setExpandForMC(false); 877 878 for (const Record *Rec : TIIPredicates) { 879 OS << (ExpandDefinition ? "" : "static ") << "bool "; 880 if (ExpandDefinition) 881 OS << TargetName << "InstrInfo::"; 882 OS << Rec->getValueAsString("FunctionName"); 883 OS << "(const MachineInstr &MI)"; 884 if (!ExpandDefinition) { 885 OS << ";\n"; 886 continue; 887 } 888 889 OS << " {\n"; 890 OS << PE.getIndent(); 891 PE.expandStatement(OS, Rec->getValueAsDef("Body")); 892 OS << "\n}\n\n"; 893 } 894 } 895 896 //===----------------------------------------------------------------------===// 897 // Main Output. 898 //===----------------------------------------------------------------------===// 899 900 // run - Emit the main instruction description records for the target... 901 void InstrInfoEmitter::run(raw_ostream &OS) { 902 emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS); 903 emitEnums(OS); 904 905 const CodeGenTarget &Target = CDP.getTargetInfo(); 906 const std::string &TargetName = std::string(Target.getName()); 907 const Record *InstrInfo = Target.getInstructionSet(); 908 909 // Collect all of the operand info records. 910 TGTimer &Timer = Records.getTimer(); 911 Timer.startTimer("Collect operand info"); 912 OperandInfoListTy OperandInfoList; 913 OperandInfoMapTy OperandInfoMap; 914 unsigned OperandInfoSize = 915 CollectOperandInfo(OperandInfoList, OperandInfoMap); 916 917 // Collect all of the instruction's implicit uses and defs. 918 Timer.startTimer("Collect uses/defs"); 919 std::map<std::vector<const Record *>, unsigned> EmittedLists; 920 std::vector<std::vector<const Record *>> ImplicitLists; 921 unsigned ImplicitListSize = 0; 922 for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) { 923 std::vector<const Record *> ImplicitOps = II->ImplicitUses; 924 llvm::append_range(ImplicitOps, II->ImplicitDefs); 925 if (EmittedLists.insert({ImplicitOps, ImplicitListSize}).second) { 926 ImplicitLists.push_back(ImplicitOps); 927 ImplicitListSize += ImplicitOps.size(); 928 } 929 } 930 931 ArrayRef<const CodeGenInstruction *> NumberedInstructions = 932 Target.getInstructionsByEnumValue(); 933 OS << "#if defined(GET_INSTRINFO_MC_DESC) || " 934 "defined(GET_INSTRINFO_CTOR_DTOR)\n"; 935 OS << "namespace llvm {\n\n"; 936 937 OS << "struct " << TargetName << "InstrTable {\n"; 938 OS << " MCInstrDesc Insts[" << NumberedInstructions.size() << "];\n"; 939 OS << " static_assert(alignof(MCInstrDesc) >= alignof(MCOperandInfo), " 940 "\"Unwanted padding between Insts and OperandInfo\");\n"; 941 OS << " MCOperandInfo OperandInfo[" << OperandInfoSize << "];\n"; 942 OS << " static_assert(alignof(MCOperandInfo) >= alignof(MCPhysReg), " 943 "\"Unwanted padding between OperandInfo and ImplicitOps\");\n"; 944 OS << " MCPhysReg ImplicitOps[" << std::max(ImplicitListSize, 1U) << "];\n"; 945 OS << "};\n\n"; 946 947 OS << "} // end namespace llvm\n"; 948 OS << "#endif // defined(GET_INSTRINFO_MC_DESC) || " 949 "defined(GET_INSTRINFO_CTOR_DTOR)\n\n"; 950 951 OS << "#ifdef GET_INSTRINFO_MC_DESC\n"; 952 OS << "#undef GET_INSTRINFO_MC_DESC\n"; 953 OS << "namespace llvm {\n\n"; 954 955 // Emit all of the MCInstrDesc records in reverse ENUM ordering. 956 Timer.startTimer("Emit InstrDesc records"); 957 OS << "static_assert(sizeof(MCOperandInfo) % sizeof(MCPhysReg) == 0);\n"; 958 OS << "static constexpr unsigned " << TargetName << "ImpOpBase = sizeof " 959 << TargetName << "InstrTable::OperandInfo / (sizeof(MCPhysReg));\n\n"; 960 961 OS << "extern const " << TargetName << "InstrTable " << TargetName 962 << "Descs = {\n {\n"; 963 SequenceToOffsetTable<std::string> InstrNames; 964 unsigned Num = NumberedInstructions.size(); 965 for (const CodeGenInstruction *Inst : reverse(NumberedInstructions)) { 966 // Keep a list of the instruction names. 967 InstrNames.add(std::string(Inst->TheDef->getName())); 968 // Emit the record into the table. 969 emitRecord(*Inst, --Num, InstrInfo, EmittedLists, OperandInfoMap, OS); 970 } 971 972 OS << " }, {\n"; 973 974 // Emit all of the operand info records. 975 Timer.startTimer("Emit operand info"); 976 EmitOperandInfo(OS, OperandInfoList); 977 978 OS << " }, {\n"; 979 980 // Emit all of the instruction's implicit uses and defs. 981 Timer.startTimer("Emit uses/defs"); 982 for (auto &List : ImplicitLists) { 983 OS << " /* " << EmittedLists[List] << " */"; 984 for (auto &Reg : List) 985 OS << ' ' << getQualifiedName(Reg) << ','; 986 OS << '\n'; 987 } 988 989 OS << " }\n};\n\n"; 990 991 // Emit the array of instruction names. 992 Timer.startTimer("Emit instruction names"); 993 InstrNames.layout(); 994 InstrNames.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName + 995 "InstrNameData[]"); 996 997 OS << "extern const unsigned " << TargetName << "InstrNameIndices[] = {"; 998 Num = 0; 999 for (const CodeGenInstruction *Inst : NumberedInstructions) { 1000 // Newline every eight entries. 1001 if (Num % 8 == 0) 1002 OS << "\n "; 1003 OS << InstrNames.get(std::string(Inst->TheDef->getName())) << "U, "; 1004 ++Num; 1005 } 1006 OS << "\n};\n\n"; 1007 1008 bool HasDeprecationFeatures = 1009 llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) { 1010 return !Inst->HasComplexDeprecationPredicate && 1011 !Inst->DeprecatedReason.empty(); 1012 }); 1013 if (HasDeprecationFeatures) { 1014 OS << "extern const uint8_t " << TargetName 1015 << "InstrDeprecationFeatures[] = {"; 1016 Num = 0; 1017 for (const CodeGenInstruction *Inst : NumberedInstructions) { 1018 if (Num % 8 == 0) 1019 OS << "\n "; 1020 if (!Inst->HasComplexDeprecationPredicate && 1021 !Inst->DeprecatedReason.empty()) 1022 OS << Target.getInstNamespace() << "::" << Inst->DeprecatedReason 1023 << ", "; 1024 else 1025 OS << "uint8_t(-1), "; 1026 ++Num; 1027 } 1028 OS << "\n};\n\n"; 1029 } 1030 1031 bool HasComplexDeprecationInfos = 1032 llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) { 1033 return Inst->HasComplexDeprecationPredicate; 1034 }); 1035 if (HasComplexDeprecationInfos) { 1036 OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName 1037 << "InstrComplexDeprecationInfos[] = {"; 1038 Num = 0; 1039 for (const CodeGenInstruction *Inst : NumberedInstructions) { 1040 if (Num % 8 == 0) 1041 OS << "\n "; 1042 if (Inst->HasComplexDeprecationPredicate) 1043 // Emit a function pointer to the complex predicate method. 1044 OS << "&get" << Inst->DeprecatedReason << "DeprecationInfo, "; 1045 else 1046 OS << "nullptr, "; 1047 ++Num; 1048 } 1049 OS << "\n};\n\n"; 1050 } 1051 1052 // MCInstrInfo initialization routine. 1053 Timer.startTimer("Emit initialization routine"); 1054 OS << "static inline void Init" << TargetName 1055 << "MCInstrInfo(MCInstrInfo *II) {\n"; 1056 OS << " II->InitMCInstrInfo(" << TargetName << "Descs.Insts, " << TargetName 1057 << "InstrNameIndices, " << TargetName << "InstrNameData, "; 1058 if (HasDeprecationFeatures) 1059 OS << TargetName << "InstrDeprecationFeatures, "; 1060 else 1061 OS << "nullptr, "; 1062 if (HasComplexDeprecationInfos) 1063 OS << TargetName << "InstrComplexDeprecationInfos, "; 1064 else 1065 OS << "nullptr, "; 1066 OS << NumberedInstructions.size() << ");\n}\n\n"; 1067 1068 OS << "} // end namespace llvm\n"; 1069 1070 OS << "#endif // GET_INSTRINFO_MC_DESC\n\n"; 1071 1072 // Create a TargetInstrInfo subclass to hide the MC layer initialization. 1073 OS << "#ifdef GET_INSTRINFO_HEADER\n"; 1074 OS << "#undef GET_INSTRINFO_HEADER\n"; 1075 1076 std::string ClassName = TargetName + "GenInstrInfo"; 1077 OS << "namespace llvm {\n"; 1078 OS << "struct " << ClassName << " : public TargetInstrInfo {\n" 1079 << " explicit " << ClassName 1080 << "(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u, " 1081 "unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u);\n" 1082 << " ~" << ClassName << "() override = default;\n"; 1083 1084 OS << "\n};\n} // end namespace llvm\n"; 1085 1086 OS << "#endif // GET_INSTRINFO_HEADER\n\n"; 1087 1088 OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n"; 1089 OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n"; 1090 emitTIIHelperMethods(OS, TargetName, /* ExpandDefinition = */ false); 1091 OS << "\n"; 1092 OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n"; 1093 1094 OS << "#ifdef GET_INSTRINFO_HELPERS\n"; 1095 OS << "#undef GET_INSTRINFO_HELPERS\n\n"; 1096 emitTIIHelperMethods(OS, TargetName, /* ExpandDefinition = */ true); 1097 OS << "#endif // GET_INSTRINFO_HELPERS\n\n"; 1098 1099 OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n"; 1100 OS << "#undef GET_INSTRINFO_CTOR_DTOR\n"; 1101 1102 OS << "namespace llvm {\n"; 1103 OS << "extern const " << TargetName << "InstrTable " << TargetName 1104 << "Descs;\n"; 1105 OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n"; 1106 OS << "extern const char " << TargetName << "InstrNameData[];\n"; 1107 if (HasDeprecationFeatures) 1108 OS << "extern const uint8_t " << TargetName 1109 << "InstrDeprecationFeatures[];\n"; 1110 if (HasComplexDeprecationInfos) 1111 OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName 1112 << "InstrComplexDeprecationInfos[];\n"; 1113 OS << ClassName << "::" << ClassName 1114 << "(unsigned CFSetupOpcode, unsigned CFDestroyOpcode, unsigned " 1115 "CatchRetOpcode, unsigned ReturnOpcode)\n" 1116 << " : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, " 1117 "ReturnOpcode) {\n" 1118 << " InitMCInstrInfo(" << TargetName << "Descs.Insts, " << TargetName 1119 << "InstrNameIndices, " << TargetName << "InstrNameData, "; 1120 if (HasDeprecationFeatures) 1121 OS << TargetName << "InstrDeprecationFeatures, "; 1122 else 1123 OS << "nullptr, "; 1124 if (HasComplexDeprecationInfos) 1125 OS << TargetName << "InstrComplexDeprecationInfos, "; 1126 else 1127 OS << "nullptr, "; 1128 OS << NumberedInstructions.size() << ");\n}\n"; 1129 OS << "} // end namespace llvm\n"; 1130 1131 OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n"; 1132 1133 Timer.startTimer("Emit operand name mappings"); 1134 emitOperandNameMappings(OS, Target, NumberedInstructions); 1135 1136 Timer.startTimer("Emit operand type mappings"); 1137 emitOperandTypeMappings(OS, Target, NumberedInstructions); 1138 1139 Timer.startTimer("Emit logical operand size mappings"); 1140 emitLogicalOperandSizeMappings(OS, TargetName, NumberedInstructions); 1141 1142 Timer.startTimer("Emit logical operand type mappings"); 1143 emitLogicalOperandTypeMappings(OS, TargetName, NumberedInstructions); 1144 1145 Timer.startTimer("Emit helper methods"); 1146 emitMCIIHelperMethods(OS, TargetName); 1147 1148 Timer.startTimer("Emit verifier methods"); 1149 emitFeatureVerifier(OS, Target); 1150 } 1151 1152 void InstrInfoEmitter::emitRecord( 1153 const CodeGenInstruction &Inst, unsigned Num, const Record *InstrInfo, 1154 std::map<std::vector<const Record *>, unsigned> &EmittedLists, 1155 const OperandInfoMapTy &OperandInfoMap, raw_ostream &OS) { 1156 int MinOperands = 0; 1157 if (!Inst.Operands.empty()) 1158 // Each logical operand can be multiple MI operands. 1159 MinOperands = 1160 Inst.Operands.back().MIOperandNo + Inst.Operands.back().MINumOperands; 1161 // Even the logical output operand may be multiple MI operands. 1162 int DefOperands = 0; 1163 if (Inst.Operands.NumDefs) { 1164 auto &Opnd = Inst.Operands[Inst.Operands.NumDefs - 1]; 1165 DefOperands = Opnd.MIOperandNo + Opnd.MINumOperands; 1166 } 1167 1168 OS << " { "; 1169 OS << Num << ",\t" << MinOperands << ",\t" << DefOperands << ",\t" 1170 << Inst.TheDef->getValueAsInt("Size") << ",\t" 1171 << SchedModels.getSchedClassIdx(Inst) << ",\t"; 1172 1173 const CodeGenTarget &Target = CDP.getTargetInfo(); 1174 1175 // Emit the implicit use/def list... 1176 OS << Inst.ImplicitUses.size() << ",\t" << Inst.ImplicitDefs.size() << ",\t"; 1177 std::vector<const Record *> ImplicitOps = Inst.ImplicitUses; 1178 llvm::append_range(ImplicitOps, Inst.ImplicitDefs); 1179 OS << Target.getName() << "ImpOpBase + " << EmittedLists[ImplicitOps] 1180 << ",\t"; 1181 1182 // Emit the operand info offset. 1183 OperandInfoTy OperandInfo = GetOperandInfo(Inst); 1184 OS << OperandInfoMap.find(OperandInfo)->second << ",\t0"; 1185 1186 // Emit all of the target independent flags... 1187 if (Inst.isPreISelOpcode) 1188 OS << "|(1ULL<<MCID::PreISelOpcode)"; 1189 if (Inst.isPseudo) 1190 OS << "|(1ULL<<MCID::Pseudo)"; 1191 if (Inst.isMeta) 1192 OS << "|(1ULL<<MCID::Meta)"; 1193 if (Inst.isReturn) 1194 OS << "|(1ULL<<MCID::Return)"; 1195 if (Inst.isEHScopeReturn) 1196 OS << "|(1ULL<<MCID::EHScopeReturn)"; 1197 if (Inst.isBranch) 1198 OS << "|(1ULL<<MCID::Branch)"; 1199 if (Inst.isIndirectBranch) 1200 OS << "|(1ULL<<MCID::IndirectBranch)"; 1201 if (Inst.isCompare) 1202 OS << "|(1ULL<<MCID::Compare)"; 1203 if (Inst.isMoveImm) 1204 OS << "|(1ULL<<MCID::MoveImm)"; 1205 if (Inst.isMoveReg) 1206 OS << "|(1ULL<<MCID::MoveReg)"; 1207 if (Inst.isBitcast) 1208 OS << "|(1ULL<<MCID::Bitcast)"; 1209 if (Inst.isAdd) 1210 OS << "|(1ULL<<MCID::Add)"; 1211 if (Inst.isTrap) 1212 OS << "|(1ULL<<MCID::Trap)"; 1213 if (Inst.isSelect) 1214 OS << "|(1ULL<<MCID::Select)"; 1215 if (Inst.isBarrier) 1216 OS << "|(1ULL<<MCID::Barrier)"; 1217 if (Inst.hasDelaySlot) 1218 OS << "|(1ULL<<MCID::DelaySlot)"; 1219 if (Inst.isCall) 1220 OS << "|(1ULL<<MCID::Call)"; 1221 if (Inst.canFoldAsLoad) 1222 OS << "|(1ULL<<MCID::FoldableAsLoad)"; 1223 if (Inst.mayLoad) 1224 OS << "|(1ULL<<MCID::MayLoad)"; 1225 if (Inst.mayStore) 1226 OS << "|(1ULL<<MCID::MayStore)"; 1227 if (Inst.mayRaiseFPException) 1228 OS << "|(1ULL<<MCID::MayRaiseFPException)"; 1229 if (Inst.isPredicable) 1230 OS << "|(1ULL<<MCID::Predicable)"; 1231 if (Inst.isConvertibleToThreeAddress) 1232 OS << "|(1ULL<<MCID::ConvertibleTo3Addr)"; 1233 if (Inst.isCommutable) 1234 OS << "|(1ULL<<MCID::Commutable)"; 1235 if (Inst.isTerminator) 1236 OS << "|(1ULL<<MCID::Terminator)"; 1237 if (Inst.isReMaterializable) 1238 OS << "|(1ULL<<MCID::Rematerializable)"; 1239 if (Inst.isNotDuplicable) 1240 OS << "|(1ULL<<MCID::NotDuplicable)"; 1241 if (Inst.Operands.hasOptionalDef) 1242 OS << "|(1ULL<<MCID::HasOptionalDef)"; 1243 if (Inst.usesCustomInserter) 1244 OS << "|(1ULL<<MCID::UsesCustomInserter)"; 1245 if (Inst.hasPostISelHook) 1246 OS << "|(1ULL<<MCID::HasPostISelHook)"; 1247 if (Inst.Operands.isVariadic) 1248 OS << "|(1ULL<<MCID::Variadic)"; 1249 if (Inst.hasSideEffects) 1250 OS << "|(1ULL<<MCID::UnmodeledSideEffects)"; 1251 if (Inst.isAsCheapAsAMove) 1252 OS << "|(1ULL<<MCID::CheapAsAMove)"; 1253 if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq) 1254 OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)"; 1255 if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq) 1256 OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)"; 1257 if (Inst.isRegSequence) 1258 OS << "|(1ULL<<MCID::RegSequence)"; 1259 if (Inst.isExtractSubreg) 1260 OS << "|(1ULL<<MCID::ExtractSubreg)"; 1261 if (Inst.isInsertSubreg) 1262 OS << "|(1ULL<<MCID::InsertSubreg)"; 1263 if (Inst.isConvergent) 1264 OS << "|(1ULL<<MCID::Convergent)"; 1265 if (Inst.variadicOpsAreDefs) 1266 OS << "|(1ULL<<MCID::VariadicOpsAreDefs)"; 1267 if (Inst.isAuthenticated) 1268 OS << "|(1ULL<<MCID::Authenticated)"; 1269 1270 // Emit all of the target-specific flags... 1271 const BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags"); 1272 if (!TSF) 1273 PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?"); 1274 uint64_t Value = 0; 1275 for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) { 1276 if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i))) 1277 Value |= uint64_t(Bit->getValue()) << i; 1278 else 1279 PrintFatalError(Inst.TheDef->getLoc(), 1280 "Invalid TSFlags bit in " + Inst.TheDef->getName()); 1281 } 1282 OS << ", 0x"; 1283 OS.write_hex(Value); 1284 OS << "ULL"; 1285 1286 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n"; 1287 } 1288 1289 // emitEnums - Print out enum values for all of the instructions. 1290 void InstrInfoEmitter::emitEnums(raw_ostream &OS) { 1291 OS << "#ifdef GET_INSTRINFO_ENUM\n"; 1292 OS << "#undef GET_INSTRINFO_ENUM\n"; 1293 1294 const CodeGenTarget &Target = CDP.getTargetInfo(); 1295 StringRef Namespace = Target.getInstNamespace(); 1296 1297 if (Namespace.empty()) 1298 PrintFatalError("No instructions defined!"); 1299 1300 OS << "namespace llvm::" << Namespace << " {\n"; 1301 1302 OS << " enum {\n"; 1303 unsigned Num = 0; 1304 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) 1305 OS << " " << Inst->TheDef->getName() 1306 << "\t= " << (Num = Target.getInstrIntValue(Inst->TheDef)) << ",\n"; 1307 OS << " INSTRUCTION_LIST_END = " << Num + 1 << "\n"; 1308 OS << " };\n\n"; 1309 OS << "} // end namespace llvm::" << Namespace << "\n"; 1310 OS << "#endif // GET_INSTRINFO_ENUM\n\n"; 1311 1312 OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n"; 1313 OS << "#undef GET_INSTRINFO_SCHED_ENUM\n"; 1314 OS << "namespace llvm::" << Namespace << "::Sched {\n\n"; 1315 OS << " enum {\n"; 1316 Num = 0; 1317 for (const auto &Class : SchedModels.explicit_classes()) 1318 OS << " " << Class.Name << "\t= " << Num++ << ",\n"; 1319 OS << " SCHED_LIST_END = " << Num << "\n"; 1320 OS << " };\n"; 1321 OS << "} // end namespace llvm::" << Namespace << "::Sched\n"; 1322 1323 OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n"; 1324 } 1325 1326 static void EmitInstrInfo(const RecordKeeper &Records, raw_ostream &OS) { 1327 TGTimer &Timer = Records.getTimer(); 1328 Timer.startTimer("Analyze DAG patterns"); 1329 InstrInfoEmitter(Records).run(OS); 1330 Timer.startTimer("Emit map table"); 1331 EmitMapTable(Records, OS); 1332 } 1333 1334 static TableGen::Emitter::Opt X("gen-instr-info", EmitInstrInfo, 1335 "Generate instruction descriptions"); 1336