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"
18 #include "CodeGenTarget.h"
20 #include "StringToOffsetTable.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/MathExtras.h"
26 static void PrintCases(std::vector<std::pair<std::string,
27 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
28 O << " case " << OpsToPrint.back().first << ": ";
29 AsmWriterOperand TheOp = OpsToPrint.back().second;
30 OpsToPrint.pop_back();
32 // Check to see if any other operands are identical in this list, and if so,
33 // emit a case label for them.
34 for (unsigned i = OpsToPrint.size(); i != 0; --i)
35 if (OpsToPrint[i-1].second == TheOp) {
36 O << "\n case " << OpsToPrint[i-1].first << ": ";
37 OpsToPrint.erase(OpsToPrint.begin()+i-1);
40 // Finally, emit the code.
46 /// EmitInstructions - Emit the last instruction in the vector and any other
47 /// instructions that are suitably similar to it.
48 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
50 AsmWriterInst FirstInst = Insts.back();
53 std::vector<AsmWriterInst> SimilarInsts;
54 unsigned DifferingOperand = ~0;
55 for (unsigned i = Insts.size(); i != 0; --i) {
56 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
58 if (DifferingOperand == ~0U) // First match!
59 DifferingOperand = DiffOp;
61 // If this differs in the same operand as the rest of the instructions in
62 // this class, move it to the SimilarInsts list.
63 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
64 SimilarInsts.push_back(Insts[i-1]);
65 Insts.erase(Insts.begin()+i-1);
70 O << " case " << FirstInst.CGI->Namespace << "::"
71 << FirstInst.CGI->TheDef->getName() << ":\n";
72 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
73 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
74 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
75 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
76 if (i != DifferingOperand) {
77 // If the operand is the same for all instructions, just print it.
78 O << " " << FirstInst.Operands[i].getCode();
80 // If this is the operand that varies between all of the instructions,
81 // emit a switch for just this operand now.
82 O << " switch (MI->getOpcode()) {\n";
83 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
84 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
85 FirstInst.CGI->TheDef->getName(),
86 FirstInst.Operands[i]));
88 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
89 AsmWriterInst &AWI = SimilarInsts[si];
90 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
91 AWI.CGI->TheDef->getName(),
94 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
95 while (!OpsToPrint.empty())
96 PrintCases(OpsToPrint, O);
104 void AsmWriterEmitter::
105 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
106 std::vector<unsigned> &InstIdxs,
107 std::vector<unsigned> &InstOpsUsed) const {
108 InstIdxs.assign(NumberedInstructions.size(), ~0U);
110 // This vector parallels UniqueOperandCommands, keeping track of which
111 // instructions each case are used for. It is a comma separated string of
113 std::vector<std::string> InstrsForCase;
114 InstrsForCase.resize(UniqueOperandCommands.size());
115 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
117 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
118 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
119 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
122 if (Inst->Operands.empty())
123 continue; // Instruction already done.
125 Command = " " + Inst->Operands[0].getCode() + "\n";
127 // Check to see if we already have 'Command' in UniqueOperandCommands.
129 bool FoundIt = false;
130 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
131 if (UniqueOperandCommands[idx] == Command) {
133 InstrsForCase[idx] += ", ";
134 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
139 InstIdxs[i] = UniqueOperandCommands.size();
140 UniqueOperandCommands.push_back(Command);
141 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
143 // This command matches one operand so far.
144 InstOpsUsed.push_back(1);
148 // For each entry of UniqueOperandCommands, there is a set of instructions
149 // that uses it. If the next command of all instructions in the set are
150 // identical, fold it into the command.
151 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
152 CommandIdx != e; ++CommandIdx) {
154 for (unsigned Op = 1; ; ++Op) {
155 // Scan for the first instruction in the set.
156 std::vector<unsigned>::iterator NIT =
157 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
158 if (NIT == InstIdxs.end()) break; // No commonality.
160 // If this instruction has no more operands, we isn't anything to merge
161 // into this command.
162 const AsmWriterInst *FirstInst =
163 getAsmWriterInstByID(NIT-InstIdxs.begin());
164 if (!FirstInst || FirstInst->Operands.size() == Op)
167 // Otherwise, scan to see if all of the other instructions in this command
168 // set share the operand.
170 // Keep track of the maximum, number of operands or any
171 // instruction we see in the group.
172 size_t MaxSize = FirstInst->Operands.size();
174 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
175 NIT != InstIdxs.end();
176 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
177 // Okay, found another instruction in this command set. If the operand
178 // matches, we're ok, otherwise bail out.
179 const AsmWriterInst *OtherInst =
180 getAsmWriterInstByID(NIT-InstIdxs.begin());
183 OtherInst->Operands.size() > FirstInst->Operands.size())
184 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
186 if (!OtherInst || OtherInst->Operands.size() == Op ||
187 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
194 // Okay, everything in this command set has the same next operand. Add it
195 // to UniqueOperandCommands and remember that it was consumed.
196 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
198 UniqueOperandCommands[CommandIdx] += Command;
199 InstOpsUsed[CommandIdx]++;
203 // Prepend some of the instructions each case is used for onto the case val.
204 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
205 std::string Instrs = InstrsForCase[i];
206 if (Instrs.size() > 70) {
207 Instrs.erase(Instrs.begin()+70, Instrs.end());
212 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
213 UniqueOperandCommands[i];
218 static void UnescapeString(std::string &Str) {
219 for (unsigned i = 0; i != Str.size(); ++i) {
220 if (Str[i] == '\\' && i != Str.size()-1) {
222 default: continue; // Don't execute the code after the switch.
223 case 'a': Str[i] = '\a'; break;
224 case 'b': Str[i] = '\b'; break;
225 case 'e': Str[i] = 27; break;
226 case 'f': Str[i] = '\f'; break;
227 case 'n': Str[i] = '\n'; break;
228 case 'r': Str[i] = '\r'; break;
229 case 't': Str[i] = '\t'; break;
230 case 'v': Str[i] = '\v'; break;
231 case '"': Str[i] = '\"'; break;
232 case '\'': Str[i] = '\''; break;
233 case '\\': Str[i] = '\\'; break;
235 // Nuke the second character.
236 Str.erase(Str.begin()+i+1);
241 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
243 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
244 CodeGenTarget Target(Records);
245 Record *AsmWriter = Target.getAsmWriter();
246 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
247 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
248 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
251 "/// printInstruction - This method is automatically generated by tablegen\n"
252 "/// from the instruction set description.\n"
253 "void " << Target.getName() << ClassName
254 << "::printInstruction(const " << MachineInstrClassName
255 << " *MI, raw_ostream &O) {\n";
257 std::vector<AsmWriterInst> Instructions;
259 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
260 E = Target.inst_end(); I != E; ++I)
261 if (!(*I)->AsmString.empty() &&
262 (*I)->TheDef->getName() != "PHI")
263 Instructions.push_back(
265 AsmWriter->getValueAsInt("Variant"),
266 AsmWriter->getValueAsInt("FirstOperandColumn"),
267 AsmWriter->getValueAsInt("OperandSpacing")));
269 // Get the instruction numbering.
270 NumberedInstructions = Target.getInstructionsByEnumValue();
272 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
273 // all machine instructions are necessarily being printed, so there may be
274 // target instructions not in this map.
275 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
276 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
278 // Build an aggregate string, and build a table of offsets into it.
279 StringToOffsetTable StringTable;
281 /// OpcodeInfo - This encodes the index of the string to use for the first
282 /// chunk of the output as well as indices used for operand printing.
283 std::vector<unsigned> OpcodeInfo;
285 unsigned MaxStringIdx = 0;
286 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
287 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
290 // Something not handled by the asmwriter printer.
292 } else if (AWI->Operands[0].OperandType !=
293 AsmWriterOperand::isLiteralTextOperand ||
294 AWI->Operands[0].Str.empty()) {
295 // Something handled by the asmwriter printer, but with no leading string.
296 Idx = StringTable.GetOrAddStringOffset("");
298 std::string Str = AWI->Operands[0].Str;
300 Idx = StringTable.GetOrAddStringOffset(Str);
301 MaxStringIdx = std::max(MaxStringIdx, Idx);
303 // Nuke the string from the operand list. It is now handled!
304 AWI->Operands.erase(AWI->Operands.begin());
307 // Bias offset by one since we want 0 as a sentinel.
308 OpcodeInfo.push_back(Idx+1);
311 // Figure out how many bits we used for the string index.
312 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
314 // To reduce code size, we compactify common instructions into a few bits
315 // in the opcode-indexed table.
316 unsigned BitsLeft = 32-AsmStrBits;
318 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
321 std::vector<std::string> UniqueOperandCommands;
322 std::vector<unsigned> InstIdxs;
323 std::vector<unsigned> NumInstOpsHandled;
324 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
327 // If we ran out of operands to print, we're done.
328 if (UniqueOperandCommands.empty()) break;
330 // Compute the number of bits we need to represent these cases, this is
331 // ceil(log2(numentries)).
332 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
334 // If we don't have enough bits for this operand, don't include it.
335 if (NumBits > BitsLeft) {
336 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
341 // Otherwise, we can include this in the initial lookup table. Add it in.
343 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
344 if (InstIdxs[i] != ~0U)
345 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
347 // Remove the info about this operand.
348 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
349 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
350 if (!Inst->Operands.empty()) {
351 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
352 assert(NumOps <= Inst->Operands.size() &&
353 "Can't remove this many ops!");
354 Inst->Operands.erase(Inst->Operands.begin(),
355 Inst->Operands.begin()+NumOps);
359 // Remember the handlers for this set of operands.
360 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
365 O<<" static const unsigned OpInfo[] = {\n";
366 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
367 O << " " << OpcodeInfo[i] << "U,\t// "
368 << NumberedInstructions[i]->TheDef->getName() << "\n";
370 // Add a dummy entry so the array init doesn't end with a comma.
374 // Emit the string itself.
375 O << " const char *AsmStrs = \n";
376 StringTable.EmitString(O);
379 O << " O << \"\\t\";\n\n";
381 O << " // Emit the opcode for the instruction.\n"
382 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
383 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
384 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
386 // Output the table driven operand information.
387 BitsLeft = 32-AsmStrBits;
388 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
389 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
391 // Compute the number of bits we need to represent these cases, this is
392 // ceil(log2(numentries)).
393 unsigned NumBits = Log2_32_Ceil(Commands.size());
394 assert(NumBits <= BitsLeft && "consistency error");
396 // Emit code to extract this field from Bits.
399 O << "\n // Fragment " << i << " encoded into " << NumBits
400 << " bits for " << Commands.size() << " unique commands.\n";
402 if (Commands.size() == 2) {
403 // Emit two possibilitys with if/else.
404 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
405 << ((1 << NumBits)-1) << ") {\n"
410 } else if (Commands.size() == 1) {
411 // Emit a single possibility.
412 O << Commands[0] << "\n\n";
414 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
415 << ((1 << NumBits)-1) << ") {\n"
416 << " default: // unreachable.\n";
418 // Print out all the cases.
419 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
420 O << " case " << i << ":\n";
428 // Okay, delete instructions with no operand info left.
429 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
430 // Entire instruction has been emitted?
431 AsmWriterInst &Inst = Instructions[i];
432 if (Inst.Operands.empty()) {
433 Instructions.erase(Instructions.begin()+i);
439 // Because this is a vector, we want to emit from the end. Reverse all of the
440 // elements in the vector.
441 std::reverse(Instructions.begin(), Instructions.end());
444 // Now that we've emitted all of the operand info that fit into 32 bits, emit
445 // information for those instructions that are left. This is a less dense
446 // encoding, but we expect the main 32-bit table to handle the majority of
448 if (!Instructions.empty()) {
449 // Find the opcode # of inline asm.
450 O << " switch (MI->getOpcode()) {\n";
451 while (!Instructions.empty())
452 EmitInstructions(Instructions, O);
462 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
463 CodeGenTarget Target(Records);
464 Record *AsmWriter = Target.getAsmWriter();
465 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
466 const std::vector<CodeGenRegister*> &Registers =
467 Target.getRegBank().getRegisters();
469 StringToOffsetTable StringTable;
471 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
472 "/// from the register set description. This returns the assembler name\n"
473 "/// for the specified register.\n"
474 "const char *" << Target.getName() << ClassName
475 << "::getRegisterName(unsigned RegNo) {\n"
476 << " assert(RegNo && RegNo < " << (Registers.size()+1)
477 << " && \"Invalid register number!\");\n"
479 << " static const unsigned RegAsmOffset[] = {";
480 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
481 const CodeGenRegister &Reg = *Registers[i];
483 std::string AsmName = Reg.TheDef->getValueAsString("AsmName");
485 AsmName = Reg.getName();
491 O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
497 O << " const char *AsmStrs =\n";
498 StringTable.EmitString(O);
501 O << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
505 void AsmWriterEmitter::EmitGetInstructionName(raw_ostream &O) {
506 CodeGenTarget Target(Records);
507 Record *AsmWriter = Target.getAsmWriter();
508 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
510 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
511 Target.getInstructionsByEnumValue();
513 StringToOffsetTable StringTable;
515 "\n\n#ifdef GET_INSTRUCTION_NAME\n"
516 "#undef GET_INSTRUCTION_NAME\n\n"
517 "/// getInstructionName: This method is automatically generated by tblgen\n"
518 "/// from the instruction set description. This returns the enum name of the\n"
519 "/// specified instruction.\n"
520 "const char *" << Target.getName() << ClassName
521 << "::getInstructionName(unsigned Opcode) {\n"
522 << " assert(Opcode < " << NumberedInstructions.size()
523 << " && \"Invalid instruction number!\");\n"
525 << " static const unsigned InstAsmOffset[] = {";
526 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
527 const CodeGenInstruction &Inst = *NumberedInstructions[i];
529 std::string AsmName = Inst.TheDef->getName();
533 O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
539 O << " const char *Strs =\n";
540 StringTable.EmitString(O);
543 O << " return Strs+InstAsmOffset[Opcode];\n"
549 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
550 /// feature which participates in instruction matching.
551 struct SubtargetFeatureInfo {
552 /// \brief The predicate record for this feature.
553 const Record *TheDef;
555 /// \brief An unique index assigned to represent this feature.
558 SubtargetFeatureInfo(const Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
560 /// \brief The name of the enumerated constant identifying this feature.
561 std::string getEnumName() const {
562 return "Feature_" + TheDef->getName();
566 struct AsmWriterInfo {
567 /// Map of Predicate records to their subtarget information.
568 std::map<const Record*, SubtargetFeatureInfo*> SubtargetFeatures;
570 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
572 SubtargetFeatureInfo *getSubtargetFeature(const Record *Def) const {
573 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
574 std::map<const Record*, SubtargetFeatureInfo*>::const_iterator I =
575 SubtargetFeatures.find(Def);
576 return I == SubtargetFeatures.end() ? 0 : I->second;
579 void addReqFeatures(const std::vector<Record*> &Features) {
580 for (std::vector<Record*>::const_iterator
581 I = Features.begin(), E = Features.end(); I != E; ++I) {
582 const Record *Pred = *I;
584 // Ignore predicates that are not intended for the assembler.
585 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
588 if (Pred->getName().empty())
589 throw TGError(Pred->getLoc(), "Predicate has no name!");
591 // Don't add the predicate again.
592 if (getSubtargetFeature(Pred))
595 unsigned FeatureNo = SubtargetFeatures.size();
596 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
597 assert(FeatureNo < 32 && "Too many subtarget features!");
601 const SubtargetFeatureInfo *getFeatureInfo(const Record *R) {
602 return SubtargetFeatures[R];
606 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
607 // they both have the same conditionals. In which case, we cannot print out the
608 // alias for that pattern.
611 std::vector<std::string> Conds;
612 std::map<StringRef, unsigned> OpMap;
614 std::string AsmString;
615 std::vector<Record*> ReqFeatures;
617 IAPrinter(AsmWriterInfo &Info, std::string R, std::string AS)
618 : AWI(Info), Result(R), AsmString(AS) {}
620 void addCond(const std::string &C) { Conds.push_back(C); }
621 void addReqFeatures(const std::vector<Record*> &Features) {
622 AWI.addReqFeatures(Features);
623 ReqFeatures = Features;
626 void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
627 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
628 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
630 bool print(raw_ostream &O) {
631 if (Conds.empty() && ReqFeatures.empty()) {
632 O.indent(6) << "return true;\n";
638 for (std::vector<std::string>::iterator
639 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
640 if (I != Conds.begin()) {
648 if (!ReqFeatures.empty()) {
649 if (Conds.begin() != Conds.end()) {
657 raw_string_ostream ReqO(Req);
659 for (std::vector<Record*>::iterator
660 I = ReqFeatures.begin(), E = ReqFeatures.end(); I != E; ++I) {
661 if (I != ReqFeatures.begin()) ReqO << " | ";
662 ReqO << AWI.getFeatureInfo(*I)->getEnumName();
665 O << "(AvailableFeatures & (" << ReqO.str() << ")) == ("
666 << ReqO.str() << ')';
670 O.indent(6) << "// " << Result << "\n";
671 O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
673 for (std::map<StringRef, unsigned>::iterator
674 I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
675 O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
676 << I->second << "));\n";
678 O.indent(6) << "break;\n";
680 return !ReqFeatures.empty();
683 bool operator==(const IAPrinter &RHS) {
684 if (Conds.size() != RHS.Conds.size())
688 for (std::vector<std::string>::iterator
689 I = Conds.begin(), E = Conds.end(); I != E; ++I)
690 if (*I != RHS.Conds[Idx++])
696 bool operator()(const IAPrinter &RHS) {
697 if (Conds.size() < RHS.Conds.size())
701 for (std::vector<std::string>::iterator
702 I = Conds.begin(), E = Conds.end(); I != E; ++I)
703 if (*I != RHS.Conds[Idx++])
704 return *I < RHS.Conds[Idx++];
710 } // end anonymous namespace
712 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
714 static void EmitSubtargetFeatureFlagEnumeration(AsmWriterInfo &Info,
716 O << "namespace {\n\n";
717 O << "// Flags for subtarget features that participate in "
718 << "alias instruction matching.\n";
719 O << "enum SubtargetFeatureFlag {\n";
721 for (std::map<const Record*, SubtargetFeatureInfo*>::const_iterator
722 I = Info.SubtargetFeatures.begin(),
723 E = Info.SubtargetFeatures.end(); I != E; ++I) {
724 SubtargetFeatureInfo &SFI = *I->second;
725 O << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
728 O << " Feature_None = 0\n";
730 O << "} // end anonymous namespace\n\n";
733 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
734 /// available features given a subtarget.
735 static void EmitComputeAvailableFeatures(AsmWriterInfo &Info,
737 CodeGenTarget &Target,
739 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
741 O << "unsigned " << Target.getName() << ClassName << "::\n"
742 << "ComputeAvailableFeatures(const " << Target.getName()
743 << "Subtarget *Subtarget) const {\n";
744 O << " unsigned Features = 0;\n";
746 for (std::map<const Record*, SubtargetFeatureInfo*>::const_iterator
747 I = Info.SubtargetFeatures.begin(),
748 E = Info.SubtargetFeatures.end(); I != E; ++I) {
749 SubtargetFeatureInfo &SFI = *I->second;
750 O << " if (" << SFI.TheDef->getValueAsString("CondString")
752 O << " Features |= " << SFI.getEnumName() << ";\n";
755 O << " return Features;\n";
759 static void EmitGetMapOperandNumber(raw_ostream &O) {
760 O << "static unsigned getMapOperandNumber("
761 << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
762 O << " StringRef Name) {\n";
763 O << " for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
764 << "const_iterator\n";
765 O << " I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
766 O << " if (I->first == Name)\n";
767 O << " return I->second;\n";
768 O << " assert(false && \"Operand not in map!\");\n";
773 void AsmWriterEmitter::EmitRegIsInRegClass(raw_ostream &O) {
774 CodeGenTarget Target(Records);
776 // Enumerate the register classes.
777 const std::vector<CodeGenRegisterClass> &RegisterClasses =
778 Target.getRegisterClasses();
780 O << "namespace { // Register classes\n";
781 O << " enum RegClass {\n";
783 // Emit the register enum value for each RegisterClass.
784 for (unsigned I = 0, E = RegisterClasses.size(); I != E; ++I) {
785 if (I != 0) O << ",\n";
786 O << " RC_" << RegisterClasses[I].TheDef->getName();
790 O << "} // end anonymous namespace\n\n";
792 // Emit a function that returns 'true' if a regsiter is part of a particular
793 // register class. I.e., RAX is part of GR64 on X86.
794 O << "static bool regIsInRegisterClass"
795 << "(unsigned RegClass, unsigned Reg) {\n";
797 // Emit the switch that checks if a register belongs to a particular register
799 O << " switch (RegClass) {\n";
800 O << " default: break;\n";
802 for (unsigned I = 0, E = RegisterClasses.size(); I != E; ++I) {
803 const CodeGenRegisterClass &RC = RegisterClasses[I];
805 // Give the register class a legal C name if it's anonymous.
806 std::string Name = RC.TheDef->getName();
807 O << " case RC_" << Name << ":\n";
809 // Emit the register list now.
810 unsigned IE = RC.getOrder().size();
812 O << " if (Reg == " << getQualifiedName(RC.getOrder()[0]) << ")\n";
813 O << " return true;\n";
815 O << " switch (Reg) {\n";
816 O << " default: break;\n";
818 for (unsigned II = 0; II != IE; ++II) {
819 Record *Reg = RC.getOrder()[II];
820 O << " case " << getQualifiedName(Reg) << ":\n";
823 O << " return true;\n";
831 O << " return false;\n";
835 static unsigned CountNumOperands(StringRef AsmString) {
837 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
839 while (!ASM.second.empty()) {
841 ASM = ASM.second.split(' ');
847 static unsigned CountResultNumOperands(StringRef AsmString) {
849 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
851 if (!ASM.second.empty()) {
852 size_t I = ASM.second.find('{');
853 StringRef Str = ASM.second;
854 if (I != StringRef::npos)
855 Str = ASM.second.substr(I, ASM.second.find('|', I));
857 ASM = Str.split(' ');
861 ASM = ASM.second.split(' ');
862 } while (!ASM.second.empty());
868 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
869 CodeGenTarget Target(Records);
870 Record *AsmWriter = Target.getAsmWriter();
872 if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
875 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
876 O << "#undef PRINT_ALIAS_INSTR\n\n";
878 EmitRegIsInRegClass(O);
880 // Emit the method that prints the alias instruction.
881 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
883 std::vector<Record*> AllInstAliases =
884 Records.getAllDerivedDefinitions("InstAlias");
886 // Create a map from the qualified name to a list of potential matches.
887 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
888 for (std::vector<Record*>::iterator
889 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
890 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
891 const Record *R = *I;
892 if (!R->getValueAsBit("EmitAlias"))
893 continue; // We were told not to emit the alias, but to emit the aliasee.
894 const DagInit *DI = R->getValueAsDag("ResultInst");
895 const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
896 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
899 // A map of which conditions need to be met for each instruction operand
900 // before it can be matched to the mnemonic.
901 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
904 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
905 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
906 std::vector<CodeGenInstAlias*> &Aliases = I->second;
908 for (std::vector<CodeGenInstAlias*>::iterator
909 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
910 const CodeGenInstAlias *CGA = *II;
911 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
912 unsigned NumResultOps =
913 CountResultNumOperands(CGA->ResultInst->AsmString);
915 // Don't emit the alias if it has more operands than what it's aliasing.
916 if (NumResultOps < CountNumOperands(CGA->AsmString))
919 IAPrinter *IAP = new IAPrinter(AWI, CGA->Result->getAsString(),
921 IAP->addReqFeatures(CGA->TheDef->getValueAsListOfDefs("Predicates"));
924 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
927 std::map<StringRef, unsigned> OpMap;
928 bool CantHandle = false;
930 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
931 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
934 default: assert(0 && "unexpected InstAlias operand kind");
935 case CodeGenInstAlias::ResultOperand::K_Record: {
936 const Record *Rec = RO.getRecord();
937 StringRef ROName = RO.getName();
939 if (Rec->isSubClassOf("RegisterClass")) {
940 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
943 if (!IAP->isOpMapped(ROName)) {
944 IAP->addOperand(ROName, i);
945 Cond = std::string("regIsInRegisterClass(RC_") +
946 CGA->ResultOperands[i].getRecord()->getName() +
947 ", MI->getOperand(" + llvm::utostr(i) + ").getReg())";
950 Cond = std::string("MI->getOperand(") +
951 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
952 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
956 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
957 // FIXME: We may need to handle these situations.
966 case CodeGenInstAlias::ResultOperand::K_Imm:
967 Cond = std::string("MI->getOperand(") +
968 llvm::utostr(i) + ").getImm() == " +
969 llvm::utostr(CGA->ResultOperands[i].getImm());
972 case CodeGenInstAlias::ResultOperand::K_Reg:
973 Cond = std::string("MI->getOperand(") +
974 llvm::utostr(i) + ").getReg() == " + Target.getName() +
975 "::" + CGA->ResultOperands[i].getRegister()->getName();
983 if (CantHandle) continue;
984 IAPrinterMap[I->first].push_back(IAP);
988 EmitSubtargetFeatureFlagEnumeration(AWI, O);
989 EmitComputeAvailableFeatures(AWI, AsmWriter, Target, O);
992 raw_string_ostream HeaderO(Header);
994 HeaderO << "bool " << Target.getName() << ClassName
995 << "::printAliasInstr(const MCInst"
996 << " *MI, raw_ostream &OS) {\n";
999 raw_string_ostream CasesO(Cases);
1000 bool NeedAvailableFeatures = false;
1002 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
1003 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
1004 std::vector<IAPrinter*> &IAPs = I->second;
1005 std::vector<IAPrinter*> UniqueIAPs;
1007 for (std::vector<IAPrinter*>::iterator
1008 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
1009 IAPrinter *LHS = *II;
1011 for (std::vector<IAPrinter*>::iterator
1012 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
1013 IAPrinter *RHS = *III;
1014 if (LHS != RHS && *LHS == *RHS) {
1020 if (!IsDup) UniqueIAPs.push_back(LHS);
1023 if (UniqueIAPs.empty()) continue;
1025 CasesO.indent(2) << "case " << I->first << ":\n";
1027 for (std::vector<IAPrinter*>::iterator
1028 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
1029 IAPrinter *IAP = *II;
1031 NeedAvailableFeatures |= IAP->print(CasesO);
1035 CasesO.indent(4) << "return false;\n";
1038 if (CasesO.str().empty()) {
1040 O << " return false;\n";
1042 O << "#endif // PRINT_ALIAS_INSTR\n";
1046 EmitGetMapOperandNumber(O);
1049 O.indent(2) << "StringRef AsmString;\n";
1050 O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
1051 if (NeedAvailableFeatures)
1052 O.indent(2) << "unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1053 O.indent(2) << "switch (MI->getOpcode()) {\n";
1054 O.indent(2) << "default: return false;\n";
1056 O.indent(2) << "}\n\n";
1058 // Code that prints the alias, replacing the operands with the ones from the
1060 O << " std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
1061 O << " OS << '\\t' << ASM.first;\n";
1063 O << " if (!ASM.second.empty()) {\n";
1064 O << " OS << '\\t';\n";
1065 O << " for (StringRef::iterator\n";
1066 O << " I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
1067 O << " if (*I == '$') {\n";
1068 O << " StringRef::iterator Start = ++I;\n";
1069 O << " while (I != E &&\n";
1070 O << " ((*I >= 'a' && *I <= 'z') ||\n";
1071 O << " (*I >= 'A' && *I <= 'Z') ||\n";
1072 O << " (*I >= '0' && *I <= '9') ||\n";
1073 O << " *I == '_'))\n";
1075 O << " StringRef Name(Start, I - Start);\n";
1076 O << " printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
1078 O << " OS << *I++;\n";
1083 O << " return true;\n";
1086 O << "#endif // PRINT_ALIAS_INSTR\n";
1089 void AsmWriterEmitter::run(raw_ostream &O) {
1090 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
1092 EmitPrintInstruction(O);
1093 EmitGetRegisterName(O);
1094 EmitGetInstructionName(O);
1095 EmitPrintAliasInstruction(O);