1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "AsmWriterEmitter.h"
16 #include "AsmWriterInst.h"
17 #include "CodeGenTarget.h"
19 #include "StringToOffsetTable.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/MathExtras.h"
25 static void PrintCases(std::vector<std::pair<std::string,
26 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
27 O << " case " << OpsToPrint.back().first << ": ";
28 AsmWriterOperand TheOp = OpsToPrint.back().second;
29 OpsToPrint.pop_back();
31 // Check to see if any other operands are identical in this list, and if so,
32 // emit a case label for them.
33 for (unsigned i = OpsToPrint.size(); i != 0; --i)
34 if (OpsToPrint[i-1].second == TheOp) {
35 O << "\n case " << OpsToPrint[i-1].first << ": ";
36 OpsToPrint.erase(OpsToPrint.begin()+i-1);
39 // Finally, emit the code.
45 /// EmitInstructions - Emit the last instruction in the vector and any other
46 /// instructions that are suitably similar to it.
47 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
49 AsmWriterInst FirstInst = Insts.back();
52 std::vector<AsmWriterInst> SimilarInsts;
53 unsigned DifferingOperand = ~0;
54 for (unsigned i = Insts.size(); i != 0; --i) {
55 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
57 if (DifferingOperand == ~0U) // First match!
58 DifferingOperand = DiffOp;
60 // If this differs in the same operand as the rest of the instructions in
61 // this class, move it to the SimilarInsts list.
62 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
63 SimilarInsts.push_back(Insts[i-1]);
64 Insts.erase(Insts.begin()+i-1);
69 O << " case " << FirstInst.CGI->Namespace << "::"
70 << FirstInst.CGI->TheDef->getName() << ":\n";
71 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
72 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
73 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
74 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
75 if (i != DifferingOperand) {
76 // If the operand is the same for all instructions, just print it.
77 O << " " << FirstInst.Operands[i].getCode();
79 // If this is the operand that varies between all of the instructions,
80 // emit a switch for just this operand now.
81 O << " switch (MI->getOpcode()) {\n";
82 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
83 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
84 FirstInst.CGI->TheDef->getName(),
85 FirstInst.Operands[i]));
87 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
88 AsmWriterInst &AWI = SimilarInsts[si];
89 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
90 AWI.CGI->TheDef->getName(),
93 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
94 while (!OpsToPrint.empty())
95 PrintCases(OpsToPrint, O);
103 void AsmWriterEmitter::
104 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
105 std::vector<unsigned> &InstIdxs,
106 std::vector<unsigned> &InstOpsUsed) const {
107 InstIdxs.assign(NumberedInstructions.size(), ~0U);
109 // This vector parallels UniqueOperandCommands, keeping track of which
110 // instructions each case are used for. It is a comma separated string of
112 std::vector<std::string> InstrsForCase;
113 InstrsForCase.resize(UniqueOperandCommands.size());
114 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
116 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
117 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
118 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
121 if (Inst->Operands.empty())
122 continue; // Instruction already done.
124 Command = " " + Inst->Operands[0].getCode() + "\n";
126 // Check to see if we already have 'Command' in UniqueOperandCommands.
128 bool FoundIt = false;
129 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
130 if (UniqueOperandCommands[idx] == Command) {
132 InstrsForCase[idx] += ", ";
133 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
138 InstIdxs[i] = UniqueOperandCommands.size();
139 UniqueOperandCommands.push_back(Command);
140 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
142 // This command matches one operand so far.
143 InstOpsUsed.push_back(1);
147 // For each entry of UniqueOperandCommands, there is a set of instructions
148 // that uses it. If the next command of all instructions in the set are
149 // identical, fold it into the command.
150 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
151 CommandIdx != e; ++CommandIdx) {
153 for (unsigned Op = 1; ; ++Op) {
154 // Scan for the first instruction in the set.
155 std::vector<unsigned>::iterator NIT =
156 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
157 if (NIT == InstIdxs.end()) break; // No commonality.
159 // If this instruction has no more operands, we isn't anything to merge
160 // into this command.
161 const AsmWriterInst *FirstInst =
162 getAsmWriterInstByID(NIT-InstIdxs.begin());
163 if (!FirstInst || FirstInst->Operands.size() == Op)
166 // Otherwise, scan to see if all of the other instructions in this command
167 // set share the operand.
169 // Keep track of the maximum, number of operands or any
170 // instruction we see in the group.
171 size_t MaxSize = FirstInst->Operands.size();
173 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
174 NIT != InstIdxs.end();
175 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
176 // Okay, found another instruction in this command set. If the operand
177 // matches, we're ok, otherwise bail out.
178 const AsmWriterInst *OtherInst =
179 getAsmWriterInstByID(NIT-InstIdxs.begin());
182 OtherInst->Operands.size() > FirstInst->Operands.size())
183 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
185 if (!OtherInst || OtherInst->Operands.size() == Op ||
186 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
193 // Okay, everything in this command set has the same next operand. Add it
194 // to UniqueOperandCommands and remember that it was consumed.
195 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
197 UniqueOperandCommands[CommandIdx] += Command;
198 InstOpsUsed[CommandIdx]++;
202 // Prepend some of the instructions each case is used for onto the case val.
203 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
204 std::string Instrs = InstrsForCase[i];
205 if (Instrs.size() > 70) {
206 Instrs.erase(Instrs.begin()+70, Instrs.end());
211 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
212 UniqueOperandCommands[i];
217 static void UnescapeString(std::string &Str) {
218 for (unsigned i = 0; i != Str.size(); ++i) {
219 if (Str[i] == '\\' && i != Str.size()-1) {
221 default: continue; // Don't execute the code after the switch.
222 case 'a': Str[i] = '\a'; break;
223 case 'b': Str[i] = '\b'; break;
224 case 'e': Str[i] = 27; break;
225 case 'f': Str[i] = '\f'; break;
226 case 'n': Str[i] = '\n'; break;
227 case 'r': Str[i] = '\r'; break;
228 case 't': Str[i] = '\t'; break;
229 case 'v': Str[i] = '\v'; break;
230 case '"': Str[i] = '\"'; break;
231 case '\'': Str[i] = '\''; break;
232 case '\\': Str[i] = '\\'; break;
234 // Nuke the second character.
235 Str.erase(Str.begin()+i+1);
240 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
242 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
243 CodeGenTarget Target(Records);
244 Record *AsmWriter = Target.getAsmWriter();
245 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
246 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
247 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
250 "/// printInstruction - This method is automatically generated by tablegen\n"
251 "/// from the instruction set description.\n"
252 "void " << Target.getName() << ClassName
253 << "::printInstruction(const " << MachineInstrClassName
254 << " *MI, raw_ostream &O) {\n";
256 std::vector<AsmWriterInst> Instructions;
258 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
259 E = Target.inst_end(); I != E; ++I)
260 if (!(*I)->AsmString.empty() &&
261 (*I)->TheDef->getName() != "PHI")
262 Instructions.push_back(
264 AsmWriter->getValueAsInt("Variant"),
265 AsmWriter->getValueAsInt("FirstOperandColumn"),
266 AsmWriter->getValueAsInt("OperandSpacing")));
268 // Get the instruction numbering.
269 NumberedInstructions = Target.getInstructionsByEnumValue();
271 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
272 // all machine instructions are necessarily being printed, so there may be
273 // target instructions not in this map.
274 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
275 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
277 // Build an aggregate string, and build a table of offsets into it.
278 StringToOffsetTable StringTable;
280 /// OpcodeInfo - This encodes the index of the string to use for the first
281 /// chunk of the output as well as indices used for operand printing.
282 std::vector<unsigned> OpcodeInfo;
284 unsigned MaxStringIdx = 0;
285 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
286 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
289 // Something not handled by the asmwriter printer.
291 } else if (AWI->Operands[0].OperandType !=
292 AsmWriterOperand::isLiteralTextOperand ||
293 AWI->Operands[0].Str.empty()) {
294 // Something handled by the asmwriter printer, but with no leading string.
295 Idx = StringTable.GetOrAddStringOffset("");
297 std::string Str = AWI->Operands[0].Str;
299 Idx = StringTable.GetOrAddStringOffset(Str);
300 MaxStringIdx = std::max(MaxStringIdx, Idx);
302 // Nuke the string from the operand list. It is now handled!
303 AWI->Operands.erase(AWI->Operands.begin());
306 // Bias offset by one since we want 0 as a sentinel.
307 OpcodeInfo.push_back(Idx+1);
310 // Figure out how many bits we used for the string index.
311 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
313 // To reduce code size, we compactify common instructions into a few bits
314 // in the opcode-indexed table.
315 unsigned BitsLeft = 32-AsmStrBits;
317 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
320 std::vector<std::string> UniqueOperandCommands;
321 std::vector<unsigned> InstIdxs;
322 std::vector<unsigned> NumInstOpsHandled;
323 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
326 // If we ran out of operands to print, we're done.
327 if (UniqueOperandCommands.empty()) break;
329 // Compute the number of bits we need to represent these cases, this is
330 // ceil(log2(numentries)).
331 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
333 // If we don't have enough bits for this operand, don't include it.
334 if (NumBits > BitsLeft) {
335 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
340 // Otherwise, we can include this in the initial lookup table. Add it in.
342 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
343 if (InstIdxs[i] != ~0U)
344 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
346 // Remove the info about this operand.
347 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
348 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
349 if (!Inst->Operands.empty()) {
350 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
351 assert(NumOps <= Inst->Operands.size() &&
352 "Can't remove this many ops!");
353 Inst->Operands.erase(Inst->Operands.begin(),
354 Inst->Operands.begin()+NumOps);
358 // Remember the handlers for this set of operands.
359 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
364 O<<" static const unsigned OpInfo[] = {\n";
365 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
366 O << " " << OpcodeInfo[i] << "U,\t// "
367 << NumberedInstructions[i]->TheDef->getName() << "\n";
369 // Add a dummy entry so the array init doesn't end with a comma.
373 // Emit the string itself.
374 O << " const char *AsmStrs = \n";
375 StringTable.EmitString(O);
378 O << " O << \"\\t\";\n\n";
380 O << " // Emit the opcode for the instruction.\n"
381 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
382 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
383 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
385 // Output the table driven operand information.
386 BitsLeft = 32-AsmStrBits;
387 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
388 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
390 // Compute the number of bits we need to represent these cases, this is
391 // ceil(log2(numentries)).
392 unsigned NumBits = Log2_32_Ceil(Commands.size());
393 assert(NumBits <= BitsLeft && "consistency error");
395 // Emit code to extract this field from Bits.
398 O << "\n // Fragment " << i << " encoded into " << NumBits
399 << " bits for " << Commands.size() << " unique commands.\n";
401 if (Commands.size() == 2) {
402 // Emit two possibilitys with if/else.
403 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
404 << ((1 << NumBits)-1) << ") {\n"
409 } else if (Commands.size() == 1) {
410 // Emit a single possibility.
411 O << Commands[0] << "\n\n";
413 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
414 << ((1 << NumBits)-1) << ") {\n"
415 << " default: // unreachable.\n";
417 // Print out all the cases.
418 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
419 O << " case " << i << ":\n";
427 // Okay, delete instructions with no operand info left.
428 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
429 // Entire instruction has been emitted?
430 AsmWriterInst &Inst = Instructions[i];
431 if (Inst.Operands.empty()) {
432 Instructions.erase(Instructions.begin()+i);
438 // Because this is a vector, we want to emit from the end. Reverse all of the
439 // elements in the vector.
440 std::reverse(Instructions.begin(), Instructions.end());
443 // Now that we've emitted all of the operand info that fit into 32 bits, emit
444 // information for those instructions that are left. This is a less dense
445 // encoding, but we expect the main 32-bit table to handle the majority of
447 if (!Instructions.empty()) {
448 // Find the opcode # of inline asm.
449 O << " switch (MI->getOpcode()) {\n";
450 while (!Instructions.empty())
451 EmitInstructions(Instructions, O);
461 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
462 CodeGenTarget Target(Records);
463 Record *AsmWriter = Target.getAsmWriter();
464 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
465 const std::vector<CodeGenRegister> &Registers = Target.getRegisters();
467 StringToOffsetTable StringTable;
469 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
470 "/// from the register set description. This returns the assembler name\n"
471 "/// for the specified register.\n"
472 "const char *" << Target.getName() << ClassName
473 << "::getRegisterName(unsigned RegNo) {\n"
474 << " assert(RegNo && RegNo < " << (Registers.size()+1)
475 << " && \"Invalid register number!\");\n"
477 << " static const unsigned RegAsmOffset[] = {";
478 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
479 const CodeGenRegister &Reg = Registers[i];
481 std::string AsmName = Reg.TheDef->getValueAsString("AsmName");
483 AsmName = Reg.getName();
489 O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
495 O << " const char *AsmStrs =\n";
496 StringTable.EmitString(O);
499 O << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
503 void AsmWriterEmitter::EmitGetInstructionName(raw_ostream &O) {
504 CodeGenTarget Target(Records);
505 Record *AsmWriter = Target.getAsmWriter();
506 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
508 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
509 Target.getInstructionsByEnumValue();
511 StringToOffsetTable StringTable;
513 "\n\n#ifdef GET_INSTRUCTION_NAME\n"
514 "#undef GET_INSTRUCTION_NAME\n\n"
515 "/// getInstructionName: This method is automatically generated by tblgen\n"
516 "/// from the instruction set description. This returns the enum name of the\n"
517 "/// specified instruction.\n"
518 "const char *" << Target.getName() << ClassName
519 << "::getInstructionName(unsigned Opcode) {\n"
520 << " assert(Opcode < " << NumberedInstructions.size()
521 << " && \"Invalid instruction number!\");\n"
523 << " static const unsigned InstAsmOffset[] = {";
524 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
525 const CodeGenInstruction &Inst = *NumberedInstructions[i];
527 std::string AsmName = Inst.TheDef->getName();
531 O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
537 O << " const char *Strs =\n";
538 StringTable.EmitString(O);
541 O << " return Strs+InstAsmOffset[Opcode];\n"
547 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
548 /// feature which participates in instruction matching.
549 struct SubtargetFeatureInfo {
550 /// \brief The predicate record for this feature.
551 const Record *TheDef;
553 /// \brief An unique index assigned to represent this feature.
556 SubtargetFeatureInfo(const Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
558 /// \brief The name of the enumerated constant identifying this feature.
559 std::string getEnumName() const {
560 return "Feature_" + TheDef->getName();
564 struct AsmWriterInfo {
565 /// Map of Predicate records to their subtarget information.
566 std::map<const Record*, SubtargetFeatureInfo*> SubtargetFeatures;
568 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
570 SubtargetFeatureInfo *getSubtargetFeature(const Record *Def) const {
571 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
572 std::map<const Record*, SubtargetFeatureInfo*>::const_iterator I =
573 SubtargetFeatures.find(Def);
574 return I == SubtargetFeatures.end() ? 0 : I->second;
577 void addReqFeatures(const std::vector<Record*> &Features) {
578 for (std::vector<Record*>::const_iterator
579 I = Features.begin(), E = Features.end(); I != E; ++I) {
580 const Record *Pred = *I;
582 // Ignore predicates that are not intended for the assembler.
583 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
586 if (Pred->getName().empty())
587 throw TGError(Pred->getLoc(), "Predicate has no name!");
589 // Don't add the predicate again.
590 if (getSubtargetFeature(Pred))
593 unsigned FeatureNo = SubtargetFeatures.size();
594 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
595 assert(FeatureNo < 32 && "Too many subtarget features!");
599 const SubtargetFeatureInfo *getFeatureInfo(const Record *R) {
600 return SubtargetFeatures[R];
604 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
605 // they both have the same conditionals. In which case, we cannot print out the
606 // alias for that pattern.
609 std::vector<std::string> Conds;
610 std::map<StringRef, unsigned> OpMap;
612 std::string AsmString;
613 std::vector<Record*> ReqFeatures;
615 IAPrinter(AsmWriterInfo &Info, std::string R, std::string AS)
616 : AWI(Info), Result(R), AsmString(AS) {}
618 void addCond(const std::string &C) { Conds.push_back(C); }
619 void addReqFeatures(const std::vector<Record*> &Features) {
620 AWI.addReqFeatures(Features);
621 ReqFeatures = Features;
624 void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
625 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
626 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
628 bool print(raw_ostream &O) {
629 if (Conds.empty() && ReqFeatures.empty()) {
630 O.indent(6) << "return true;\n";
636 for (std::vector<std::string>::iterator
637 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
638 if (I != Conds.begin()) {
646 if (!ReqFeatures.empty()) {
647 if (Conds.begin() != Conds.end()) {
655 raw_string_ostream ReqO(Req);
657 for (std::vector<Record*>::iterator
658 I = ReqFeatures.begin(), E = ReqFeatures.end(); I != E; ++I) {
659 if (I != ReqFeatures.begin()) ReqO << " | ";
660 ReqO << AWI.getFeatureInfo(*I)->getEnumName();
663 O << "(AvailableFeatures & (" << ReqO.str() << ")) == ("
664 << ReqO.str() << ')';
668 O.indent(6) << "// " << Result << "\n";
669 O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
671 for (std::map<StringRef, unsigned>::iterator
672 I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
673 O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
674 << I->second << "));\n";
676 O.indent(6) << "break;\n";
678 return !ReqFeatures.empty();
681 bool operator==(const IAPrinter &RHS) {
682 if (Conds.size() != RHS.Conds.size())
686 for (std::vector<std::string>::iterator
687 I = Conds.begin(), E = Conds.end(); I != E; ++I)
688 if (*I != RHS.Conds[Idx++])
694 bool operator()(const IAPrinter &RHS) {
695 if (Conds.size() < RHS.Conds.size())
699 for (std::vector<std::string>::iterator
700 I = Conds.begin(), E = Conds.end(); I != E; ++I)
701 if (*I != RHS.Conds[Idx++])
702 return *I < RHS.Conds[Idx++];
708 } // end anonymous namespace
710 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
712 static void EmitSubtargetFeatureFlagEnumeration(AsmWriterInfo &Info,
714 O << "namespace {\n\n";
715 O << "// Flags for subtarget features that participate in "
716 << "alias instruction matching.\n";
717 O << "enum SubtargetFeatureFlag {\n";
719 for (std::map<const Record*, SubtargetFeatureInfo*>::const_iterator
720 I = Info.SubtargetFeatures.begin(),
721 E = Info.SubtargetFeatures.end(); I != E; ++I) {
722 SubtargetFeatureInfo &SFI = *I->second;
723 O << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
726 O << " Feature_None = 0\n";
728 O << "} // end anonymous namespace\n\n";
731 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
732 /// available features given a subtarget.
733 static void EmitComputeAvailableFeatures(AsmWriterInfo &Info,
735 CodeGenTarget &Target,
737 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
739 O << "unsigned " << Target.getName() << ClassName << "::\n"
740 << "ComputeAvailableFeatures(const " << Target.getName()
741 << "Subtarget *Subtarget) const {\n";
742 O << " unsigned Features = 0;\n";
744 for (std::map<const Record*, SubtargetFeatureInfo*>::const_iterator
745 I = Info.SubtargetFeatures.begin(),
746 E = Info.SubtargetFeatures.end(); I != E; ++I) {
747 SubtargetFeatureInfo &SFI = *I->second;
748 O << " if (" << SFI.TheDef->getValueAsString("CondString")
750 O << " Features |= " << SFI.getEnumName() << ";\n";
753 O << " return Features;\n";
757 static void EmitGetMapOperandNumber(raw_ostream &O) {
758 O << "static unsigned getMapOperandNumber("
759 << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
760 O << " StringRef Name) {\n";
761 O << " for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
762 << "const_iterator\n";
763 O << " I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
764 O << " if (I->first == Name)\n";
765 O << " return I->second;\n";
766 O << " assert(false && \"Operand not in map!\");\n";
771 void AsmWriterEmitter::EmitRegIsInRegClass(raw_ostream &O) {
772 CodeGenTarget Target(Records);
774 // Enumerate the register classes.
775 const std::vector<CodeGenRegisterClass> &RegisterClasses =
776 Target.getRegisterClasses();
778 O << "namespace { // Register classes\n";
779 O << " enum RegClass {\n";
781 // Emit the register enum value for each RegisterClass.
782 for (unsigned I = 0, E = RegisterClasses.size(); I != E; ++I) {
783 if (I != 0) O << ",\n";
784 O << " RC_" << RegisterClasses[I].TheDef->getName();
788 O << "} // end anonymous namespace\n\n";
790 // Emit a function that returns 'true' if a regsiter is part of a particular
791 // register class. I.e., RAX is part of GR64 on X86.
792 O << "static bool regIsInRegisterClass"
793 << "(unsigned RegClass, unsigned Reg) {\n";
795 // Emit the switch that checks if a register belongs to a particular register
797 O << " switch (RegClass) {\n";
798 O << " default: break;\n";
800 for (unsigned I = 0, E = RegisterClasses.size(); I != E; ++I) {
801 const CodeGenRegisterClass &RC = RegisterClasses[I];
803 // Give the register class a legal C name if it's anonymous.
804 std::string Name = RC.TheDef->getName();
805 O << " case RC_" << Name << ":\n";
807 // Emit the register list now.
808 unsigned IE = RC.Elements.size();
810 O << " if (Reg == " << getQualifiedName(RC.Elements[0]) << ")\n";
811 O << " return true;\n";
813 O << " switch (Reg) {\n";
814 O << " default: break;\n";
816 for (unsigned II = 0; II != IE; ++II) {
817 Record *Reg = RC.Elements[II];
818 O << " case " << getQualifiedName(Reg) << ":\n";
821 O << " return true;\n";
829 O << " return false;\n";
833 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
834 CodeGenTarget Target(Records);
835 Record *AsmWriter = Target.getAsmWriter();
837 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
838 O << "#undef PRINT_ALIAS_INSTR\n\n";
840 EmitRegIsInRegClass(O);
842 // Emit the method that prints the alias instruction.
843 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
845 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
846 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
848 std::vector<Record*> AllInstAliases =
849 Records.getAllDerivedDefinitions("InstAlias");
851 // Create a map from the qualified name to a list of potential matches.
852 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
853 for (std::vector<Record*>::iterator
854 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
855 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
856 const Record *R = *I;
857 if (!R->getValueAsBit("EmitAlias"))
858 continue; // We were told not to emit the alias, but to emit the aliasee.
859 const DagInit *DI = R->getValueAsDag("ResultInst");
860 const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
861 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
864 // A map of which conditions need to be met for each instruction operand
865 // before it can be matched to the mnemonic.
866 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
869 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
870 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
871 std::vector<CodeGenInstAlias*> &Aliases = I->second;
873 for (std::vector<CodeGenInstAlias*>::iterator
874 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
875 const CodeGenInstAlias *CGA = *II;
876 IAPrinter *IAP = new IAPrinter(AWI, CGA->Result->getAsString(),
879 IAP->addReqFeatures(CGA->TheDef->getValueAsListOfDefs("Predicates"));
881 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
884 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
887 std::map<StringRef, unsigned> OpMap;
888 bool CantHandle = false;
890 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
891 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
894 default: assert(0 && "unexpected InstAlias operand kind");
895 case CodeGenInstAlias::ResultOperand::K_Record: {
896 const Record *Rec = RO.getRecord();
897 StringRef ROName = RO.getName();
899 if (Rec->isSubClassOf("RegisterClass")) {
900 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
903 if (!IAP->isOpMapped(ROName)) {
904 IAP->addOperand(ROName, i);
905 Cond = std::string("regIsInRegisterClass(RC_") +
906 CGA->ResultOperands[i].getRecord()->getName() +
907 ", MI->getOperand(" + llvm::utostr(i) + ").getReg())";
910 Cond = std::string("MI->getOperand(") +
911 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
912 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
916 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
917 // FIXME: We need to handle these situations.
926 case CodeGenInstAlias::ResultOperand::K_Imm:
927 Cond = std::string("MI->getOperand(") +
928 llvm::utostr(i) + ").getImm() == " +
929 llvm::utostr(CGA->ResultOperands[i].getImm());
932 case CodeGenInstAlias::ResultOperand::K_Reg:
933 Cond = std::string("MI->getOperand(") +
934 llvm::utostr(i) + ").getReg() == " + Target.getName() +
935 "::" + CGA->ResultOperands[i].getRegister()->getName();
943 if (CantHandle) continue;
944 IAPrinterMap[I->first].push_back(IAP);
948 EmitSubtargetFeatureFlagEnumeration(AWI, O);
949 EmitComputeAvailableFeatures(AWI, AsmWriter, Target, O);
952 raw_string_ostream HeaderO(Header);
954 HeaderO << "bool " << Target.getName() << ClassName
955 << "::printAliasInstr(const " << MachineInstrClassName
956 << " *MI, raw_ostream &OS) {\n";
959 raw_string_ostream CasesO(Cases);
960 bool NeedAvailableFeatures = false;
962 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
963 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
964 std::vector<IAPrinter*> &IAPs = I->second;
965 std::vector<IAPrinter*> UniqueIAPs;
967 for (std::vector<IAPrinter*>::iterator
968 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
969 IAPrinter *LHS = *II;
971 for (std::vector<IAPrinter*>::iterator
972 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
973 IAPrinter *RHS = *III;
974 if (LHS != RHS && *LHS == *RHS) {
980 if (!IsDup) UniqueIAPs.push_back(LHS);
983 if (UniqueIAPs.empty()) continue;
985 CasesO.indent(2) << "case " << I->first << ":\n";
987 for (std::vector<IAPrinter*>::iterator
988 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
989 IAPrinter *IAP = *II;
991 NeedAvailableFeatures |= IAP->print(CasesO);
995 CasesO.indent(4) << "return false;\n";
998 if (CasesO.str().empty() || !isMC) {
1000 O << " return false;\n";
1002 O << "#endif // PRINT_ALIAS_INSTR\n";
1006 EmitGetMapOperandNumber(O);
1009 O.indent(2) << "StringRef AsmString;\n";
1010 O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
1011 if (NeedAvailableFeatures)
1012 O.indent(2) << "unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1013 O.indent(2) << "switch (MI->getOpcode()) {\n";
1014 O.indent(2) << "default: return false;\n";
1016 O.indent(2) << "}\n\n";
1018 // Code that prints the alias, replacing the operands with the ones from the
1020 O << " std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
1021 O << " OS << '\\t' << ASM.first;\n";
1023 O << " if (!ASM.second.empty()) {\n";
1024 O << " OS << '\\t';\n";
1025 O << " for (StringRef::iterator\n";
1026 O << " I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
1027 O << " if (*I == '$') {\n";
1028 O << " StringRef::iterator Start = ++I;\n";
1029 O << " while (I != E &&\n";
1030 O << " ((*I >= 'a' && *I <= 'z') ||\n";
1031 O << " (*I >= 'A' && *I <= 'Z') ||\n";
1032 O << " (*I >= '0' && *I <= '9') ||\n";
1033 O << " *I == '_'))\n";
1035 O << " StringRef Name(Start, I - Start);\n";
1036 O << " printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
1038 O << " OS << *I++;\n";
1043 O << " return true;\n";
1046 O << "#endif // PRINT_ALIAS_INSTR\n";
1049 void AsmWriterEmitter::run(raw_ostream &O) {
1050 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
1052 EmitPrintInstruction(O);
1053 EmitGetRegisterName(O);
1054 EmitGetInstructionName(O);
1055 EmitPrintAliasInstruction(O);