1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This tablegen backend is emits an assembly printer for the current target. 11 // Note that this is currently fairly skeletal, but will grow over time. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "AsmWriterInst.h" 16 #include "CodeGenTarget.h" 17 #include "SequenceToOffsetTable.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/Format.h" 22 #include "llvm/Support/MathExtras.h" 23 #include "llvm/TableGen/Error.h" 24 #include "llvm/TableGen/Record.h" 25 #include "llvm/TableGen/TableGenBackend.h" 26 #include <algorithm> 27 #include <cassert> 28 #include <map> 29 #include <vector> 30 using namespace llvm; 31 32 #define DEBUG_TYPE "asm-writer-emitter" 33 34 namespace { 35 class AsmWriterEmitter { 36 RecordKeeper &Records; 37 CodeGenTarget Target; 38 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap; 39 const std::vector<const CodeGenInstruction*> *NumberedInstructions; 40 std::vector<AsmWriterInst> Instructions; 41 public: 42 AsmWriterEmitter(RecordKeeper &R); 43 44 void run(raw_ostream &o); 45 46 private: 47 void EmitPrintInstruction(raw_ostream &o); 48 void EmitGetRegisterName(raw_ostream &o); 49 void EmitPrintAliasInstruction(raw_ostream &O); 50 51 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const { 52 assert(ID < NumberedInstructions->size()); 53 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I = 54 CGIAWIMap.find(NumberedInstructions->at(ID)); 55 assert(I != CGIAWIMap.end() && "Didn't find inst!"); 56 return I->second; 57 } 58 void FindUniqueOperandCommands(std::vector<std::string> &UOC, 59 std::vector<unsigned> &InstIdxs, 60 std::vector<unsigned> &InstOpsUsed) const; 61 }; 62 } // end anonymous namespace 63 64 static void PrintCases(std::vector<std::pair<std::string, 65 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) { 66 O << " case " << OpsToPrint.back().first << ": "; 67 AsmWriterOperand TheOp = OpsToPrint.back().second; 68 OpsToPrint.pop_back(); 69 70 // Check to see if any other operands are identical in this list, and if so, 71 // emit a case label for them. 72 for (unsigned i = OpsToPrint.size(); i != 0; --i) 73 if (OpsToPrint[i-1].second == TheOp) { 74 O << "\n case " << OpsToPrint[i-1].first << ": "; 75 OpsToPrint.erase(OpsToPrint.begin()+i-1); 76 } 77 78 // Finally, emit the code. 79 O << TheOp.getCode(); 80 O << "break;\n"; 81 } 82 83 84 /// EmitInstructions - Emit the last instruction in the vector and any other 85 /// instructions that are suitably similar to it. 86 static void EmitInstructions(std::vector<AsmWriterInst> &Insts, 87 raw_ostream &O) { 88 AsmWriterInst FirstInst = Insts.back(); 89 Insts.pop_back(); 90 91 std::vector<AsmWriterInst> SimilarInsts; 92 unsigned DifferingOperand = ~0; 93 for (unsigned i = Insts.size(); i != 0; --i) { 94 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst); 95 if (DiffOp != ~1U) { 96 if (DifferingOperand == ~0U) // First match! 97 DifferingOperand = DiffOp; 98 99 // If this differs in the same operand as the rest of the instructions in 100 // this class, move it to the SimilarInsts list. 101 if (DifferingOperand == DiffOp || DiffOp == ~0U) { 102 SimilarInsts.push_back(Insts[i-1]); 103 Insts.erase(Insts.begin()+i-1); 104 } 105 } 106 } 107 108 O << " case " << FirstInst.CGI->Namespace << "::" 109 << FirstInst.CGI->TheDef->getName() << ":\n"; 110 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i) 111 O << " case " << SimilarInsts[i].CGI->Namespace << "::" 112 << SimilarInsts[i].CGI->TheDef->getName() << ":\n"; 113 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) { 114 if (i != DifferingOperand) { 115 // If the operand is the same for all instructions, just print it. 116 O << " " << FirstInst.Operands[i].getCode(); 117 } else { 118 // If this is the operand that varies between all of the instructions, 119 // emit a switch for just this operand now. 120 O << " switch (MI->getOpcode()) {\n"; 121 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint; 122 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" + 123 FirstInst.CGI->TheDef->getName(), 124 FirstInst.Operands[i])); 125 126 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) { 127 AsmWriterInst &AWI = SimilarInsts[si]; 128 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+ 129 AWI.CGI->TheDef->getName(), 130 AWI.Operands[i])); 131 } 132 std::reverse(OpsToPrint.begin(), OpsToPrint.end()); 133 while (!OpsToPrint.empty()) 134 PrintCases(OpsToPrint, O); 135 O << " }"; 136 } 137 O << "\n"; 138 } 139 O << " break;\n"; 140 } 141 142 void AsmWriterEmitter:: 143 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, 144 std::vector<unsigned> &InstIdxs, 145 std::vector<unsigned> &InstOpsUsed) const { 146 InstIdxs.assign(NumberedInstructions->size(), ~0U); 147 148 // This vector parallels UniqueOperandCommands, keeping track of which 149 // instructions each case are used for. It is a comma separated string of 150 // enums. 151 std::vector<std::string> InstrsForCase; 152 InstrsForCase.resize(UniqueOperandCommands.size()); 153 InstOpsUsed.assign(UniqueOperandCommands.size(), 0); 154 155 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) { 156 const AsmWriterInst *Inst = getAsmWriterInstByID(i); 157 if (!Inst) 158 continue; // PHI, INLINEASM, CFI_INSTRUCTION, etc. 159 160 std::string Command; 161 if (Inst->Operands.empty()) 162 continue; // Instruction already done. 163 164 Command = " " + Inst->Operands[0].getCode() + "\n"; 165 166 // Check to see if we already have 'Command' in UniqueOperandCommands. 167 // If not, add it. 168 bool FoundIt = false; 169 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx) 170 if (UniqueOperandCommands[idx] == Command) { 171 InstIdxs[i] = idx; 172 InstrsForCase[idx] += ", "; 173 InstrsForCase[idx] += Inst->CGI->TheDef->getName(); 174 FoundIt = true; 175 break; 176 } 177 if (!FoundIt) { 178 InstIdxs[i] = UniqueOperandCommands.size(); 179 UniqueOperandCommands.push_back(Command); 180 InstrsForCase.push_back(Inst->CGI->TheDef->getName()); 181 182 // This command matches one operand so far. 183 InstOpsUsed.push_back(1); 184 } 185 } 186 187 // For each entry of UniqueOperandCommands, there is a set of instructions 188 // that uses it. If the next command of all instructions in the set are 189 // identical, fold it into the command. 190 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size(); 191 CommandIdx != e; ++CommandIdx) { 192 193 for (unsigned Op = 1; ; ++Op) { 194 // Scan for the first instruction in the set. 195 std::vector<unsigned>::iterator NIT = 196 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx); 197 if (NIT == InstIdxs.end()) break; // No commonality. 198 199 // If this instruction has no more operands, we isn't anything to merge 200 // into this command. 201 const AsmWriterInst *FirstInst = 202 getAsmWriterInstByID(NIT-InstIdxs.begin()); 203 if (!FirstInst || FirstInst->Operands.size() == Op) 204 break; 205 206 // Otherwise, scan to see if all of the other instructions in this command 207 // set share the operand. 208 bool AllSame = true; 209 // Keep track of the maximum, number of operands or any 210 // instruction we see in the group. 211 size_t MaxSize = FirstInst->Operands.size(); 212 213 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx); 214 NIT != InstIdxs.end(); 215 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) { 216 // Okay, found another instruction in this command set. If the operand 217 // matches, we're ok, otherwise bail out. 218 const AsmWriterInst *OtherInst = 219 getAsmWriterInstByID(NIT-InstIdxs.begin()); 220 221 if (OtherInst && 222 OtherInst->Operands.size() > FirstInst->Operands.size()) 223 MaxSize = std::max(MaxSize, OtherInst->Operands.size()); 224 225 if (!OtherInst || OtherInst->Operands.size() == Op || 226 OtherInst->Operands[Op] != FirstInst->Operands[Op]) { 227 AllSame = false; 228 break; 229 } 230 } 231 if (!AllSame) break; 232 233 // Okay, everything in this command set has the same next operand. Add it 234 // to UniqueOperandCommands and remember that it was consumed. 235 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n"; 236 237 UniqueOperandCommands[CommandIdx] += Command; 238 InstOpsUsed[CommandIdx]++; 239 } 240 } 241 242 // Prepend some of the instructions each case is used for onto the case val. 243 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) { 244 std::string Instrs = InstrsForCase[i]; 245 if (Instrs.size() > 70) { 246 Instrs.erase(Instrs.begin()+70, Instrs.end()); 247 Instrs += "..."; 248 } 249 250 if (!Instrs.empty()) 251 UniqueOperandCommands[i] = " // " + Instrs + "\n" + 252 UniqueOperandCommands[i]; 253 } 254 } 255 256 257 static void UnescapeString(std::string &Str) { 258 for (unsigned i = 0; i != Str.size(); ++i) { 259 if (Str[i] == '\\' && i != Str.size()-1) { 260 switch (Str[i+1]) { 261 default: continue; // Don't execute the code after the switch. 262 case 'a': Str[i] = '\a'; break; 263 case 'b': Str[i] = '\b'; break; 264 case 'e': Str[i] = 27; break; 265 case 'f': Str[i] = '\f'; break; 266 case 'n': Str[i] = '\n'; break; 267 case 'r': Str[i] = '\r'; break; 268 case 't': Str[i] = '\t'; break; 269 case 'v': Str[i] = '\v'; break; 270 case '"': Str[i] = '\"'; break; 271 case '\'': Str[i] = '\''; break; 272 case '\\': Str[i] = '\\'; break; 273 } 274 // Nuke the second character. 275 Str.erase(Str.begin()+i+1); 276 } 277 } 278 } 279 280 /// EmitPrintInstruction - Generate the code for the "printInstruction" method 281 /// implementation. Destroys all instances of AsmWriterInst information, by 282 /// clearing the Instructions vector. 283 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { 284 Record *AsmWriter = Target.getAsmWriter(); 285 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 286 287 O << 288 "/// printInstruction - This method is automatically generated by tablegen\n" 289 "/// from the instruction set description.\n" 290 "void " << Target.getName() << ClassName 291 << "::printInstruction(const MCInst *MI, raw_ostream &O) {\n"; 292 293 // Build an aggregate string, and build a table of offsets into it. 294 SequenceToOffsetTable<std::string> StringTable; 295 296 /// OpcodeInfo - This encodes the index of the string to use for the first 297 /// chunk of the output as well as indices used for operand printing. 298 /// To reduce the number of unhandled cases, we expand the size from 32-bit 299 /// to 32+16 = 48-bit. 300 std::vector<uint64_t> OpcodeInfo; 301 302 // Add all strings to the string table upfront so it can generate an optimized 303 // representation. 304 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) { 305 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)]; 306 if (AWI && 307 AWI->Operands[0].OperandType == 308 AsmWriterOperand::isLiteralTextOperand && 309 !AWI->Operands[0].Str.empty()) { 310 std::string Str = AWI->Operands[0].Str; 311 UnescapeString(Str); 312 StringTable.add(Str); 313 } 314 } 315 316 StringTable.layout(); 317 318 unsigned MaxStringIdx = 0; 319 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) { 320 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)]; 321 unsigned Idx; 322 if (!AWI) { 323 // Something not handled by the asmwriter printer. 324 Idx = ~0U; 325 } else if (AWI->Operands[0].OperandType != 326 AsmWriterOperand::isLiteralTextOperand || 327 AWI->Operands[0].Str.empty()) { 328 // Something handled by the asmwriter printer, but with no leading string. 329 Idx = StringTable.get(""); 330 } else { 331 std::string Str = AWI->Operands[0].Str; 332 UnescapeString(Str); 333 Idx = StringTable.get(Str); 334 MaxStringIdx = std::max(MaxStringIdx, Idx); 335 336 // Nuke the string from the operand list. It is now handled! 337 AWI->Operands.erase(AWI->Operands.begin()); 338 } 339 340 // Bias offset by one since we want 0 as a sentinel. 341 OpcodeInfo.push_back(Idx+1); 342 } 343 344 // Figure out how many bits we used for the string index. 345 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2); 346 347 // To reduce code size, we compactify common instructions into a few bits 348 // in the opcode-indexed table. 349 unsigned BitsLeft = 64-AsmStrBits; 350 351 std::vector<std::vector<std::string> > TableDrivenOperandPrinters; 352 353 while (1) { 354 std::vector<std::string> UniqueOperandCommands; 355 std::vector<unsigned> InstIdxs; 356 std::vector<unsigned> NumInstOpsHandled; 357 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs, 358 NumInstOpsHandled); 359 360 // If we ran out of operands to print, we're done. 361 if (UniqueOperandCommands.empty()) break; 362 363 // Compute the number of bits we need to represent these cases, this is 364 // ceil(log2(numentries)). 365 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size()); 366 367 // If we don't have enough bits for this operand, don't include it. 368 if (NumBits > BitsLeft) { 369 DEBUG(errs() << "Not enough bits to densely encode " << NumBits 370 << " more bits\n"); 371 break; 372 } 373 374 // Otherwise, we can include this in the initial lookup table. Add it in. 375 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i) 376 if (InstIdxs[i] != ~0U) { 377 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft); 378 } 379 BitsLeft -= NumBits; 380 381 // Remove the info about this operand. 382 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) { 383 if (AsmWriterInst *Inst = getAsmWriterInstByID(i)) 384 if (!Inst->Operands.empty()) { 385 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]]; 386 assert(NumOps <= Inst->Operands.size() && 387 "Can't remove this many ops!"); 388 Inst->Operands.erase(Inst->Operands.begin(), 389 Inst->Operands.begin()+NumOps); 390 } 391 } 392 393 // Remember the handlers for this set of operands. 394 TableDrivenOperandPrinters.push_back(UniqueOperandCommands); 395 } 396 397 398 // We always emit at least one 32-bit table. A second table is emitted if 399 // more bits are needed. 400 O<<" static const uint32_t OpInfo[] = {\n"; 401 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) { 402 O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// " 403 << NumberedInstructions->at(i)->TheDef->getName() << "\n"; 404 } 405 // Add a dummy entry so the array init doesn't end with a comma. 406 O << " 0U\n"; 407 O << " };\n\n"; 408 409 if (BitsLeft < 32) { 410 // Add a second OpInfo table only when it is necessary. 411 // Adjust the type of the second table based on the number of bits needed. 412 O << " static const uint" 413 << ((BitsLeft < 16) ? "32" : (BitsLeft < 24) ? "16" : "8") 414 << "_t OpInfo2[] = {\n"; 415 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) { 416 O << " " << (OpcodeInfo[i] >> 32) << "U,\t// " 417 << NumberedInstructions->at(i)->TheDef->getName() << "\n"; 418 } 419 // Add a dummy entry so the array init doesn't end with a comma. 420 O << " 0U\n"; 421 O << " };\n\n"; 422 } 423 424 // Emit the string itself. 425 O << " const char AsmStrs[] = {\n"; 426 StringTable.emit(O, printChar); 427 O << " };\n\n"; 428 429 O << " O << \"\\t\";\n\n"; 430 431 O << " // Emit the opcode for the instruction.\n"; 432 if (BitsLeft < 32) { 433 // If we have two tables then we need to perform two lookups and combine 434 // the results into a single 64-bit value. 435 O << " uint64_t Bits1 = OpInfo[MI->getOpcode()];\n" 436 << " uint64_t Bits2 = OpInfo2[MI->getOpcode()];\n" 437 << " uint64_t Bits = (Bits2 << 32) | Bits1;\n"; 438 } else { 439 // If only one table is used we just need to perform a single lookup. 440 O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n"; 441 } 442 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n" 443 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n"; 444 445 // Output the table driven operand information. 446 BitsLeft = 64-AsmStrBits; 447 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) { 448 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i]; 449 450 // Compute the number of bits we need to represent these cases, this is 451 // ceil(log2(numentries)). 452 unsigned NumBits = Log2_32_Ceil(Commands.size()); 453 assert(NumBits <= BitsLeft && "consistency error"); 454 455 // Emit code to extract this field from Bits. 456 O << "\n // Fragment " << i << " encoded into " << NumBits 457 << " bits for " << Commands.size() << " unique commands.\n"; 458 459 if (Commands.size() == 2) { 460 // Emit two possibilitys with if/else. 461 O << " if ((Bits >> " 462 << (64-BitsLeft) << ") & " 463 << ((1 << NumBits)-1) << ") {\n" 464 << Commands[1] 465 << " } else {\n" 466 << Commands[0] 467 << " }\n\n"; 468 } else if (Commands.size() == 1) { 469 // Emit a single possibility. 470 O << Commands[0] << "\n\n"; 471 } else { 472 O << " switch ((Bits >> " 473 << (64-BitsLeft) << ") & " 474 << ((1 << NumBits)-1) << ") {\n" 475 << " default: // unreachable.\n"; 476 477 // Print out all the cases. 478 for (unsigned i = 0, e = Commands.size(); i != e; ++i) { 479 O << " case " << i << ":\n"; 480 O << Commands[i]; 481 O << " break;\n"; 482 } 483 O << " }\n\n"; 484 } 485 BitsLeft -= NumBits; 486 } 487 488 // Okay, delete instructions with no operand info left. 489 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) { 490 // Entire instruction has been emitted? 491 AsmWriterInst &Inst = Instructions[i]; 492 if (Inst.Operands.empty()) { 493 Instructions.erase(Instructions.begin()+i); 494 --i; --e; 495 } 496 } 497 498 499 // Because this is a vector, we want to emit from the end. Reverse all of the 500 // elements in the vector. 501 std::reverse(Instructions.begin(), Instructions.end()); 502 503 504 // Now that we've emitted all of the operand info that fit into 32 bits, emit 505 // information for those instructions that are left. This is a less dense 506 // encoding, but we expect the main 32-bit table to handle the majority of 507 // instructions. 508 if (!Instructions.empty()) { 509 // Find the opcode # of inline asm. 510 O << " switch (MI->getOpcode()) {\n"; 511 while (!Instructions.empty()) 512 EmitInstructions(Instructions, O); 513 514 O << " }\n"; 515 O << " return;\n"; 516 } 517 518 O << "}\n"; 519 } 520 521 static void 522 emitRegisterNameString(raw_ostream &O, StringRef AltName, 523 const std::vector<CodeGenRegister*> &Registers) { 524 SequenceToOffsetTable<std::string> StringTable; 525 SmallVector<std::string, 4> AsmNames(Registers.size()); 526 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 527 const CodeGenRegister &Reg = *Registers[i]; 528 std::string &AsmName = AsmNames[i]; 529 530 // "NoRegAltName" is special. We don't need to do a lookup for that, 531 // as it's just a reference to the default register name. 532 if (AltName == "" || AltName == "NoRegAltName") { 533 AsmName = Reg.TheDef->getValueAsString("AsmName"); 534 if (AsmName.empty()) 535 AsmName = Reg.getName(); 536 } else { 537 // Make sure the register has an alternate name for this index. 538 std::vector<Record*> AltNameList = 539 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices"); 540 unsigned Idx = 0, e; 541 for (e = AltNameList.size(); 542 Idx < e && (AltNameList[Idx]->getName() != AltName); 543 ++Idx) 544 ; 545 // If the register has an alternate name for this index, use it. 546 // Otherwise, leave it empty as an error flag. 547 if (Idx < e) { 548 std::vector<std::string> AltNames = 549 Reg.TheDef->getValueAsListOfStrings("AltNames"); 550 if (AltNames.size() <= Idx) 551 PrintFatalError(Reg.TheDef->getLoc(), 552 "Register definition missing alt name for '" + 553 AltName + "'."); 554 AsmName = AltNames[Idx]; 555 } 556 } 557 StringTable.add(AsmName); 558 } 559 560 StringTable.layout(); 561 O << " static const char AsmStrs" << AltName << "[] = {\n"; 562 StringTable.emit(O, printChar); 563 O << " };\n\n"; 564 565 O << " static const uint32_t RegAsmOffset" << AltName << "[] = {"; 566 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 567 if ((i % 14) == 0) 568 O << "\n "; 569 O << StringTable.get(AsmNames[i]) << ", "; 570 } 571 O << "\n };\n" 572 << "\n"; 573 } 574 575 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { 576 Record *AsmWriter = Target.getAsmWriter(); 577 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 578 const std::vector<CodeGenRegister*> &Registers = 579 Target.getRegBank().getRegisters(); 580 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices(); 581 bool hasAltNames = AltNameIndices.size() > 1; 582 583 O << 584 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n" 585 "/// from the register set description. This returns the assembler name\n" 586 "/// for the specified register.\n" 587 "const char *" << Target.getName() << ClassName << "::"; 588 if (hasAltNames) 589 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n"; 590 else 591 O << "getRegisterName(unsigned RegNo) {\n"; 592 O << " assert(RegNo && RegNo < " << (Registers.size()+1) 593 << " && \"Invalid register number!\");\n" 594 << "\n"; 595 596 if (hasAltNames) { 597 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) 598 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers); 599 } else 600 emitRegisterNameString(O, "", Registers); 601 602 if (hasAltNames) { 603 O << " const uint32_t *RegAsmOffset;\n" 604 << " const char *AsmStrs;\n" 605 << " switch(AltIdx) {\n" 606 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n"; 607 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) { 608 std::string Namespace = AltNameIndices[1]->getValueAsString("Namespace"); 609 std::string AltName(AltNameIndices[i]->getName()); 610 O << " case " << Namespace << "::" << AltName 611 << ":\n" 612 << " AsmStrs = AsmStrs" << AltName << ";\n" 613 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n" 614 << " break;\n"; 615 } 616 O << "}\n"; 617 } 618 619 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n" 620 << " \"Invalid alt name index for register!\");\n" 621 << " return AsmStrs+RegAsmOffset[RegNo-1];\n" 622 << "}\n"; 623 } 624 625 namespace { 626 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if 627 // they both have the same conditionals. In which case, we cannot print out the 628 // alias for that pattern. 629 class IAPrinter { 630 std::vector<std::string> Conds; 631 std::map<StringRef, unsigned> OpMap; 632 std::string Result; 633 std::string AsmString; 634 SmallVector<Record*, 4> ReqFeatures; 635 public: 636 IAPrinter(std::string R, std::string AS) 637 : Result(R), AsmString(AS) {} 638 639 void addCond(const std::string &C) { Conds.push_back(C); } 640 641 void addOperand(StringRef Op, unsigned Idx) { 642 assert(Idx < 0xFF && "Index too large!"); 643 OpMap[Op] = Idx; 644 } 645 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; } 646 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); } 647 648 void print(raw_ostream &O) { 649 if (Conds.empty() && ReqFeatures.empty()) { 650 O.indent(6) << "return true;\n"; 651 return; 652 } 653 654 O << "if ("; 655 656 for (std::vector<std::string>::iterator 657 I = Conds.begin(), E = Conds.end(); I != E; ++I) { 658 if (I != Conds.begin()) { 659 O << " &&\n"; 660 O.indent(8); 661 } 662 663 O << *I; 664 } 665 666 O << ") {\n"; 667 O.indent(6) << "// " << Result << "\n"; 668 669 // Directly mangle mapped operands into the string. Each operand is 670 // identified by a '$' sign followed by a byte identifying the number of the 671 // operand. We add one to the index to avoid zero bytes. 672 std::pair<StringRef, StringRef> ASM = StringRef(AsmString).split(' '); 673 SmallString<128> OutString = ASM.first; 674 if (!ASM.second.empty()) { 675 raw_svector_ostream OS(OutString); 676 OS << ' '; 677 for (StringRef::iterator I = ASM.second.begin(), E = ASM.second.end(); 678 I != E;) { 679 OS << *I; 680 if (*I == '$') { 681 StringRef::iterator Start = ++I; 682 while (I != E && 683 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') || 684 (*I >= '0' && *I <= '9') || *I == '_')) 685 ++I; 686 StringRef Name(Start, I - Start); 687 assert(isOpMapped(Name) && "Unmapped operand!"); 688 OS << format("\\x%02X", (unsigned char)getOpIndex(Name) + 1); 689 } else { 690 ++I; 691 } 692 } 693 } 694 695 // Emit the string. 696 O.indent(6) << "AsmString = \"" << OutString.str() << "\";\n"; 697 698 O.indent(6) << "break;\n"; 699 O.indent(4) << '}'; 700 } 701 702 bool operator==(const IAPrinter &RHS) { 703 if (Conds.size() != RHS.Conds.size()) 704 return false; 705 706 unsigned Idx = 0; 707 for (std::vector<std::string>::iterator 708 I = Conds.begin(), E = Conds.end(); I != E; ++I) 709 if (*I != RHS.Conds[Idx++]) 710 return false; 711 712 return true; 713 } 714 }; 715 716 } // end anonymous namespace 717 718 static unsigned CountNumOperands(StringRef AsmString) { 719 unsigned NumOps = 0; 720 std::pair<StringRef, StringRef> ASM = AsmString.split(' '); 721 722 while (!ASM.second.empty()) { 723 ++NumOps; 724 ASM = ASM.second.split(' '); 725 } 726 727 return NumOps; 728 } 729 730 static unsigned CountResultNumOperands(StringRef AsmString) { 731 unsigned NumOps = 0; 732 std::pair<StringRef, StringRef> ASM = AsmString.split('\t'); 733 734 if (!ASM.second.empty()) { 735 size_t I = ASM.second.find('{'); 736 StringRef Str = ASM.second; 737 if (I != StringRef::npos) 738 Str = ASM.second.substr(I, ASM.second.find('|', I)); 739 740 ASM = Str.split(' '); 741 742 do { 743 ++NumOps; 744 ASM = ASM.second.split(' '); 745 } while (!ASM.second.empty()); 746 } 747 748 return NumOps; 749 } 750 751 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { 752 Record *AsmWriter = Target.getAsmWriter(); 753 754 O << "\n#ifdef PRINT_ALIAS_INSTR\n"; 755 O << "#undef PRINT_ALIAS_INSTR\n\n"; 756 757 // Emit the method that prints the alias instruction. 758 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 759 760 std::vector<Record*> AllInstAliases = 761 Records.getAllDerivedDefinitions("InstAlias"); 762 763 // Create a map from the qualified name to a list of potential matches. 764 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap; 765 for (std::vector<Record*>::iterator 766 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) { 767 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target); 768 const Record *R = *I; 769 if (!R->getValueAsBit("EmitAlias")) 770 continue; // We were told not to emit the alias, but to emit the aliasee. 771 const DagInit *DI = R->getValueAsDag("ResultInst"); 772 const DefInit *Op = cast<DefInit>(DI->getOperator()); 773 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias); 774 } 775 776 // A map of which conditions need to be met for each instruction operand 777 // before it can be matched to the mnemonic. 778 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap; 779 780 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator 781 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) { 782 std::vector<CodeGenInstAlias*> &Aliases = I->second; 783 784 for (std::vector<CodeGenInstAlias*>::iterator 785 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) { 786 const CodeGenInstAlias *CGA = *II; 787 unsigned LastOpNo = CGA->ResultInstOperandIndex.size(); 788 unsigned NumResultOps = 789 CountResultNumOperands(CGA->ResultInst->AsmString); 790 791 // Don't emit the alias if it has more operands than what it's aliasing. 792 if (NumResultOps < CountNumOperands(CGA->AsmString)) 793 continue; 794 795 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(), 796 CGA->AsmString); 797 798 std::string Cond; 799 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo); 800 IAP->addCond(Cond); 801 802 bool CantHandle = false; 803 804 for (unsigned i = 0, e = LastOpNo; i != e; ++i) { 805 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i]; 806 807 switch (RO.Kind) { 808 case CodeGenInstAlias::ResultOperand::K_Record: { 809 const Record *Rec = RO.getRecord(); 810 StringRef ROName = RO.getName(); 811 812 813 if (Rec->isSubClassOf("RegisterOperand")) 814 Rec = Rec->getValueAsDef("RegClass"); 815 if (Rec->isSubClassOf("RegisterClass")) { 816 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()"; 817 IAP->addCond(Cond); 818 819 if (!IAP->isOpMapped(ROName)) { 820 IAP->addOperand(ROName, i); 821 Record *R = CGA->ResultOperands[i].getRecord(); 822 if (R->isSubClassOf("RegisterOperand")) 823 R = R->getValueAsDef("RegClass"); 824 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" + 825 R->getName() + "RegClassID)" 826 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())"; 827 IAP->addCond(Cond); 828 } else { 829 Cond = std::string("MI->getOperand(") + 830 llvm::utostr(i) + ").getReg() == MI->getOperand(" + 831 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()"; 832 IAP->addCond(Cond); 833 } 834 } else { 835 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 836 // FIXME: We may need to handle these situations. 837 delete IAP; 838 IAP = nullptr; 839 CantHandle = true; 840 break; 841 } 842 843 break; 844 } 845 case CodeGenInstAlias::ResultOperand::K_Imm: { 846 std::string Op = "MI->getOperand(" + llvm::utostr(i) + ")"; 847 848 // Just because the alias has an immediate result, doesn't mean the 849 // MCInst will. An MCExpr could be present, for example. 850 IAP->addCond(Op + ".isImm()"); 851 852 Cond = Op + ".getImm() == " 853 + llvm::utostr(CGA->ResultOperands[i].getImm()); 854 IAP->addCond(Cond); 855 break; 856 } 857 case CodeGenInstAlias::ResultOperand::K_Reg: 858 // If this is zero_reg, something's playing tricks we're not 859 // equipped to handle. 860 if (!CGA->ResultOperands[i].getRegister()) { 861 CantHandle = true; 862 break; 863 } 864 865 Cond = std::string("MI->getOperand(") + 866 llvm::utostr(i) + ").getReg() == " + Target.getName() + 867 "::" + CGA->ResultOperands[i].getRegister()->getName(); 868 IAP->addCond(Cond); 869 break; 870 } 871 872 if (!IAP) break; 873 } 874 875 if (CantHandle) continue; 876 IAPrinterMap[I->first].push_back(IAP); 877 } 878 } 879 880 std::string Header; 881 raw_string_ostream HeaderO(Header); 882 883 HeaderO << "bool " << Target.getName() << ClassName 884 << "::printAliasInstr(const MCInst" 885 << " *MI, raw_ostream &OS) {\n"; 886 887 std::string Cases; 888 raw_string_ostream CasesO(Cases); 889 890 for (std::map<std::string, std::vector<IAPrinter*> >::iterator 891 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) { 892 std::vector<IAPrinter*> &IAPs = I->second; 893 std::vector<IAPrinter*> UniqueIAPs; 894 895 for (std::vector<IAPrinter*>::iterator 896 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) { 897 IAPrinter *LHS = *II; 898 bool IsDup = false; 899 for (std::vector<IAPrinter*>::iterator 900 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) { 901 IAPrinter *RHS = *III; 902 if (LHS != RHS && *LHS == *RHS) { 903 IsDup = true; 904 break; 905 } 906 } 907 908 if (!IsDup) UniqueIAPs.push_back(LHS); 909 } 910 911 if (UniqueIAPs.empty()) continue; 912 913 CasesO.indent(2) << "case " << I->first << ":\n"; 914 915 for (std::vector<IAPrinter*>::iterator 916 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) { 917 IAPrinter *IAP = *II; 918 CasesO.indent(4); 919 IAP->print(CasesO); 920 CasesO << '\n'; 921 } 922 923 CasesO.indent(4) << "return false;\n"; 924 } 925 926 if (CasesO.str().empty()) { 927 O << HeaderO.str(); 928 O << " return false;\n"; 929 O << "}\n\n"; 930 O << "#endif // PRINT_ALIAS_INSTR\n"; 931 return; 932 } 933 934 O << HeaderO.str(); 935 O.indent(2) << "const char *AsmString;\n"; 936 O.indent(2) << "switch (MI->getOpcode()) {\n"; 937 O.indent(2) << "default: return false;\n"; 938 O << CasesO.str(); 939 O.indent(2) << "}\n\n"; 940 941 // Code that prints the alias, replacing the operands with the ones from the 942 // MCInst. 943 O << " unsigned I = 0;\n"; 944 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\0')\n"; 945 O << " ++I;\n"; 946 O << " OS << '\\t' << StringRef(AsmString, I);\n"; 947 948 O << " if (AsmString[I] != '\\0') {\n"; 949 O << " OS << '\\t';\n"; 950 O << " do {\n"; 951 O << " if (AsmString[I] == '$') {\n"; 952 O << " ++I;\n"; 953 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, OS);\n"; 954 O << " } else {\n"; 955 O << " OS << AsmString[I++];\n"; 956 O << " }\n"; 957 O << " } while (AsmString[I] != '\\0');\n"; 958 O << " }\n\n"; 959 960 O << " return true;\n"; 961 O << "}\n\n"; 962 963 O << "#endif // PRINT_ALIAS_INSTR\n"; 964 } 965 966 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) { 967 Record *AsmWriter = Target.getAsmWriter(); 968 for (CodeGenTarget::inst_iterator I = Target.inst_begin(), 969 E = Target.inst_end(); 970 I != E; ++I) 971 if (!(*I)->AsmString.empty() && (*I)->TheDef->getName() != "PHI") 972 Instructions.push_back( 973 AsmWriterInst(**I, AsmWriter->getValueAsInt("Variant"), 974 AsmWriter->getValueAsInt("OperandSpacing"))); 975 976 // Get the instruction numbering. 977 NumberedInstructions = &Target.getInstructionsByEnumValue(); 978 979 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not 980 // all machine instructions are necessarily being printed, so there may be 981 // target instructions not in this map. 982 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) 983 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i])); 984 } 985 986 void AsmWriterEmitter::run(raw_ostream &O) { 987 EmitPrintInstruction(O); 988 EmitGetRegisterName(O); 989 EmitPrintAliasInstruction(O); 990 } 991 992 993 namespace llvm { 994 995 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { 996 emitSourceFileHeader("Assembly Writer Source Fragment", OS); 997 AsmWriterEmitter(RK).run(OS); 998 } 999 1000 } // End llvm namespace 1001