AsmWriterEmitter.cpp revision 199481
150477Speter//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===// 245699Sdes// 3101043Sdes// The LLVM Compiler Infrastructure 445699Sdes// 5336039Sjamie// This file is distributed under the University of Illinois Open Source 6336039Sjamie// License. See LICENSE.TXT for details. 7336039Sjamie// 845699Sdes//===----------------------------------------------------------------------===// 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 "AsmWriterEmitter.h" 16#include "CodeGenTarget.h" 17#include "Record.h" 18#include "StringToOffsetTable.h" 19#include "llvm/ADT/StringExtras.h" 20#include "llvm/Support/Debug.h" 21#include "llvm/Support/MathExtras.h" 22#include <algorithm> 23using namespace llvm; 24 25 26static bool isIdentChar(char C) { 27 return (C >= 'a' && C <= 'z') || 28 (C >= 'A' && C <= 'Z') || 29 (C >= '0' && C <= '9') || 30 C == '_'; 31} 32 33// This should be an anon namespace, this works around a GCC warning. 34namespace llvm { 35 struct AsmWriterOperand { 36 enum OpType { 37 // Output this text surrounded by quotes to the asm. 38 isLiteralTextOperand, 39 // This is the name of a routine to call to print the operand. 40 isMachineInstrOperand, 41 // Output this text verbatim to the asm writer. It is code that 42 // will output some text to the asm. 43 isLiteralStatementOperand 44 } OperandType; 45 46 /// Str - For isLiteralTextOperand, this IS the literal text. For 47 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.. 48 /// For isLiteralStatementOperand, this is the code to insert verbatim 49 /// into the asm writer. 50 std::string Str; 51 52 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the 53 /// machine instruction. 54 unsigned MIOpNo; 55 56 /// MiModifier - For isMachineInstrOperand, this is the modifier string for 57 /// an operand, specified with syntax like ${opname:modifier}. 58 std::string MiModifier; 59 60 // To make VS STL happy 61 AsmWriterOperand(OpType op = isLiteralTextOperand):OperandType(op) {} 62 63 AsmWriterOperand(const std::string &LitStr, 64 OpType op = isLiteralTextOperand) 65 : OperandType(op), Str(LitStr) {} 66 67 AsmWriterOperand(const std::string &Printer, unsigned OpNo, 68 const std::string &Modifier, 69 OpType op = isMachineInstrOperand) 70 : OperandType(op), Str(Printer), MIOpNo(OpNo), 71 MiModifier(Modifier) {} 72 73 bool operator!=(const AsmWriterOperand &Other) const { 74 if (OperandType != Other.OperandType || Str != Other.Str) return true; 75 if (OperandType == isMachineInstrOperand) 76 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier; 77 return false; 78 } 79 bool operator==(const AsmWriterOperand &Other) const { 80 return !operator!=(Other); 81 } 82 83 /// getCode - Return the code that prints this operand. 84 std::string getCode() const; 85 }; 86} 87 88namespace llvm { 89 class AsmWriterInst { 90 public: 91 std::vector<AsmWriterOperand> Operands; 92 const CodeGenInstruction *CGI; 93 94 AsmWriterInst(const CodeGenInstruction &CGI, Record *AsmWriter); 95 96 /// MatchesAllButOneOp - If this instruction is exactly identical to the 97 /// specified instruction except for one differing operand, return the 98 /// differing operand number. Otherwise return ~0. 99 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const; 100 101 private: 102 void AddLiteralString(const std::string &Str) { 103 // If the last operand was already a literal text string, append this to 104 // it, otherwise add a new operand. 105 if (!Operands.empty() && 106 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand) 107 Operands.back().Str.append(Str); 108 else 109 Operands.push_back(AsmWriterOperand(Str)); 110 } 111 }; 112} 113 114 115std::string AsmWriterOperand::getCode() const { 116 if (OperandType == isLiteralTextOperand) { 117 if (Str.size() == 1) 118 return "O << '" + Str + "'; "; 119 return "O << \"" + Str + "\"; "; 120 } 121 122 if (OperandType == isLiteralStatementOperand) 123 return Str; 124 125 std::string Result = Str + "(MI"; 126 if (MIOpNo != ~0U) 127 Result += ", " + utostr(MIOpNo); 128 if (!MiModifier.empty()) 129 Result += ", \"" + MiModifier + '"'; 130 return Result + "); "; 131} 132 133 134/// ParseAsmString - Parse the specified Instruction's AsmString into this 135/// AsmWriterInst. 136/// 137AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, Record *AsmWriter) { 138 this->CGI = &CGI; 139 140 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 141 int FirstOperandColumn = AsmWriter->getValueAsInt("FirstOperandColumn"); 142 int OperandSpacing = AsmWriter->getValueAsInt("OperandSpacing"); 143 144 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #. 145 146 // This is the number of tabs we've seen if we're doing columnar layout. 147 unsigned CurColumn = 0; 148 149 150 // NOTE: Any extensions to this code need to be mirrored in the 151 // AsmPrinter::printInlineAsm code that executes as compile time (assuming 152 // that inline asm strings should also get the new feature)! 153 const std::string &AsmString = CGI.AsmString; 154 std::string::size_type LastEmitted = 0; 155 while (LastEmitted != AsmString.size()) { 156 std::string::size_type DollarPos = 157 AsmString.find_first_of("${|}\\", LastEmitted); 158 if (DollarPos == std::string::npos) DollarPos = AsmString.size(); 159 160 // Emit a constant string fragment. 161 162 if (DollarPos != LastEmitted) { 163 if (CurVariant == Variant || CurVariant == ~0U) { 164 for (; LastEmitted != DollarPos; ++LastEmitted) 165 switch (AsmString[LastEmitted]) { 166 case '\n': 167 AddLiteralString("\\n"); 168 break; 169 case '\t': 170 // If the asm writer is not using a columnar layout, \t is not 171 // magic. 172 if (FirstOperandColumn == -1 || OperandSpacing == -1) { 173 AddLiteralString("\\t"); 174 } else { 175 // We recognize a tab as an operand delimeter. 176 unsigned DestColumn = FirstOperandColumn + 177 CurColumn++ * OperandSpacing; 178 Operands.push_back( 179 AsmWriterOperand("O.PadToColumn(" + 180 utostr(DestColumn) + ");\n", 181 AsmWriterOperand::isLiteralStatementOperand)); 182 } 183 break; 184 case '"': 185 AddLiteralString("\\\""); 186 break; 187 case '\\': 188 AddLiteralString("\\\\"); 189 break; 190 default: 191 AddLiteralString(std::string(1, AsmString[LastEmitted])); 192 break; 193 } 194 } else { 195 LastEmitted = DollarPos; 196 } 197 } else if (AsmString[DollarPos] == '\\') { 198 if (DollarPos+1 != AsmString.size() && 199 (CurVariant == Variant || CurVariant == ~0U)) { 200 if (AsmString[DollarPos+1] == 'n') { 201 AddLiteralString("\\n"); 202 } else if (AsmString[DollarPos+1] == 't') { 203 // If the asm writer is not using a columnar layout, \t is not 204 // magic. 205 if (FirstOperandColumn == -1 || OperandSpacing == -1) { 206 AddLiteralString("\\t"); 207 break; 208 } 209 210 // We recognize a tab as an operand delimeter. 211 unsigned DestColumn = FirstOperandColumn + 212 CurColumn++ * OperandSpacing; 213 Operands.push_back( 214 AsmWriterOperand("O.PadToColumn(" + utostr(DestColumn) + ");\n", 215 AsmWriterOperand::isLiteralStatementOperand)); 216 break; 217 } else if (std::string("${|}\\").find(AsmString[DollarPos+1]) 218 != std::string::npos) { 219 AddLiteralString(std::string(1, AsmString[DollarPos+1])); 220 } else { 221 throw "Non-supported escaped character found in instruction '" + 222 CGI.TheDef->getName() + "'!"; 223 } 224 LastEmitted = DollarPos+2; 225 continue; 226 } 227 } else if (AsmString[DollarPos] == '{') { 228 if (CurVariant != ~0U) 229 throw "Nested variants found for instruction '" + 230 CGI.TheDef->getName() + "'!"; 231 LastEmitted = DollarPos+1; 232 CurVariant = 0; // We are now inside of the variant! 233 } else if (AsmString[DollarPos] == '|') { 234 if (CurVariant == ~0U) 235 throw "'|' character found outside of a variant in instruction '" 236 + CGI.TheDef->getName() + "'!"; 237 ++CurVariant; 238 ++LastEmitted; 239 } else if (AsmString[DollarPos] == '}') { 240 if (CurVariant == ~0U) 241 throw "'}' character found outside of a variant in instruction '" 242 + CGI.TheDef->getName() + "'!"; 243 ++LastEmitted; 244 CurVariant = ~0U; 245 } else if (DollarPos+1 != AsmString.size() && 246 AsmString[DollarPos+1] == '$') { 247 if (CurVariant == Variant || CurVariant == ~0U) { 248 AddLiteralString("$"); // "$$" -> $ 249 } 250 LastEmitted = DollarPos+2; 251 } else { 252 // Get the name of the variable. 253 std::string::size_type VarEnd = DollarPos+1; 254 255 // handle ${foo}bar as $foo by detecting whether the character following 256 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos 257 // so the variable name does not contain the leading curly brace. 258 bool hasCurlyBraces = false; 259 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) { 260 hasCurlyBraces = true; 261 ++DollarPos; 262 ++VarEnd; 263 } 264 265 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd])) 266 ++VarEnd; 267 std::string VarName(AsmString.begin()+DollarPos+1, 268 AsmString.begin()+VarEnd); 269 270 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed 271 // into printOperand. Also support ${:feature}, which is passed into 272 // PrintSpecial. 273 std::string Modifier; 274 275 // In order to avoid starting the next string at the terminating curly 276 // brace, advance the end position past it if we found an opening curly 277 // brace. 278 if (hasCurlyBraces) { 279 if (VarEnd >= AsmString.size()) 280 throw "Reached end of string before terminating curly brace in '" 281 + CGI.TheDef->getName() + "'"; 282 283 // Look for a modifier string. 284 if (AsmString[VarEnd] == ':') { 285 ++VarEnd; 286 if (VarEnd >= AsmString.size()) 287 throw "Reached end of string before terminating curly brace in '" 288 + CGI.TheDef->getName() + "'"; 289 290 unsigned ModifierStart = VarEnd; 291 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd])) 292 ++VarEnd; 293 Modifier = std::string(AsmString.begin()+ModifierStart, 294 AsmString.begin()+VarEnd); 295 if (Modifier.empty()) 296 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'"; 297 } 298 299 if (AsmString[VarEnd] != '}') 300 throw "Variable name beginning with '{' did not end with '}' in '" 301 + CGI.TheDef->getName() + "'"; 302 ++VarEnd; 303 } 304 if (VarName.empty() && Modifier.empty()) 305 throw "Stray '$' in '" + CGI.TheDef->getName() + 306 "' asm string, maybe you want $$?"; 307 308 if (VarName.empty()) { 309 // Just a modifier, pass this into PrintSpecial. 310 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier)); 311 } else { 312 // Otherwise, normal operand. 313 unsigned OpNo = CGI.getOperandNamed(VarName); 314 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo]; 315 316 if (CurVariant == Variant || CurVariant == ~0U) { 317 unsigned MIOp = OpInfo.MIOperandNo; 318 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp, 319 Modifier)); 320 } 321 } 322 LastEmitted = VarEnd; 323 } 324 } 325 326 Operands.push_back(AsmWriterOperand("return;", 327 AsmWriterOperand::isLiteralStatementOperand)); 328} 329 330/// MatchesAllButOneOp - If this instruction is exactly identical to the 331/// specified instruction except for one differing operand, return the differing 332/// operand number. If more than one operand mismatches, return ~1, otherwise 333/// if the instructions are identical return ~0. 334unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{ 335 if (Operands.size() != Other.Operands.size()) return ~1; 336 337 unsigned MismatchOperand = ~0U; 338 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 339 if (Operands[i] != Other.Operands[i]) { 340 if (MismatchOperand != ~0U) // Already have one mismatch? 341 return ~1U; 342 else 343 MismatchOperand = i; 344 } 345 } 346 return MismatchOperand; 347} 348 349static void PrintCases(std::vector<std::pair<std::string, 350 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) { 351 O << " case " << OpsToPrint.back().first << ": "; 352 AsmWriterOperand TheOp = OpsToPrint.back().second; 353 OpsToPrint.pop_back(); 354 355 // Check to see if any other operands are identical in this list, and if so, 356 // emit a case label for them. 357 for (unsigned i = OpsToPrint.size(); i != 0; --i) 358 if (OpsToPrint[i-1].second == TheOp) { 359 O << "\n case " << OpsToPrint[i-1].first << ": "; 360 OpsToPrint.erase(OpsToPrint.begin()+i-1); 361 } 362 363 // Finally, emit the code. 364 O << TheOp.getCode(); 365 O << "break;\n"; 366} 367 368 369/// EmitInstructions - Emit the last instruction in the vector and any other 370/// instructions that are suitably similar to it. 371static void EmitInstructions(std::vector<AsmWriterInst> &Insts, 372 raw_ostream &O) { 373 AsmWriterInst FirstInst = Insts.back(); 374 Insts.pop_back(); 375 376 std::vector<AsmWriterInst> SimilarInsts; 377 unsigned DifferingOperand = ~0; 378 for (unsigned i = Insts.size(); i != 0; --i) { 379 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst); 380 if (DiffOp != ~1U) { 381 if (DifferingOperand == ~0U) // First match! 382 DifferingOperand = DiffOp; 383 384 // If this differs in the same operand as the rest of the instructions in 385 // this class, move it to the SimilarInsts list. 386 if (DifferingOperand == DiffOp || DiffOp == ~0U) { 387 SimilarInsts.push_back(Insts[i-1]); 388 Insts.erase(Insts.begin()+i-1); 389 } 390 } 391 } 392 393 O << " case " << FirstInst.CGI->Namespace << "::" 394 << FirstInst.CGI->TheDef->getName() << ":\n"; 395 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i) 396 O << " case " << SimilarInsts[i].CGI->Namespace << "::" 397 << SimilarInsts[i].CGI->TheDef->getName() << ":\n"; 398 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) { 399 if (i != DifferingOperand) { 400 // If the operand is the same for all instructions, just print it. 401 O << " " << FirstInst.Operands[i].getCode(); 402 } else { 403 // If this is the operand that varies between all of the instructions, 404 // emit a switch for just this operand now. 405 O << " switch (MI->getOpcode()) {\n"; 406 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint; 407 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" + 408 FirstInst.CGI->TheDef->getName(), 409 FirstInst.Operands[i])); 410 411 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) { 412 AsmWriterInst &AWI = SimilarInsts[si]; 413 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+ 414 AWI.CGI->TheDef->getName(), 415 AWI.Operands[i])); 416 } 417 std::reverse(OpsToPrint.begin(), OpsToPrint.end()); 418 while (!OpsToPrint.empty()) 419 PrintCases(OpsToPrint, O); 420 O << " }"; 421 } 422 O << "\n"; 423 } 424 O << " break;\n"; 425} 426 427void AsmWriterEmitter:: 428FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, 429 std::vector<unsigned> &InstIdxs, 430 std::vector<unsigned> &InstOpsUsed) const { 431 InstIdxs.assign(NumberedInstructions.size(), ~0U); 432 433 // This vector parallels UniqueOperandCommands, keeping track of which 434 // instructions each case are used for. It is a comma separated string of 435 // enums. 436 std::vector<std::string> InstrsForCase; 437 InstrsForCase.resize(UniqueOperandCommands.size()); 438 InstOpsUsed.assign(UniqueOperandCommands.size(), 0); 439 440 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 441 const AsmWriterInst *Inst = getAsmWriterInstByID(i); 442 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc. 443 444 std::string Command; 445 if (Inst->Operands.empty()) 446 continue; // Instruction already done. 447 448 Command = " " + Inst->Operands[0].getCode() + "\n"; 449 450 // Check to see if we already have 'Command' in UniqueOperandCommands. 451 // If not, add it. 452 bool FoundIt = false; 453 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx) 454 if (UniqueOperandCommands[idx] == Command) { 455 InstIdxs[i] = idx; 456 InstrsForCase[idx] += ", "; 457 InstrsForCase[idx] += Inst->CGI->TheDef->getName(); 458 FoundIt = true; 459 break; 460 } 461 if (!FoundIt) { 462 InstIdxs[i] = UniqueOperandCommands.size(); 463 UniqueOperandCommands.push_back(Command); 464 InstrsForCase.push_back(Inst->CGI->TheDef->getName()); 465 466 // This command matches one operand so far. 467 InstOpsUsed.push_back(1); 468 } 469 } 470 471 // For each entry of UniqueOperandCommands, there is a set of instructions 472 // that uses it. If the next command of all instructions in the set are 473 // identical, fold it into the command. 474 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size(); 475 CommandIdx != e; ++CommandIdx) { 476 477 for (unsigned Op = 1; ; ++Op) { 478 // Scan for the first instruction in the set. 479 std::vector<unsigned>::iterator NIT = 480 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx); 481 if (NIT == InstIdxs.end()) break; // No commonality. 482 483 // If this instruction has no more operands, we isn't anything to merge 484 // into this command. 485 const AsmWriterInst *FirstInst = 486 getAsmWriterInstByID(NIT-InstIdxs.begin()); 487 if (!FirstInst || FirstInst->Operands.size() == Op) 488 break; 489 490 // Otherwise, scan to see if all of the other instructions in this command 491 // set share the operand. 492 bool AllSame = true; 493 // Keep track of the maximum, number of operands or any 494 // instruction we see in the group. 495 size_t MaxSize = FirstInst->Operands.size(); 496 497 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx); 498 NIT != InstIdxs.end(); 499 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) { 500 // Okay, found another instruction in this command set. If the operand 501 // matches, we're ok, otherwise bail out. 502 const AsmWriterInst *OtherInst = 503 getAsmWriterInstByID(NIT-InstIdxs.begin()); 504 505 if (OtherInst && 506 OtherInst->Operands.size() > FirstInst->Operands.size()) 507 MaxSize = std::max(MaxSize, OtherInst->Operands.size()); 508 509 if (!OtherInst || OtherInst->Operands.size() == Op || 510 OtherInst->Operands[Op] != FirstInst->Operands[Op]) { 511 AllSame = false; 512 break; 513 } 514 } 515 if (!AllSame) break; 516 517 // Okay, everything in this command set has the same next operand. Add it 518 // to UniqueOperandCommands and remember that it was consumed. 519 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n"; 520 521 UniqueOperandCommands[CommandIdx] += Command; 522 InstOpsUsed[CommandIdx]++; 523 } 524 } 525 526 // Prepend some of the instructions each case is used for onto the case val. 527 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) { 528 std::string Instrs = InstrsForCase[i]; 529 if (Instrs.size() > 70) { 530 Instrs.erase(Instrs.begin()+70, Instrs.end()); 531 Instrs += "..."; 532 } 533 534 if (!Instrs.empty()) 535 UniqueOperandCommands[i] = " // " + Instrs + "\n" + 536 UniqueOperandCommands[i]; 537 } 538} 539 540 541static void UnescapeString(std::string &Str) { 542 for (unsigned i = 0; i != Str.size(); ++i) { 543 if (Str[i] == '\\' && i != Str.size()-1) { 544 switch (Str[i+1]) { 545 default: continue; // Don't execute the code after the switch. 546 case 'a': Str[i] = '\a'; break; 547 case 'b': Str[i] = '\b'; break; 548 case 'e': Str[i] = 27; break; 549 case 'f': Str[i] = '\f'; break; 550 case 'n': Str[i] = '\n'; break; 551 case 'r': Str[i] = '\r'; break; 552 case 't': Str[i] = '\t'; break; 553 case 'v': Str[i] = '\v'; break; 554 case '"': Str[i] = '\"'; break; 555 case '\'': Str[i] = '\''; break; 556 case '\\': Str[i] = '\\'; break; 557 } 558 // Nuke the second character. 559 Str.erase(Str.begin()+i+1); 560 } 561 } 562} 563 564/// EmitPrintInstruction - Generate the code for the "printInstruction" method 565/// implementation. 566void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { 567 CodeGenTarget Target; 568 Record *AsmWriter = Target.getAsmWriter(); 569 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 570 571 O << 572 "/// printInstruction - This method is automatically generated by tablegen\n" 573 "/// from the instruction set description.\n" 574 "void " << Target.getName() << ClassName 575 << "::printInstruction(const MachineInstr *MI) {\n"; 576 577 std::vector<AsmWriterInst> Instructions; 578 579 for (CodeGenTarget::inst_iterator I = Target.inst_begin(), 580 E = Target.inst_end(); I != E; ++I) 581 if (!I->second.AsmString.empty() && 582 I->second.TheDef->getName() != "PHI") 583 Instructions.push_back(AsmWriterInst(I->second, AsmWriter)); 584 585 // Get the instruction numbering. 586 Target.getInstructionsByEnumValue(NumberedInstructions); 587 588 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not 589 // all machine instructions are necessarily being printed, so there may be 590 // target instructions not in this map. 591 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) 592 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i])); 593 594 // Build an aggregate string, and build a table of offsets into it. 595 StringToOffsetTable StringTable; 596 597 /// OpcodeInfo - This encodes the index of the string to use for the first 598 /// chunk of the output as well as indices used for operand printing. 599 std::vector<unsigned> OpcodeInfo; 600 601 unsigned MaxStringIdx = 0; 602 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 603 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]]; 604 unsigned Idx; 605 if (AWI == 0) { 606 // Something not handled by the asmwriter printer. 607 Idx = ~0U; 608 } else if (AWI->Operands[0].OperandType != 609 AsmWriterOperand::isLiteralTextOperand || 610 AWI->Operands[0].Str.empty()) { 611 // Something handled by the asmwriter printer, but with no leading string. 612 Idx = StringTable.GetOrAddStringOffset(""); 613 } else { 614 std::string Str = AWI->Operands[0].Str; 615 UnescapeString(Str); 616 Idx = StringTable.GetOrAddStringOffset(Str); 617 MaxStringIdx = std::max(MaxStringIdx, Idx); 618 619 // Nuke the string from the operand list. It is now handled! 620 AWI->Operands.erase(AWI->Operands.begin()); 621 } 622 623 // Bias offset by one since we want 0 as a sentinel. 624 OpcodeInfo.push_back(Idx+1); 625 } 626 627 // Figure out how many bits we used for the string index. 628 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2); 629 630 // To reduce code size, we compactify common instructions into a few bits 631 // in the opcode-indexed table. 632 unsigned BitsLeft = 32-AsmStrBits; 633 634 std::vector<std::vector<std::string> > TableDrivenOperandPrinters; 635 636 while (1) { 637 std::vector<std::string> UniqueOperandCommands; 638 std::vector<unsigned> InstIdxs; 639 std::vector<unsigned> NumInstOpsHandled; 640 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs, 641 NumInstOpsHandled); 642 643 // If we ran out of operands to print, we're done. 644 if (UniqueOperandCommands.empty()) break; 645 646 // Compute the number of bits we need to represent these cases, this is 647 // ceil(log2(numentries)). 648 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size()); 649 650 // If we don't have enough bits for this operand, don't include it. 651 if (NumBits > BitsLeft) { 652 DEBUG(errs() << "Not enough bits to densely encode " << NumBits 653 << " more bits\n"); 654 break; 655 } 656 657 // Otherwise, we can include this in the initial lookup table. Add it in. 658 BitsLeft -= NumBits; 659 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i) 660 if (InstIdxs[i] != ~0U) 661 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits); 662 663 // Remove the info about this operand. 664 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 665 if (AsmWriterInst *Inst = getAsmWriterInstByID(i)) 666 if (!Inst->Operands.empty()) { 667 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]]; 668 assert(NumOps <= Inst->Operands.size() && 669 "Can't remove this many ops!"); 670 Inst->Operands.erase(Inst->Operands.begin(), 671 Inst->Operands.begin()+NumOps); 672 } 673 } 674 675 // Remember the handlers for this set of operands. 676 TableDrivenOperandPrinters.push_back(UniqueOperandCommands); 677 } 678 679 680 681 O<<" static const unsigned OpInfo[] = {\n"; 682 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 683 O << " " << OpcodeInfo[i] << "U,\t// " 684 << NumberedInstructions[i]->TheDef->getName() << "\n"; 685 } 686 // Add a dummy entry so the array init doesn't end with a comma. 687 O << " 0U\n"; 688 O << " };\n\n"; 689 690 // Emit the string itself. 691 O << " const char *AsmStrs = \n"; 692 StringTable.EmitString(O); 693 O << ";\n\n"; 694 695 O << "\n#ifndef NO_ASM_WRITER_BOILERPLATE\n"; 696 697 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n" 698 << " printInlineAsm(MI);\n" 699 << " return;\n" 700 << " } else if (MI->isLabel()) {\n" 701 << " printLabel(MI);\n" 702 << " return;\n" 703 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n" 704 << " printImplicitDef(MI);\n" 705 << " return;\n" 706 << " } else if (MI->getOpcode() == TargetInstrInfo::KILL) {\n" 707 << " printKill(MI);\n" 708 << " return;\n" 709 << " }\n\n"; 710 711 O << "\n#endif\n"; 712 713 O << " O << \"\\t\";\n\n"; 714 715 O << " // Emit the opcode for the instruction.\n" 716 << " unsigned Bits = OpInfo[MI->getOpcode()];\n" 717 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n" 718 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n"; 719 720 // Output the table driven operand information. 721 BitsLeft = 32-AsmStrBits; 722 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) { 723 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i]; 724 725 // Compute the number of bits we need to represent these cases, this is 726 // ceil(log2(numentries)). 727 unsigned NumBits = Log2_32_Ceil(Commands.size()); 728 assert(NumBits <= BitsLeft && "consistency error"); 729 730 // Emit code to extract this field from Bits. 731 BitsLeft -= NumBits; 732 733 O << "\n // Fragment " << i << " encoded into " << NumBits 734 << " bits for " << Commands.size() << " unique commands.\n"; 735 736 if (Commands.size() == 2) { 737 // Emit two possibilitys with if/else. 738 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & " 739 << ((1 << NumBits)-1) << ") {\n" 740 << Commands[1] 741 << " } else {\n" 742 << Commands[0] 743 << " }\n\n"; 744 } else { 745 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & " 746 << ((1 << NumBits)-1) << ") {\n" 747 << " default: // unreachable.\n"; 748 749 // Print out all the cases. 750 for (unsigned i = 0, e = Commands.size(); i != e; ++i) { 751 O << " case " << i << ":\n"; 752 O << Commands[i]; 753 O << " break;\n"; 754 } 755 O << " }\n\n"; 756 } 757 } 758 759 // Okay, delete instructions with no operand info left. 760 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) { 761 // Entire instruction has been emitted? 762 AsmWriterInst &Inst = Instructions[i]; 763 if (Inst.Operands.empty()) { 764 Instructions.erase(Instructions.begin()+i); 765 --i; --e; 766 } 767 } 768 769 770 // Because this is a vector, we want to emit from the end. Reverse all of the 771 // elements in the vector. 772 std::reverse(Instructions.begin(), Instructions.end()); 773 774 775 // Now that we've emitted all of the operand info that fit into 32 bits, emit 776 // information for those instructions that are left. This is a less dense 777 // encoding, but we expect the main 32-bit table to handle the majority of 778 // instructions. 779 if (!Instructions.empty()) { 780 // Find the opcode # of inline asm. 781 O << " switch (MI->getOpcode()) {\n"; 782 while (!Instructions.empty()) 783 EmitInstructions(Instructions, O); 784 785 O << " }\n"; 786 O << " return;\n"; 787 } 788 789 O << "}\n"; 790} 791 792 793void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { 794 CodeGenTarget Target; 795 Record *AsmWriter = Target.getAsmWriter(); 796 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 797 const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); 798 799 StringToOffsetTable StringTable; 800 O << 801 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n" 802 "/// from the register set description. This returns the assembler name\n" 803 "/// for the specified register.\n" 804 "const char *" << Target.getName() << ClassName 805 << "::getRegisterName(unsigned RegNo) {\n" 806 << " assert(RegNo && RegNo < " << (Registers.size()+1) 807 << " && \"Invalid register number!\");\n" 808 << "\n" 809 << " static const unsigned RegAsmOffset[] = {"; 810 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 811 const CodeGenRegister &Reg = Registers[i]; 812 813 std::string AsmName = Reg.TheDef->getValueAsString("AsmName"); 814 if (AsmName.empty()) 815 AsmName = Reg.getName(); 816 817 818 if ((i % 14) == 0) 819 O << "\n "; 820 821 O << StringTable.GetOrAddStringOffset(AsmName) << ", "; 822 } 823 O << "0\n" 824 << " };\n" 825 << "\n"; 826 827 O << " const char *AsmStrs =\n"; 828 StringTable.EmitString(O); 829 O << ";\n"; 830 831 O << " return AsmStrs+RegAsmOffset[RegNo-1];\n" 832 << "}\n"; 833} 834 835 836void AsmWriterEmitter::run(raw_ostream &O) { 837 EmitSourceFileHeader("Assembly Writer Source Fragment", O); 838 839 EmitPrintInstruction(O); 840 EmitGetRegisterName(O); 841} 842 843