1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===// 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 emits an assembly printer for the current target. 10 // Note that this is currently fairly skeletal, but will grow over time. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AsmWriterInst.h" 15 #include "CodeGenInstruction.h" 16 #include "CodeGenRegisters.h" 17 #include "CodeGenTarget.h" 18 #include "SequenceToOffsetTable.h" 19 #include "Types.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Twine.h" 28 #include "llvm/Support/Casting.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/Format.h" 32 #include "llvm/Support/FormatVariadic.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/TableGen/Error.h" 36 #include "llvm/TableGen/Record.h" 37 #include "llvm/TableGen/TableGenBackend.h" 38 #include <algorithm> 39 #include <cassert> 40 #include <cstddef> 41 #include <cstdint> 42 #include <deque> 43 #include <iterator> 44 #include <map> 45 #include <set> 46 #include <string> 47 #include <tuple> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "asm-writer-emitter" 54 55 namespace { 56 57 class AsmWriterEmitter { 58 RecordKeeper &Records; 59 CodeGenTarget Target; 60 ArrayRef<const CodeGenInstruction *> NumberedInstructions; 61 std::vector<AsmWriterInst> Instructions; 62 63 public: 64 AsmWriterEmitter(RecordKeeper &R); 65 66 void run(raw_ostream &o); 67 68 private: 69 void EmitPrintInstruction(raw_ostream &o); 70 void EmitGetRegisterName(raw_ostream &o); 71 void EmitPrintAliasInstruction(raw_ostream &O); 72 73 void FindUniqueOperandCommands(std::vector<std::string> &UOC, 74 std::vector<std::vector<unsigned>> &InstIdxs, 75 std::vector<unsigned> &InstOpsUsed, 76 bool PassSubtarget) const; 77 }; 78 79 } // end anonymous namespace 80 81 static void PrintCases(std::vector<std::pair<std::string, 82 AsmWriterOperand>> &OpsToPrint, raw_ostream &O, 83 bool PassSubtarget) { 84 O << " case " << OpsToPrint.back().first << ":"; 85 AsmWriterOperand TheOp = OpsToPrint.back().second; 86 OpsToPrint.pop_back(); 87 88 // Check to see if any other operands are identical in this list, and if so, 89 // emit a case label for them. 90 for (unsigned i = OpsToPrint.size(); i != 0; --i) 91 if (OpsToPrint[i-1].second == TheOp) { 92 O << "\n case " << OpsToPrint[i-1].first << ":"; 93 OpsToPrint.erase(OpsToPrint.begin()+i-1); 94 } 95 96 // Finally, emit the code. 97 O << "\n " << TheOp.getCode(PassSubtarget); 98 O << "\n break;\n"; 99 } 100 101 /// EmitInstructions - Emit the last instruction in the vector and any other 102 /// instructions that are suitably similar to it. 103 static void EmitInstructions(std::vector<AsmWriterInst> &Insts, 104 raw_ostream &O, bool PassSubtarget) { 105 AsmWriterInst FirstInst = Insts.back(); 106 Insts.pop_back(); 107 108 std::vector<AsmWriterInst> SimilarInsts; 109 unsigned DifferingOperand = ~0; 110 for (unsigned i = Insts.size(); i != 0; --i) { 111 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst); 112 if (DiffOp != ~1U) { 113 if (DifferingOperand == ~0U) // First match! 114 DifferingOperand = DiffOp; 115 116 // If this differs in the same operand as the rest of the instructions in 117 // this class, move it to the SimilarInsts list. 118 if (DifferingOperand == DiffOp || DiffOp == ~0U) { 119 SimilarInsts.push_back(Insts[i-1]); 120 Insts.erase(Insts.begin()+i-1); 121 } 122 } 123 } 124 125 O << " case " << FirstInst.CGI->Namespace << "::" 126 << FirstInst.CGI->TheDef->getName() << ":\n"; 127 for (const AsmWriterInst &AWI : SimilarInsts) 128 O << " case " << AWI.CGI->Namespace << "::" 129 << AWI.CGI->TheDef->getName() << ":\n"; 130 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) { 131 if (i != DifferingOperand) { 132 // If the operand is the same for all instructions, just print it. 133 O << " " << FirstInst.Operands[i].getCode(PassSubtarget); 134 } else { 135 // If this is the operand that varies between all of the instructions, 136 // emit a switch for just this operand now. 137 O << " switch (MI->getOpcode()) {\n"; 138 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; 139 std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint; 140 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" + 141 FirstInst.CGI->TheDef->getName().str(), 142 FirstInst.Operands[i])); 143 144 for (const AsmWriterInst &AWI : SimilarInsts) { 145 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" + 146 AWI.CGI->TheDef->getName().str(), 147 AWI.Operands[i])); 148 } 149 std::reverse(OpsToPrint.begin(), OpsToPrint.end()); 150 while (!OpsToPrint.empty()) 151 PrintCases(OpsToPrint, O, PassSubtarget); 152 O << " }"; 153 } 154 O << "\n"; 155 } 156 O << " break;\n"; 157 } 158 159 void AsmWriterEmitter:: 160 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, 161 std::vector<std::vector<unsigned>> &InstIdxs, 162 std::vector<unsigned> &InstOpsUsed, 163 bool PassSubtarget) const { 164 // This vector parallels UniqueOperandCommands, keeping track of which 165 // instructions each case are used for. It is a comma separated string of 166 // enums. 167 std::vector<std::string> InstrsForCase; 168 InstrsForCase.resize(UniqueOperandCommands.size()); 169 InstOpsUsed.assign(UniqueOperandCommands.size(), 0); 170 171 for (size_t i = 0, e = Instructions.size(); i != e; ++i) { 172 const AsmWriterInst &Inst = Instructions[i]; 173 if (Inst.Operands.empty()) 174 continue; // Instruction already done. 175 176 std::string Command = " "+Inst.Operands[0].getCode(PassSubtarget)+"\n"; 177 178 // Check to see if we already have 'Command' in UniqueOperandCommands. 179 // If not, add it. 180 auto I = llvm::find(UniqueOperandCommands, Command); 181 if (I != UniqueOperandCommands.end()) { 182 size_t idx = I - UniqueOperandCommands.begin(); 183 InstrsForCase[idx] += ", "; 184 InstrsForCase[idx] += Inst.CGI->TheDef->getName(); 185 InstIdxs[idx].push_back(i); 186 } else { 187 UniqueOperandCommands.push_back(std::move(Command)); 188 InstrsForCase.push_back(Inst.CGI->TheDef->getName()); 189 InstIdxs.emplace_back(); 190 InstIdxs.back().push_back(i); 191 192 // This command matches one operand so far. 193 InstOpsUsed.push_back(1); 194 } 195 } 196 197 // For each entry of UniqueOperandCommands, there is a set of instructions 198 // that uses it. If the next command of all instructions in the set are 199 // identical, fold it into the command. 200 for (size_t CommandIdx = 0, e = UniqueOperandCommands.size(); 201 CommandIdx != e; ++CommandIdx) { 202 203 const auto &Idxs = InstIdxs[CommandIdx]; 204 205 for (unsigned Op = 1; ; ++Op) { 206 // Find the first instruction in the set. 207 const AsmWriterInst &FirstInst = Instructions[Idxs.front()]; 208 // If this instruction has no more operands, we isn't anything to merge 209 // into this command. 210 if (FirstInst.Operands.size() == Op) 211 break; 212 213 // Otherwise, scan to see if all of the other instructions in this command 214 // set share the operand. 215 if (std::any_of(Idxs.begin()+1, Idxs.end(), 216 [&](unsigned Idx) { 217 const AsmWriterInst &OtherInst = Instructions[Idx]; 218 return OtherInst.Operands.size() == Op || 219 OtherInst.Operands[Op] != FirstInst.Operands[Op]; 220 })) 221 break; 222 223 // Okay, everything in this command set has the same next operand. Add it 224 // to UniqueOperandCommands and remember that it was consumed. 225 std::string Command = " " + 226 FirstInst.Operands[Op].getCode(PassSubtarget) + "\n"; 227 228 UniqueOperandCommands[CommandIdx] += Command; 229 InstOpsUsed[CommandIdx]++; 230 } 231 } 232 233 // Prepend some of the instructions each case is used for onto the case val. 234 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) { 235 std::string Instrs = InstrsForCase[i]; 236 if (Instrs.size() > 70) { 237 Instrs.erase(Instrs.begin()+70, Instrs.end()); 238 Instrs += "..."; 239 } 240 241 if (!Instrs.empty()) 242 UniqueOperandCommands[i] = " // " + Instrs + "\n" + 243 UniqueOperandCommands[i]; 244 } 245 } 246 247 static void UnescapeString(std::string &Str) { 248 for (unsigned i = 0; i != Str.size(); ++i) { 249 if (Str[i] == '\\' && i != Str.size()-1) { 250 switch (Str[i+1]) { 251 default: continue; // Don't execute the code after the switch. 252 case 'a': Str[i] = '\a'; break; 253 case 'b': Str[i] = '\b'; break; 254 case 'e': Str[i] = 27; break; 255 case 'f': Str[i] = '\f'; break; 256 case 'n': Str[i] = '\n'; break; 257 case 'r': Str[i] = '\r'; break; 258 case 't': Str[i] = '\t'; break; 259 case 'v': Str[i] = '\v'; break; 260 case '"': Str[i] = '\"'; break; 261 case '\'': Str[i] = '\''; break; 262 case '\\': Str[i] = '\\'; break; 263 } 264 // Nuke the second character. 265 Str.erase(Str.begin()+i+1); 266 } 267 } 268 } 269 270 /// EmitPrintInstruction - Generate the code for the "printInstruction" method 271 /// implementation. Destroys all instances of AsmWriterInst information, by 272 /// clearing the Instructions vector. 273 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { 274 Record *AsmWriter = Target.getAsmWriter(); 275 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 276 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 277 278 O << 279 "/// printInstruction - This method is automatically generated by tablegen\n" 280 "/// from the instruction set description.\n" 281 "void " << Target.getName() << ClassName 282 << "::printInstruction(const MCInst *MI, " 283 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 284 << "raw_ostream &O) {\n"; 285 286 // Build an aggregate string, and build a table of offsets into it. 287 SequenceToOffsetTable<std::string> StringTable; 288 289 /// OpcodeInfo - This encodes the index of the string to use for the first 290 /// chunk of the output as well as indices used for operand printing. 291 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size()); 292 const unsigned OpcodeInfoBits = 64; 293 294 // Add all strings to the string table upfront so it can generate an optimized 295 // representation. 296 for (AsmWriterInst &AWI : Instructions) { 297 if (AWI.Operands[0].OperandType == 298 AsmWriterOperand::isLiteralTextOperand && 299 !AWI.Operands[0].Str.empty()) { 300 std::string Str = AWI.Operands[0].Str; 301 UnescapeString(Str); 302 StringTable.add(Str); 303 } 304 } 305 306 StringTable.layout(); 307 308 unsigned MaxStringIdx = 0; 309 for (AsmWriterInst &AWI : Instructions) { 310 unsigned Idx; 311 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand || 312 AWI.Operands[0].Str.empty()) { 313 // Something handled by the asmwriter printer, but with no leading string. 314 Idx = StringTable.get(""); 315 } else { 316 std::string Str = AWI.Operands[0].Str; 317 UnescapeString(Str); 318 Idx = StringTable.get(Str); 319 MaxStringIdx = std::max(MaxStringIdx, Idx); 320 321 // Nuke the string from the operand list. It is now handled! 322 AWI.Operands.erase(AWI.Operands.begin()); 323 } 324 325 // Bias offset by one since we want 0 as a sentinel. 326 OpcodeInfo[AWI.CGIIndex] = Idx+1; 327 } 328 329 // Figure out how many bits we used for the string index. 330 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2); 331 332 // To reduce code size, we compactify common instructions into a few bits 333 // in the opcode-indexed table. 334 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits; 335 336 std::vector<std::vector<std::string>> TableDrivenOperandPrinters; 337 338 while (true) { 339 std::vector<std::string> UniqueOperandCommands; 340 std::vector<std::vector<unsigned>> InstIdxs; 341 std::vector<unsigned> NumInstOpsHandled; 342 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs, 343 NumInstOpsHandled, PassSubtarget); 344 345 // If we ran out of operands to print, we're done. 346 if (UniqueOperandCommands.empty()) break; 347 348 // Compute the number of bits we need to represent these cases, this is 349 // ceil(log2(numentries)). 350 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size()); 351 352 // If we don't have enough bits for this operand, don't include it. 353 if (NumBits > BitsLeft) { 354 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits 355 << " more bits\n"); 356 break; 357 } 358 359 // Otherwise, we can include this in the initial lookup table. Add it in. 360 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) { 361 unsigned NumOps = NumInstOpsHandled[i]; 362 for (unsigned Idx : InstIdxs[i]) { 363 OpcodeInfo[Instructions[Idx].CGIIndex] |= 364 (uint64_t)i << (OpcodeInfoBits-BitsLeft); 365 // Remove the info about this operand from the instruction. 366 AsmWriterInst &Inst = Instructions[Idx]; 367 if (!Inst.Operands.empty()) { 368 assert(NumOps <= Inst.Operands.size() && 369 "Can't remove this many ops!"); 370 Inst.Operands.erase(Inst.Operands.begin(), 371 Inst.Operands.begin()+NumOps); 372 } 373 } 374 } 375 BitsLeft -= NumBits; 376 377 // Remember the handlers for this set of operands. 378 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands)); 379 } 380 381 // Emit the string table itself. 382 O << " static const char AsmStrs[] = {\n"; 383 StringTable.emit(O, printChar); 384 O << " };\n\n"; 385 386 // Emit the lookup tables in pieces to minimize wasted bytes. 387 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8; 388 unsigned Table = 0, Shift = 0; 389 SmallString<128> BitsString; 390 raw_svector_ostream BitsOS(BitsString); 391 // If the total bits is more than 32-bits we need to use a 64-bit type. 392 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32) 393 << "_t Bits = 0;\n"; 394 while (BytesNeeded != 0) { 395 // Figure out how big this table section needs to be, but no bigger than 4. 396 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4); 397 BytesNeeded -= TableSize; 398 TableSize *= 8; // Convert to bits; 399 uint64_t Mask = (1ULL << TableSize) - 1; 400 O << " static const uint" << TableSize << "_t OpInfo" << Table 401 << "[] = {\n"; 402 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 403 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// " 404 << NumberedInstructions[i]->TheDef->getName() << "\n"; 405 } 406 O << " };\n\n"; 407 // Emit string to combine the individual table lookups. 408 BitsOS << " Bits |= "; 409 // If the total bits is more than 32-bits we need to use a 64-bit type. 410 if (BitsLeft < (OpcodeInfoBits - 32)) 411 BitsOS << "(uint64_t)"; 412 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n"; 413 // Prepare the shift for the next iteration and increment the table count. 414 Shift += TableSize; 415 ++Table; 416 } 417 418 // Emit the initial tab character. 419 O << " O << \"\\t\";\n\n"; 420 421 O << " // Emit the opcode for the instruction.\n"; 422 O << BitsString; 423 424 // Emit the starting string. 425 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n" 426 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n"; 427 428 // Output the table driven operand information. 429 BitsLeft = OpcodeInfoBits-AsmStrBits; 430 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) { 431 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i]; 432 433 // Compute the number of bits we need to represent these cases, this is 434 // ceil(log2(numentries)). 435 unsigned NumBits = Log2_32_Ceil(Commands.size()); 436 assert(NumBits <= BitsLeft && "consistency error"); 437 438 // Emit code to extract this field from Bits. 439 O << "\n // Fragment " << i << " encoded into " << NumBits 440 << " bits for " << Commands.size() << " unique commands.\n"; 441 442 if (Commands.size() == 2) { 443 // Emit two possibilitys with if/else. 444 O << " if ((Bits >> " 445 << (OpcodeInfoBits-BitsLeft) << ") & " 446 << ((1 << NumBits)-1) << ") {\n" 447 << Commands[1] 448 << " } else {\n" 449 << Commands[0] 450 << " }\n\n"; 451 } else if (Commands.size() == 1) { 452 // Emit a single possibility. 453 O << Commands[0] << "\n\n"; 454 } else { 455 O << " switch ((Bits >> " 456 << (OpcodeInfoBits-BitsLeft) << ") & " 457 << ((1 << NumBits)-1) << ") {\n" 458 << " default: llvm_unreachable(\"Invalid command number.\");\n"; 459 460 // Print out all the cases. 461 for (unsigned j = 0, e = Commands.size(); j != e; ++j) { 462 O << " case " << j << ":\n"; 463 O << Commands[j]; 464 O << " break;\n"; 465 } 466 O << " }\n\n"; 467 } 468 BitsLeft -= NumBits; 469 } 470 471 // Okay, delete instructions with no operand info left. 472 auto I = llvm::remove_if(Instructions, 473 [](AsmWriterInst &Inst) { return Inst.Operands.empty(); }); 474 Instructions.erase(I, Instructions.end()); 475 476 477 // Because this is a vector, we want to emit from the end. Reverse all of the 478 // elements in the vector. 479 std::reverse(Instructions.begin(), Instructions.end()); 480 481 482 // Now that we've emitted all of the operand info that fit into 64 bits, emit 483 // information for those instructions that are left. This is a less dense 484 // encoding, but we expect the main 64-bit table to handle the majority of 485 // instructions. 486 if (!Instructions.empty()) { 487 // Find the opcode # of inline asm. 488 O << " switch (MI->getOpcode()) {\n"; 489 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; 490 while (!Instructions.empty()) 491 EmitInstructions(Instructions, O, PassSubtarget); 492 493 O << " }\n"; 494 } 495 496 O << "}\n"; 497 } 498 499 static void 500 emitRegisterNameString(raw_ostream &O, StringRef AltName, 501 const std::deque<CodeGenRegister> &Registers) { 502 SequenceToOffsetTable<std::string> StringTable; 503 SmallVector<std::string, 4> AsmNames(Registers.size()); 504 unsigned i = 0; 505 for (const auto &Reg : Registers) { 506 std::string &AsmName = AsmNames[i++]; 507 508 // "NoRegAltName" is special. We don't need to do a lookup for that, 509 // as it's just a reference to the default register name. 510 if (AltName == "" || AltName == "NoRegAltName") { 511 AsmName = Reg.TheDef->getValueAsString("AsmName"); 512 if (AsmName.empty()) 513 AsmName = Reg.getName(); 514 } else { 515 // Make sure the register has an alternate name for this index. 516 std::vector<Record*> AltNameList = 517 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices"); 518 unsigned Idx = 0, e; 519 for (e = AltNameList.size(); 520 Idx < e && (AltNameList[Idx]->getName() != AltName); 521 ++Idx) 522 ; 523 // If the register has an alternate name for this index, use it. 524 // Otherwise, leave it empty as an error flag. 525 if (Idx < e) { 526 std::vector<StringRef> AltNames = 527 Reg.TheDef->getValueAsListOfStrings("AltNames"); 528 if (AltNames.size() <= Idx) 529 PrintFatalError(Reg.TheDef->getLoc(), 530 "Register definition missing alt name for '" + 531 AltName + "'."); 532 AsmName = AltNames[Idx]; 533 } 534 } 535 StringTable.add(AsmName); 536 } 537 538 StringTable.layout(); 539 O << " static const char AsmStrs" << AltName << "[] = {\n"; 540 StringTable.emit(O, printChar); 541 O << " };\n\n"; 542 543 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32) 544 << " RegAsmOffset" << AltName << "[] = {"; 545 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 546 if ((i % 14) == 0) 547 O << "\n "; 548 O << StringTable.get(AsmNames[i]) << ", "; 549 } 550 O << "\n };\n" 551 << "\n"; 552 } 553 554 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { 555 Record *AsmWriter = Target.getAsmWriter(); 556 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 557 const auto &Registers = Target.getRegBank().getRegisters(); 558 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices(); 559 bool hasAltNames = AltNameIndices.size() > 1; 560 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace"); 561 562 O << 563 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n" 564 "/// from the register set description. This returns the assembler name\n" 565 "/// for the specified register.\n" 566 "const char *" << Target.getName() << ClassName << "::"; 567 if (hasAltNames) 568 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n"; 569 else 570 O << "getRegisterName(unsigned RegNo) {\n"; 571 O << " assert(RegNo && RegNo < " << (Registers.size()+1) 572 << " && \"Invalid register number!\");\n" 573 << "\n"; 574 575 if (hasAltNames) { 576 for (const Record *R : AltNameIndices) 577 emitRegisterNameString(O, R->getName(), Registers); 578 } else 579 emitRegisterNameString(O, "", Registers); 580 581 if (hasAltNames) { 582 O << " switch(AltIdx) {\n" 583 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n"; 584 for (const Record *R : AltNameIndices) { 585 StringRef AltName = R->getName(); 586 O << " case "; 587 if (!Namespace.empty()) 588 O << Namespace << "::"; 589 O << AltName << ":\n"; 590 if (R->isValueUnset("FallbackRegAltNameIndex")) 591 O << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 592 << "[RegNo-1]) &&\n" 593 << " \"Invalid alt name index for register!\");\n"; 594 else { 595 O << " if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 596 << "[RegNo-1]))\n" 597 << " return getRegisterName(RegNo, "; 598 if (!Namespace.empty()) 599 O << Namespace << "::"; 600 O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n"; 601 } 602 O << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName 603 << "[RegNo-1];\n"; 604 } 605 O << " }\n"; 606 } else { 607 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n" 608 << " \"Invalid alt name index for register!\");\n" 609 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"; 610 } 611 O << "}\n"; 612 } 613 614 namespace { 615 616 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if 617 // they both have the same conditionals. In which case, we cannot print out the 618 // alias for that pattern. 619 class IAPrinter { 620 std::map<StringRef, std::pair<int, int>> OpMap; 621 622 std::vector<std::string> Conds; 623 624 std::string Result; 625 std::string AsmString; 626 627 unsigned NumMIOps; 628 629 public: 630 IAPrinter(std::string R, std::string AS, unsigned NumMIOps) 631 : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {} 632 633 void addCond(std::string C) { Conds.push_back(std::move(C)); } 634 ArrayRef<std::string> getConds() const { return Conds; } 635 size_t getCondCount() const { return Conds.size(); } 636 637 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) { 638 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range"); 639 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF && 640 "Idx out of range"); 641 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx); 642 } 643 644 unsigned getNumMIOps() { return NumMIOps; } 645 646 StringRef getResult() { return Result; } 647 648 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); } 649 int getOpIndex(StringRef Op) { return OpMap[Op].first; } 650 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; } 651 652 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start, 653 StringRef::iterator End) { 654 StringRef::iterator I = Start; 655 StringRef::iterator Next; 656 if (*I == '{') { 657 // ${some_name} 658 Start = ++I; 659 while (I != End && *I != '}') 660 ++I; 661 Next = I; 662 // eat the final '}' 663 if (Next != End) 664 ++Next; 665 } else { 666 // $name, just eat the usual suspects. 667 while (I != End && 668 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') || 669 (*I >= '0' && *I <= '9') || *I == '_')) 670 ++I; 671 Next = I; 672 } 673 674 return std::make_pair(StringRef(Start, I - Start), Next); 675 } 676 677 std::string formatAliasString(uint32_t &UnescapedSize) { 678 // Directly mangle mapped operands into the string. Each operand is 679 // identified by a '$' sign followed by a byte identifying the number of the 680 // operand. We add one to the index to avoid zero bytes. 681 StringRef ASM(AsmString); 682 std::string OutString; 683 raw_string_ostream OS(OutString); 684 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) { 685 OS << *I; 686 ++UnescapedSize; 687 if (*I == '$') { 688 StringRef Name; 689 std::tie(Name, I) = parseName(++I, E); 690 assert(isOpMapped(Name) && "Unmapped operand!"); 691 692 int OpIndex, PrintIndex; 693 std::tie(OpIndex, PrintIndex) = getOpData(Name); 694 if (PrintIndex == -1) { 695 // Can use the default printOperand route. 696 OS << format("\\x%02X", (unsigned char)OpIndex + 1); 697 ++UnescapedSize; 698 } else { 699 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand 700 // number, and which of our pre-detected Methods to call. 701 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1); 702 UnescapedSize += 3; 703 } 704 } else { 705 ++I; 706 } 707 } 708 709 OS.flush(); 710 return OutString; 711 } 712 713 bool operator==(const IAPrinter &RHS) const { 714 if (NumMIOps != RHS.NumMIOps) 715 return false; 716 if (Conds.size() != RHS.Conds.size()) 717 return false; 718 719 unsigned Idx = 0; 720 for (const auto &str : Conds) 721 if (str != RHS.Conds[Idx++]) 722 return false; 723 724 return true; 725 } 726 }; 727 728 } // end anonymous namespace 729 730 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) { 731 return AsmString.count(' ') + AsmString.count('\t'); 732 } 733 734 namespace { 735 736 struct AliasPriorityComparator { 737 typedef std::pair<CodeGenInstAlias, int> ValueType; 738 bool operator()(const ValueType &LHS, const ValueType &RHS) const { 739 if (LHS.second == RHS.second) { 740 // We don't actually care about the order, but for consistency it 741 // shouldn't depend on pointer comparisons. 742 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef); 743 } 744 745 // Aliases with larger priorities should be considered first. 746 return LHS.second > RHS.second; 747 } 748 }; 749 750 } // end anonymous namespace 751 752 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { 753 Record *AsmWriter = Target.getAsmWriter(); 754 755 O << "\n#ifdef PRINT_ALIAS_INSTR\n"; 756 O << "#undef PRINT_ALIAS_INSTR\n\n"; 757 758 ////////////////////////////// 759 // Gather information about aliases we need to print 760 ////////////////////////////// 761 762 // Emit the method that prints the alias instruction. 763 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 764 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 765 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 766 767 std::vector<Record*> AllInstAliases = 768 Records.getAllDerivedDefinitions("InstAlias"); 769 770 // Create a map from the qualified name to a list of potential matches. 771 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator> 772 AliasWithPriority; 773 std::map<std::string, AliasWithPriority> AliasMap; 774 for (Record *R : AllInstAliases) { 775 int Priority = R->getValueAsInt("EmitPriority"); 776 if (Priority < 1) 777 continue; // Aliases with priority 0 are never emitted. 778 779 const DagInit *DI = R->getValueAsDag("ResultInst"); 780 AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert( 781 std::make_pair(CodeGenInstAlias(R, Target), Priority)); 782 } 783 784 // A map of which conditions need to be met for each instruction operand 785 // before it can be matched to the mnemonic. 786 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap; 787 788 std::vector<std::string> PrintMethods; 789 790 // A list of MCOperandPredicates for all operands in use, and the reverse map 791 std::vector<const Record*> MCOpPredicates; 792 DenseMap<const Record*, unsigned> MCOpPredicateMap; 793 794 for (auto &Aliases : AliasMap) { 795 // Collection of instruction alias rules. May contain ambiguous rules. 796 std::vector<IAPrinter> IAPs; 797 798 for (auto &Alias : Aliases.second) { 799 const CodeGenInstAlias &CGA = Alias.first; 800 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 801 std::string FlatInstAsmString = 802 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString, 803 Variant); 804 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant); 805 806 std::string FlatAliasAsmString = 807 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant); 808 809 // Don't emit the alias if it has more operands than what it's aliasing. 810 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant)) 811 continue; 812 813 StringRef Namespace = Target.getName(); 814 unsigned NumMIOps = 0; 815 for (auto &ResultInstOpnd : CGA.ResultInst->Operands) 816 NumMIOps += ResultInstOpnd.MINumOperands; 817 818 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps); 819 820 bool CantHandle = false; 821 822 unsigned MIOpNum = 0; 823 for (unsigned i = 0, e = LastOpNo; i != e; ++i) { 824 // Skip over tied operands as they're not part of an alias declaration. 825 auto &Operands = CGA.ResultInst->Operands; 826 while (true) { 827 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first; 828 if (Operands[OpNum].MINumOperands == 1 && 829 Operands[OpNum].getTiedRegister() != -1) { 830 // Tied operands of different RegisterClass should be explicit within 831 // an instruction's syntax and so cannot be skipped. 832 int TiedOpNum = Operands[OpNum].getTiedRegister(); 833 if (Operands[OpNum].Rec->getName() == 834 Operands[TiedOpNum].Rec->getName()) { 835 ++MIOpNum; 836 continue; 837 } 838 } 839 break; 840 } 841 842 // Ignore unchecked result operands. 843 while (IAP.getCondCount() < MIOpNum) 844 IAP.addCond("AliasPatternCond::K_Ignore, 0"); 845 846 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i]; 847 848 switch (RO.Kind) { 849 case CodeGenInstAlias::ResultOperand::K_Record: { 850 const Record *Rec = RO.getRecord(); 851 StringRef ROName = RO.getName(); 852 int PrintMethodIdx = -1; 853 854 // These two may have a PrintMethod, which we want to record (if it's 855 // the first time we've seen it) and provide an index for the aliasing 856 // code to use. 857 if (Rec->isSubClassOf("RegisterOperand") || 858 Rec->isSubClassOf("Operand")) { 859 StringRef PrintMethod = Rec->getValueAsString("PrintMethod"); 860 if (PrintMethod != "" && PrintMethod != "printOperand") { 861 PrintMethodIdx = 862 llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin(); 863 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size()) 864 PrintMethods.push_back(PrintMethod); 865 } 866 } 867 868 if (Rec->isSubClassOf("RegisterOperand")) 869 Rec = Rec->getValueAsDef("RegClass"); 870 if (Rec->isSubClassOf("RegisterClass")) { 871 if (!IAP.isOpMapped(ROName)) { 872 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 873 Record *R = CGA.ResultOperands[i].getRecord(); 874 if (R->isSubClassOf("RegisterOperand")) 875 R = R->getValueAsDef("RegClass"); 876 IAP.addCond(formatv( 877 "AliasPatternCond::K_RegClass, {0}::{1}RegClassID", Namespace, 878 R->getName())); 879 } else { 880 IAP.addCond(formatv("AliasPatternCond::K_TiedReg, {0}", 881 IAP.getOpIndex(ROName))); 882 } 883 } else { 884 // Assume all printable operands are desired for now. This can be 885 // overridden in the InstAlias instantiation if necessary. 886 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 887 888 // There might be an additional predicate on the MCOperand 889 unsigned Entry = MCOpPredicateMap[Rec]; 890 if (!Entry) { 891 if (!Rec->isValueUnset("MCOperandPredicate")) { 892 MCOpPredicates.push_back(Rec); 893 Entry = MCOpPredicates.size(); 894 MCOpPredicateMap[Rec] = Entry; 895 } else 896 break; // No conditions on this operand at all 897 } 898 IAP.addCond(formatv("AliasPatternCond::K_Custom, {0}", Entry)); 899 } 900 break; 901 } 902 case CodeGenInstAlias::ResultOperand::K_Imm: { 903 // Just because the alias has an immediate result, doesn't mean the 904 // MCInst will. An MCExpr could be present, for example. 905 auto Imm = CGA.ResultOperands[i].getImm(); 906 int32_t Imm32 = int32_t(Imm); 907 if (Imm != Imm32) 908 PrintFatalError("Matching an alias with an immediate out of the " 909 "range of int32_t is not supported"); 910 IAP.addCond(formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32)); 911 break; 912 } 913 case CodeGenInstAlias::ResultOperand::K_Reg: 914 // If this is zero_reg, something's playing tricks we're not 915 // equipped to handle. 916 if (!CGA.ResultOperands[i].getRegister()) { 917 CantHandle = true; 918 break; 919 } 920 921 StringRef Reg = CGA.ResultOperands[i].getRegister()->getName(); 922 IAP.addCond( 923 formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg)); 924 break; 925 } 926 927 MIOpNum += RO.getMINumOperands(); 928 } 929 930 if (CantHandle) continue; 931 932 std::vector<Record *> ReqFeatures; 933 if (PassSubtarget) { 934 // We only consider ReqFeatures predicates if PassSubtarget 935 std::vector<Record *> RF = 936 CGA.TheDef->getValueAsListOfDefs("Predicates"); 937 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) { 938 return R->getValueAsBit("AssemblerMatcherPredicate"); 939 }); 940 } 941 942 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) { 943 Record *R = *I; 944 StringRef AsmCondString = R->getValueAsString("AssemblerCondString"); 945 946 // AsmCondString has syntax [!]F(,[!]F)* 947 SmallVector<StringRef, 4> Ops; 948 SplitString(AsmCondString, Ops, ","); 949 assert(!Ops.empty() && "AssemblerCondString cannot be empty"); 950 951 for (StringRef Op : Ops) { 952 assert(!Op.empty() && "Empty operator"); 953 bool IsNeg = Op[0] == '!'; 954 StringRef Feature = Op.drop_front(IsNeg ? 1 : 0); 955 IAP.addCond(formatv("AliasPatternCond::K_{0}Feature, {1}::{2}", 956 IsNeg ? "Neg" : "", Namespace, Feature)); 957 } 958 } 959 960 IAPrinterMap[Aliases.first].push_back(std::move(IAP)); 961 } 962 } 963 964 ////////////////////////////// 965 // Write out the printAliasInstr function 966 ////////////////////////////// 967 968 std::string Header; 969 raw_string_ostream HeaderO(Header); 970 971 HeaderO << "bool " << Target.getName() << ClassName 972 << "::printAliasInstr(const MCInst" 973 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 974 << "raw_ostream &OS) {\n"; 975 976 std::string PatternsForOpcode; 977 raw_string_ostream OpcodeO(PatternsForOpcode); 978 979 unsigned PatternCount = 0; 980 std::string Patterns; 981 raw_string_ostream PatternO(Patterns); 982 983 unsigned CondCount = 0; 984 std::string Conds; 985 raw_string_ostream CondO(Conds); 986 987 // All flattened alias strings. 988 std::map<std::string, uint32_t> AsmStringOffsets; 989 std::vector<std::pair<uint32_t, std::string>> AsmStrings; 990 size_t AsmStringsSize = 0; 991 992 // Iterate over the opcodes in enum order so they are sorted by opcode for 993 // binary search. 994 for (const CodeGenInstruction *Inst : NumberedInstructions) { 995 auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef)); 996 if (It == IAPrinterMap.end()) 997 continue; 998 std::vector<IAPrinter> &IAPs = It->second; 999 std::vector<IAPrinter*> UniqueIAPs; 1000 1001 // Remove any ambiguous alias rules. 1002 for (auto &LHS : IAPs) { 1003 bool IsDup = false; 1004 for (const auto &RHS : IAPs) { 1005 if (&LHS != &RHS && LHS == RHS) { 1006 IsDup = true; 1007 break; 1008 } 1009 } 1010 1011 if (!IsDup) 1012 UniqueIAPs.push_back(&LHS); 1013 } 1014 1015 if (UniqueIAPs.empty()) continue; 1016 1017 unsigned PatternStart = PatternCount; 1018 1019 // Insert the pattern start and opcode in the pattern list for debugging. 1020 PatternO << formatv(" // {0} - {1}\n", It->first, PatternStart); 1021 1022 for (IAPrinter *IAP : UniqueIAPs) { 1023 // Start each condition list with a comment of the resulting pattern that 1024 // we're trying to match. 1025 unsigned CondStart = CondCount; 1026 CondO << formatv(" // {0} - {1}\n", IAP->getResult(), CondStart); 1027 for (const auto &Cond : IAP->getConds()) 1028 CondO << " {" << Cond << "},\n"; 1029 CondCount += IAP->getCondCount(); 1030 1031 // After operands have been examined, re-encode the alias string with 1032 // escapes indicating how operands should be printed. 1033 uint32_t UnescapedSize = 0; 1034 std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize); 1035 auto Insertion = 1036 AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize}); 1037 if (Insertion.second) { 1038 // If the string is new, add it to the vector. 1039 AsmStrings.push_back({AsmStringsSize, EncodedAsmString}); 1040 AsmStringsSize += UnescapedSize + 1; 1041 } 1042 unsigned AsmStrOffset = Insertion.first->second; 1043 1044 PatternO << formatv(" {{{0}, {1}, {2}, {3} },\n", AsmStrOffset, 1045 CondStart, IAP->getNumMIOps(), IAP->getCondCount()); 1046 ++PatternCount; 1047 } 1048 1049 OpcodeO << formatv(" {{{0}, {1}, {2} },\n", It->first, PatternStart, 1050 PatternCount - PatternStart); 1051 } 1052 1053 if (OpcodeO.str().empty()) { 1054 O << HeaderO.str(); 1055 O << " return false;\n"; 1056 O << "}\n\n"; 1057 O << "#endif // PRINT_ALIAS_INSTR\n"; 1058 return; 1059 } 1060 1061 // Forward declare the validation method if needed. 1062 if (!MCOpPredicates.empty()) 1063 O << "static bool " << Target.getName() << ClassName 1064 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1065 << " const MCSubtargetInfo &STI,\n" 1066 << " unsigned PredicateIndex);\n"; 1067 1068 O << HeaderO.str(); 1069 O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n"; 1070 O << OpcodeO.str(); 1071 O.indent(2) << "};\n\n"; 1072 O.indent(2) << "static const AliasPattern Patterns[] = {\n"; 1073 O << PatternO.str(); 1074 O.indent(2) << "};\n\n"; 1075 O.indent(2) << "static const AliasPatternCond Conds[] = {\n"; 1076 O << CondO.str(); 1077 O.indent(2) << "};\n\n"; 1078 O.indent(2) << "static const char AsmStrings[] =\n"; 1079 for (const auto &P : AsmStrings) { 1080 O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n"; 1081 } 1082 1083 O.indent(2) << ";\n\n"; 1084 1085 // Assert that the opcode table is sorted. Use a static local constructor to 1086 // ensure that the check only happens once on first run. 1087 O << "#ifndef NDEBUG\n"; 1088 O.indent(2) << "static struct SortCheck {\n"; 1089 O.indent(2) << " SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n"; 1090 O.indent(2) << " assert(std::is_sorted(\n"; 1091 O.indent(2) << " OpToPatterns.begin(), OpToPatterns.end(),\n"; 1092 O.indent(2) << " [](const PatternsForOpcode &L, const " 1093 "PatternsForOpcode &R) {\n"; 1094 O.indent(2) << " return L.Opcode < R.Opcode;\n"; 1095 O.indent(2) << " }) &&\n"; 1096 O.indent(2) << " \"tablegen failed to sort opcode patterns\");\n"; 1097 O.indent(2) << " }\n"; 1098 O.indent(2) << "} sortCheckVar(OpToPatterns);\n"; 1099 O << "#endif\n\n"; 1100 1101 O.indent(2) << "AliasMatchingData M {\n"; 1102 O.indent(2) << " makeArrayRef(OpToPatterns),\n"; 1103 O.indent(2) << " makeArrayRef(Patterns),\n"; 1104 O.indent(2) << " makeArrayRef(Conds),\n"; 1105 O.indent(2) << " StringRef(AsmStrings, array_lengthof(AsmStrings)),\n"; 1106 if (MCOpPredicates.empty()) 1107 O.indent(2) << " nullptr,\n"; 1108 else 1109 O.indent(2) << " &" << Target.getName() << ClassName << "ValidateMCOperand,\n"; 1110 O.indent(2) << "};\n"; 1111 1112 O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, " 1113 << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n"; 1114 O.indent(2) << "if (!AsmString) return false;\n\n"; 1115 1116 // Code that prints the alias, replacing the operands with the ones from the 1117 // MCInst. 1118 O << " unsigned I = 0;\n"; 1119 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n"; 1120 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n"; 1121 O << " ++I;\n"; 1122 O << " OS << '\\t' << StringRef(AsmString, I);\n"; 1123 1124 O << " if (AsmString[I] != '\\0') {\n"; 1125 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n"; 1126 O << " OS << '\\t';\n"; 1127 O << " ++I;\n"; 1128 O << " }\n"; 1129 O << " do {\n"; 1130 O << " if (AsmString[I] == '$') {\n"; 1131 O << " ++I;\n"; 1132 O << " if (AsmString[I] == (char)0xff) {\n"; 1133 O << " ++I;\n"; 1134 O << " int OpIdx = AsmString[I++] - 1;\n"; 1135 O << " int PrintMethodIdx = AsmString[I++] - 1;\n"; 1136 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, "; 1137 O << (PassSubtarget ? "STI, " : ""); 1138 O << "OS);\n"; 1139 O << " } else\n"; 1140 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, "; 1141 O << (PassSubtarget ? "STI, " : ""); 1142 O << "OS);\n"; 1143 O << " } else {\n"; 1144 O << " OS << AsmString[I++];\n"; 1145 O << " }\n"; 1146 O << " } while (AsmString[I] != '\\0');\n"; 1147 O << " }\n\n"; 1148 1149 O << " return true;\n"; 1150 O << "}\n\n"; 1151 1152 ////////////////////////////// 1153 // Write out the printCustomAliasOperand function 1154 ////////////////////////////// 1155 1156 O << "void " << Target.getName() << ClassName << "::" 1157 << "printCustomAliasOperand(\n" 1158 << " const MCInst *MI, unsigned OpIdx,\n" 1159 << " unsigned PrintMethodIdx,\n" 1160 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "") 1161 << " raw_ostream &OS) {\n"; 1162 if (PrintMethods.empty()) 1163 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"; 1164 else { 1165 O << " switch (PrintMethodIdx) {\n" 1166 << " default:\n" 1167 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n" 1168 << " break;\n"; 1169 1170 for (unsigned i = 0; i < PrintMethods.size(); ++i) { 1171 O << " case " << i << ":\n" 1172 << " " << PrintMethods[i] << "(MI, OpIdx, " 1173 << (PassSubtarget ? "STI, " : "") << "OS);\n" 1174 << " break;\n"; 1175 } 1176 O << " }\n"; 1177 } 1178 O << "}\n\n"; 1179 1180 if (!MCOpPredicates.empty()) { 1181 O << "static bool " << Target.getName() << ClassName 1182 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1183 << " const MCSubtargetInfo &STI,\n" 1184 << " unsigned PredicateIndex) {\n" 1185 << " switch (PredicateIndex) {\n" 1186 << " default:\n" 1187 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n" 1188 << " break;\n"; 1189 1190 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) { 1191 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate"); 1192 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) { 1193 O << " case " << i + 1 << ": {\n" 1194 << SI->getValue() << "\n" 1195 << " }\n"; 1196 } else 1197 llvm_unreachable("Unexpected MCOperandPredicate field!"); 1198 } 1199 O << " }\n" 1200 << "}\n\n"; 1201 } 1202 1203 O << "#endif // PRINT_ALIAS_INSTR\n"; 1204 } 1205 1206 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) { 1207 Record *AsmWriter = Target.getAsmWriter(); 1208 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 1209 1210 // Get the instruction numbering. 1211 NumberedInstructions = Target.getInstructionsByEnumValue(); 1212 1213 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 1214 const CodeGenInstruction *I = NumberedInstructions[i]; 1215 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI") 1216 Instructions.emplace_back(*I, i, Variant); 1217 } 1218 } 1219 1220 void AsmWriterEmitter::run(raw_ostream &O) { 1221 EmitPrintInstruction(O); 1222 EmitGetRegisterName(O); 1223 EmitPrintAliasInstruction(O); 1224 } 1225 1226 namespace llvm { 1227 1228 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { 1229 emitSourceFileHeader("Assembly Writer Source Fragment", OS); 1230 AsmWriterEmitter(RK).run(OS); 1231 } 1232 1233 } // end namespace llvm 1234