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