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