1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
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 implements a simple two pass scheduler. The first pass attempts to push
11 // backward any lengthy instructions and critical paths. The second pass packs
12 // instructions into semi-optimal time slots.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "pre-RA-sched"
17 #include "llvm/Constants.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
32 STATISTIC(NumCommutes, "Number of instructions commuted");
34 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
35 const TargetMachine &tm)
36 : DAG(dag), BB(bb), TM(tm), RegInfo(BB->getParent()->getRegInfo()) {
37 TII = TM.getInstrInfo();
38 MF = &DAG.getMachineFunction();
39 TRI = TM.getRegisterInfo();
40 ConstPool = BB->getParent()->getConstantPool();
43 /// CheckForPhysRegDependency - Check if the dependency between def and use of
44 /// a specified operand is a physical register dependency. If so, returns the
45 /// register and the cost of copying the register.
46 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
47 const TargetRegisterInfo *TRI,
48 const TargetInstrInfo *TII,
49 unsigned &PhysReg, int &Cost) {
50 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
53 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
54 if (TargetRegisterInfo::isVirtualRegister(Reg))
57 unsigned ResNo = Use->getOperand(2).ResNo;
58 if (Def->isTargetOpcode()) {
59 const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
60 if (ResNo >= II.getNumDefs() &&
61 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
63 const TargetRegisterClass *RC =
64 TRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
65 Cost = RC->getCopyCost();
70 SUnit *ScheduleDAG::Clone(SUnit *Old) {
71 SUnit *SU = NewSUnit(Old->Node);
72 SU->FlaggedNodes = Old->FlaggedNodes;
73 SU->InstanceNo = SUnitMap[Old->Node].size();
74 SU->Latency = Old->Latency;
75 SU->isTwoAddress = Old->isTwoAddress;
76 SU->isCommutable = Old->isCommutable;
77 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
78 SUnitMap[Old->Node].push_back(SU);
83 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
84 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
85 /// together nodes with a single SUnit.
86 void ScheduleDAG::BuildSchedUnits() {
87 // Reserve entries in the vector for each of the SUnits we are creating. This
88 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
90 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
92 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
93 E = DAG.allnodes_end(); NI != E; ++NI) {
94 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
97 // If this node has already been processed, stop now.
98 if (SUnitMap[NI].size()) continue;
100 SUnit *NodeSUnit = NewSUnit(NI);
102 // See if anything is flagged to this node, if so, add them to flagged
103 // nodes. Nodes can have at most one flag input and one flag output. Flags
104 // are required the be the last operand and result of a node.
106 // Scan up, adding flagged preds to FlaggedNodes.
108 if (N->getNumOperands() &&
109 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
111 N = N->getOperand(N->getNumOperands()-1).Val;
112 NodeSUnit->FlaggedNodes.push_back(N);
113 SUnitMap[N].push_back(NodeSUnit);
114 } while (N->getNumOperands() &&
115 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
116 std::reverse(NodeSUnit->FlaggedNodes.begin(),
117 NodeSUnit->FlaggedNodes.end());
120 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
121 // have a user of the flag operand.
123 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
124 SDOperand FlagVal(N, N->getNumValues()-1);
126 // There are either zero or one users of the Flag result.
127 bool HasFlagUse = false;
128 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
130 if (FlagVal.isOperandOf(*UI)) {
132 NodeSUnit->FlaggedNodes.push_back(N);
133 SUnitMap[N].push_back(NodeSUnit);
137 if (!HasFlagUse) break;
140 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
143 SUnitMap[N].push_back(NodeSUnit);
145 ComputeLatency(NodeSUnit);
148 // Pass 2: add the preds, succs, etc.
149 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
150 SUnit *SU = &SUnits[su];
151 SDNode *MainNode = SU->Node;
153 if (MainNode->isTargetOpcode()) {
154 unsigned Opc = MainNode->getTargetOpcode();
155 const TargetInstrDesc &TID = TII->get(Opc);
156 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
157 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
158 SU->isTwoAddress = true;
162 if (TID.isCommutable())
163 SU->isCommutable = true;
166 // Find all predecessors and successors of the group.
167 // Temporarily add N to make code simpler.
168 SU->FlaggedNodes.push_back(MainNode);
170 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
171 SDNode *N = SU->FlaggedNodes[n];
172 if (N->isTargetOpcode() &&
173 TII->get(N->getTargetOpcode()).getImplicitDefs() &&
174 CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
175 SU->hasPhysRegDefs = true;
177 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
178 SDNode *OpN = N->getOperand(i).Val;
179 if (isPassiveNode(OpN)) continue; // Not scheduled.
180 SUnit *OpSU = SUnitMap[OpN].front();
181 assert(OpSU && "Node has no SUnit!");
182 if (OpSU == SU) continue; // In the same group.
184 MVT::ValueType OpVT = N->getOperand(i).getValueType();
185 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
186 bool isChain = OpVT == MVT::Other;
188 unsigned PhysReg = 0;
190 // Determine if this is a physical register dependency.
191 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
192 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
196 // Remove MainNode from FlaggedNodes again.
197 SU->FlaggedNodes.pop_back();
203 void ScheduleDAG::ComputeLatency(SUnit *SU) {
204 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
206 // Compute the latency for the node. We use the sum of the latencies for
207 // all nodes flagged together into this SUnit.
208 if (InstrItins.isEmpty()) {
209 // No latency information.
213 if (SU->Node->isTargetOpcode()) {
214 unsigned SchedClass =
215 TII->get(SU->Node->getTargetOpcode()).getSchedClass();
216 InstrStage *S = InstrItins.begin(SchedClass);
217 InstrStage *E = InstrItins.end(SchedClass);
219 SU->Latency += S->Cycles;
221 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
222 SDNode *FNode = SU->FlaggedNodes[i];
223 if (FNode->isTargetOpcode()) {
224 unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
225 InstrStage *S = InstrItins.begin(SchedClass);
226 InstrStage *E = InstrItins.end(SchedClass);
228 SU->Latency += S->Cycles;
234 /// CalculateDepths - compute depths using algorithms for the longest
236 void ScheduleDAG::CalculateDepths() {
237 unsigned DAGSize = SUnits.size();
238 std::vector<unsigned> InDegree(DAGSize);
239 std::vector<SUnit*> WorkList;
240 WorkList.reserve(DAGSize);
242 // Initialize the data structures
243 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
244 SUnit *SU = &SUnits[i];
245 int NodeNum = SU->NodeNum;
246 unsigned Degree = SU->Preds.size();
247 InDegree[NodeNum] = Degree;
250 // Is it a node without dependencies?
252 assert(SU->Preds.empty() && "SUnit should have no predecessors");
253 // Collect leaf nodes
254 WorkList.push_back(SU);
258 // Process nodes in the topological order
259 while (!WorkList.empty()) {
260 SUnit *SU = WorkList.back();
262 unsigned &SUDepth = SU->Depth;
264 // Use dynamic programming:
265 // When current node is being processed, all of its dependencies
266 // are already processed.
267 // So, just iterate over all predecessors and take the longest path
268 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
270 unsigned PredDepth = I->Dep->Depth;
271 if (PredDepth+1 > SUDepth) {
272 SUDepth = PredDepth + 1;
276 // Update InDegrees of all nodes depending on current SUnit
277 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
280 if (!--InDegree[SU->NodeNum])
281 // If all dependencies of the node are processed already,
282 // then the longest path for the node can be computed now
283 WorkList.push_back(SU);
288 /// CalculateHeights - compute heights using algorithms for the longest
290 void ScheduleDAG::CalculateHeights() {
291 unsigned DAGSize = SUnits.size();
292 std::vector<unsigned> InDegree(DAGSize);
293 std::vector<SUnit*> WorkList;
294 WorkList.reserve(DAGSize);
296 // Initialize the data structures
297 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
298 SUnit *SU = &SUnits[i];
299 int NodeNum = SU->NodeNum;
300 unsigned Degree = SU->Succs.size();
301 InDegree[NodeNum] = Degree;
304 // Is it a node without dependencies?
306 assert(SU->Succs.empty() && "Something wrong");
307 assert(WorkList.empty() && "Should be empty");
308 // Collect leaf nodes
309 WorkList.push_back(SU);
313 // Process nodes in the topological order
314 while (!WorkList.empty()) {
315 SUnit *SU = WorkList.back();
317 unsigned &SUHeight = SU->Height;
319 // Use dynamic programming:
320 // When current node is being processed, all of its dependencies
321 // are already processed.
322 // So, just iterate over all successors and take the longest path
323 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
325 unsigned SuccHeight = I->Dep->Height;
326 if (SuccHeight+1 > SUHeight) {
327 SUHeight = SuccHeight + 1;
331 // Update InDegrees of all nodes depending on current SUnit
332 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
335 if (!--InDegree[SU->NodeNum])
336 // If all dependencies of the node are processed already,
337 // then the longest path for the node can be computed now
338 WorkList.push_back(SU);
343 /// CountResults - The results of target nodes have register or immediate
344 /// operands first, then an optional chain, and optional flag operands (which do
345 /// not go into the resulting MachineInstr).
346 unsigned ScheduleDAG::CountResults(SDNode *Node) {
347 unsigned N = Node->getNumValues();
348 while (N && Node->getValueType(N - 1) == MVT::Flag)
350 if (N && Node->getValueType(N - 1) == MVT::Other)
351 --N; // Skip over chain result.
355 /// CountOperands - The inputs to target nodes have any actual inputs first,
356 /// followed by special operands that describe memory references, then an
357 /// optional chain operand, then flag operands. Compute the number of
358 /// actual operands that will go into the resulting MachineInstr.
359 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
360 unsigned N = ComputeMemOperandsEnd(Node);
361 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
362 --N; // Ignore MemOperand nodes
366 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
368 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
369 unsigned N = Node->getNumOperands();
370 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
372 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
373 --N; // Ignore chain if it exists.
377 static const TargetRegisterClass *getInstrOperandRegClass(
378 const TargetRegisterInfo *TRI,
379 const TargetInstrInfo *TII,
380 const TargetInstrDesc &II,
382 if (Op >= II.getNumOperands()) {
383 assert(II.isVariadic() && "Invalid operand # of instruction");
386 if (II.OpInfo[Op].isLookupPtrRegClass())
387 return TII->getPointerRegClass();
388 return TRI->getRegClass(II.OpInfo[Op].RegClass);
391 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
392 unsigned InstanceNo, unsigned SrcReg,
393 DenseMap<SDOperand, unsigned> &VRBaseMap) {
395 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
396 // Just use the input register directly!
398 VRBaseMap.erase(SDOperand(Node, ResNo));
399 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
400 assert(isNew && "Node emitted out of order - early");
404 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
405 // the CopyToReg'd destination register instead of creating a new vreg.
406 bool MatchReg = true;
407 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
411 if (Use->getOpcode() == ISD::CopyToReg &&
412 Use->getOperand(2).Val == Node &&
413 Use->getOperand(2).ResNo == ResNo) {
414 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
415 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
418 } else if (DestReg != SrcReg)
421 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
422 SDOperand Op = Use->getOperand(i);
423 if (Op.Val != Node || Op.ResNo != ResNo)
425 MVT::ValueType VT = Node->getValueType(Op.ResNo);
426 if (VT != MVT::Other && VT != MVT::Flag)
435 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
436 SrcRC = TRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
438 // Figure out the register class to create for the destreg.
440 DstRC = RegInfo.getRegClass(VRBase);
442 DstRC = DAG.getTargetLoweringInfo()
443 .getRegClassFor(Node->getValueType(ResNo));
446 // If all uses are reading from the src physical register and copying the
447 // register is either impossible or very expensive, then don't create a copy.
448 if (MatchReg && SrcRC->getCopyCost() < 0) {
451 // Create the reg, emit the copy.
452 VRBase = RegInfo.createVirtualRegister(DstRC);
453 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
457 VRBaseMap.erase(SDOperand(Node, ResNo));
458 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
459 assert(isNew && "Node emitted out of order - early");
462 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
464 const TargetInstrDesc &II,
465 DenseMap<SDOperand, unsigned> &VRBaseMap) {
466 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
467 // If the specific node value is only used by a CopyToReg and the dest reg
468 // is a vreg, use the CopyToReg'd destination register instead of creating
471 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
474 if (Use->getOpcode() == ISD::CopyToReg &&
475 Use->getOperand(2).Val == Node &&
476 Use->getOperand(2).ResNo == i) {
477 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
478 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
480 MI->addOperand(MachineOperand::CreateReg(Reg, true));
486 // Create the result registers for this node and add the result regs to
487 // the machine instruction.
489 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
490 assert(RC && "Isn't a register operand!");
491 VRBase = RegInfo.createVirtualRegister(RC);
492 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
495 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
496 assert(isNew && "Node emitted out of order - early");
500 /// getVR - Return the virtual register corresponding to the specified result
501 /// of the specified node.
502 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
503 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
504 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
509 /// AddOperand - Add the specified operand to the specified machine instr. II
510 /// specifies the instruction information for the node, and IIOpNum is the
511 /// operand number (in the II) that we are adding. IIOpNum and II are used for
513 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
515 const TargetInstrDesc *II,
516 DenseMap<SDOperand, unsigned> &VRBaseMap) {
517 if (Op.isTargetOpcode()) {
518 // Note that this case is redundant with the final else block, but we
519 // include it because it is the most common and it makes the logic
521 assert(Op.getValueType() != MVT::Other &&
522 Op.getValueType() != MVT::Flag &&
523 "Chain and flag operands should occur at end of operand list!");
525 // Get/emit the operand.
526 unsigned VReg = getVR(Op, VRBaseMap);
527 const TargetInstrDesc &TID = MI->getDesc();
528 bool isOptDef = (IIOpNum < TID.getNumOperands())
529 ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
530 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
532 // Verify that it is right.
533 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
536 // There may be no register class for this operand if it is a variadic
537 // argument (RC will be NULL in this case). In this case, we just assume
538 // the regclass is ok.
539 const TargetRegisterClass *RC =
540 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
541 assert((RC || II->isVariadic()) && "Expected reg class info!");
542 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
543 if (RC && VRC != RC) {
544 cerr << "Register class of operand and regclass of use don't agree!\n";
545 cerr << "Operand = " << IIOpNum << "\n";
546 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
547 cerr << "MI = "; MI->print(cerr);
548 cerr << "VReg = " << VReg << "\n";
549 cerr << "VReg RegClass size = " << VRC->getSize()
550 << ", align = " << VRC->getAlignment() << "\n";
551 cerr << "Expected RegClass size = " << RC->getSize()
552 << ", align = " << RC->getAlignment() << "\n";
553 cerr << "Fatal error, aborting.\n";
558 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
559 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
560 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
561 const Type *FType = MVT::getTypeForValueType(Op.getValueType());
562 ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
563 MI->addOperand(MachineOperand::CreateFPImm(CFP));
564 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
565 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
566 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
567 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
568 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
569 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
570 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
571 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
572 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
573 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
574 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
575 int Offset = CP->getOffset();
576 unsigned Align = CP->getAlignment();
577 const Type *Type = CP->getType();
578 // MachineConstantPool wants an explicit alignment.
580 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
582 // Alignment of vector types. FIXME!
583 Align = TM.getTargetData()->getABITypeSize(Type);
584 Align = Log2_64(Align);
589 if (CP->isMachineConstantPoolEntry())
590 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
592 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
593 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
594 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
595 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
597 assert(Op.getValueType() != MVT::Other &&
598 Op.getValueType() != MVT::Flag &&
599 "Chain and flag operands should occur at end of operand list!");
600 unsigned VReg = getVR(Op, VRBaseMap);
601 MI->addOperand(MachineOperand::CreateReg(VReg, false));
603 // Verify that it is right. Note that the reg class of the physreg and the
604 // vreg don't necessarily need to match, but the target copy insertion has
605 // to be able to handle it. This handles things like copies from ST(0) to
606 // an FP vreg on x86.
607 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
608 if (II && !II->isVariadic()) {
609 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
610 "Don't have operand info for this instruction!");
616 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
617 MI->addMemOperand(MO);
620 // Returns the Register Class of a subregister
621 static const TargetRegisterClass *getSubRegisterRegClass(
622 const TargetRegisterClass *TRC,
624 // Pick the register class of the subregister
625 TargetRegisterInfo::regclass_iterator I =
626 TRC->subregclasses_begin() + SubIdx-1;
627 assert(I < TRC->subregclasses_end() &&
628 "Invalid subregister index for register class");
632 static const TargetRegisterClass *getSuperregRegisterClass(
633 const TargetRegisterClass *TRC,
636 // Pick the register class of the superegister for this type
637 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
638 E = TRC->superregclasses_end(); I != E; ++I)
639 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
641 assert(false && "Couldn't find the register class");
645 /// EmitSubregNode - Generate machine code for subreg nodes.
647 void ScheduleDAG::EmitSubregNode(SDNode *Node,
648 DenseMap<SDOperand, unsigned> &VRBaseMap) {
650 unsigned Opc = Node->getTargetOpcode();
651 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
652 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
653 // the CopyToReg'd destination register instead of creating a new vreg.
654 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
657 if (Use->getOpcode() == ISD::CopyToReg &&
658 Use->getOperand(2).Val == Node) {
659 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
660 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
667 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
669 // TODO: If the node is a use of a CopyFromReg from a physical register
670 // fold the extract into the copy now
672 // Create the extract_subreg machine instruction.
674 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
676 // Figure out the register class to create for the destreg.
677 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
678 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
679 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
682 // Grab the destination register
683 const TargetRegisterClass *DRC = RegInfo.getRegClass(VRBase);
684 assert(SRC && DRC && SRC == DRC &&
685 "Source subregister and destination must have the same class");
688 assert(SRC && "Couldn't find source register class");
689 VRBase = RegInfo.createVirtualRegister(SRC);
692 // Add def, source, and subreg index
693 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
694 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
695 MI->addOperand(MachineOperand::CreateImm(SubIdx));
697 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
698 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
699 "Malformed insert_subreg node");
700 bool isUndefInput = (Node->getNumOperands() == 2);
705 SubReg = getVR(Node->getOperand(0), VRBaseMap);
706 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
708 SubReg = getVR(Node->getOperand(1), VRBaseMap);
709 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
712 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
713 // to allow coalescing in the allocator
715 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
716 // the CopyToReg'd destination register instead of creating a new vreg.
717 // If the CopyToReg'd destination register is physical, then fold the
718 // insert into the copy
719 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
722 if (Use->getOpcode() == ISD::CopyToReg &&
723 Use->getOperand(2).Val == Node) {
724 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
725 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
732 // Create the insert_subreg machine instruction.
734 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
736 // Figure out the register class to create for the destreg.
737 const TargetRegisterClass *TRC = 0;
739 TRC = RegInfo.getRegClass(VRBase);
741 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
742 Node->getValueType(0));
743 assert(TRC && "Couldn't determine register class for insert_subreg");
744 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
747 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
748 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
750 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
751 MI->addOperand(MachineOperand::CreateImm(SubIdx));
753 assert(0 && "Node is not a subreg insert or extract");
755 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
756 assert(isNew && "Node emitted out of order - early");
759 /// EmitNode - Generate machine code for an node and needed dependencies.
761 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
762 DenseMap<SDOperand, unsigned> &VRBaseMap) {
763 // If machine instruction
764 if (Node->isTargetOpcode()) {
765 unsigned Opc = Node->getTargetOpcode();
767 // Handle subreg insert/extract specially
768 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
769 Opc == TargetInstrInfo::INSERT_SUBREG) {
770 EmitSubregNode(Node, VRBaseMap);
774 const TargetInstrDesc &II = TII->get(Opc);
776 unsigned NumResults = CountResults(Node);
777 unsigned NodeOperands = CountOperands(Node);
778 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
779 unsigned NumMIOperands = NodeOperands + NumResults;
780 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
781 II.getImplicitDefs() != 0;
783 assert((II.getNumOperands() == NumMIOperands ||
784 HasPhysRegOuts || II.isVariadic()) &&
785 "#operands for dag node doesn't match .td file!");
788 // Create the new machine instruction.
789 MachineInstr *MI = new MachineInstr(II);
791 // Add result register values for things that are defined by this
794 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
796 // Emit all of the actual operands of this instruction, adding them to the
797 // instruction as appropriate.
798 for (unsigned i = 0; i != NodeOperands; ++i)
799 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
801 // Emit all of the memory operands of this instruction
802 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
803 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
805 // Commute node if it has been determined to be profitable.
806 if (CommuteSet.count(Node)) {
807 MachineInstr *NewMI = TII->commuteInstruction(MI);
809 DOUT << "Sched: COMMUTING FAILED!\n";
811 DOUT << "Sched: COMMUTED TO: " << *NewMI;
820 if (II.usesCustomDAGSchedInsertionHook())
821 // Insert this instruction into the basic block using a target
822 // specific inserter which may returns a new basic block.
823 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
827 // Additional results must be an physical register def.
828 if (HasPhysRegOuts) {
829 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
830 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
831 if (Node->hasAnyUseOfValue(i))
832 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
836 switch (Node->getOpcode()) {
841 assert(0 && "This target-independent node should have been selected!");
842 case ISD::EntryToken: // fall thru
843 case ISD::TokenFactor:
848 case ISD::CopyToReg: {
850 SDOperand SrcVal = Node->getOperand(2);
851 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
852 SrcReg = R->getReg();
854 SrcReg = getVR(SrcVal, VRBaseMap);
856 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
857 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
860 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
861 // Get the register classes of the src/dst.
862 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
863 SrcTRC = RegInfo.getRegClass(SrcReg);
865 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcVal.getValueType(),SrcReg);
867 if (TargetRegisterInfo::isVirtualRegister(DestReg))
868 DstTRC = RegInfo.getRegClass(DestReg);
870 DstTRC = TRI->getPhysicalRegisterRegClass(
871 Node->getOperand(1).getValueType(),
873 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
876 case ISD::CopyFromReg: {
877 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
878 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
881 case ISD::INLINEASM: {
882 unsigned NumOps = Node->getNumOperands();
883 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
884 --NumOps; // Ignore the flag operand.
886 // Create the inline asm machine instruction.
888 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
890 // Add the asm string as an external symbol operand.
892 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
893 MI->addOperand(MachineOperand::CreateES(AsmStr));
895 // Add all of the operand registers to the instruction.
896 for (unsigned i = 2; i != NumOps;) {
897 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
898 unsigned NumVals = Flags >> 3;
900 MI->addOperand(MachineOperand::CreateImm(Flags));
901 ++i; // Skip the ID value.
904 default: assert(0 && "Bad flags!");
905 case 1: // Use of register.
906 for (; NumVals; --NumVals, ++i) {
907 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
908 MI->addOperand(MachineOperand::CreateReg(Reg, false));
911 case 2: // Def of register.
912 for (; NumVals; --NumVals, ++i) {
913 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
914 MI->addOperand(MachineOperand::CreateReg(Reg, true));
917 case 3: { // Immediate.
918 for (; NumVals; --NumVals, ++i) {
919 if (ConstantSDNode *CS =
920 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
921 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
922 } else if (GlobalAddressSDNode *GA =
923 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
924 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
927 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
928 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
933 case 4: // Addressing mode.
934 // The addressing mode has been selected, just add all of the
935 // operands to the machine instruction.
936 for (; NumVals; --NumVals, ++i)
937 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
947 void ScheduleDAG::EmitNoop() {
948 TII->insertNoop(*BB, BB->end());
951 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
952 DenseMap<SUnit*, unsigned> &VRBaseMap) {
953 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
955 if (I->isCtrl) continue; // ignore chain preds
957 // Copy to physical register.
958 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
959 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
960 // Find the destination physical register.
962 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
963 EE = SU->Succs.end(); II != EE; ++II) {
969 assert(I->Reg && "Unknown physical register!");
970 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
971 SU->CopyDstRC, SU->CopySrcRC);
973 // Copy from physical register.
974 assert(I->Reg && "Unknown physical register!");
975 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
976 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
977 assert(isNew && "Node emitted out of order - early");
978 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
979 SU->CopyDstRC, SU->CopySrcRC);
985 /// EmitSchedule - Emit the machine code in scheduled order.
986 void ScheduleDAG::EmitSchedule() {
987 // If this is the first basic block in the function, and if it has live ins
988 // that need to be copied into vregs, emit the copies into the top of the
989 // block before emitting the code for the block.
990 if (&MF->front() == BB) {
991 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
992 E = RegInfo.livein_end(); LI != E; ++LI)
994 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
995 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1001 // Finally, emit the code for all of the scheduled instructions.
1002 DenseMap<SDOperand, unsigned> VRBaseMap;
1003 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1004 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1005 if (SUnit *SU = Sequence[i]) {
1006 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1007 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
1009 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
1011 EmitCrossRCCopy(SU, CopyVRBaseMap);
1013 // Null SUnit* is a noop.
1019 /// dump - dump the schedule.
1020 void ScheduleDAG::dumpSchedule() const {
1021 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1022 if (SUnit *SU = Sequence[i])
1025 cerr << "**** NOOP ****\n";
1030 /// Run - perform scheduling.
1032 MachineBasicBlock *ScheduleDAG::Run() {
1037 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1038 /// a group of nodes flagged together.
1039 void SUnit::dump(const SelectionDAG *G) const {
1040 cerr << "SU(" << NodeNum << "): ";
1044 cerr << "CROSS RC COPY ";
1046 if (FlaggedNodes.size() != 0) {
1047 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1049 FlaggedNodes[i]->dump(G);
1055 void SUnit::dumpAll(const SelectionDAG *G) const {
1058 cerr << " # preds left : " << NumPredsLeft << "\n";
1059 cerr << " # succs left : " << NumSuccsLeft << "\n";
1060 cerr << " Latency : " << Latency << "\n";
1061 cerr << " Depth : " << Depth << "\n";
1062 cerr << " Height : " << Height << "\n";
1064 if (Preds.size() != 0) {
1065 cerr << " Predecessors:\n";
1066 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1072 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1078 if (Succs.size() != 0) {
1079 cerr << " Successors:\n";
1080 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1086 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";