blob: d1f271208e53796b427426236d73c9718efc31bc [file] [log] [blame]
Owen Anderson4e818902011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder 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// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "decoder-emitter"
16
17#include "FixedLenDecoderEmitter.h"
18#include "CodeGenTarget.h"
19#include "Record.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/raw_ostream.h"
23
24#include <vector>
25#include <map>
26#include <string>
27
28using namespace llvm;
29
30// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
31// for a bit value.
32//
33// BIT_UNFILTERED is used as the init value for a filter position. It is used
34// only for filter processings.
35typedef enum {
36 BIT_TRUE, // '1'
37 BIT_FALSE, // '0'
38 BIT_UNSET, // '?'
39 BIT_UNFILTERED // unfiltered
40} bit_value_t;
41
42static bool ValueSet(bit_value_t V) {
43 return (V == BIT_TRUE || V == BIT_FALSE);
44}
45static bool ValueNotSet(bit_value_t V) {
46 return (V == BIT_UNSET);
47}
48static int Value(bit_value_t V) {
49 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
50}
David Greeneaf8ee2c2011-07-29 22:43:06 +000051static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
52 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +000053 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
54
55 // The bit is uninitialized.
56 return BIT_UNSET;
57}
58// Prints the bit value for each position.
David Greeneaf8ee2c2011-07-29 22:43:06 +000059static void dumpBits(raw_ostream &o, BitsInit &bits) {
Owen Anderson4e818902011-02-18 21:51:29 +000060 unsigned index;
61
62 for (index = bits.getNumBits(); index > 0; index--) {
63 switch (bitFromBits(bits, index - 1)) {
64 case BIT_TRUE:
65 o << "1";
66 break;
67 case BIT_FALSE:
68 o << "0";
69 break;
70 case BIT_UNSET:
71 o << "_";
72 break;
73 default:
74 assert(0 && "unexpected return value from bitFromBits");
75 }
76 }
77}
78
David Greeneaf8ee2c2011-07-29 22:43:06 +000079static BitsInit &getBitsField(const Record &def, const char *str) {
80 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +000081 return *bits;
82}
83
84// Forward declaration.
85class FilterChooser;
86
Owen Anderson4e818902011-02-18 21:51:29 +000087// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +000088typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +000089
90/// Filter - Filter works with FilterChooser to produce the decoding tree for
91/// the ISA.
92///
93/// It is useful to think of a Filter as governing the switch stmts of the
94/// decoding tree in a certain level. Each case stmt delegates to an inferior
95/// FilterChooser to decide what further decoding logic to employ, or in another
96/// words, what other remaining bits to look at. The FilterChooser eventually
97/// chooses a best Filter to do its job.
98///
99/// This recursive scheme ends when the number of Opcodes assigned to the
100/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
101/// the Filter/FilterChooser combo does not know how to distinguish among the
102/// Opcodes assigned.
103///
104/// An example of a conflict is
105///
106/// Conflict:
107/// 111101000.00........00010000....
108/// 111101000.00........0001........
109/// 1111010...00........0001........
110/// 1111010...00....................
111/// 1111010.........................
112/// 1111............................
113/// ................................
114/// VST4q8a 111101000_00________00010000____
115/// VST4q8b 111101000_00________00010000____
116///
117/// The Debug output shows the path that the decoding tree follows to reach the
118/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
119/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
120///
121/// The encoding info in the .td files does not specify this meta information,
122/// which could have been used by the decoder to resolve the conflict. The
123/// decoder could try to decode the even/odd register numbering and assign to
124/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
125/// version and return the Opcode since the two have the same Asm format string.
126class Filter {
127protected:
128 FilterChooser *Owner; // points to the FilterChooser who owns this filter
129 unsigned StartBit; // the starting bit position
130 unsigned NumBits; // number of bits to filter
131 bool Mixed; // a mixed region contains both set and unset bits
132
133 // Map of well-known segment value to the set of uid's with that value.
134 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
135
136 // Set of uid's with non-constant segment values.
137 std::vector<unsigned> VariableInstructions;
138
139 // Map of well-known segment value to its delegate.
140 std::map<unsigned, FilterChooser*> FilterChooserMap;
141
142 // Number of instructions which fall under FilteredInstructions category.
143 unsigned NumFiltered;
144
145 // Keeps track of the last opcode in the filtered bucket.
146 unsigned LastOpcFiltered;
147
148 // Number of instructions which fall under VariableInstructions category.
149 unsigned NumVariable;
150
151public:
152 unsigned getNumFiltered() { return NumFiltered; }
153 unsigned getNumVariable() { return NumVariable; }
154 unsigned getSingletonOpc() {
155 assert(NumFiltered == 1);
156 return LastOpcFiltered;
157 }
158 // Return the filter chooser for the group of instructions without constant
159 // segment values.
160 FilterChooser &getVariableFC() {
161 assert(NumFiltered == 1);
162 assert(FilterChooserMap.size() == 1);
163 return *(FilterChooserMap.find((unsigned)-1)->second);
164 }
165
166 Filter(const Filter &f);
167 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
168
169 ~Filter();
170
171 // Divides the decoding task into sub tasks and delegates them to the
172 // inferior FilterChooser's.
173 //
174 // A special case arises when there's only one entry in the filtered
175 // instructions. In order to unambiguously decode the singleton, we need to
176 // match the remaining undecoded encoding bits against the singleton.
177 void recurse();
178
179 // Emit code to decode instructions given a segment or segments of bits.
180 void emit(raw_ostream &o, unsigned &Indentation);
181
182 // Returns the number of fanout produced by the filter. More fanout implies
183 // the filter distinguishes more categories of instructions.
184 unsigned usefulness() const;
185}; // End of class Filter
186
187// These are states of our finite state machines used in FilterChooser's
188// filterProcessor() which produces the filter candidates to use.
189typedef enum {
190 ATTR_NONE,
191 ATTR_FILTERED,
192 ATTR_ALL_SET,
193 ATTR_ALL_UNSET,
194 ATTR_MIXED
195} bitAttr_t;
196
197/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
198/// in order to perform the decoding of instructions at the current level.
199///
200/// Decoding proceeds from the top down. Based on the well-known encoding bits
201/// of instructions available, FilterChooser builds up the possible Filters that
202/// can further the task of decoding by distinguishing among the remaining
203/// candidate instructions.
204///
205/// Once a filter has been chosen, it is called upon to divide the decoding task
206/// into sub-tasks and delegates them to its inferior FilterChoosers for further
207/// processings.
208///
209/// It is useful to think of a Filter as governing the switch stmts of the
210/// decoding tree. And each case is delegated to an inferior FilterChooser to
211/// decide what further remaining bits to look at.
212class FilterChooser {
213protected:
214 friend class Filter;
215
216 // Vector of codegen instructions to choose our filter.
217 const std::vector<const CodeGenInstruction*> &AllInstructions;
218
219 // Vector of uid's for this filter chooser to work on.
220 const std::vector<unsigned> Opcodes;
221
222 // Lookup table for the operand decoding of instructions.
223 std::map<unsigned, std::vector<OperandInfo> > &Operands;
224
225 // Vector of candidate filters.
226 std::vector<Filter> Filters;
227
228 // Array of bit values passed down from our parent.
229 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000230 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000231
232 // Links to the FilterChooser above us in the decoding tree.
233 FilterChooser *Parent;
234
235 // Index of the best filter from Filters.
236 int BestIndex;
237
Owen Andersonc78e03c2011-07-19 21:06:00 +0000238 // Width of instructions
239 unsigned BitWidth;
240
Owen Andersona4043c42011-08-17 17:44:15 +0000241 // Parent emitter
242 const FixedLenDecoderEmitter *Emitter;
243
Owen Anderson4e818902011-02-18 21:51:29 +0000244public:
245 FilterChooser(const FilterChooser &FC) :
246 AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000247 Operands(FC.Operands), Filters(FC.Filters),
248 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
Owen Andersona4043c42011-08-17 17:44:15 +0000249 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
250 Emitter(FC.Emitter) { }
Owen Anderson4e818902011-02-18 21:51:29 +0000251
252 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
253 const std::vector<unsigned> &IDs,
Owen Andersonc78e03c2011-07-19 21:06:00 +0000254 std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000255 unsigned BW,
256 const FixedLenDecoderEmitter *E) :
Owen Anderson4e818902011-02-18 21:51:29 +0000257 AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Owen Andersona4043c42011-08-17 17:44:15 +0000258 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000259 for (unsigned i = 0; i < BitWidth; ++i)
260 FilterBitValues.push_back(BIT_UNFILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +0000261
262 doFilter();
263 }
264
265 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
266 const std::vector<unsigned> &IDs,
267 std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersonc78e03c2011-07-19 21:06:00 +0000268 std::vector<bit_value_t> &ParentFilterBitValues,
Owen Anderson4e818902011-02-18 21:51:29 +0000269 FilterChooser &parent) :
270 AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000271 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000272 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
273 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000274 doFilter();
275 }
276
277 // The top level filter chooser has NULL as its parent.
278 bool isTopLevel() { return Parent == NULL; }
279
280 // Emit the top level typedef and decodeInstruction() function.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000281 void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace);
Owen Anderson4e818902011-02-18 21:51:29 +0000282
283protected:
284 // Populates the insn given the uid.
285 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000286 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000287
Owen Andersonc78e03c2011-07-19 21:06:00 +0000288 for (unsigned i = 0; i < BitWidth; ++i)
289 Insn.push_back(bitFromBits(Bits, i));
Owen Anderson4e818902011-02-18 21:51:29 +0000290 }
291
292 // Returns the record name.
293 const std::string &nameWithID(unsigned Opcode) const {
294 return AllInstructions[Opcode]->TheDef->getName();
295 }
296
297 // Populates the field of the insn given the start position and the number of
298 // consecutive bits to scan for.
299 //
300 // Returns false if there exists any uninitialized bit value in the range.
301 // Returns true, otherwise.
302 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
303 unsigned NumBits) const;
304
305 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
306 /// filter array as a series of chars.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000307 void dumpFilterArray(raw_ostream &o, std::vector<bit_value_t> & filter);
Owen Anderson4e818902011-02-18 21:51:29 +0000308
309 /// dumpStack - dumpStack traverses the filter chooser chain and calls
310 /// dumpFilterArray on each filter chooser up to the top level one.
311 void dumpStack(raw_ostream &o, const char *prefix);
312
313 Filter &bestFilter() {
314 assert(BestIndex != -1 && "BestIndex not set");
315 return Filters[BestIndex];
316 }
317
318 // Called from Filter::recurse() when singleton exists. For debug purpose.
319 void SingletonExists(unsigned Opc);
320
321 bool PositionFiltered(unsigned i) {
322 return ValueSet(FilterBitValues[i]);
323 }
324
325 // Calculates the island(s) needed to decode the instruction.
326 // This returns a lit of undecoded bits of an instructions, for example,
327 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
328 // decoded bits in order to verify that the instruction matches the Opcode.
329 unsigned getIslands(std::vector<unsigned> &StartBits,
330 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
331 insn_t &Insn);
332
333 // Emits code to decode the singleton. Return true if we have matched all the
334 // well-known bits.
335 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
336
337 // Emits code to decode the singleton, and then to decode the rest.
338 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
339
Owen Andersone3591652011-07-28 21:54:31 +0000340 void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
341 OperandInfo &OpInfo);
342
Owen Anderson4e818902011-02-18 21:51:29 +0000343 // Assign a single filter and run with it.
344 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
345 bool mixed);
346
347 // reportRegion is a helper function for filterProcessor to mark a region as
348 // eligible for use as a filter region.
349 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
350 bool AllowMixed);
351
352 // FilterProcessor scans the well-known encoding bits of the instructions and
353 // builds up a list of candidate filters. It chooses the best filter and
354 // recursively descends down the decoding tree.
355 bool filterProcessor(bool AllowMixed, bool Greedy = true);
356
357 // Decides on the best configuration of filter(s) to use in order to decode
358 // the instructions. A conflict of instructions may occur, in which case we
359 // dump the conflict set to the standard error.
360 void doFilter();
361
362 // Emits code to decode our share of instructions. Returns true if the
363 // emitted code causes a return, which occurs if we know how to decode
364 // the instruction at this level or the instruction is not decodeable.
365 bool emit(raw_ostream &o, unsigned &Indentation);
366};
367
368///////////////////////////
369// //
370// Filter Implmenetation //
371// //
372///////////////////////////
373
374Filter::Filter(const Filter &f) :
375 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
376 FilteredInstructions(f.FilteredInstructions),
377 VariableInstructions(f.VariableInstructions),
378 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
379 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
380}
381
382Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
383 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
384 Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000385 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000386
387 NumFiltered = 0;
388 LastOpcFiltered = 0;
389 NumVariable = 0;
390
391 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
392 insn_t Insn;
393
394 // Populates the insn given the uid.
395 Owner->insnWithID(Insn, Owner->Opcodes[i]);
396
397 uint64_t Field;
398 // Scans the segment for possibly well-specified encoding bits.
399 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
400
401 if (ok) {
402 // The encoding bits are well-known. Lets add the uid of the
403 // instruction into the bucket keyed off the constant field value.
404 LastOpcFiltered = Owner->Opcodes[i];
405 FilteredInstructions[Field].push_back(LastOpcFiltered);
406 ++NumFiltered;
407 } else {
408 // Some of the encoding bit(s) are unspecfied. This contributes to
409 // one additional member of "Variable" instructions.
410 VariableInstructions.push_back(Owner->Opcodes[i]);
411 ++NumVariable;
412 }
413 }
414
415 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
416 && "Filter returns no instruction categories");
417}
418
419Filter::~Filter() {
420 std::map<unsigned, FilterChooser*>::iterator filterIterator;
421 for (filterIterator = FilterChooserMap.begin();
422 filterIterator != FilterChooserMap.end();
423 filterIterator++) {
424 delete filterIterator->second;
425 }
426}
427
428// Divides the decoding task into sub tasks and delegates them to the
429// inferior FilterChooser's.
430//
431// A special case arises when there's only one entry in the filtered
432// instructions. In order to unambiguously decode the singleton, we need to
433// match the remaining undecoded encoding bits against the singleton.
434void Filter::recurse() {
435 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
436
Owen Anderson4e818902011-02-18 21:51:29 +0000437 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000438 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000439
440 unsigned bitIndex;
441
442 if (VariableInstructions.size()) {
443 // Conservatively marks each segment position as BIT_UNSET.
444 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
445 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
446
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000447 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000448 // group of instructions whose segment values are variable.
449 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
450 (unsigned)-1,
451 new FilterChooser(Owner->AllInstructions,
452 VariableInstructions,
453 Owner->Operands,
454 BitValueArray,
455 *Owner)
456 ));
457 }
458
459 // No need to recurse for a singleton filtered instruction.
460 // See also Filter::emit().
461 if (getNumFiltered() == 1) {
462 //Owner->SingletonExists(LastOpcFiltered);
463 assert(FilterChooserMap.size() == 1);
464 return;
465 }
466
467 // Otherwise, create sub choosers.
468 for (mapIterator = FilteredInstructions.begin();
469 mapIterator != FilteredInstructions.end();
470 mapIterator++) {
471
472 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
473 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
474 if (mapIterator->first & (1ULL << bitIndex))
475 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
476 else
477 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
478 }
479
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000480 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000481 // category of instructions.
482 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
483 mapIterator->first,
484 new FilterChooser(Owner->AllInstructions,
485 mapIterator->second,
486 Owner->Operands,
487 BitValueArray,
488 *Owner)
489 ));
490 }
491}
492
493// Emit code to decode instructions given a segment or segments of bits.
494void Filter::emit(raw_ostream &o, unsigned &Indentation) {
495 o.indent(Indentation) << "// Check Inst{";
496
497 if (NumBits > 1)
498 o << (StartBit + NumBits - 1) << '-';
499
500 o << StartBit << "} ...\n";
501
Owen Andersonc78e03c2011-07-19 21:06:00 +0000502 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
503 << "(insn, " << StartBit << ", "
504 << NumBits << ")) {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000505
506 std::map<unsigned, FilterChooser*>::iterator filterIterator;
507
508 bool DefaultCase = false;
509 for (filterIterator = FilterChooserMap.begin();
510 filterIterator != FilterChooserMap.end();
511 filterIterator++) {
512
513 // Field value -1 implies a non-empty set of variable instructions.
514 // See also recurse().
515 if (filterIterator->first == (unsigned)-1) {
516 DefaultCase = true;
517
518 o.indent(Indentation) << "default:\n";
519 o.indent(Indentation) << " break; // fallthrough\n";
520
521 // Closing curly brace for the switch statement.
522 // This is unconventional because we want the default processing to be
523 // performed for the fallthrough cases as well, i.e., when the "cases"
524 // did not prove a decoded instruction.
525 o.indent(Indentation) << "}\n";
526
527 } else
528 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
529
530 // We arrive at a category of instructions with the same segment value.
531 // Now delegate to the sub filter chooser for further decodings.
532 // The case may fallthrough, which happens if the remaining well-known
533 // encoding bits do not match exactly.
534 if (!DefaultCase) { ++Indentation; ++Indentation; }
535
536 bool finished = filterIterator->second->emit(o, Indentation);
537 // For top level default case, there's no need for a break statement.
538 if (Owner->isTopLevel() && DefaultCase)
539 break;
540 if (!finished)
541 o.indent(Indentation) << "break;\n";
542
543 if (!DefaultCase) { --Indentation; --Indentation; }
544 }
545
546 // If there is no default case, we still need to supply a closing brace.
547 if (!DefaultCase) {
548 // Closing curly brace for the switch statement.
549 o.indent(Indentation) << "}\n";
550 }
551}
552
553// Returns the number of fanout produced by the filter. More fanout implies
554// the filter distinguishes more categories of instructions.
555unsigned Filter::usefulness() const {
556 if (VariableInstructions.size())
557 return FilteredInstructions.size();
558 else
559 return FilteredInstructions.size() + 1;
560}
561
562//////////////////////////////////
563// //
564// Filterchooser Implementation //
565// //
566//////////////////////////////////
567
568// Emit the top level typedef and decodeInstruction() function.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000569void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
570 std::string Namespace) {
Owen Anderson4e818902011-02-18 21:51:29 +0000571 o.indent(Indentation) <<
Owen Andersona4043c42011-08-17 17:44:15 +0000572 "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction" << BitWidth
Owen Andersonc78e03c2011-07-19 21:06:00 +0000573 << "(MCInst &MI, uint" << BitWidth << "_t insn, uint64_t Address, "
574 << "const void *Decoder) {\n";
Owen Andersona4043c42011-08-17 17:44:15 +0000575 o.indent(Indentation) << " unsigned tmp = 0;\n (void)tmp;\n" << Emitter->Locals << "\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000576
577 ++Indentation; ++Indentation;
578 // Emits code to decode the instructions.
579 emit(o, Indentation);
580
581 o << '\n';
Owen Andersona4043c42011-08-17 17:44:15 +0000582 o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000583 --Indentation; --Indentation;
584
585 o.indent(Indentation) << "}\n";
586
587 o << '\n';
588}
589
590// Populates the field of the insn given the start position and the number of
591// consecutive bits to scan for.
592//
593// Returns false if and on the first uninitialized bit value encountered.
594// Returns true, otherwise.
595bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
596 unsigned StartBit, unsigned NumBits) const {
597 Field = 0;
598
599 for (unsigned i = 0; i < NumBits; ++i) {
600 if (Insn[StartBit + i] == BIT_UNSET)
601 return false;
602
603 if (Insn[StartBit + i] == BIT_TRUE)
604 Field = Field | (1ULL << i);
605 }
606
607 return true;
608}
609
610/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
611/// filter array as a series of chars.
612void FilterChooser::dumpFilterArray(raw_ostream &o,
Owen Andersonc78e03c2011-07-19 21:06:00 +0000613 std::vector<bit_value_t> &filter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000614 unsigned bitIndex;
615
Owen Andersonc78e03c2011-07-19 21:06:00 +0000616 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000617 switch (filter[bitIndex - 1]) {
618 case BIT_UNFILTERED:
619 o << ".";
620 break;
621 case BIT_UNSET:
622 o << "_";
623 break;
624 case BIT_TRUE:
625 o << "1";
626 break;
627 case BIT_FALSE:
628 o << "0";
629 break;
630 }
631 }
632}
633
634/// dumpStack - dumpStack traverses the filter chooser chain and calls
635/// dumpFilterArray on each filter chooser up to the top level one.
636void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
637 FilterChooser *current = this;
638
639 while (current) {
640 o << prefix;
641 dumpFilterArray(o, current->FilterBitValues);
642 o << '\n';
643 current = current->Parent;
644 }
645}
646
647// Called from Filter::recurse() when singleton exists. For debug purpose.
648void FilterChooser::SingletonExists(unsigned Opc) {
649 insn_t Insn0;
650 insnWithID(Insn0, Opc);
651
652 errs() << "Singleton exists: " << nameWithID(Opc)
653 << " with its decoding dominating ";
654 for (unsigned i = 0; i < Opcodes.size(); ++i) {
655 if (Opcodes[i] == Opc) continue;
656 errs() << nameWithID(Opcodes[i]) << ' ';
657 }
658 errs() << '\n';
659
660 dumpStack(errs(), "\t\t");
661 for (unsigned i = 0; i < Opcodes.size(); i++) {
662 const std::string &Name = nameWithID(Opcodes[i]);
663
664 errs() << '\t' << Name << " ";
665 dumpBits(errs(),
666 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
667 errs() << '\n';
668 }
669}
670
671// Calculates the island(s) needed to decode the instruction.
672// This returns a list of undecoded bits of an instructions, for example,
673// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
674// decoded bits in order to verify that the instruction matches the Opcode.
675unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
676 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
677 insn_t &Insn) {
678 unsigned Num, BitNo;
679 Num = BitNo = 0;
680
681 uint64_t FieldVal = 0;
682
683 // 0: Init
684 // 1: Water (the bit value does not affect decoding)
685 // 2: Island (well-known bit value needed for decoding)
686 int State = 0;
687 int Val = -1;
688
Owen Andersonc78e03c2011-07-19 21:06:00 +0000689 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000690 Val = Value(Insn[i]);
691 bool Filtered = PositionFiltered(i);
692 switch (State) {
693 default:
694 assert(0 && "Unreachable code!");
695 break;
696 case 0:
697 case 1:
698 if (Filtered || Val == -1)
699 State = 1; // Still in Water
700 else {
701 State = 2; // Into the Island
702 BitNo = 0;
703 StartBits.push_back(i);
704 FieldVal = Val;
705 }
706 break;
707 case 2:
708 if (Filtered || Val == -1) {
709 State = 1; // Into the Water
710 EndBits.push_back(i - 1);
711 FieldVals.push_back(FieldVal);
712 ++Num;
713 } else {
714 State = 2; // Still in Island
715 ++BitNo;
716 FieldVal = FieldVal | Val << BitNo;
717 }
718 break;
719 }
720 }
721 // If we are still in Island after the loop, do some housekeeping.
722 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000723 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +0000724 FieldVals.push_back(FieldVal);
725 ++Num;
726 }
727
728 assert(StartBits.size() == Num && EndBits.size() == Num &&
729 FieldVals.size() == Num);
730 return Num;
731}
732
Owen Andersone3591652011-07-28 21:54:31 +0000733void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
734 OperandInfo &OpInfo) {
735 std::string &Decoder = OpInfo.Decoder;
736
737 if (OpInfo.numFields() == 1) {
738 OperandInfo::iterator OI = OpInfo.begin();
739 o.indent(Indentation) << " tmp = fieldFromInstruction" << BitWidth
740 << "(insn, " << OI->Base << ", " << OI->Width
741 << ");\n";
742 } else {
743 o.indent(Indentation) << " tmp = 0;\n";
744 for (OperandInfo::iterator OI = OpInfo.begin(), OE = OpInfo.end();
745 OI != OE; ++OI) {
746 o.indent(Indentation) << " tmp |= (fieldFromInstruction" << BitWidth
747 << "(insn, " << OI->Base << ", " << OI->Width
748 << ") << " << OI->Offset << ");\n";
749 }
750 }
751
752 if (Decoder != "")
Owen Andersona4043c42011-08-17 17:44:15 +0000753 o.indent(Indentation) << " " << Emitter->GuardPrefix << Decoder
754 << "(MI, tmp, Address, Decoder)" << Emitter->GuardPostfix << "\n";
Owen Andersone3591652011-07-28 21:54:31 +0000755 else
756 o.indent(Indentation) << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
757
758}
759
Owen Anderson4e818902011-02-18 21:51:29 +0000760// Emits code to decode the singleton. Return true if we have matched all the
761// well-known bits.
762bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
763 unsigned Opc) {
764 std::vector<unsigned> StartBits;
765 std::vector<unsigned> EndBits;
766 std::vector<uint64_t> FieldVals;
767 insn_t Insn;
768 insnWithID(Insn, Opc);
769
770 // Look for islands of undecoded bits of the singleton.
771 getIslands(StartBits, EndBits, FieldVals, Insn);
772
773 unsigned Size = StartBits.size();
774 unsigned I, NumBits;
775
776 // If we have matched all the well-known bits, just issue a return.
777 if (Size == 0) {
778 o.indent(Indentation) << "{\n";
779 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
780 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
781 for (std::vector<OperandInfo>::iterator
782 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
783 // If a custom instruction decoder was specified, use that.
Owen Andersone3591652011-07-28 21:54:31 +0000784 if (I->numFields() == 0 && I->Decoder.size()) {
Owen Andersona4043c42011-08-17 17:44:15 +0000785 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
786 << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000787 break;
788 }
789
Owen Andersone3591652011-07-28 21:54:31 +0000790 emitBinaryParser(o, Indentation, *I);
Owen Anderson4e818902011-02-18 21:51:29 +0000791 }
792
Owen Andersona4043c42011-08-17 17:44:15 +0000793 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
Owen Anderson4e818902011-02-18 21:51:29 +0000794 << '\n';
795 o.indent(Indentation) << "}\n";
796 return true;
797 }
798
799 // Otherwise, there are more decodings to be done!
800
801 // Emit code to match the island(s) for the singleton.
802 o.indent(Indentation) << "// Check ";
803
804 for (I = Size; I != 0; --I) {
805 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
806 if (I > 1)
807 o << "&& ";
808 else
809 o << "for singleton decoding...\n";
810 }
811
812 o.indent(Indentation) << "if (";
813
814 for (I = Size; I != 0; --I) {
815 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Owen Andersonc78e03c2011-07-19 21:06:00 +0000816 o << "fieldFromInstruction" << BitWidth << "(insn, "
817 << StartBits[I-1] << ", " << NumBits
Owen Anderson4e818902011-02-18 21:51:29 +0000818 << ") == " << FieldVals[I-1];
819 if (I > 1)
820 o << " && ";
821 else
822 o << ") {\n";
823 }
824 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
825 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
826 for (std::vector<OperandInfo>::iterator
827 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
828 // If a custom instruction decoder was specified, use that.
Owen Andersone3591652011-07-28 21:54:31 +0000829 if (I->numFields() == 0 && I->Decoder.size()) {
Owen Andersona4043c42011-08-17 17:44:15 +0000830 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
831 << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000832 break;
833 }
834
Owen Andersone3591652011-07-28 21:54:31 +0000835 emitBinaryParser(o, Indentation, *I);
Owen Anderson4e818902011-02-18 21:51:29 +0000836 }
Owen Andersona4043c42011-08-17 17:44:15 +0000837 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
Owen Anderson4e818902011-02-18 21:51:29 +0000838 << '\n';
839 o.indent(Indentation) << "}\n";
840
841 return false;
842}
843
844// Emits code to decode the singleton, and then to decode the rest.
845void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
846 Filter &Best) {
847
848 unsigned Opc = Best.getSingletonOpc();
849
850 emitSingletonDecoder(o, Indentation, Opc);
851
852 // Emit code for the rest.
853 o.indent(Indentation) << "else\n";
854
855 Indentation += 2;
856 Best.getVariableFC().emit(o, Indentation);
857 Indentation -= 2;
858}
859
860// Assign a single filter and run with it. Top level API client can initialize
861// with a single filter to start the filtering process.
862void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
863 unsigned numBit, bool mixed) {
864 Filters.clear();
865 Filter F(*this, startBit, numBit, true);
866 Filters.push_back(F);
867 BestIndex = 0; // Sole Filter instance to choose from.
868 bestFilter().recurse();
869}
870
871// reportRegion is a helper function for filterProcessor to mark a region as
872// eligible for use as a filter region.
873void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
874 unsigned BitIndex, bool AllowMixed) {
875 if (RA == ATTR_MIXED && AllowMixed)
876 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
877 else if (RA == ATTR_ALL_SET && !AllowMixed)
878 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
879}
880
881// FilterProcessor scans the well-known encoding bits of the instructions and
882// builds up a list of candidate filters. It chooses the best filter and
883// recursively descends down the decoding tree.
884bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
885 Filters.clear();
886 BestIndex = -1;
887 unsigned numInstructions = Opcodes.size();
888
889 assert(numInstructions && "Filter created with no instructions");
890
891 // No further filtering is necessary.
892 if (numInstructions == 1)
893 return true;
894
895 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
896 // instructions is 3.
897 if (AllowMixed && !Greedy) {
898 assert(numInstructions == 3);
899
900 for (unsigned i = 0; i < Opcodes.size(); ++i) {
901 std::vector<unsigned> StartBits;
902 std::vector<unsigned> EndBits;
903 std::vector<uint64_t> FieldVals;
904 insn_t Insn;
905
906 insnWithID(Insn, Opcodes[i]);
907
908 // Look for islands of undecoded bits of any instruction.
909 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
910 // Found an instruction with island(s). Now just assign a filter.
911 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
912 true);
913 return true;
914 }
915 }
916 }
917
918 unsigned BitIndex, InsnIndex;
919
920 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
921 // The automaton consumes the corresponding bit from each
922 // instruction.
923 //
924 // Input symbols: 0, 1, and _ (unset).
925 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
926 // Initial state: NONE.
927 //
928 // (NONE) ------- [01] -> (ALL_SET)
929 // (NONE) ------- _ ----> (ALL_UNSET)
930 // (ALL_SET) ---- [01] -> (ALL_SET)
931 // (ALL_SET) ---- _ ----> (MIXED)
932 // (ALL_UNSET) -- [01] -> (MIXED)
933 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
934 // (MIXED) ------ . ----> (MIXED)
935 // (FILTERED)---- . ----> (FILTERED)
936
Owen Andersonc78e03c2011-07-19 21:06:00 +0000937 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +0000938
939 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
940 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000941 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000942 if (FilterBitValues[BitIndex] == BIT_TRUE ||
943 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +0000944 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +0000945 else
Owen Andersonc78e03c2011-07-19 21:06:00 +0000946 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +0000947
948 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
949 insn_t insn;
950
951 insnWithID(insn, Opcodes[InsnIndex]);
952
Owen Andersonc78e03c2011-07-19 21:06:00 +0000953 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +0000954 switch (bitAttrs[BitIndex]) {
955 case ATTR_NONE:
956 if (insn[BitIndex] == BIT_UNSET)
957 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
958 else
959 bitAttrs[BitIndex] = ATTR_ALL_SET;
960 break;
961 case ATTR_ALL_SET:
962 if (insn[BitIndex] == BIT_UNSET)
963 bitAttrs[BitIndex] = ATTR_MIXED;
964 break;
965 case ATTR_ALL_UNSET:
966 if (insn[BitIndex] != BIT_UNSET)
967 bitAttrs[BitIndex] = ATTR_MIXED;
968 break;
969 case ATTR_MIXED:
970 case ATTR_FILTERED:
971 break;
972 }
973 }
974 }
975
976 // The regionAttr automaton consumes the bitAttrs automatons' state,
977 // lowest-to-highest.
978 //
979 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
980 // States: NONE, ALL_SET, MIXED
981 // Initial state: NONE
982 //
983 // (NONE) ----- F --> (NONE)
984 // (NONE) ----- S --> (ALL_SET) ; and set region start
985 // (NONE) ----- U --> (NONE)
986 // (NONE) ----- M --> (MIXED) ; and set region start
987 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
988 // (ALL_SET) -- S --> (ALL_SET)
989 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
990 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
991 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
992 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
993 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
994 // (MIXED) ---- M --> (MIXED)
995
996 bitAttr_t RA = ATTR_NONE;
997 unsigned StartBit = 0;
998
Owen Andersonc78e03c2011-07-19 21:06:00 +0000999 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
Owen Anderson4e818902011-02-18 21:51:29 +00001000 bitAttr_t bitAttr = bitAttrs[BitIndex];
1001
1002 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1003
1004 switch (RA) {
1005 case ATTR_NONE:
1006 switch (bitAttr) {
1007 case ATTR_FILTERED:
1008 break;
1009 case ATTR_ALL_SET:
1010 StartBit = BitIndex;
1011 RA = ATTR_ALL_SET;
1012 break;
1013 case ATTR_ALL_UNSET:
1014 break;
1015 case ATTR_MIXED:
1016 StartBit = BitIndex;
1017 RA = ATTR_MIXED;
1018 break;
1019 default:
1020 assert(0 && "Unexpected bitAttr!");
1021 }
1022 break;
1023 case ATTR_ALL_SET:
1024 switch (bitAttr) {
1025 case ATTR_FILTERED:
1026 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1027 RA = ATTR_NONE;
1028 break;
1029 case ATTR_ALL_SET:
1030 break;
1031 case ATTR_ALL_UNSET:
1032 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1033 RA = ATTR_NONE;
1034 break;
1035 case ATTR_MIXED:
1036 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1037 StartBit = BitIndex;
1038 RA = ATTR_MIXED;
1039 break;
1040 default:
1041 assert(0 && "Unexpected bitAttr!");
1042 }
1043 break;
1044 case ATTR_MIXED:
1045 switch (bitAttr) {
1046 case ATTR_FILTERED:
1047 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1048 StartBit = BitIndex;
1049 RA = ATTR_NONE;
1050 break;
1051 case ATTR_ALL_SET:
1052 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1053 StartBit = BitIndex;
1054 RA = ATTR_ALL_SET;
1055 break;
1056 case ATTR_ALL_UNSET:
1057 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1058 RA = ATTR_NONE;
1059 break;
1060 case ATTR_MIXED:
1061 break;
1062 default:
1063 assert(0 && "Unexpected bitAttr!");
1064 }
1065 break;
1066 case ATTR_ALL_UNSET:
1067 assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1068 case ATTR_FILTERED:
1069 assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1070 }
1071 }
1072
1073 // At the end, if we're still in ALL_SET or MIXED states, report a region
1074 switch (RA) {
1075 case ATTR_NONE:
1076 break;
1077 case ATTR_FILTERED:
1078 break;
1079 case ATTR_ALL_SET:
1080 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1081 break;
1082 case ATTR_ALL_UNSET:
1083 break;
1084 case ATTR_MIXED:
1085 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1086 break;
1087 }
1088
1089 // We have finished with the filter processings. Now it's time to choose
1090 // the best performing filter.
1091 BestIndex = 0;
1092 bool AllUseless = true;
1093 unsigned BestScore = 0;
1094
1095 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1096 unsigned Usefulness = Filters[i].usefulness();
1097
1098 if (Usefulness)
1099 AllUseless = false;
1100
1101 if (Usefulness > BestScore) {
1102 BestIndex = i;
1103 BestScore = Usefulness;
1104 }
1105 }
1106
1107 if (!AllUseless)
1108 bestFilter().recurse();
1109
1110 return !AllUseless;
1111} // end of FilterChooser::filterProcessor(bool)
1112
1113// Decides on the best configuration of filter(s) to use in order to decode
1114// the instructions. A conflict of instructions may occur, in which case we
1115// dump the conflict set to the standard error.
1116void FilterChooser::doFilter() {
1117 unsigned Num = Opcodes.size();
1118 assert(Num && "FilterChooser created with no instructions");
1119
1120 // Try regions of consecutive known bit values first.
1121 if (filterProcessor(false))
1122 return;
1123
1124 // Then regions of mixed bits (both known and unitialized bit values allowed).
1125 if (filterProcessor(true))
1126 return;
1127
1128 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1129 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1130 // well-known encoding pattern. In such case, we backtrack and scan for the
1131 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1132 if (Num == 3 && filterProcessor(true, false))
1133 return;
1134
1135 // If we come to here, the instruction decoding has failed.
1136 // Set the BestIndex to -1 to indicate so.
1137 BestIndex = -1;
1138}
1139
1140// Emits code to decode our share of instructions. Returns true if the
1141// emitted code causes a return, which occurs if we know how to decode
1142// the instruction at this level or the instruction is not decodeable.
1143bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1144 if (Opcodes.size() == 1)
1145 // There is only one instruction in the set, which is great!
1146 // Call emitSingletonDecoder() to see whether there are any remaining
1147 // encodings bits.
1148 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1149
1150 // Choose the best filter to do the decodings!
1151 if (BestIndex != -1) {
1152 Filter &Best = bestFilter();
1153 if (Best.getNumFiltered() == 1)
1154 emitSingletonDecoder(o, Indentation, Best);
1155 else
1156 bestFilter().emit(o, Indentation);
1157 return false;
1158 }
1159
1160 // We don't know how to decode these instructions! Return 0 and dump the
1161 // conflict set!
1162 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1163 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1164 o << nameWithID(Opcodes[i]);
1165 if (i < (N - 1))
1166 o << ", ";
1167 else
1168 o << '\n';
1169 }
1170
1171 // Print out useful conflict information for postmortem analysis.
1172 errs() << "Decoding Conflict:\n";
1173
1174 dumpStack(errs(), "\t\t");
1175
1176 for (unsigned i = 0; i < Opcodes.size(); i++) {
1177 const std::string &Name = nameWithID(Opcodes[i]);
1178
1179 errs() << '\t' << Name << " ";
1180 dumpBits(errs(),
1181 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1182 errs() << '\n';
1183 }
1184
1185 return true;
1186}
1187
Owen Andersonc78e03c2011-07-19 21:06:00 +00001188static bool populateInstruction(const CodeGenInstruction &CGI,
1189 unsigned Opc,
1190 std::map<unsigned, std::vector<OperandInfo> >& Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001191 const Record &Def = *CGI.TheDef;
1192 // If all the bit positions are not specified; do not decode this instruction.
1193 // We are bound to fail! For proper disassembly, the well-known encoding bits
1194 // of the instruction must be fully specified.
1195 //
1196 // This also removes pseudo instructions from considerations of disassembly,
1197 // which is a better design and less fragile than the name matchings.
Owen Anderson4e818902011-02-18 21:51:29 +00001198 // Ignore "asm parser only" instructions.
Owen Anderson0fabf102011-03-14 20:58:49 +00001199 if (Def.getValueAsBit("isAsmParserOnly") ||
1200 Def.getValueAsBit("isCodeGenOnly"))
Owen Anderson4e818902011-02-18 21:51:29 +00001201 return false;
1202
David Greeneaf8ee2c2011-07-29 22:43:06 +00001203 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001204 if (Bits.allInComplete()) return false;
1205
Owen Anderson4e818902011-02-18 21:51:29 +00001206 std::vector<OperandInfo> InsnOperands;
1207
1208 // If the instruction has specified a custom decoding hook, use that instead
1209 // of trying to auto-generate the decoder.
1210 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1211 if (InstDecoder != "") {
Owen Andersone3591652011-07-28 21:54:31 +00001212 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001213 Operands[Opc] = InsnOperands;
1214 return true;
1215 }
1216
1217 // Generate a description of the operand of the instruction that we know
1218 // how to decode automatically.
1219 // FIXME: We'll need to have a way to manually override this as needed.
1220
1221 // Gather the outputs/inputs of the instruction, so we can find their
1222 // positions in the encoding. This assumes for now that they appear in the
1223 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001224 std::vector<std::pair<Init*, std::string> > InOutOperands;
1225 DagInit *Out = Def.getValueAsDag("OutOperandList");
1226 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001227 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1228 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1229 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1230 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1231
Owen Anderson53562d02011-07-28 23:56:20 +00001232 // Search for tied operands, so that we can correctly instantiate
1233 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001234 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001235 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1236 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001237 if (tiedTo != -1) {
1238 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1239 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1240 }
Owen Anderson53562d02011-07-28 23:56:20 +00001241 }
1242
Owen Anderson4e818902011-02-18 21:51:29 +00001243 // For each operand, see if we can figure out where it is encoded.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001244 for (std::vector<std::pair<Init*, std::string> >::iterator
Owen Anderson4e818902011-02-18 21:51:29 +00001245 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Owen Anderson4e818902011-02-18 21:51:29 +00001246 std::string Decoder = "";
1247
Owen Andersone3591652011-07-28 21:54:31 +00001248 // At this point, we can locate the field, but we need to know how to
1249 // interpret it. As a first step, require the target to provide callbacks
1250 // for decoding register classes.
1251 // FIXME: This need to be extended to handle instructions with custom
1252 // decoder methods, and operands with (simple) MIOperandInfo's.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001253 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
Owen Andersone3591652011-07-28 21:54:31 +00001254 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1255 Record *TypeRecord = Type->getRecord();
1256 bool isReg = false;
1257 if (TypeRecord->isSubClassOf("RegisterOperand"))
1258 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1259 if (TypeRecord->isSubClassOf("RegisterClass")) {
1260 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1261 isReg = true;
1262 }
1263
1264 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greeneaf8ee2c2011-07-29 22:43:06 +00001265 StringInit *String = DecoderString ?
1266 dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
Owen Andersone3591652011-07-28 21:54:31 +00001267 if (!isReg && String && String->getValue() != "")
1268 Decoder = String->getValue();
1269
1270 OperandInfo OpInfo(Decoder);
1271 unsigned Base = ~0U;
1272 unsigned Width = 0;
1273 unsigned Offset = 0;
1274
Owen Anderson4e818902011-02-18 21:51:29 +00001275 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Owen Anderson3022d672011-08-01 22:45:43 +00001276 VarInit *Var = 0;
David Greeneaf8ee2c2011-07-29 22:43:06 +00001277 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001278 if (BI)
1279 Var = dynamic_cast<VarInit*>(BI->getVariable());
1280 else
1281 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1282
1283 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001284 if (Base != ~0U) {
1285 OpInfo.addField(Base, Width, Offset);
1286 Base = ~0U;
1287 Width = 0;
1288 Offset = 0;
1289 }
1290 continue;
1291 }
Owen Anderson4e818902011-02-18 21:51:29 +00001292
Owen Anderson53562d02011-07-28 23:56:20 +00001293 if (Var->getName() != NI->second &&
Owen Andersoncb32ce22011-07-29 18:28:52 +00001294 Var->getName() != TiedNames[NI->second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001295 if (Base != ~0U) {
1296 OpInfo.addField(Base, Width, Offset);
1297 Base = ~0U;
1298 Width = 0;
1299 Offset = 0;
1300 }
1301 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001302 }
1303
Owen Andersone3591652011-07-28 21:54:31 +00001304 if (Base == ~0U) {
1305 Base = bi;
1306 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001307 Offset = BI ? BI->getBitNum() : 0;
1308 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001309 OpInfo.addField(Base, Width, Offset);
1310 Base = bi;
1311 Width = 1;
1312 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00001313 } else {
1314 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00001315 }
Owen Anderson4e818902011-02-18 21:51:29 +00001316 }
1317
Owen Andersone3591652011-07-28 21:54:31 +00001318 if (Base != ~0U)
1319 OpInfo.addField(Base, Width, Offset);
1320
1321 if (OpInfo.numFields() > 0)
1322 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001323 }
1324
1325 Operands[Opc] = InsnOperands;
1326
1327
1328#if 0
1329 DEBUG({
1330 // Dumps the instruction encoding bits.
1331 dumpBits(errs(), Bits);
1332
1333 errs() << '\n';
1334
1335 // Dumps the list of operand info.
1336 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1337 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1338 const std::string &OperandName = Info.Name;
1339 const Record &OperandDef = *Info.Rec;
1340
1341 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1342 }
1343 });
1344#endif
1345
1346 return true;
1347}
1348
Owen Andersonc78e03c2011-07-19 21:06:00 +00001349static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1350 unsigned Indentation = 0;
1351 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
Owen Anderson4e818902011-02-18 21:51:29 +00001352
Owen Andersonc78e03c2011-07-19 21:06:00 +00001353 o << '\n';
1354
1355 o.indent(Indentation) << "static " << WidthStr <<
1356 " fieldFromInstruction" << BitWidth <<
1357 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1358
1359 o.indent(Indentation) << "{\n";
1360
1361 ++Indentation; ++Indentation;
1362 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1363 << " && \"Instruction field out of bounds!\");\n";
1364 o << '\n';
1365 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1366 o << '\n';
1367 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1368
1369 ++Indentation; ++Indentation;
1370 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1371 --Indentation; --Indentation;
1372
1373 o.indent(Indentation) << "else\n";
1374
1375 ++Indentation; ++Indentation;
1376 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1377 --Indentation; --Indentation;
1378
1379 o << '\n';
1380 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1381 --Indentation; --Indentation;
1382
1383 o.indent(Indentation) << "}\n";
1384
1385 o << '\n';
Owen Anderson4e818902011-02-18 21:51:29 +00001386}
1387
1388// Emits disassembler code for instruction decoding.
1389void FixedLenDecoderEmitter::run(raw_ostream &o)
1390{
1391 o << "#include \"llvm/MC/MCInst.h\"\n";
1392 o << "#include \"llvm/Support/DataTypes.h\"\n";
1393 o << "#include <assert.h>\n";
1394 o << '\n';
1395 o << "namespace llvm {\n\n";
1396
Owen Andersonc78e03c2011-07-19 21:06:00 +00001397 // Parameterize the decoders based on namespace and instruction width.
Owen Anderson4e818902011-02-18 21:51:29 +00001398 NumberedInstructions = Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00001399 std::map<std::pair<std::string, unsigned>,
1400 std::vector<unsigned> > OpcMap;
1401 std::map<unsigned, std::vector<OperandInfo> > Operands;
1402
1403 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1404 const CodeGenInstruction *Inst = NumberedInstructions[i];
1405 Record *Def = Inst->TheDef;
1406 unsigned Size = Def->getValueAsInt("Size");
1407 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1408 Def->getValueAsBit("isPseudo") ||
1409 Def->getValueAsBit("isAsmParserOnly") ||
1410 Def->getValueAsBit("isCodeGenOnly"))
1411 continue;
1412
1413 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1414
1415 if (Size) {
1416 if (populateInstruction(*Inst, i, Operands)) {
1417 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1418 }
1419 }
1420 }
1421
1422 std::set<unsigned> Sizes;
1423 for (std::map<std::pair<std::string, unsigned>,
1424 std::vector<unsigned> >::iterator
1425 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1426 // If we haven't visited this instruction width before, emit the
1427 // helper method to extract fields.
1428 if (!Sizes.count(I->first.second)) {
1429 emitHelper(o, 8*I->first.second);
1430 Sizes.insert(I->first.second);
1431 }
1432
1433 // Emit the decoder for this namespace+width combination.
1434 FilterChooser FC(NumberedInstructions, I->second, Operands,
Owen Andersona4043c42011-08-17 17:44:15 +00001435 8*I->first.second, this);
Owen Andersonc78e03c2011-07-19 21:06:00 +00001436 FC.emitTop(o, 0, I->first.first);
1437 }
Owen Anderson4e818902011-02-18 21:51:29 +00001438
1439 o << "\n} // End llvm namespace \n";
1440}