Introduce a string_ostream string builder facilty
[oota-llvm.git] / utils / TableGen / CodeEmitterGen.cpp
1 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // CodeEmitterGen uses the descriptions of instructions and their fields to
11 // construct an automated code emitter: a function that, given a MachineInstr,
12 // returns the (currently, 32-bit unsigned) value of the instruction.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/TableGenBackend.h"
22 #include <map>
23 #include <string>
24 #include <vector>
25 using namespace llvm;
26
27 // FIXME: Somewhat hackish to use a command line option for this. There should
28 // be a CodeEmitter class in the Target.td that controls this sort of thing
29 // instead.
30 static cl::opt<bool>
31 MCEmitter("mc-emitter",
32           cl::desc("Generate CodeEmitter for use with the MC library."),
33           cl::init(false));
34
35 namespace {
36
37 class CodeEmitterGen {
38   RecordKeeper &Records;
39 public:
40   CodeEmitterGen(RecordKeeper &R) : Records(R) {}
41
42   void run(raw_ostream &o);
43 private:
44   int getVariableBit(const std::string &VarName, BitsInit *BI, int bit);
45   std::string getInstructionCase(Record *R, CodeGenTarget &Target);
46   void AddCodeToMergeInOperand(Record *R, BitsInit *BI,
47                                const std::string &VarName,
48                                unsigned &NumberedOp,
49                                std::set<unsigned> &NamedOpIndices,
50                                std::string &Case, CodeGenTarget &Target);
51
52 };
53
54 // If the VarBitInit at position 'bit' matches the specified variable then
55 // return the variable bit position.  Otherwise return -1.
56 int CodeEmitterGen::getVariableBit(const std::string &VarName,
57                                    BitsInit *BI, int bit) {
58   if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) {
59     if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar()))
60       if (VI->getName() == VarName)
61         return VBI->getBitNum();
62   } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) {
63     if (VI->getName() == VarName)
64       return 0;
65   }
66
67   return -1;
68 }
69
70 void CodeEmitterGen::
71 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
72                         unsigned &NumberedOp,
73                         std::set<unsigned> &NamedOpIndices,
74                         std::string &Case, CodeGenTarget &Target) {
75   CodeGenInstruction &CGI = Target.getInstruction(R);
76
77   // Determine if VarName actually contributes to the Inst encoding.
78   int bit = BI->getNumBits()-1;
79
80   // Scan for a bit that this contributed to.
81   for (; bit >= 0; ) {
82     if (getVariableBit(VarName, BI, bit) != -1)
83       break;
84     
85     --bit;
86   }
87   
88   // If we found no bits, ignore this value, otherwise emit the call to get the
89   // operand encoding.
90   if (bit < 0) return;
91   
92   // If the operand matches by name, reference according to that
93   // operand number. Non-matching operands are assumed to be in
94   // order.
95   unsigned OpIdx;
96   if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
97     // Get the machine operand number for the indicated operand.
98     OpIdx = CGI.Operands[OpIdx].MIOperandNo;
99     assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
100            "Explicitly used operand also marked as not emitted!");
101   } else {
102     unsigned NumberOps = CGI.Operands.size();
103     /// If this operand is not supposed to be emitted by the
104     /// generated emitter, skip it.
105     while (NumberedOp < NumberOps &&
106            (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
107               (NamedOpIndices.size() && NamedOpIndices.count(
108                 CGI.Operands.getSubOperandNumber(NumberedOp).first)))) {
109       ++NumberedOp;
110
111       if (NumberedOp >= CGI.Operands.back().MIOperandNo +
112                         CGI.Operands.back().MINumOperands) {
113         errs() << "Too few operands in record " << R->getName() <<
114                   " (no match for variable " << VarName << "):\n";
115         errs() << *R;
116         errs() << '\n';
117
118         return;
119       }
120     }
121
122     OpIdx = NumberedOp++;
123   }
124   
125   std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
126   std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
127   
128   // If the source operand has a custom encoder, use it. This will
129   // get the encoding for all of the suboperands.
130   if (!EncoderMethodName.empty()) {
131     // A custom encoder has all of the information for the
132     // sub-operands, if there are more than one, so only
133     // query the encoder once per source operand.
134     if (SO.second == 0) {
135       Case += "      // op: " + VarName + "\n" +
136               "      op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
137       if (MCEmitter)
138         Case += ", Fixups, STI";
139       Case += ");\n";
140     }
141   } else {
142     Case += "      // op: " + VarName + "\n" +
143       "      op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
144     if (MCEmitter)
145       Case += ", Fixups, STI";
146     Case += ");\n";
147   }
148   
149   for (; bit >= 0; ) {
150     int varBit = getVariableBit(VarName, BI, bit);
151     
152     // If this bit isn't from a variable, skip it.
153     if (varBit == -1) {
154       --bit;
155       continue;
156     }
157     
158     // Figure out the consecutive range of bits covered by this operand, in
159     // order to generate better encoding code.
160     int beginInstBit = bit;
161     int beginVarBit = varBit;
162     int N = 1;
163     for (--bit; bit >= 0;) {
164       varBit = getVariableBit(VarName, BI, bit);
165       if (varBit == -1 || varBit != (beginVarBit - N)) break;
166       ++N;
167       --bit;
168     }
169      
170     uint64_t opMask = ~(uint64_t)0 >> (64-N);
171     int opShift = beginVarBit - N + 1;
172     opMask <<= opShift;
173     opShift = beginInstBit - beginVarBit;
174     
175     if (opShift > 0) {
176       Case += "      Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
177               itostr(opShift) + ";\n";
178     } else if (opShift < 0) {
179       Case += "      Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " + 
180               itostr(-opShift) + ";\n";
181     } else {
182       Case += "      Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
183     }
184   }
185 }
186
187
188 std::string CodeEmitterGen::getInstructionCase(Record *R,
189                                                CodeGenTarget &Target) {
190   std::string Case;
191   
192   BitsInit *BI = R->getValueAsBitsInit("Inst");
193   const std::vector<RecordVal> &Vals = R->getValues();
194   unsigned NumberedOp = 0;
195
196   std::set<unsigned> NamedOpIndices;
197   // Collect the set of operand indices that might correspond to named
198   // operand, and skip these when assigning operands based on position.
199   if (Target.getInstructionSet()->
200        getValueAsBit("noNamedPositionallyEncodedOperands")) {
201     CodeGenInstruction &CGI = Target.getInstruction(R);
202     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
203       unsigned OpIdx;
204       if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
205         continue;
206
207       NamedOpIndices.insert(OpIdx);
208     }
209   }
210
211   // Loop over all of the fields in the instruction, determining which are the
212   // operands to the instruction.
213   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
214     // Ignore fixed fields in the record, we're looking for values like:
215     //    bits<5> RST = { ?, ?, ?, ?, ? };
216     if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
217       continue;
218     
219     AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp,
220                             NamedOpIndices, Case, Target);
221   }
222   
223   std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
224   if (!PostEmitter.empty()) {
225     Case += "      Value = " + PostEmitter + "(MI, Value";
226     if (MCEmitter)
227       Case += ", STI";
228     Case += ");\n";
229   }
230   
231   return Case;
232 }
233
234 void CodeEmitterGen::run(raw_ostream &o) {
235   CodeGenTarget Target(Records);
236   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
237
238   // For little-endian instruction bit encodings, reverse the bit order
239   Target.reverseBitsForLittleEndianEncoding();
240
241   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
242     Target.getInstructionsByEnumValue();
243
244   // Emit function declaration
245   o << "uint64_t " << Target.getName();
246   if (MCEmitter)
247     o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
248       << "    SmallVectorImpl<MCFixup> &Fixups,\n"
249       << "    const MCSubtargetInfo &STI) const {\n";
250   else
251     o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
252
253   // Emit instruction base values
254   o << "  static const uint64_t InstBits[] = {\n";
255   for (std::vector<const CodeGenInstruction*>::const_iterator
256           IN = NumberedInstructions.begin(),
257           EN = NumberedInstructions.end();
258        IN != EN; ++IN) {
259     const CodeGenInstruction *CGI = *IN;
260     Record *R = CGI->TheDef;
261
262     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
263         R->getValueAsBit("isPseudo")) {
264       o << "    UINT64_C(0),\n";
265       continue;
266     }
267
268     BitsInit *BI = R->getValueAsBitsInit("Inst");
269
270     // Start by filling in fixed values.
271     uint64_t Value = 0;
272     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
273       if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1)))
274         Value |= (uint64_t)B->getValue() << (e-i-1);
275     }
276     o << "    UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
277   }
278   o << "    UINT64_C(0)\n  };\n";
279
280   // Map to accumulate all the cases.
281   std::map<std::string, std::vector<std::string> > CaseMap;
282
283   // Construct all cases statement for each opcode
284   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
285         IC != EC; ++IC) {
286     Record *R = *IC;
287     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
288         R->getValueAsBit("isPseudo"))
289       continue;
290     const std::string &InstName = R->getValueAsString("Namespace") + "::"
291       + R->getName();
292     std::string Case = getInstructionCase(R, Target);
293
294     CaseMap[Case].push_back(InstName);
295   }
296
297   // Emit initial function code
298   o << "  const unsigned opcode = MI.getOpcode();\n"
299     << "  uint64_t Value = InstBits[opcode];\n"
300     << "  uint64_t op = 0;\n"
301     << "  (void)op;  // suppress warning\n"
302     << "  switch (opcode) {\n";
303
304   // Emit each case statement
305   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
306   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
307     const std::string &Case = IE->first;
308     std::vector<std::string> &InstList = IE->second;
309
310     for (int i = 0, N = InstList.size(); i < N; i++) {
311       if (i) o << "\n";
312       o << "    case " << InstList[i]  << ":";
313     }
314     o << " {\n";
315     o << Case;
316     o << "      break;\n"
317       << "    }\n";
318   }
319
320   // Default case: unhandled opcode
321   o << "  default:\n"
322     << "    string_ostream Msg;\n"
323     << "    Msg << \"Not supported instr: \" << MI;\n"
324     << "    report_fatal_error(Msg.str());\n"
325     << "  }\n"
326     << "  return Value;\n"
327     << "}\n\n";
328 }
329
330 } // End anonymous namespace
331
332 namespace llvm {
333
334 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
335   emitSourceFileHeader("Machine Code Emitter", OS);
336   CodeEmitterGen(RK).run(OS);
337 }
338
339 } // End llvm namespace