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?");
535 const TargetRegisterClass *RC =
536 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
537 assert(RC && "Don't have operand info for this instruction!");
538 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
540 cerr << "Register class of operand and regclass of use don't agree!\n";
542 cerr << "Operand = " << IIOpNum << "\n";
543 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
544 cerr << "MI = "; MI->print(cerr);
545 cerr << "VReg = " << VReg << "\n";
546 cerr << "VReg RegClass size = " << VRC->getSize()
547 << ", align = " << VRC->getAlignment() << "\n";
548 cerr << "Expected RegClass size = " << RC->getSize()
549 << ", align = " << RC->getAlignment() << "\n";
551 cerr << "Fatal error, aborting.\n";
555 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
556 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
557 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
558 const Type *FType = MVT::getTypeForValueType(Op.getValueType());
559 ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
560 MI->addOperand(MachineOperand::CreateFPImm(CFP));
561 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
562 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
563 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
564 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
565 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
566 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
567 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
568 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
569 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
570 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
571 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
572 int Offset = CP->getOffset();
573 unsigned Align = CP->getAlignment();
574 const Type *Type = CP->getType();
575 // MachineConstantPool wants an explicit alignment.
577 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
579 // Alignment of vector types. FIXME!
580 Align = TM.getTargetData()->getABITypeSize(Type);
581 Align = Log2_64(Align);
586 if (CP->isMachineConstantPoolEntry())
587 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
589 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
590 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
591 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
592 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
594 assert(Op.getValueType() != MVT::Other &&
595 Op.getValueType() != MVT::Flag &&
596 "Chain and flag operands should occur at end of operand list!");
597 unsigned VReg = getVR(Op, VRBaseMap);
598 MI->addOperand(MachineOperand::CreateReg(VReg, false));
600 // Verify that it is right. Note that the reg class of the physreg and the
601 // vreg don't necessarily need to match, but the target copy insertion has
602 // to be able to handle it. This handles things like copies from ST(0) to
603 // an FP vreg on x86.
604 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
606 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
607 "Don't have operand info for this instruction!");
613 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
614 MI->addMemOperand(MO);
617 // Returns the Register Class of a subregister
618 static const TargetRegisterClass *getSubRegisterRegClass(
619 const TargetRegisterClass *TRC,
621 // Pick the register class of the subregister
622 TargetRegisterInfo::regclass_iterator I =
623 TRC->subregclasses_begin() + SubIdx-1;
624 assert(I < TRC->subregclasses_end() &&
625 "Invalid subregister index for register class");
629 static const TargetRegisterClass *getSuperregRegisterClass(
630 const TargetRegisterClass *TRC,
633 // Pick the register class of the superegister for this type
634 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
635 E = TRC->superregclasses_end(); I != E; ++I)
636 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
638 assert(false && "Couldn't find the register class");
642 /// EmitSubregNode - Generate machine code for subreg nodes.
644 void ScheduleDAG::EmitSubregNode(SDNode *Node,
645 DenseMap<SDOperand, unsigned> &VRBaseMap) {
647 unsigned Opc = Node->getTargetOpcode();
648 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
649 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
650 // the CopyToReg'd destination register instead of creating a new vreg.
651 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
654 if (Use->getOpcode() == ISD::CopyToReg &&
655 Use->getOperand(2).Val == Node) {
656 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
657 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
664 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
666 // TODO: If the node is a use of a CopyFromReg from a physical register
667 // fold the extract into the copy now
669 // Create the extract_subreg machine instruction.
671 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
673 // Figure out the register class to create for the destreg.
674 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
675 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
676 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
679 // Grab the destination register
680 const TargetRegisterClass *DRC = RegInfo.getRegClass(VRBase);
681 assert(SRC && DRC && SRC == DRC &&
682 "Source subregister and destination must have the same class");
685 assert(SRC && "Couldn't find source register class");
686 VRBase = RegInfo.createVirtualRegister(SRC);
689 // Add def, source, and subreg index
690 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
691 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
692 MI->addOperand(MachineOperand::CreateImm(SubIdx));
694 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
695 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
696 "Malformed insert_subreg node");
697 bool isUndefInput = (Node->getNumOperands() == 2);
702 SubReg = getVR(Node->getOperand(0), VRBaseMap);
703 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
705 SubReg = getVR(Node->getOperand(1), VRBaseMap);
706 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
709 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
710 // to allow coalescing in the allocator
712 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
713 // the CopyToReg'd destination register instead of creating a new vreg.
714 // If the CopyToReg'd destination register is physical, then fold the
715 // insert into the copy
716 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
719 if (Use->getOpcode() == ISD::CopyToReg &&
720 Use->getOperand(2).Val == Node) {
721 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
722 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
729 // Create the insert_subreg machine instruction.
731 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
733 // Figure out the register class to create for the destreg.
734 const TargetRegisterClass *TRC = 0;
736 TRC = RegInfo.getRegClass(VRBase);
738 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
739 Node->getValueType(0));
740 assert(TRC && "Couldn't determine register class for insert_subreg");
741 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
744 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
745 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
747 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
748 MI->addOperand(MachineOperand::CreateImm(SubIdx));
750 assert(0 && "Node is not a subreg insert or extract");
752 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
753 assert(isNew && "Node emitted out of order - early");
756 /// EmitNode - Generate machine code for an node and needed dependencies.
758 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
759 DenseMap<SDOperand, unsigned> &VRBaseMap) {
760 // If machine instruction
761 if (Node->isTargetOpcode()) {
762 unsigned Opc = Node->getTargetOpcode();
764 // Handle subreg insert/extract specially
765 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
766 Opc == TargetInstrInfo::INSERT_SUBREG) {
767 EmitSubregNode(Node, VRBaseMap);
771 const TargetInstrDesc &II = TII->get(Opc);
773 unsigned NumResults = CountResults(Node);
774 unsigned NodeOperands = CountOperands(Node);
775 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
776 unsigned NumMIOperands = NodeOperands + NumResults;
777 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
778 II.getImplicitDefs() != 0;
780 assert((II.getNumOperands() == NumMIOperands ||
781 HasPhysRegOuts || II.isVariadic()) &&
782 "#operands for dag node doesn't match .td file!");
785 // Create the new machine instruction.
786 MachineInstr *MI = new MachineInstr(II);
788 // Add result register values for things that are defined by this
791 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
793 // Emit all of the actual operands of this instruction, adding them to the
794 // instruction as appropriate.
795 for (unsigned i = 0; i != NodeOperands; ++i)
796 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
798 // Emit all of the memory operands of this instruction
799 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
800 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
802 // Commute node if it has been determined to be profitable.
803 if (CommuteSet.count(Node)) {
804 MachineInstr *NewMI = TII->commuteInstruction(MI);
806 DOUT << "Sched: COMMUTING FAILED!\n";
808 DOUT << "Sched: COMMUTED TO: " << *NewMI;
817 if (II.usesCustomDAGSchedInsertionHook())
818 // Insert this instruction into the basic block using a target
819 // specific inserter which may returns a new basic block.
820 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
824 // Additional results must be an physical register def.
825 if (HasPhysRegOuts) {
826 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
827 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
828 if (Node->hasAnyUseOfValue(i))
829 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
833 switch (Node->getOpcode()) {
838 assert(0 && "This target-independent node should have been selected!");
839 case ISD::EntryToken: // fall thru
840 case ISD::TokenFactor:
845 case ISD::CopyToReg: {
847 SDOperand SrcVal = Node->getOperand(2);
848 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
849 SrcReg = R->getReg();
851 SrcReg = getVR(SrcVal, VRBaseMap);
853 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
854 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
857 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
858 // Get the register classes of the src/dst.
859 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
860 SrcTRC = RegInfo.getRegClass(SrcReg);
862 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcVal.getValueType(),SrcReg);
864 if (TargetRegisterInfo::isVirtualRegister(DestReg))
865 DstTRC = RegInfo.getRegClass(DestReg);
867 DstTRC = TRI->getPhysicalRegisterRegClass(
868 Node->getOperand(1).getValueType(),
870 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
873 case ISD::CopyFromReg: {
874 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
875 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
878 case ISD::INLINEASM: {
879 unsigned NumOps = Node->getNumOperands();
880 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
881 --NumOps; // Ignore the flag operand.
883 // Create the inline asm machine instruction.
885 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
887 // Add the asm string as an external symbol operand.
889 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
890 MI->addOperand(MachineOperand::CreateES(AsmStr));
892 // Add all of the operand registers to the instruction.
893 for (unsigned i = 2; i != NumOps;) {
894 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
895 unsigned NumVals = Flags >> 3;
897 MI->addOperand(MachineOperand::CreateImm(Flags));
898 ++i; // Skip the ID value.
901 default: assert(0 && "Bad flags!");
902 case 1: // Use of register.
903 for (; NumVals; --NumVals, ++i) {
904 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
905 MI->addOperand(MachineOperand::CreateReg(Reg, false));
908 case 2: // Def of register.
909 for (; NumVals; --NumVals, ++i) {
910 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
911 MI->addOperand(MachineOperand::CreateReg(Reg, true));
914 case 3: { // Immediate.
915 for (; NumVals; --NumVals, ++i) {
916 if (ConstantSDNode *CS =
917 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
918 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
919 } else if (GlobalAddressSDNode *GA =
920 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
921 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
924 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
925 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
930 case 4: // Addressing mode.
931 // The addressing mode has been selected, just add all of the
932 // operands to the machine instruction.
933 for (; NumVals; --NumVals, ++i)
934 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
944 void ScheduleDAG::EmitNoop() {
945 TII->insertNoop(*BB, BB->end());
948 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
949 DenseMap<SUnit*, unsigned> &VRBaseMap) {
950 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
952 if (I->isCtrl) continue; // ignore chain preds
954 // Copy to physical register.
955 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
956 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
957 // Find the destination physical register.
959 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
960 EE = SU->Succs.end(); II != EE; ++II) {
966 assert(I->Reg && "Unknown physical register!");
967 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
968 SU->CopyDstRC, SU->CopySrcRC);
970 // Copy from physical register.
971 assert(I->Reg && "Unknown physical register!");
972 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
973 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
974 assert(isNew && "Node emitted out of order - early");
975 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
976 SU->CopyDstRC, SU->CopySrcRC);
982 /// EmitSchedule - Emit the machine code in scheduled order.
983 void ScheduleDAG::EmitSchedule() {
984 // If this is the first basic block in the function, and if it has live ins
985 // that need to be copied into vregs, emit the copies into the top of the
986 // block before emitting the code for the block.
987 if (&MF->front() == BB) {
988 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
989 E = RegInfo.livein_end(); LI != E; ++LI)
991 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
992 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
998 // Finally, emit the code for all of the scheduled instructions.
999 DenseMap<SDOperand, unsigned> VRBaseMap;
1000 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1001 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1002 if (SUnit *SU = Sequence[i]) {
1003 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1004 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
1006 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
1008 EmitCrossRCCopy(SU, CopyVRBaseMap);
1010 // Null SUnit* is a noop.
1016 /// dump - dump the schedule.
1017 void ScheduleDAG::dumpSchedule() const {
1018 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1019 if (SUnit *SU = Sequence[i])
1022 cerr << "**** NOOP ****\n";
1027 /// Run - perform scheduling.
1029 MachineBasicBlock *ScheduleDAG::Run() {
1034 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1035 /// a group of nodes flagged together.
1036 void SUnit::dump(const SelectionDAG *G) const {
1037 cerr << "SU(" << NodeNum << "): ";
1041 cerr << "CROSS RC COPY ";
1043 if (FlaggedNodes.size() != 0) {
1044 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1046 FlaggedNodes[i]->dump(G);
1052 void SUnit::dumpAll(const SelectionDAG *G) const {
1055 cerr << " # preds left : " << NumPredsLeft << "\n";
1056 cerr << " # succs left : " << NumSuccsLeft << "\n";
1057 cerr << " Latency : " << Latency << "\n";
1058 cerr << " Depth : " << Depth << "\n";
1059 cerr << " Height : " << Height << "\n";
1061 if (Preds.size() != 0) {
1062 cerr << " Predecessors:\n";
1063 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1069 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1075 if (Succs.size() != 0) {
1076 cerr << " Successors:\n";
1077 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1083 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";