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