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