1 //===- EDEmitter.cpp - Generate instruction descriptions for ED -*- C++ -*-===//
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 responsible for emitting a description of each
11 // instruction in a format that the enhanced disassembler can use to tokenize
12 // and parse instructions.
14 //===----------------------------------------------------------------------===//
16 #include "EDEmitter.h"
18 #include "CodeGenTarget.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/raw_ostream.h"
28 #define MAX_OPERANDS 5
29 #define MAX_SYNTAXES 2
33 ///////////////////////////////////////////////////////////
34 // Support classes for emitting nested C data structures //
35 ///////////////////////////////////////////////////////////
42 std::vector<std::string> Entries;
44 EnumEmitter(const char *N) : Name(N) {
46 int addEntry(const char *e) {
47 Entries.push_back(std::string(e));
48 return Entries.size() - 1;
50 void emit(raw_ostream &o, unsigned int &i) {
51 o.indent(i) << "enum " << Name.c_str() << " {" << "\n";
54 unsigned int index = 0;
55 unsigned int numEntries = Entries.size();
56 for(index = 0; index < numEntries; ++index) {
57 o.indent(i) << Entries[index];
58 if(index < (numEntries - 1))
64 o.indent(i) << "};" << "\n";
67 void emitAsFlags(raw_ostream &o, unsigned int &i) {
68 o.indent(i) << "enum " << Name.c_str() << " {" << "\n";
71 unsigned int index = 0;
72 unsigned int numEntries = Entries.size();
73 unsigned int flag = 1;
74 for (index = 0; index < numEntries; ++index) {
75 o.indent(i) << Entries[index] << " = " << format("0x%x", flag);
76 if (index < (numEntries - 1))
83 o.indent(i) << "};" << "\n";
90 std::vector<std::string> MemberTypes;
91 std::vector<std::string> MemberNames;
93 StructEmitter(const char *N) : Name(N) {
95 void addMember(const char *t, const char *n) {
96 MemberTypes.push_back(std::string(t));
97 MemberNames.push_back(std::string(n));
99 void emit(raw_ostream &o, unsigned int &i) {
100 o.indent(i) << "struct " << Name.c_str() << " {" << "\n";
103 unsigned int index = 0;
104 unsigned int numMembers = MemberTypes.size();
105 for (index = 0; index < numMembers; ++index) {
106 o.indent(i) << MemberTypes[index] << " " << MemberNames[index] << ";";
111 o.indent(i) << "};" << "\n";
115 class ConstantEmitter {
117 virtual ~ConstantEmitter() { }
118 virtual void emit(raw_ostream &o, unsigned int &i) = 0;
121 class LiteralConstantEmitter : public ConstantEmitter {
125 LiteralConstantEmitter(const char *literal) : Literal(literal) {
127 LiteralConstantEmitter(int literal) {
129 snprintf(buf, 256, "%d", literal);
132 void emit(raw_ostream &o, unsigned int &i) {
137 class CompoundConstantEmitter : public ConstantEmitter {
139 std::vector<ConstantEmitter*> Entries;
141 CompoundConstantEmitter() {
143 ~CompoundConstantEmitter() {
145 unsigned int numEntries = Entries.size();
146 for (index = 0; index < numEntries; ++index) {
147 delete Entries[index];
150 CompoundConstantEmitter &addEntry(ConstantEmitter *e) {
151 Entries.push_back(e);
154 void emit(raw_ostream &o, unsigned int &i) {
159 unsigned int numEntries = Entries.size();
160 for (index = 0; index < numEntries; ++index) {
162 Entries[index]->emit(o, i);
163 if (index < (numEntries - 1))
173 class FlagsConstantEmitter : public ConstantEmitter {
175 std::vector<std::string> Flags;
177 FlagsConstantEmitter() {
179 FlagsConstantEmitter &addEntry(const char *f) {
180 Flags.push_back(std::string(f));
183 void emit(raw_ostream &o, unsigned int &i) {
185 unsigned int numFlags = Flags.size();
189 for (index = 0; index < numFlags; ++index) {
190 o << Flags[index].c_str();
191 if (index < (numFlags - 1))
198 EDEmitter::EDEmitter(RecordKeeper &R) : Records(R) {
201 //////////////////////////////////////////////
202 // Support functions for parsing AsmStrings //
203 //////////////////////////////////////////////
205 /// parseError - A better error reporter for use in AsmString parsers
207 /// @arg asmString - The original assembly string, for use in the error report
208 /// @arg index - The character where the error occurred
209 /// @arg err - The text of the error itself
210 static void parseError(const std::string& asmString,
213 errs() << "In: " << asmString.c_str() << "\n";
214 errs() << "Error at " << format("%d", index) << ": " << err << "\n";
215 llvm_unreachable("Parse error");
218 /// resolveBraces - Interprets the brace syntax in an AsmString in favor of just
219 /// one syntax, and returns the result. "{A}" is resolved to "A" for syntax 0
220 /// and "" for all others; "{A|B}" is resolved to "A" for syntax 0, "B" for
221 /// syntax 1, and "" for all others; and so on.
223 /// @arg asmString - The original string, as loaded from the .td file
224 /// @arg syntaxIndex - The index to use
225 static std::string resolveBraces(const std::string &asmString,
226 unsigned int syntaxIndex) {
230 unsigned int numChars = asmString.length();
232 // Brace parsing countable-state transducer
234 // STATES - -1, 0, 1, ..., error
235 // SYMBOLS - '{', '|', '}', ?, EOF
238 // state input -> state output
247 // n ? -> n ? if n == syntaxIndex
253 for (index = 0; index < numChars; ++index) {
254 char input = asmString[index];
260 if (state == (int)syntaxIndex)
261 ret.push_back(input);
264 parseError(asmString, index, "Nested { in AsmString");
277 ret.push_back(input);
283 parseError(asmString, index, "| outside braces in AsmString");
286 parseError(asmString, index, "Unmatched } in AsmString");
294 parseError(asmString, index, "Unmatched { in AsmString");
299 /// getOperandIndex - looks up a named operand in an instruction and determines
300 /// its index in the operand descriptor array, returning the index or -1 if it
303 /// @arg asmString - The assembly string for the instruction, for errors only
304 /// @arg operand - The operand's name
305 /// @arg inst - The instruction to use when looking up the operand
306 static int8_t getOperandIndex(const std::string &asmString,
307 const std::string &operand,
308 const CodeGenInstruction &inst) {
311 if(operand.length() == 0) {
312 errs() << "In: " << asmString << "\n";
313 errs() << "Operand: " << operand << "\n";
314 llvm_unreachable("Empty operand");
318 operandIndex = inst.getOperandNamed(operand);
327 /// isAlphanumeric - returns true if a character is a valid alphanumeric
328 /// character, and false otherwise
330 /// input - The character to query
331 static inline bool isAlphanumeric(char input) {
332 if((input >= 'a' && input <= 'z') ||
333 (input >= 'A' && input <= 'Z') ||
334 (input >= '0' && input <= '9') ||
341 /// populateOperandOrder - reads a resolved AsmString (see resolveBraces) and
342 /// records the index into the operand descriptor array for each operand in
343 /// that string, in the order of appearance.
345 /// @arg operandOrder - The array that will be populated with the operand
346 /// mapping. Each entry will contain -1 (invalid index
347 /// into the operands present in the AsmString) or a number
348 /// representing an index in the operand descriptor array.
349 /// @arg asmString - The operand's name
350 /// @arg inst - The instruction to use when looking up the operand
351 void populateOperandOrder(CompoundConstantEmitter *operandOrder,
352 const std::string &asmString,
353 const CodeGenInstruction &inst) {
357 unsigned int numChars = asmString.length();
358 unsigned int numArgs = 0;
360 // Argument processing finite-state transducer
362 // STATES - 0, 1, error
363 // SYMBOLS - A(lphanumeric), '$', ?, EOF
366 // state input -> state aux
376 unsigned int state = 0;
378 for (index = 0; index < numChars; ++index) {
379 char input = asmString[index];
383 parseError(asmString, index, "Parser in unreachable state");
390 if (isAlphanumeric(input)) {
391 aux.push_back(input);
393 else if (input == '$') {
394 parseError(asmString, index, "$ found in argument name");
397 int8_t operandIndex = getOperandIndex(asmString, aux, inst);
399 snprintf(buf, sizeof(buf), "%d", operandIndex);
400 operandOrder->addEntry(new LiteralConstantEmitter(buf));
410 int8_t operandIndex = getOperandIndex(asmString, aux, inst);
412 snprintf(buf, 2, "%d", operandIndex);
413 operandOrder->addEntry(new LiteralConstantEmitter(buf));
418 for(; numArgs < MAX_OPERANDS; numArgs++) {
419 operandOrder->addEntry(new LiteralConstantEmitter("-1"));
423 /////////////////////////////////////////////////////
424 // Support functions for handling X86 instructions //
425 /////////////////////////////////////////////////////
427 #define ADDFLAG(flag) flags->addEntry(flag)
429 #define REG(str) if (name == str) { ADDFLAG("kOperandFlagRegister"); return 0; }
430 #define MEM(str) if (name == str) { ADDFLAG("kOperandFlagMemory"); return 0; }
431 #define LEA(str) if (name == str) { ADDFLAG("kOperandFlagEffectiveAddress"); \
433 #define IMM(str) if (name == str) { ADDFLAG("kOperandFlagImmediate"); \
435 #define PCR(str) if (name == str) { ADDFLAG("kOperandFlagMemory"); \
436 ADDFLAG("kOperandFlagPCRelative"); \
439 /// X86FlagFromOpName - Processes the name of a single X86 operand (which is
440 /// actually its type) and translates it into an operand flag
442 /// @arg flags - The flags object to add the flag to
443 /// @arg name - The name of the operand
444 static int X86FlagFromOpName(FlagsConstantEmitter *flags,
445 const std::string &name) {
462 REG("CONTROL_REG_32");
463 REG("CONTROL_REG_64");
495 IMM("i64i32imm_pcrel");
515 /// X86PopulateOperands - Handles all the operands in an X86 instruction, adding
516 /// the appropriate flags to their descriptors
518 /// @operandFlags - A reference the array of operand flag objects
519 /// @inst - The instruction to use as a source of information
520 static void X86PopulateOperands(
521 FlagsConstantEmitter *(&operandFlags)[MAX_OPERANDS],
522 const CodeGenInstruction &inst) {
523 if (!inst.TheDef->isSubClassOf("X86Inst"))
527 unsigned int numOperands = inst.OperandList.size();
529 for (index = 0; index < numOperands; ++index) {
530 const CodeGenInstruction::OperandInfo &operandInfo =
531 inst.OperandList[index];
532 Record &rec = *operandInfo.Rec;
534 if (X86FlagFromOpName(operandFlags[index], rec.getName())) {
535 errs() << "Operand type: " << rec.getName().c_str() << "\n";
536 errs() << "Operand name: " << operandInfo.Name.c_str() << "\n";
537 errs() << "Instruction mame: " << inst.TheDef->getName().c_str() << "\n";
538 llvm_unreachable("Unhandled type");
543 /// decorate1 - Decorates a named operand with a new flag
545 /// @operandFlags - The array of operand flag objects, which don't have names
546 /// @inst - The CodeGenInstruction, which provides a way to translate
547 /// between names and operand indices
548 /// @opName - The name of the operand
549 /// @flag - The name of the flag to add
550 static inline void decorate1(FlagsConstantEmitter *(&operandFlags)[MAX_OPERANDS],
551 const CodeGenInstruction &inst,
553 const char *opFlag) {
557 opIndex = inst.getOperandNamed(std::string(opName));
560 errs() << "Instruction: " << inst.TheDef->getName().c_str() << "\n";
561 errs() << "Operand name: " << opName << "\n";
562 llvm_unreachable("Couldn't find operand");
565 operandFlags[opIndex]->addEntry(opFlag);
568 #define DECORATE1(opName, opFlag) decorate1(operandFlags, inst, opName, opFlag)
570 #define MOV(source, target) { \
571 instFlags.addEntry("kInstructionFlagMove"); \
572 DECORATE1(source, "kOperandFlagSource"); \
573 DECORATE1(target, "kOperandFlagTarget"); \
576 #define BRANCH(target) { \
577 instFlags.addEntry("kInstructionFlagBranch"); \
578 DECORATE1(target, "kOperandFlagTarget"); \
581 #define PUSH(source) { \
582 instFlags.addEntry("kInstructionFlagPush"); \
583 DECORATE1(source, "kOperandFlagSource"); \
586 #define POP(target) { \
587 instFlags.addEntry("kInstructionFlagPop"); \
588 DECORATE1(target, "kOperandFlagTarget"); \
591 #define CALL(target) { \
592 instFlags.addEntry("kInstructionFlagCall"); \
593 DECORATE1(target, "kOperandFlagTarget"); \
597 instFlags.addEntry("kInstructionFlagReturn"); \
600 /// X86ExtractSemantics - Performs various checks on the name of an X86
601 /// instruction to determine what sort of an instruction it is and then adds
602 /// the appropriate flags to the instruction and its operands
604 /// @arg instFlags - A reference to the flags for the instruction as a whole
605 /// @arg operandFlags - A reference to the array of operand flag object pointers
606 /// @arg inst - A reference to the original instruction
607 static void X86ExtractSemantics(FlagsConstantEmitter &instFlags,
608 FlagsConstantEmitter *(&operandFlags)[MAX_OPERANDS],
609 const CodeGenInstruction &inst) {
610 const std::string &name = inst.TheDef->getName();
612 if (name.find("MOV") != name.npos) {
613 if (name.find("MOV_V") != name.npos) {
614 // ignore (this is a pseudoinstruction)
616 else if (name.find("MASK") != name.npos) {
617 // ignore (this is a masking move)
619 else if (name.find("r0") != name.npos) {
620 // ignore (this is a pseudoinstruction)
622 else if (name.find("PS") != name.npos ||
623 name.find("PD") != name.npos) {
624 // ignore (this is a shuffling move)
626 else if (name.find("MOVS") != name.npos) {
627 // ignore (this is a string move)
629 else if (name.find("_F") != name.npos) {
630 // TODO handle _F moves to ST(0)
632 else if (name.find("a") != name.npos) {
633 // TODO handle moves to/from %ax
635 else if (name.find("CMOV") != name.npos) {
638 else if (name.find("PC") != name.npos) {
646 if (name.find("JMP") != name.npos ||
647 name.find("J") == 0) {
648 if (name.find("FAR") != name.npos && name.find("i") != name.npos) {
656 if (name.find("PUSH") != name.npos) {
657 if (name.find("FS") != name.npos ||
658 name.find("GS") != name.npos) {
659 instFlags.addEntry("kInstructionFlagPush");
660 // TODO add support for fixed operands
662 else if (name.find("F") != name.npos) {
663 // ignore (this pushes onto the FP stack)
665 else if (name[name.length() - 1] == 'm') {
668 else if (name.find("i") != name.npos) {
676 if (name.find("POP") != name.npos) {
677 if (name.find("POPCNT") != name.npos) {
678 // ignore (not a real pop)
680 else if (name.find("FS") != name.npos ||
681 name.find("GS") != name.npos) {
682 instFlags.addEntry("kInstructionFlagPop");
683 // TODO add support for fixed operands
685 else if (name.find("F") != name.npos) {
686 // ignore (this pops from the FP stack)
688 else if (name[name.length() - 1] == 'm') {
696 if (name.find("CALL") != name.npos) {
697 if (name.find("ADJ") != name.npos) {
698 // ignore (not a call)
700 else if (name.find("SYSCALL") != name.npos) {
701 // ignore (doesn't go anywhere we know about)
703 else if (name.find("VMCALL") != name.npos) {
704 // ignore (rather different semantics than a regular call)
706 else if (name.find("FAR") != name.npos && name.find("i") != name.npos) {
714 if (name.find("RET") != name.npos) {
726 #undef COND_DECORATE_2
727 #undef COND_DECORATE_1
730 /// populateInstInfo - Fills an array of InstInfos with information about each
731 /// instruction in a target
733 /// @arg infoArray - The array of InstInfo objects to populate
734 /// @arg target - The CodeGenTarget to use as a source of instructions
735 static void populateInstInfo(CompoundConstantEmitter &infoArray,
736 CodeGenTarget &target) {
737 std::vector<const CodeGenInstruction*> numberedInstructions;
738 target.getInstructionsByEnumValue(numberedInstructions);
741 unsigned int numInstructions = numberedInstructions.size();
743 for (index = 0; index < numInstructions; ++index) {
744 const CodeGenInstruction& inst = *numberedInstructions[index];
746 CompoundConstantEmitter *infoStruct = new CompoundConstantEmitter;
747 infoArray.addEntry(infoStruct);
749 FlagsConstantEmitter *instFlags = new FlagsConstantEmitter;
750 infoStruct->addEntry(instFlags);
752 LiteralConstantEmitter *numOperandsEmitter =
753 new LiteralConstantEmitter(inst.OperandList.size());
754 infoStruct->addEntry(numOperandsEmitter);
756 CompoundConstantEmitter *operandFlagArray = new CompoundConstantEmitter;
757 infoStruct->addEntry(operandFlagArray);
759 FlagsConstantEmitter *operandFlags[MAX_OPERANDS];
761 for (unsigned operandIndex = 0; operandIndex < MAX_OPERANDS; ++operandIndex) {
762 operandFlags[operandIndex] = new FlagsConstantEmitter;
763 operandFlagArray->addEntry(operandFlags[operandIndex]);
766 unsigned numSyntaxes = 0;
768 if (target.getName() == "X86") {
769 X86PopulateOperands(operandFlags, inst);
770 X86ExtractSemantics(*instFlags, operandFlags, inst);
774 CompoundConstantEmitter *operandOrderArray = new CompoundConstantEmitter;
775 infoStruct->addEntry(operandOrderArray);
777 for (unsigned syntaxIndex = 0; syntaxIndex < MAX_SYNTAXES; ++syntaxIndex) {
778 CompoundConstantEmitter *operandOrder = new CompoundConstantEmitter;
779 operandOrderArray->addEntry(operandOrder);
781 if (syntaxIndex < numSyntaxes) {
782 std::string asmString = inst.AsmString;
783 asmString = resolveBraces(asmString, syntaxIndex);
784 populateOperandOrder(operandOrder, asmString, inst);
787 for (unsigned operandIndex = 0;
788 operandIndex < MAX_OPERANDS;
790 operandOrder->addEntry(new LiteralConstantEmitter("-1"));
797 void EDEmitter::run(raw_ostream &o) {
800 CompoundConstantEmitter infoArray;
801 CodeGenTarget target;
803 populateInstInfo(infoArray, target);
805 o << "InstInfo instInfo" << target.getName().c_str() << "[] = ";
806 infoArray.emit(o, i);
810 void EDEmitter::runHeader(raw_ostream &o) {
811 EmitSourceFileHeader("Semantic Information Header", o);
813 o << "#ifndef SemanticInfo_" << "\n";
814 o << "#define SemanticInfo_" << "\n";
816 o << "#include <inttypes.h>" << "\n";
818 o << "#define MAX_OPERANDS " << format("%d", MAX_OPERANDS) << "\n";
819 o << "#define MAX_SYNTAXES " << format("%d", MAX_SYNTAXES) << "\n";
824 EnumEmitter operandFlags("OperandFlags");
825 operandFlags.addEntry("kOperandFlagImmediate");
826 operandFlags.addEntry("kOperandFlagRegister");
827 operandFlags.addEntry("kOperandFlagMemory");
828 operandFlags.addEntry("kOperandFlagEffectiveAddress");
829 operandFlags.addEntry("kOperandFlagPCRelative");
830 operandFlags.addEntry("kOperandFlagSource");
831 operandFlags.addEntry("kOperandFlagTarget");
832 operandFlags.emitAsFlags(o, i);
836 EnumEmitter instructionFlags("InstructionFlags");
837 instructionFlags.addEntry("kInstructionFlagMove");
838 instructionFlags.addEntry("kInstructionFlagBranch");
839 instructionFlags.addEntry("kInstructionFlagPush");
840 instructionFlags.addEntry("kInstructionFlagPop");
841 instructionFlags.addEntry("kInstructionFlagCall");
842 instructionFlags.addEntry("kInstructionFlagReturn");
843 instructionFlags.emitAsFlags(o, i);
847 StructEmitter instInfo("InstInfo");
848 instInfo.addMember("uint32_t", "instructionFlags");
849 instInfo.addMember("uint8_t", "numOperands");
850 instInfo.addMember("uint8_t", "operandFlags[MAX_OPERANDS]");
851 instInfo.addMember("const char", "operandOrders[MAX_SYNTAXES][MAX_OPERANDS]");
855 o << "#endif" << "\n";