1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
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 the target
11 // instruction set for the code generator.
13 //===----------------------------------------------------------------------===//
15 #include "InstrInfoEmitter.h"
16 #include "CodeGenTarget.h"
22 static void PrintDefList(const std::vector<Record*> &Uses,
23 unsigned Num, std::ostream &OS) {
24 OS << "static const unsigned ImplicitList" << Num << "[] = { ";
25 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
26 OS << getQualifiedName(Uses[i]) << ", ";
30 //===----------------------------------------------------------------------===//
31 // Instruction Itinerary Information.
32 //===----------------------------------------------------------------------===//
34 struct RecordNameComparator {
35 bool operator()(const Record *Rec1, const Record *Rec2) const {
36 return Rec1->getName() < Rec2->getName();
40 void InstrInfoEmitter::GatherItinClasses() {
41 std::vector<Record*> DefList =
42 Records.getAllDerivedDefinitions("InstrItinClass");
43 std::sort(DefList.begin(), DefList.end(), RecordNameComparator());
45 for (unsigned i = 0, N = DefList.size(); i < N; i++)
46 ItinClassMap[DefList[i]->getName()] = i;
49 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
50 return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
53 //===----------------------------------------------------------------------===//
54 // Operand Info Emission.
55 //===----------------------------------------------------------------------===//
57 std::vector<std::string>
58 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
59 std::vector<std::string> Result;
61 for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
62 // Handle aggregate operands and normal operands the same way by expanding
63 // either case into a list of operands for this op.
64 std::vector<CodeGenInstruction::OperandInfo> OperandList;
66 // This might be a multiple operand thing. Targets like X86 have
67 // registers in their multi-operand operands. It may also be an anonymous
68 // operand, which has a single operand, but no declared class for the
70 DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
72 if (!MIOI || MIOI->getNumArgs() == 0) {
73 // Single, anonymous, operand.
74 OperandList.push_back(Inst.OperandList[i]);
76 for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
77 OperandList.push_back(Inst.OperandList[i]);
79 Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
80 OperandList.back().Rec = OpR;
84 for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
85 Record *OpR = OperandList[j].Rec;
88 if (OpR->isSubClassOf("RegisterClass"))
89 Res += getQualifiedName(OpR) + "RegClassID, ";
92 // Fill in applicable flags.
95 // Ptr value whose register class is resolved via callback.
96 if (OpR->getName() == "ptr_rc")
97 Res += "|M_LOOK_UP_PTR_REG_CLASS";
99 // Predicate operands. Check to see if the original unexpanded operand
100 // was of type PredicateOperand.
101 if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
102 Res += "|M_PREDICATE_OPERAND";
104 // Optional def operands. Check to see if the original unexpanded operand
105 // was of type OptionalDefOperand.
106 if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
107 Res += "|M_OPTIONAL_DEF_OPERAND";
109 // Fill in constraint info.
110 Res += ", " + Inst.OperandList[i].Constraints[j];
111 Result.push_back(Res);
118 void InstrInfoEmitter::EmitOperandInfo(std::ostream &OS,
119 OperandInfoMapTy &OperandInfoIDs) {
120 // ID #0 is for no operand info.
121 unsigned OperandListNum = 0;
122 OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
125 const CodeGenTarget &Target = CDP.getTargetInfo();
126 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
127 E = Target.inst_end(); II != E; ++II) {
128 std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
129 unsigned &N = OperandInfoIDs[OperandInfo];
130 if (N != 0) continue;
132 N = ++OperandListNum;
133 OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
134 for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
135 OS << "{ " << OperandInfo[i] << " }, ";
140 //===----------------------------------------------------------------------===//
141 // Instruction Analysis
142 //===----------------------------------------------------------------------===//
145 const CodeGenDAGPatterns &CDP;
148 bool &NeverHasSideEffects;
150 InstAnalyzer(const CodeGenDAGPatterns &cdp,
151 bool &isstore, bool &isload, bool &nhse)
152 : CDP(cdp), isStore(isstore), isLoad(isload), NeverHasSideEffects(nhse) {
155 void Analyze(Record *InstRecord) {
156 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
157 if (Pattern == 0) return; // No pattern.
159 // Assume there is no side-effect unless we see one.
160 // FIXME: Enable this.
161 //NeverHasSideEffects = true;
164 // FIXME: Assume only the first tree is the pattern. The others are clobber
166 AnalyzeNode(Pattern->getTree(0));
170 void AnalyzeNode(const TreePatternNode *N) {
175 if (N->getOperator()->getName() != "set") {
176 // Get information about the SDNode for the operator.
177 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
179 // If this is a store node, it obviously stores to memory.
180 if (OpInfo.getEnumName() == "ISD::STORE") {
183 } else if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
184 // If this is an intrinsic, analyze it.
185 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
186 isStore = true; // Intrinsics that can write to memory are 'isStore'.
190 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
191 AnalyzeNode(N->getChild(i));
196 void InstrInfoEmitter::InferFromPattern(const CodeGenInstruction &Inst,
197 bool &isStore, bool &isLoad,
198 bool &NeverHasSideEffects) {
199 isStore = Inst.isStore;
200 isLoad = Inst.isLoad;
201 NeverHasSideEffects = Inst.neverHasSideEffects;
203 InstAnalyzer(CDP, isStore, isLoad, NeverHasSideEffects).Analyze(Inst.TheDef);
205 // If the .td file explicitly says there is no side effect, believe it.
206 if (Inst.neverHasSideEffects)
207 NeverHasSideEffects = true;
211 //===----------------------------------------------------------------------===//
213 //===----------------------------------------------------------------------===//
215 // run - Emit the main instruction description records for the target...
216 void InstrInfoEmitter::run(std::ostream &OS) {
219 EmitSourceFileHeader("Target Instruction Descriptors", OS);
220 OS << "namespace llvm {\n\n";
222 CodeGenTarget Target;
223 const std::string &TargetName = Target.getName();
224 Record *InstrInfo = Target.getInstructionSet();
226 // Keep track of all of the def lists we have emitted already.
227 std::map<std::vector<Record*>, unsigned> EmittedLists;
228 unsigned ListNumber = 0;
230 // Emit all of the instruction's implicit uses and defs.
231 for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
232 E = Target.inst_end(); II != E; ++II) {
233 Record *Inst = II->second.TheDef;
234 std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
236 unsigned &IL = EmittedLists[Uses];
237 if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
239 std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
241 unsigned &IL = EmittedLists[Defs];
242 if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
246 OperandInfoMapTy OperandInfoIDs;
248 // Emit all of the operand info records.
249 EmitOperandInfo(OS, OperandInfoIDs);
251 // Emit all of the TargetInstrDescriptor records in their ENUM ordering.
253 OS << "\nstatic const TargetInstrDescriptor " << TargetName
255 std::vector<const CodeGenInstruction*> NumberedInstructions;
256 Target.getInstructionsByEnumValue(NumberedInstructions);
258 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
259 emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
262 OS << "} // End llvm namespace \n";
265 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
267 std::map<std::vector<Record*>, unsigned> &EmittedLists,
268 const OperandInfoMapTy &OpInfo,
270 // Determine properties of the instruction from its pattern.
271 bool isStore, isLoad, NeverHasSideEffects;
272 InferFromPattern(Inst, isStore, isLoad, NeverHasSideEffects);
274 if (NeverHasSideEffects && Inst.mayHaveSideEffects) {
275 std::cerr << "error: Instruction '" << Inst.getName()
276 << "' is marked with 'mayHaveSideEffects', but it can never have them!\n";
281 if (!Inst.OperandList.empty())
282 // Each logical operand can be multiple MI operands.
283 MinOperands = Inst.OperandList.back().MIOperandNo +
284 Inst.OperandList.back().MINumOperands;
287 OS << Num << ",\t" << MinOperands << ",\t"
288 << Inst.NumDefs << ",\t\"" << Inst.getName();
289 OS << "\",\t" << getItinClassNumber(Inst.TheDef) << ", 0";
291 // Emit all of the target indepedent flags...
292 if (Inst.isReturn) OS << "|M_RET_FLAG";
293 if (Inst.isBranch) OS << "|M_BRANCH_FLAG";
294 if (Inst.isIndirectBranch) OS << "|M_INDIRECT_FLAG";
295 if (Inst.isBarrier) OS << "|M_BARRIER_FLAG";
296 if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
297 if (Inst.isCall) OS << "|M_CALL_FLAG";
298 if (isLoad) OS << "|M_LOAD_FLAG";
299 if (isStore) OS << "|M_STORE_FLAG";
300 if (Inst.isImplicitDef)OS << "|M_IMPLICIT_DEF_FLAG";
301 if (Inst.isPredicable) OS << "|M_PREDICABLE";
302 if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
303 if (Inst.isCommutable) OS << "|M_COMMUTABLE";
304 if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
305 if (Inst.isReMaterializable) OS << "|M_REMATERIALIZIBLE";
306 if (Inst.isNotDuplicable) OS << "|M_NOT_DUPLICABLE";
307 if (Inst.hasOptionalDef) OS << "|M_HAS_OPTIONAL_DEF";
308 if (Inst.usesCustomDAGSchedInserter)
309 OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
310 if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS";
311 if (Inst.mayHaveSideEffects) OS << "|M_MAY_HAVE_SIDE_EFFECTS";
312 if (NeverHasSideEffects) OS << "|M_NEVER_HAS_SIDE_EFFECTS";
315 // Emit all of the target-specific flags...
316 ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
317 ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
318 if (LI->getSize() != Shift->getSize())
319 throw "Lengths of " + InstrInfo->getName() +
320 ":(TargetInfoFields, TargetInfoPositions) must be equal!";
322 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
323 emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
324 dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
328 // Emit the implicit uses and defs lists...
329 std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
333 OS << "ImplicitList" << EmittedLists[UseList] << ", ";
335 std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
339 OS << "ImplicitList" << EmittedLists[DefList] << ", ";
341 // Emit the operand info.
342 std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
343 if (OperandInfo.empty())
346 OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
348 OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
352 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
353 IntInit *ShiftInt, std::ostream &OS) {
354 if (Val == 0 || ShiftInt == 0)
355 throw std::string("Illegal value or shift amount in TargetInfo*!");
356 RecordVal *RV = R->getValue(Val->getValue());
357 int Shift = ShiftInt->getValue();
359 if (RV == 0 || RV->getValue() == 0) {
360 // This isn't an error if this is a builtin instruction.
361 if (R->getName() != "PHI" &&
362 R->getName() != "INLINEASM" &&
363 R->getName() != "LABEL" &&
364 R->getName() != "EXTRACT_SUBREG" &&
365 R->getName() != "INSERT_SUBREG")
366 throw R->getName() + " doesn't have a field named '" +
367 Val->getValue() + "'!";
371 Init *Value = RV->getValue();
372 if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
373 if (BI->getValue()) OS << "|(1<<" << Shift << ")";
375 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
376 // Convert the Bits to an integer to print...
377 Init *I = BI->convertInitializerTo(new IntRecTy());
379 if (IntInit *II = dynamic_cast<IntInit*>(I)) {
380 if (II->getValue()) {
382 OS << "|(" << II->getValue() << "<<" << Shift << ")";
384 OS << "|" << II->getValue();
389 } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
390 if (II->getValue()) {
392 OS << "|(" << II->getValue() << "<<" << Shift << ")";
394 OS << II->getValue();
399 std::cerr << "Unhandled initializer: " << *Val << "\n";
400 throw "In record '" + R->getName() + "' for TSFlag emission.";