1 //===- TableGen.cpp - Top-Level TableGen implementation -------------------===//
3 // TableGen is a tool which can be used to build up a description of something,
4 // then invoke one or more "tablegen backends" to emit information about the
5 // description in some predefined format. In practice, this is used by the LLVM
6 // code generators to automate generation of a code generator through a
7 // high-level description of the target.
9 //===----------------------------------------------------------------------===//
12 #include "Support/CommandLine.h"
13 #include "Support/Signals.h"
14 #include "Support/FileUtilities.h"
15 #include "CodeEmitterGen.h"
16 #include "RegisterInfoEmitter.h"
17 #include "InstrInfoEmitter.h"
18 #include "InstrSelectorEmitter.h"
26 GenRegisterEnums, GenRegister, GenRegisterHeader,
27 GenInstrEnums, GenInstrs, GenInstrSelector,
34 Action(cl::desc("Action to perform:"),
35 cl::values(clEnumValN(PrintRecords, "print-records",
36 "Print all records to stdout (default)"),
37 clEnumValN(GenEmitter, "gen-emitter",
38 "Generate machine code emitter"),
39 clEnumValN(GenRegisterEnums, "gen-register-enums",
40 "Generate enum values for registers"),
41 clEnumValN(GenRegister, "gen-register-desc",
42 "Generate a register info description"),
43 clEnumValN(GenRegisterHeader, "gen-register-desc-header",
44 "Generate a register info description header"),
45 clEnumValN(GenInstrEnums, "gen-instr-enums",
46 "Generate enum values for instructions"),
47 clEnumValN(GenInstrs, "gen-instr-desc",
48 "Generate instruction descriptions"),
49 clEnumValN(GenInstrSelector, "gen-instr-selector",
50 "Generate an instruction selector"),
51 clEnumValN(PrintEnums, "print-enums",
52 "Print enum values for a class"),
53 clEnumValN(Parse, "parse",
54 "Interpret machine code (testing only)"),
58 Class("class", cl::desc("Print Enum list for this class"),
59 cl::value_desc("class name"));
62 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
66 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
70 void ParseFile(const std::string &Filename);
74 static Init *getBit(Record *R, unsigned BitNo) {
75 const std::vector<RecordVal> &V = R->getValues();
76 for (unsigned i = 0, e = V.size(); i != e; ++i)
77 if (V[i].getPrefix()) {
78 assert(dynamic_cast<BitsInit*>(V[i].getValue()) &&
79 "Can only handle fields of bits<> type!");
80 BitsInit *I = (BitsInit*)V[i].getValue();
81 if (BitNo < I->getNumBits())
82 return I->getBit(BitNo);
83 BitNo -= I->getNumBits();
86 std::cerr << "Cannot find requested bit!\n";
91 static unsigned getNumBits(Record *R) {
92 const std::vector<RecordVal> &V = R->getValues();
94 for (unsigned i = 0, e = V.size(); i != e; ++i)
95 if (V[i].getPrefix()) {
96 assert(dynamic_cast<BitsInit*>(V[i].getValue()) &&
97 "Can only handle fields of bits<> type!");
98 Num += ((BitsInit*)V[i].getValue())->getNumBits();
103 static bool BitsAreFixed(Record *I1, Record *I2, unsigned BitNo) {
104 return dynamic_cast<BitInit*>(getBit(I1, BitNo)) &&
105 dynamic_cast<BitInit*>(getBit(I2, BitNo));
108 static bool BitsAreEqual(Record *I1, Record *I2, unsigned BitNo) {
109 BitInit *Bit1 = dynamic_cast<BitInit*>(getBit(I1, BitNo));
110 BitInit *Bit2 = dynamic_cast<BitInit*>(getBit(I2, BitNo));
112 return Bit1 && Bit2 && Bit1->getValue() == Bit2->getValue();
115 static bool BitRangesEqual(Record *I1, Record *I2,
116 unsigned Start, unsigned End) {
117 for (unsigned i = Start; i != End; ++i)
118 if (!BitsAreEqual(I1, I2, i))
123 static unsigned getFirstFixedBit(Record *R, unsigned FirstFixedBit) {
124 // Look for the first bit of the pair that are required to be 0 or 1.
125 while (!dynamic_cast<BitInit*>(getBit(R, FirstFixedBit)))
127 return FirstFixedBit;
130 static void FindInstDifferences(Record *I1, Record *I2,
131 unsigned FirstFixedBit, unsigned MaxBits,
132 unsigned &FirstVaryingBitOverall,
133 unsigned &LastFixedBitOverall) {
134 // Compare the first instruction to the rest of the instructions, looking for
135 // fields that differ.
137 unsigned FirstVaryingBit = FirstFixedBit;
138 while (FirstVaryingBit < MaxBits && BitsAreEqual(I1, I2, FirstVaryingBit))
141 unsigned LastFixedBit = FirstVaryingBit;
142 while (LastFixedBit < MaxBits && BitsAreFixed(I1, I2, LastFixedBit))
145 if (FirstVaryingBit < FirstVaryingBitOverall)
146 FirstVaryingBitOverall = FirstVaryingBit;
147 if (LastFixedBit < LastFixedBitOverall)
148 LastFixedBitOverall = LastFixedBit;
151 static bool getBitValue(Record *R, unsigned BitNo) {
152 Init *I = getBit(R, BitNo);
153 assert(dynamic_cast<BitInit*>(I) && "Bit should be fixed!");
154 return ((BitInit*)I)->getValue();
157 struct BitComparator {
158 unsigned BitBegin, BitEnd;
159 BitComparator(unsigned B, unsigned E) : BitBegin(B), BitEnd(E) {}
161 bool operator()(Record *R1, Record *R2) { // Return true if R1 is less than R2
162 for (unsigned i = BitBegin; i != BitEnd; ++i) {
163 bool V1 = getBitValue(R1, i), V2 = getBitValue(R2, i);
173 static void PrintRange(std::vector<Record*>::iterator I,
174 std::vector<Record*>::iterator E) {
175 while (I != E) std::cerr << **I++;
178 static bool getMemoryBit(unsigned char *M, unsigned i) {
179 return (M[i/8] & (1 << (i&7))) != 0;
182 static unsigned getFirstFixedBitInSequence(std::vector<Record*>::iterator IB,
183 std::vector<Record*>::iterator IE,
185 unsigned FirstFixedBit = 0;
186 for (std::vector<Record*>::iterator I = IB; I != IE; ++I)
187 FirstFixedBit = std::max(FirstFixedBit, getFirstFixedBit(*I, StartBit));
188 return FirstFixedBit;
191 // ParseMachineCode - Try to split the vector of instructions (which is
192 // intentially taken by-copy) in half, narrowing down the possible instructions
193 // that we may have found. Eventually, this list will get pared down to zero or
194 // one instruction, in which case we have a match or failure.
196 static Record *ParseMachineCode(std::vector<Record*>::iterator InstsB,
197 std::vector<Record*>::iterator InstsE,
199 assert(InstsB != InstsE && "Empty range?");
200 if (InstsB+1 == InstsE) {
201 // Only a single instruction, see if we match it...
202 Record *Inst = *InstsB;
203 for (unsigned i = 0, e = getNumBits(Inst); i != e; ++i)
204 if (BitInit *BI = dynamic_cast<BitInit*>(getBit(Inst, i)))
205 if (getMemoryBit(M, i) != BI->getValue())
206 throw std::string("Parse failed!\n");
210 unsigned MaxBits = ~0;
211 for (std::vector<Record*>::iterator I = InstsB; I != InstsE; ++I)
212 MaxBits = std::min(MaxBits, getNumBits(*I));
214 unsigned FirstFixedBit = getFirstFixedBitInSequence(InstsB, InstsE, 0);
215 unsigned FirstVaryingBit, LastFixedBit;
217 FirstVaryingBit = ~0;
219 for (std::vector<Record*>::iterator I = InstsB+1; I != InstsE; ++I)
220 FindInstDifferences(*InstsB, *I, FirstFixedBit, MaxBits,
221 FirstVaryingBit, LastFixedBit);
222 if (FirstVaryingBit == MaxBits) {
223 std::cerr << "ERROR: Could not find bit to distinguish between "
224 << "the following entries!\n";
225 PrintRange(InstsB, InstsE);
229 std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
230 << ": " << InstsE-InstsB << "\n";
233 FirstFixedBit = getFirstFixedBitInSequence(InstsB, InstsE, FirstVaryingBit);
234 } while (FirstVaryingBit != FirstFixedBit);
236 //std::cerr << "\n\nXXXXXXXXXXXXXXXXX\n\n";
237 //PrintRange(InstsB, InstsE);
239 // Sort the Insts list so that the entries have all of the bits in the range
240 // [FirstVaryingBit,LastFixedBit) sorted. These bits are all guaranteed to be
241 // set to either 0 or 1 (BitInit values), which simplifies things.
243 std::sort(InstsB, InstsE, BitComparator(FirstVaryingBit, LastFixedBit));
245 // Once the list is sorted by these bits, split the bit list into smaller
246 // lists, and recurse on each one.
248 std::vector<Record*>::iterator RangeBegin = InstsB;
250 while (RangeBegin != InstsE) {
251 std::vector<Record*>::iterator RangeEnd = RangeBegin+1;
252 while (RangeEnd != InstsE &&
253 BitRangesEqual(*RangeBegin, *RangeEnd, FirstVaryingBit, LastFixedBit))
256 // We just identified a range of equal instructions. If this range is the
257 // input range, we were not able to distinguish between the instructions in
258 // the set. Print an error and exit!
260 if (RangeBegin == InstsB && RangeEnd == InstsE) {
261 std::cerr << "Error: Could not distinguish among the following insts!:\n";
262 PrintRange(InstsB, InstsE);
267 std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
268 << ": [" << RangeEnd-RangeBegin << "] - ";
269 for (int i = LastFixedBit-1; i >= (int)FirstVaryingBit; --i)
270 std::cerr << (int)((BitInit*)getBit(*RangeBegin, i))->getValue() << " ";
274 if (Record *R = ParseMachineCode(RangeBegin, RangeEnd, M)) {
276 std::cerr << "Error: Multiple matches found:\n";
277 PrintRange(InstsB, InstsE);
280 assert(Match == 0 && "Multiple matches??");
283 RangeBegin = RangeEnd;
289 static void PrintValue(Record *I, unsigned char *Ptr, const RecordVal &Val) {
290 assert(dynamic_cast<BitsInit*>(Val.getValue()) &&
291 "Can only handle undefined bits<> types!");
292 BitsInit *BI = (BitsInit*)Val.getValue();
293 assert(BI->getNumBits() <= 32 && "Can only handle fields up to 32 bits!");
296 const std::vector<RecordVal> &Vals = I->getValues();
298 // Start by filling in fixed values...
299 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
300 if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(i)))
301 Value |= B->getValue() << i;
303 // Loop over all of the fields in the instruction adding in any
304 // contributions to this value (due to bit references).
307 for (unsigned f = 0, e = Vals.size(); f != e; ++f)
308 if (Vals[f].getPrefix()) {
309 BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();
310 if (&Vals[f] == &Val) {
311 // Read the bits directly now...
312 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
313 Value |= getMemoryBit(Ptr, Offset+i) << i;
317 // Scan through the field looking for bit initializers of the current
319 for (unsigned i = 0, e = FieldInitializer->getNumBits(); i != e; ++i)
320 if (VarBitInit *VBI =
321 dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) {
322 TypedInit *TI = VBI->getVariable();
323 if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
324 if (VI->getName() == Val.getName())
325 Value |= getMemoryBit(Ptr, Offset+i) << VBI->getBitNum();
326 } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {
327 // FIXME: implement this!
328 std::cerr << "FIELD INIT not implemented yet!\n";
331 Offset += FieldInitializer->getNumBits();
334 std::cout << "0x" << std::hex << Value << std::dec;
337 static void PrintInstruction(Record *I, unsigned char *Ptr) {
338 std::cout << "Inst " << getNumBits(I)/8 << " bytes: "
339 << "\t" << I->getName() << "\t" << *I->getValue("Name")->getValue()
342 const std::vector<RecordVal> &Vals = I->getValues();
343 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
344 if (!Vals[i].getValue()->isComplete()) {
345 std::cout << Vals[i].getName() << "=";
346 PrintValue(I, Ptr, Vals[i]);
350 std::cout << "\n";// << *I;
353 static void ParseMachineCode() {
355 unsigned char Buffer[] = {
357 0x89, 0xE5, // mov EBP, ESP
358 //0x83, 0xEC, 0x08, // sub ESP, 0x8
359 0xE8, 1, 2, 3, 4, // call +0x04030201
360 0x89, 0xEC, // mov ESP, EBP
365 0x89, 0xF6, // mov ESI, ESI
366 0x68, 1, 2, 3, 4, // push 0x04030201
368 0xFF, 0xD0, // call EAX
369 0xB8, 1, 2, 3, 4, // mov EAX, 0x04030201
370 0x85, 0xC0, // test EAX, EAX
376 unsigned char Buffer[] = { 0xbf, 0xe0, 0x20, 0x1f, 0x1, 0x0, 0x0, 0x1,
377 0x0, 0x0, 0x0, 0x0, 0xc1, 0x0, 0x20, 0x1, 0x1,
378 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
379 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x1,
380 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
381 0x0, 0x0, 0xaf, 0xe8, 0x20, 0x17
385 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
387 unsigned char *BuffPtr = Buffer;
389 Record *R = ParseMachineCode(Insts.begin(), Insts.end(), BuffPtr);
390 PrintInstruction(R, BuffPtr);
392 unsigned Bits = getNumBits(R);
393 assert((Bits & 7) == 0 && "Instruction is not an even number of bytes!");
399 int main(int argc, char **argv) {
400 cl::ParseCommandLineOptions(argc, argv);
401 ParseFile(InputFilename);
403 std::ostream *Out = &std::cout;
404 if (OutputFilename != "-") {
405 // Output to a .tmp file, because we don't actually want to overwrite the
406 // output file unless the generated file is different or the specified file
408 Out = new std::ofstream((OutputFilename+".tmp").c_str());
411 std::cerr << argv[0] << ": error opening " << OutputFilename << ".tmp!\n";
415 // Make sure the file gets removed if *gasp* tablegen crashes...
416 RemoveFileOnSignal(OutputFilename+".tmp");
422 *Out << Records; // No argument, dump all contents
428 CodeEmitterGen(Records).run(*Out);
431 case GenRegisterEnums:
432 RegisterInfoEmitter(Records).runEnums(*Out);
435 RegisterInfoEmitter(Records).run(*Out);
437 case GenRegisterHeader:
438 RegisterInfoEmitter(Records).runHeader(*Out);
442 InstrInfoEmitter(Records).runEnums(*Out);
445 InstrInfoEmitter(Records).run(*Out);
447 case GenInstrSelector:
448 InstrSelectorEmitter(Records).run(*Out);
451 std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class);
452 for (unsigned i = 0, e = Recs.size(); i != e; ++i)
453 *Out << Recs[i] << ", ";
457 } catch (const std::string &Error) {
458 std::cerr << Error << "\n";
459 if (Out != &std::cout) {
460 delete Out; // Close the file
461 std::remove(OutputFilename.c_str()); // Remove the file, it's broken
466 if (Out != &std::cout) {
467 delete Out; // Close the file
469 // Now that we have generated the result, check to see if we either don't
470 // have the requested file, or if the requested file is different than the
471 // file we generated. If so, move the generated file over the requested
472 // file. Otherwise, just remove the file we just generated, so 'make'
473 // doesn't try to regenerate tons of dependencies.
475 MoveFileOverIfUpdated(OutputFilename+".tmp", OutputFilename);