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(std::string(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 /// UnescapeAliasString - Supports literal braces in InstAlias asm string which 271 /// are escaped with '\\' to avoid being interpreted as variants. Braces must 272 /// be unescaped before c++ code is generated as (e.g.): 273 /// 274 /// AsmString = "foo \{$\x01\}"; 275 /// 276 /// causes non-standard escape character warnings. 277 static void UnescapeAliasString(std::string &Str) { 278 for (unsigned i = 0; i != Str.size(); ++i) { 279 if (Str[i] == '\\' && i != Str.size()-1) { 280 switch (Str[i+1]) { 281 default: continue; // Don't execute the code after the switch. 282 case '{': Str[i] = '{'; break; 283 case '}': Str[i] = '}'; break; 284 } 285 // Nuke the second character. 286 Str.erase(Str.begin()+i+1); 287 } 288 } 289 } 290 291 /// EmitPrintInstruction - Generate the code for the "printInstruction" method 292 /// implementation. Destroys all instances of AsmWriterInst information, by 293 /// clearing the Instructions vector. 294 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { 295 Record *AsmWriter = Target.getAsmWriter(); 296 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 297 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 298 299 O << "/// printInstruction - This method is automatically generated by " 300 "tablegen\n" 301 "/// from the instruction set description.\n" 302 "void " 303 << Target.getName() << ClassName 304 << "::printInstruction(const MCInst *MI, uint64_t Address, " 305 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 306 << "raw_ostream &O) {\n"; 307 308 // Build an aggregate string, and build a table of offsets into it. 309 SequenceToOffsetTable<std::string> StringTable; 310 311 /// OpcodeInfo - This encodes the index of the string to use for the first 312 /// chunk of the output as well as indices used for operand printing. 313 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size()); 314 const unsigned OpcodeInfoBits = 64; 315 316 // Add all strings to the string table upfront so it can generate an optimized 317 // representation. 318 for (AsmWriterInst &AWI : Instructions) { 319 if (AWI.Operands[0].OperandType == 320 AsmWriterOperand::isLiteralTextOperand && 321 !AWI.Operands[0].Str.empty()) { 322 std::string Str = AWI.Operands[0].Str; 323 UnescapeString(Str); 324 StringTable.add(Str); 325 } 326 } 327 328 StringTable.layout(); 329 330 unsigned MaxStringIdx = 0; 331 for (AsmWriterInst &AWI : Instructions) { 332 unsigned Idx; 333 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand || 334 AWI.Operands[0].Str.empty()) { 335 // Something handled by the asmwriter printer, but with no leading string. 336 Idx = StringTable.get(""); 337 } else { 338 std::string Str = AWI.Operands[0].Str; 339 UnescapeString(Str); 340 Idx = StringTable.get(Str); 341 MaxStringIdx = std::max(MaxStringIdx, Idx); 342 343 // Nuke the string from the operand list. It is now handled! 344 AWI.Operands.erase(AWI.Operands.begin()); 345 } 346 347 // Bias offset by one since we want 0 as a sentinel. 348 OpcodeInfo[AWI.CGIIndex] = Idx+1; 349 } 350 351 // Figure out how many bits we used for the string index. 352 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2); 353 354 // To reduce code size, we compactify common instructions into a few bits 355 // in the opcode-indexed table. 356 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits; 357 358 std::vector<std::vector<std::string>> TableDrivenOperandPrinters; 359 360 while (true) { 361 std::vector<std::string> UniqueOperandCommands; 362 std::vector<std::vector<unsigned>> InstIdxs; 363 std::vector<unsigned> NumInstOpsHandled; 364 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs, 365 NumInstOpsHandled, PassSubtarget); 366 367 // If we ran out of operands to print, we're done. 368 if (UniqueOperandCommands.empty()) break; 369 370 // Compute the number of bits we need to represent these cases, this is 371 // ceil(log2(numentries)). 372 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size()); 373 374 // If we don't have enough bits for this operand, don't include it. 375 if (NumBits > BitsLeft) { 376 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits 377 << " more bits\n"); 378 break; 379 } 380 381 // Otherwise, we can include this in the initial lookup table. Add it in. 382 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) { 383 unsigned NumOps = NumInstOpsHandled[i]; 384 for (unsigned Idx : InstIdxs[i]) { 385 OpcodeInfo[Instructions[Idx].CGIIndex] |= 386 (uint64_t)i << (OpcodeInfoBits-BitsLeft); 387 // Remove the info about this operand from the instruction. 388 AsmWriterInst &Inst = Instructions[Idx]; 389 if (!Inst.Operands.empty()) { 390 assert(NumOps <= Inst.Operands.size() && 391 "Can't remove this many ops!"); 392 Inst.Operands.erase(Inst.Operands.begin(), 393 Inst.Operands.begin()+NumOps); 394 } 395 } 396 } 397 BitsLeft -= NumBits; 398 399 // Remember the handlers for this set of operands. 400 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands)); 401 } 402 403 // Emit the string table itself. 404 StringTable.emitStringLiteralDef(O, " static const char AsmStrs[]"); 405 406 // Emit the lookup tables in pieces to minimize wasted bytes. 407 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8; 408 unsigned Table = 0, Shift = 0; 409 SmallString<128> BitsString; 410 raw_svector_ostream BitsOS(BitsString); 411 // If the total bits is more than 32-bits we need to use a 64-bit type. 412 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32) 413 << "_t Bits = 0;\n"; 414 while (BytesNeeded != 0) { 415 // Figure out how big this table section needs to be, but no bigger than 4. 416 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4); 417 BytesNeeded -= TableSize; 418 TableSize *= 8; // Convert to bits; 419 uint64_t Mask = (1ULL << TableSize) - 1; 420 O << " static const uint" << TableSize << "_t OpInfo" << Table 421 << "[] = {\n"; 422 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 423 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// " 424 << NumberedInstructions[i]->TheDef->getName() << "\n"; 425 } 426 O << " };\n\n"; 427 // Emit string to combine the individual table lookups. 428 BitsOS << " Bits |= "; 429 // If the total bits is more than 32-bits we need to use a 64-bit type. 430 if (BitsLeft < (OpcodeInfoBits - 32)) 431 BitsOS << "(uint64_t)"; 432 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n"; 433 // Prepare the shift for the next iteration and increment the table count. 434 Shift += TableSize; 435 ++Table; 436 } 437 438 // Emit the initial tab character. 439 O << " O << \"\\t\";\n\n"; 440 441 O << " // Emit the opcode for the instruction.\n"; 442 O << BitsString; 443 444 // Emit the starting string. 445 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n" 446 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n"; 447 448 // Output the table driven operand information. 449 BitsLeft = OpcodeInfoBits-AsmStrBits; 450 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) { 451 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i]; 452 453 // Compute the number of bits we need to represent these cases, this is 454 // ceil(log2(numentries)). 455 unsigned NumBits = Log2_32_Ceil(Commands.size()); 456 assert(NumBits <= BitsLeft && "consistency error"); 457 458 // Emit code to extract this field from Bits. 459 O << "\n // Fragment " << i << " encoded into " << NumBits 460 << " bits for " << Commands.size() << " unique commands.\n"; 461 462 if (Commands.size() == 2) { 463 // Emit two possibilitys with if/else. 464 O << " if ((Bits >> " 465 << (OpcodeInfoBits-BitsLeft) << ") & " 466 << ((1 << NumBits)-1) << ") {\n" 467 << Commands[1] 468 << " } else {\n" 469 << Commands[0] 470 << " }\n\n"; 471 } else if (Commands.size() == 1) { 472 // Emit a single possibility. 473 O << Commands[0] << "\n\n"; 474 } else { 475 O << " switch ((Bits >> " 476 << (OpcodeInfoBits-BitsLeft) << ") & " 477 << ((1 << NumBits)-1) << ") {\n" 478 << " default: llvm_unreachable(\"Invalid command number.\");\n"; 479 480 // Print out all the cases. 481 for (unsigned j = 0, e = Commands.size(); j != e; ++j) { 482 O << " case " << j << ":\n"; 483 O << Commands[j]; 484 O << " break;\n"; 485 } 486 O << " }\n\n"; 487 } 488 BitsLeft -= NumBits; 489 } 490 491 // Okay, delete instructions with no operand info left. 492 auto I = llvm::remove_if(Instructions, 493 [](AsmWriterInst &Inst) { return Inst.Operands.empty(); }); 494 Instructions.erase(I, Instructions.end()); 495 496 497 // Because this is a vector, we want to emit from the end. Reverse all of the 498 // elements in the vector. 499 std::reverse(Instructions.begin(), Instructions.end()); 500 501 502 // Now that we've emitted all of the operand info that fit into 64 bits, emit 503 // information for those instructions that are left. This is a less dense 504 // encoding, but we expect the main 64-bit table to handle the majority of 505 // instructions. 506 if (!Instructions.empty()) { 507 // Find the opcode # of inline asm. 508 O << " switch (MI->getOpcode()) {\n"; 509 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; 510 while (!Instructions.empty()) 511 EmitInstructions(Instructions, O, PassSubtarget); 512 513 O << " }\n"; 514 } 515 516 O << "}\n"; 517 } 518 519 static void 520 emitRegisterNameString(raw_ostream &O, StringRef AltName, 521 const std::deque<CodeGenRegister> &Registers) { 522 SequenceToOffsetTable<std::string> StringTable; 523 SmallVector<std::string, 4> AsmNames(Registers.size()); 524 unsigned i = 0; 525 for (const auto &Reg : Registers) { 526 std::string &AsmName = AsmNames[i++]; 527 528 // "NoRegAltName" is special. We don't need to do a lookup for that, 529 // as it's just a reference to the default register name. 530 if (AltName == "" || AltName == "NoRegAltName") { 531 AsmName = std::string(Reg.TheDef->getValueAsString("AsmName")); 532 if (AsmName.empty()) 533 AsmName = std::string(Reg.getName()); 534 } else { 535 // Make sure the register has an alternate name for this index. 536 std::vector<Record*> AltNameList = 537 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices"); 538 unsigned Idx = 0, e; 539 for (e = AltNameList.size(); 540 Idx < e && (AltNameList[Idx]->getName() != AltName); 541 ++Idx) 542 ; 543 // If the register has an alternate name for this index, use it. 544 // Otherwise, leave it empty as an error flag. 545 if (Idx < e) { 546 std::vector<StringRef> AltNames = 547 Reg.TheDef->getValueAsListOfStrings("AltNames"); 548 if (AltNames.size() <= Idx) 549 PrintFatalError(Reg.TheDef->getLoc(), 550 "Register definition missing alt name for '" + 551 AltName + "'."); 552 AsmName = std::string(AltNames[Idx]); 553 } 554 } 555 StringTable.add(AsmName); 556 } 557 558 StringTable.layout(); 559 StringTable.emitStringLiteralDef(O, Twine(" static const char AsmStrs") + 560 AltName + "[]"); 561 562 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32) 563 << " RegAsmOffset" << AltName << "[] = {"; 564 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 565 if ((i % 14) == 0) 566 O << "\n "; 567 O << StringTable.get(AsmNames[i]) << ", "; 568 } 569 O << "\n };\n" 570 << "\n"; 571 } 572 573 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { 574 Record *AsmWriter = Target.getAsmWriter(); 575 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 576 const auto &Registers = Target.getRegBank().getRegisters(); 577 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices(); 578 bool hasAltNames = AltNameIndices.size() > 1; 579 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace"); 580 581 O << 582 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n" 583 "/// from the register set description. This returns the assembler name\n" 584 "/// for the specified register.\n" 585 "const char *" << Target.getName() << ClassName << "::"; 586 if (hasAltNames) 587 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n"; 588 else 589 O << "getRegisterName(unsigned RegNo) {\n"; 590 O << " assert(RegNo && RegNo < " << (Registers.size()+1) 591 << " && \"Invalid register number!\");\n" 592 << "\n"; 593 594 if (hasAltNames) { 595 for (const Record *R : AltNameIndices) 596 emitRegisterNameString(O, R->getName(), Registers); 597 } else 598 emitRegisterNameString(O, "", Registers); 599 600 if (hasAltNames) { 601 O << " switch(AltIdx) {\n" 602 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n"; 603 for (const Record *R : AltNameIndices) { 604 StringRef AltName = R->getName(); 605 O << " case "; 606 if (!Namespace.empty()) 607 O << Namespace << "::"; 608 O << AltName << ":\n"; 609 if (R->isValueUnset("FallbackRegAltNameIndex")) 610 O << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 611 << "[RegNo-1]) &&\n" 612 << " \"Invalid alt name index for register!\");\n"; 613 else { 614 O << " if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 615 << "[RegNo-1]))\n" 616 << " return getRegisterName(RegNo, "; 617 if (!Namespace.empty()) 618 O << Namespace << "::"; 619 O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n"; 620 } 621 O << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName 622 << "[RegNo-1];\n"; 623 } 624 O << " }\n"; 625 } else { 626 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n" 627 << " \"Invalid alt name index for register!\");\n" 628 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"; 629 } 630 O << "}\n"; 631 } 632 633 namespace { 634 635 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if 636 // they both have the same conditionals. In which case, we cannot print out the 637 // alias for that pattern. 638 class IAPrinter { 639 std::map<StringRef, std::pair<int, int>> OpMap; 640 641 std::vector<std::string> Conds; 642 643 std::string Result; 644 std::string AsmString; 645 646 unsigned NumMIOps; 647 648 public: 649 IAPrinter(std::string R, std::string AS, unsigned NumMIOps) 650 : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {} 651 652 void addCond(std::string C) { Conds.push_back(std::move(C)); } 653 ArrayRef<std::string> getConds() const { return Conds; } 654 size_t getCondCount() const { return Conds.size(); } 655 656 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) { 657 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range"); 658 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF && 659 "Idx out of range"); 660 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx); 661 } 662 663 unsigned getNumMIOps() { return NumMIOps; } 664 665 StringRef getResult() { return Result; } 666 667 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); } 668 int getOpIndex(StringRef Op) { return OpMap[Op].first; } 669 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; } 670 671 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start, 672 StringRef::iterator End) { 673 StringRef::iterator I = Start; 674 StringRef::iterator Next; 675 if (*I == '{') { 676 // ${some_name} 677 Start = ++I; 678 while (I != End && *I != '}') 679 ++I; 680 Next = I; 681 // eat the final '}' 682 if (Next != End) 683 ++Next; 684 } else { 685 // $name, just eat the usual suspects. 686 while (I != End && 687 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') || 688 (*I >= '0' && *I <= '9') || *I == '_')) 689 ++I; 690 Next = I; 691 } 692 693 return std::make_pair(StringRef(Start, I - Start), Next); 694 } 695 696 std::string formatAliasString(uint32_t &UnescapedSize) { 697 // Directly mangle mapped operands into the string. Each operand is 698 // identified by a '$' sign followed by a byte identifying the number of the 699 // operand. We add one to the index to avoid zero bytes. 700 StringRef ASM(AsmString); 701 std::string OutString; 702 raw_string_ostream OS(OutString); 703 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) { 704 OS << *I; 705 ++UnescapedSize; 706 if (*I == '$') { 707 StringRef Name; 708 std::tie(Name, I) = parseName(++I, E); 709 assert(isOpMapped(Name) && "Unmapped operand!"); 710 711 int OpIndex, PrintIndex; 712 std::tie(OpIndex, PrintIndex) = getOpData(Name); 713 if (PrintIndex == -1) { 714 // Can use the default printOperand route. 715 OS << format("\\x%02X", (unsigned char)OpIndex + 1); 716 ++UnescapedSize; 717 } else { 718 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand 719 // number, and which of our pre-detected Methods to call. 720 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1); 721 UnescapedSize += 3; 722 } 723 } else { 724 ++I; 725 } 726 } 727 728 OS.flush(); 729 return OutString; 730 } 731 732 bool operator==(const IAPrinter &RHS) const { 733 if (NumMIOps != RHS.NumMIOps) 734 return false; 735 if (Conds.size() != RHS.Conds.size()) 736 return false; 737 738 unsigned Idx = 0; 739 for (const auto &str : Conds) 740 if (str != RHS.Conds[Idx++]) 741 return false; 742 743 return true; 744 } 745 }; 746 747 } // end anonymous namespace 748 749 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) { 750 return AsmString.count(' ') + AsmString.count('\t'); 751 } 752 753 namespace { 754 755 struct AliasPriorityComparator { 756 typedef std::pair<CodeGenInstAlias, int> ValueType; 757 bool operator()(const ValueType &LHS, const ValueType &RHS) const { 758 if (LHS.second == RHS.second) { 759 // We don't actually care about the order, but for consistency it 760 // shouldn't depend on pointer comparisons. 761 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef); 762 } 763 764 // Aliases with larger priorities should be considered first. 765 return LHS.second > RHS.second; 766 } 767 }; 768 769 } // end anonymous namespace 770 771 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { 772 Record *AsmWriter = Target.getAsmWriter(); 773 774 O << "\n#ifdef PRINT_ALIAS_INSTR\n"; 775 O << "#undef PRINT_ALIAS_INSTR\n\n"; 776 777 ////////////////////////////// 778 // Gather information about aliases we need to print 779 ////////////////////////////// 780 781 // Emit the method that prints the alias instruction. 782 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 783 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 784 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 785 786 std::vector<Record*> AllInstAliases = 787 Records.getAllDerivedDefinitions("InstAlias"); 788 789 // Create a map from the qualified name to a list of potential matches. 790 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator> 791 AliasWithPriority; 792 std::map<std::string, AliasWithPriority> AliasMap; 793 for (Record *R : AllInstAliases) { 794 int Priority = R->getValueAsInt("EmitPriority"); 795 if (Priority < 1) 796 continue; // Aliases with priority 0 are never emitted. 797 798 const DagInit *DI = R->getValueAsDag("ResultInst"); 799 AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert( 800 std::make_pair(CodeGenInstAlias(R, Target), Priority)); 801 } 802 803 // A map of which conditions need to be met for each instruction operand 804 // before it can be matched to the mnemonic. 805 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap; 806 807 std::vector<std::pair<std::string, bool>> PrintMethods; 808 809 // A list of MCOperandPredicates for all operands in use, and the reverse map 810 std::vector<const Record*> MCOpPredicates; 811 DenseMap<const Record*, unsigned> MCOpPredicateMap; 812 813 for (auto &Aliases : AliasMap) { 814 // Collection of instruction alias rules. May contain ambiguous rules. 815 std::vector<IAPrinter> IAPs; 816 817 for (auto &Alias : Aliases.second) { 818 const CodeGenInstAlias &CGA = Alias.first; 819 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 820 std::string FlatInstAsmString = 821 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString, 822 Variant); 823 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant); 824 825 std::string FlatAliasAsmString = 826 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant); 827 UnescapeAliasString(FlatAliasAsmString); 828 829 // Don't emit the alias if it has more operands than what it's aliasing. 830 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant)) 831 continue; 832 833 StringRef Namespace = Target.getName(); 834 unsigned NumMIOps = 0; 835 for (auto &ResultInstOpnd : CGA.ResultInst->Operands) 836 NumMIOps += ResultInstOpnd.MINumOperands; 837 838 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps); 839 840 bool CantHandle = false; 841 842 unsigned MIOpNum = 0; 843 for (unsigned i = 0, e = LastOpNo; i != e; ++i) { 844 // Skip over tied operands as they're not part of an alias declaration. 845 auto &Operands = CGA.ResultInst->Operands; 846 while (true) { 847 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first; 848 if (Operands[OpNum].MINumOperands == 1 && 849 Operands[OpNum].getTiedRegister() != -1) { 850 // Tied operands of different RegisterClass should be explicit within 851 // an instruction's syntax and so cannot be skipped. 852 int TiedOpNum = Operands[OpNum].getTiedRegister(); 853 if (Operands[OpNum].Rec->getName() == 854 Operands[TiedOpNum].Rec->getName()) { 855 ++MIOpNum; 856 continue; 857 } 858 } 859 break; 860 } 861 862 // Ignore unchecked result operands. 863 while (IAP.getCondCount() < MIOpNum) 864 IAP.addCond("AliasPatternCond::K_Ignore, 0"); 865 866 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i]; 867 868 switch (RO.Kind) { 869 case CodeGenInstAlias::ResultOperand::K_Record: { 870 const Record *Rec = RO.getRecord(); 871 StringRef ROName = RO.getName(); 872 int PrintMethodIdx = -1; 873 874 // These two may have a PrintMethod, which we want to record (if it's 875 // the first time we've seen it) and provide an index for the aliasing 876 // code to use. 877 if (Rec->isSubClassOf("RegisterOperand") || 878 Rec->isSubClassOf("Operand")) { 879 StringRef PrintMethod = Rec->getValueAsString("PrintMethod"); 880 bool IsPCRel = 881 Rec->getValueAsString("OperandType") == "OPERAND_PCREL"; 882 if (PrintMethod != "" && PrintMethod != "printOperand") { 883 PrintMethodIdx = llvm::find_if(PrintMethods, 884 [&](auto &X) { 885 return X.first == PrintMethod; 886 }) - 887 PrintMethods.begin(); 888 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size()) 889 PrintMethods.emplace_back(std::string(PrintMethod), IsPCRel); 890 } 891 } 892 893 if (Rec->isSubClassOf("RegisterOperand")) 894 Rec = Rec->getValueAsDef("RegClass"); 895 if (Rec->isSubClassOf("RegisterClass")) { 896 if (!IAP.isOpMapped(ROName)) { 897 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 898 Record *R = CGA.ResultOperands[i].getRecord(); 899 if (R->isSubClassOf("RegisterOperand")) 900 R = R->getValueAsDef("RegClass"); 901 IAP.addCond(std::string( 902 formatv("AliasPatternCond::K_RegClass, {0}::{1}RegClassID", 903 Namespace, R->getName()))); 904 } else { 905 IAP.addCond(std::string(formatv( 906 "AliasPatternCond::K_TiedReg, {0}", IAP.getOpIndex(ROName)))); 907 } 908 } else { 909 // Assume all printable operands are desired for now. This can be 910 // overridden in the InstAlias instantiation if necessary. 911 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 912 913 // There might be an additional predicate on the MCOperand 914 unsigned Entry = MCOpPredicateMap[Rec]; 915 if (!Entry) { 916 if (!Rec->isValueUnset("MCOperandPredicate")) { 917 MCOpPredicates.push_back(Rec); 918 Entry = MCOpPredicates.size(); 919 MCOpPredicateMap[Rec] = Entry; 920 } else 921 break; // No conditions on this operand at all 922 } 923 IAP.addCond( 924 std::string(formatv("AliasPatternCond::K_Custom, {0}", Entry))); 925 } 926 break; 927 } 928 case CodeGenInstAlias::ResultOperand::K_Imm: { 929 // Just because the alias has an immediate result, doesn't mean the 930 // MCInst will. An MCExpr could be present, for example. 931 auto Imm = CGA.ResultOperands[i].getImm(); 932 int32_t Imm32 = int32_t(Imm); 933 if (Imm != Imm32) 934 PrintFatalError("Matching an alias with an immediate out of the " 935 "range of int32_t is not supported"); 936 IAP.addCond(std::string( 937 formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32))); 938 break; 939 } 940 case CodeGenInstAlias::ResultOperand::K_Reg: 941 // If this is zero_reg, something's playing tricks we're not 942 // equipped to handle. 943 if (!CGA.ResultOperands[i].getRegister()) { 944 CantHandle = true; 945 break; 946 } 947 948 StringRef Reg = CGA.ResultOperands[i].getRegister()->getName(); 949 IAP.addCond(std::string( 950 formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg))); 951 break; 952 } 953 954 MIOpNum += RO.getMINumOperands(); 955 } 956 957 if (CantHandle) continue; 958 959 std::vector<Record *> ReqFeatures; 960 if (PassSubtarget) { 961 // We only consider ReqFeatures predicates if PassSubtarget 962 std::vector<Record *> RF = 963 CGA.TheDef->getValueAsListOfDefs("Predicates"); 964 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) { 965 return R->getValueAsBit("AssemblerMatcherPredicate"); 966 }); 967 } 968 969 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) { 970 Record *R = *I; 971 const DagInit *D = R->getValueAsDag("AssemblerCondDag"); 972 std::string CombineType = D->getOperator()->getAsString(); 973 if (CombineType != "any_of" && CombineType != "all_of") 974 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 975 if (D->getNumArgs() == 0) 976 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 977 bool IsOr = CombineType == "any_of"; 978 979 for (auto *Arg : D->getArgs()) { 980 bool IsNeg = false; 981 if (auto *NotArg = dyn_cast<DagInit>(Arg)) { 982 if (NotArg->getOperator()->getAsString() != "not" || 983 NotArg->getNumArgs() != 1) 984 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 985 Arg = NotArg->getArg(0); 986 IsNeg = true; 987 } 988 if (!isa<DefInit>(Arg) || 989 !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature")) 990 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 991 992 IAP.addCond(std::string(formatv( 993 "AliasPatternCond::K_{0}{1}Feature, {2}::{3}", IsOr ? "Or" : "", 994 IsNeg ? "Neg" : "", Namespace, Arg->getAsString()))); 995 } 996 // If an AssemblerPredicate with ors is used, note end of list should 997 // these be combined. 998 if (IsOr) 999 IAP.addCond("AliasPatternCond::K_EndOrFeatures, 0"); 1000 } 1001 1002 IAPrinterMap[Aliases.first].push_back(std::move(IAP)); 1003 } 1004 } 1005 1006 ////////////////////////////// 1007 // Write out the printAliasInstr function 1008 ////////////////////////////// 1009 1010 std::string Header; 1011 raw_string_ostream HeaderO(Header); 1012 1013 HeaderO << "bool " << Target.getName() << ClassName 1014 << "::printAliasInstr(const MCInst" 1015 << " *MI, uint64_t Address, " 1016 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 1017 << "raw_ostream &OS) {\n"; 1018 1019 std::string PatternsForOpcode; 1020 raw_string_ostream OpcodeO(PatternsForOpcode); 1021 1022 unsigned PatternCount = 0; 1023 std::string Patterns; 1024 raw_string_ostream PatternO(Patterns); 1025 1026 unsigned CondCount = 0; 1027 std::string Conds; 1028 raw_string_ostream CondO(Conds); 1029 1030 // All flattened alias strings. 1031 std::map<std::string, uint32_t> AsmStringOffsets; 1032 std::vector<std::pair<uint32_t, std::string>> AsmStrings; 1033 size_t AsmStringsSize = 0; 1034 1035 // Iterate over the opcodes in enum order so they are sorted by opcode for 1036 // binary search. 1037 for (const CodeGenInstruction *Inst : NumberedInstructions) { 1038 auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef)); 1039 if (It == IAPrinterMap.end()) 1040 continue; 1041 std::vector<IAPrinter> &IAPs = It->second; 1042 std::vector<IAPrinter*> UniqueIAPs; 1043 1044 // Remove any ambiguous alias rules. 1045 for (auto &LHS : IAPs) { 1046 bool IsDup = false; 1047 for (const auto &RHS : IAPs) { 1048 if (&LHS != &RHS && LHS == RHS) { 1049 IsDup = true; 1050 break; 1051 } 1052 } 1053 1054 if (!IsDup) 1055 UniqueIAPs.push_back(&LHS); 1056 } 1057 1058 if (UniqueIAPs.empty()) continue; 1059 1060 unsigned PatternStart = PatternCount; 1061 1062 // Insert the pattern start and opcode in the pattern list for debugging. 1063 PatternO << formatv(" // {0} - {1}\n", It->first, PatternStart); 1064 1065 for (IAPrinter *IAP : UniqueIAPs) { 1066 // Start each condition list with a comment of the resulting pattern that 1067 // we're trying to match. 1068 unsigned CondStart = CondCount; 1069 CondO << formatv(" // {0} - {1}\n", IAP->getResult(), CondStart); 1070 for (const auto &Cond : IAP->getConds()) 1071 CondO << " {" << Cond << "},\n"; 1072 CondCount += IAP->getCondCount(); 1073 1074 // After operands have been examined, re-encode the alias string with 1075 // escapes indicating how operands should be printed. 1076 uint32_t UnescapedSize = 0; 1077 std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize); 1078 auto Insertion = 1079 AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize}); 1080 if (Insertion.second) { 1081 // If the string is new, add it to the vector. 1082 AsmStrings.push_back({AsmStringsSize, EncodedAsmString}); 1083 AsmStringsSize += UnescapedSize + 1; 1084 } 1085 unsigned AsmStrOffset = Insertion.first->second; 1086 1087 PatternO << formatv(" {{{0}, {1}, {2}, {3} },\n", AsmStrOffset, 1088 CondStart, IAP->getNumMIOps(), IAP->getCondCount()); 1089 ++PatternCount; 1090 } 1091 1092 OpcodeO << formatv(" {{{0}, {1}, {2} },\n", It->first, PatternStart, 1093 PatternCount - PatternStart); 1094 } 1095 1096 if (OpcodeO.str().empty()) { 1097 O << HeaderO.str(); 1098 O << " return false;\n"; 1099 O << "}\n\n"; 1100 O << "#endif // PRINT_ALIAS_INSTR\n"; 1101 return; 1102 } 1103 1104 // Forward declare the validation method if needed. 1105 if (!MCOpPredicates.empty()) 1106 O << "static bool " << Target.getName() << ClassName 1107 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1108 << " const MCSubtargetInfo &STI,\n" 1109 << " unsigned PredicateIndex);\n"; 1110 1111 O << HeaderO.str(); 1112 O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n"; 1113 O << OpcodeO.str(); 1114 O.indent(2) << "};\n\n"; 1115 O.indent(2) << "static const AliasPattern Patterns[] = {\n"; 1116 O << PatternO.str(); 1117 O.indent(2) << "};\n\n"; 1118 O.indent(2) << "static const AliasPatternCond Conds[] = {\n"; 1119 O << CondO.str(); 1120 O.indent(2) << "};\n\n"; 1121 O.indent(2) << "static const char AsmStrings[] =\n"; 1122 for (const auto &P : AsmStrings) { 1123 O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n"; 1124 } 1125 1126 O.indent(2) << ";\n\n"; 1127 1128 // Assert that the opcode table is sorted. Use a static local constructor to 1129 // ensure that the check only happens once on first run. 1130 O << "#ifndef NDEBUG\n"; 1131 O.indent(2) << "static struct SortCheck {\n"; 1132 O.indent(2) << " SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n"; 1133 O.indent(2) << " assert(std::is_sorted(\n"; 1134 O.indent(2) << " OpToPatterns.begin(), OpToPatterns.end(),\n"; 1135 O.indent(2) << " [](const PatternsForOpcode &L, const " 1136 "PatternsForOpcode &R) {\n"; 1137 O.indent(2) << " return L.Opcode < R.Opcode;\n"; 1138 O.indent(2) << " }) &&\n"; 1139 O.indent(2) << " \"tablegen failed to sort opcode patterns\");\n"; 1140 O.indent(2) << " }\n"; 1141 O.indent(2) << "} sortCheckVar(OpToPatterns);\n"; 1142 O << "#endif\n\n"; 1143 1144 O.indent(2) << "AliasMatchingData M {\n"; 1145 O.indent(2) << " makeArrayRef(OpToPatterns),\n"; 1146 O.indent(2) << " makeArrayRef(Patterns),\n"; 1147 O.indent(2) << " makeArrayRef(Conds),\n"; 1148 O.indent(2) << " StringRef(AsmStrings, array_lengthof(AsmStrings)),\n"; 1149 if (MCOpPredicates.empty()) 1150 O.indent(2) << " nullptr,\n"; 1151 else 1152 O.indent(2) << " &" << Target.getName() << ClassName << "ValidateMCOperand,\n"; 1153 O.indent(2) << "};\n"; 1154 1155 O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, " 1156 << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n"; 1157 O.indent(2) << "if (!AsmString) return false;\n\n"; 1158 1159 // Code that prints the alias, replacing the operands with the ones from the 1160 // MCInst. 1161 O << " unsigned I = 0;\n"; 1162 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n"; 1163 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n"; 1164 O << " ++I;\n"; 1165 O << " OS << '\\t' << StringRef(AsmString, I);\n"; 1166 1167 O << " if (AsmString[I] != '\\0') {\n"; 1168 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n"; 1169 O << " OS << '\\t';\n"; 1170 O << " ++I;\n"; 1171 O << " }\n"; 1172 O << " do {\n"; 1173 O << " if (AsmString[I] == '$') {\n"; 1174 O << " ++I;\n"; 1175 O << " if (AsmString[I] == (char)0xff) {\n"; 1176 O << " ++I;\n"; 1177 O << " int OpIdx = AsmString[I++] - 1;\n"; 1178 O << " int PrintMethodIdx = AsmString[I++] - 1;\n"; 1179 O << " printCustomAliasOperand(MI, Address, OpIdx, PrintMethodIdx, "; 1180 O << (PassSubtarget ? "STI, " : ""); 1181 O << "OS);\n"; 1182 O << " } else\n"; 1183 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, "; 1184 O << (PassSubtarget ? "STI, " : ""); 1185 O << "OS);\n"; 1186 O << " } else {\n"; 1187 O << " OS << AsmString[I++];\n"; 1188 O << " }\n"; 1189 O << " } while (AsmString[I] != '\\0');\n"; 1190 O << " }\n\n"; 1191 1192 O << " return true;\n"; 1193 O << "}\n\n"; 1194 1195 ////////////////////////////// 1196 // Write out the printCustomAliasOperand function 1197 ////////////////////////////// 1198 1199 O << "void " << Target.getName() << ClassName << "::" 1200 << "printCustomAliasOperand(\n" 1201 << " const MCInst *MI, uint64_t Address, unsigned OpIdx,\n" 1202 << " unsigned PrintMethodIdx,\n" 1203 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "") 1204 << " raw_ostream &OS) {\n"; 1205 if (PrintMethods.empty()) 1206 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"; 1207 else { 1208 O << " switch (PrintMethodIdx) {\n" 1209 << " default:\n" 1210 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n" 1211 << " break;\n"; 1212 1213 for (unsigned i = 0; i < PrintMethods.size(); ++i) { 1214 O << " case " << i << ":\n" 1215 << " " << PrintMethods[i].first << "(MI, " 1216 << (PrintMethods[i].second ? "Address, " : "") << "OpIdx, " 1217 << (PassSubtarget ? "STI, " : "") << "OS);\n" 1218 << " break;\n"; 1219 } 1220 O << " }\n"; 1221 } 1222 O << "}\n\n"; 1223 1224 if (!MCOpPredicates.empty()) { 1225 O << "static bool " << Target.getName() << ClassName 1226 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1227 << " const MCSubtargetInfo &STI,\n" 1228 << " unsigned PredicateIndex) {\n" 1229 << " switch (PredicateIndex) {\n" 1230 << " default:\n" 1231 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n" 1232 << " break;\n"; 1233 1234 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) { 1235 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate"); 1236 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) { 1237 O << " case " << i + 1 << ": {\n" 1238 << SI->getValue() << "\n" 1239 << " }\n"; 1240 } else 1241 llvm_unreachable("Unexpected MCOperandPredicate field!"); 1242 } 1243 O << " }\n" 1244 << "}\n\n"; 1245 } 1246 1247 O << "#endif // PRINT_ALIAS_INSTR\n"; 1248 } 1249 1250 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) { 1251 Record *AsmWriter = Target.getAsmWriter(); 1252 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 1253 1254 // Get the instruction numbering. 1255 NumberedInstructions = Target.getInstructionsByEnumValue(); 1256 1257 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 1258 const CodeGenInstruction *I = NumberedInstructions[i]; 1259 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI") 1260 Instructions.emplace_back(*I, i, Variant); 1261 } 1262 } 1263 1264 void AsmWriterEmitter::run(raw_ostream &O) { 1265 EmitPrintInstruction(O); 1266 EmitGetRegisterName(O); 1267 EmitPrintAliasInstruction(O); 1268 } 1269 1270 namespace llvm { 1271 1272 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { 1273 emitSourceFileHeader("Assembly Writer Source Fragment", OS); 1274 AsmWriterEmitter(RK).run(OS); 1275 } 1276 1277 } // end namespace llvm 1278