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 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
73 SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
74 SU->InstanceNo = SUnitMap[Old->Node].size();
75 SU->Latency = Old->Latency;
76 SU->isTwoAddress = Old->isTwoAddress;
77 SU->isCommutable = Old->isCommutable;
78 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
79 SUnitMap[Old->Node].push_back(SU);
84 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
85 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
86 /// together nodes with a single SUnit.
87 void ScheduleDAG::BuildSchedUnits() {
88 // Reserve entries in the vector for each of the SUnits we are creating. This
89 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
91 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
93 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
94 E = DAG.allnodes_end(); NI != E; ++NI) {
95 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
98 // If this node has already been processed, stop now.
99 if (SUnitMap[NI].size()) continue;
101 SUnit *NodeSUnit = NewSUnit(NI);
103 // See if anything is flagged to this node, if so, add them to flagged
104 // nodes. Nodes can have at most one flag input and one flag output. Flags
105 // are required the be the last operand and result of a node.
107 // Scan up, adding flagged preds to FlaggedNodes.
109 if (N->getNumOperands() &&
110 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
112 N = N->getOperand(N->getNumOperands()-1).Val;
113 NodeSUnit->FlaggedNodes.push_back(N);
114 SUnitMap[N].push_back(NodeSUnit);
115 } while (N->getNumOperands() &&
116 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
117 std::reverse(NodeSUnit->FlaggedNodes.begin(),
118 NodeSUnit->FlaggedNodes.end());
121 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
122 // have a user of the flag operand.
124 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
125 SDOperand FlagVal(N, N->getNumValues()-1);
127 // There are either zero or one users of the Flag result.
128 bool HasFlagUse = false;
129 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
131 if (FlagVal.isOperandOf(*UI)) {
133 NodeSUnit->FlaggedNodes.push_back(N);
134 SUnitMap[N].push_back(NodeSUnit);
138 if (!HasFlagUse) break;
141 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
144 SUnitMap[N].push_back(NodeSUnit);
146 ComputeLatency(NodeSUnit);
149 // Pass 2: add the preds, succs, etc.
150 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
151 SUnit *SU = &SUnits[su];
152 SDNode *MainNode = SU->Node;
154 if (MainNode->isTargetOpcode()) {
155 unsigned Opc = MainNode->getTargetOpcode();
156 const TargetInstrDesc &TID = TII->get(Opc);
157 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
158 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
159 SU->isTwoAddress = true;
163 if (TID.isCommutable())
164 SU->isCommutable = true;
167 // Find all predecessors and successors of the group.
168 // Temporarily add N to make code simpler.
169 SU->FlaggedNodes.push_back(MainNode);
171 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
172 SDNode *N = SU->FlaggedNodes[n];
173 if (N->isTargetOpcode() &&
174 TII->get(N->getTargetOpcode()).getImplicitDefs() &&
175 CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
176 SU->hasPhysRegDefs = true;
178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
179 SDNode *OpN = N->getOperand(i).Val;
180 if (isPassiveNode(OpN)) continue; // Not scheduled.
181 SUnit *OpSU = SUnitMap[OpN].front();
182 assert(OpSU && "Node has no SUnit!");
183 if (OpSU == SU) continue; // In the same group.
185 MVT::ValueType OpVT = N->getOperand(i).getValueType();
186 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
187 bool isChain = OpVT == MVT::Other;
189 unsigned PhysReg = 0;
191 // Determine if this is a physical register dependency.
192 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
193 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
197 // Remove MainNode from FlaggedNodes again.
198 SU->FlaggedNodes.pop_back();
204 void ScheduleDAG::ComputeLatency(SUnit *SU) {
205 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
207 // Compute the latency for the node. We use the sum of the latencies for
208 // all nodes flagged together into this SUnit.
209 if (InstrItins.isEmpty()) {
210 // No latency information.
214 if (SU->Node->isTargetOpcode()) {
215 unsigned SchedClass =
216 TII->get(SU->Node->getTargetOpcode()).getSchedClass();
217 InstrStage *S = InstrItins.begin(SchedClass);
218 InstrStage *E = InstrItins.end(SchedClass);
220 SU->Latency += S->Cycles;
222 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
223 SDNode *FNode = SU->FlaggedNodes[i];
224 if (FNode->isTargetOpcode()) {
225 unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
226 InstrStage *S = InstrItins.begin(SchedClass);
227 InstrStage *E = InstrItins.end(SchedClass);
229 SU->Latency += S->Cycles;
235 /// CalculateDepths - compute depths using algorithms for the longest
237 void ScheduleDAG::CalculateDepths() {
238 unsigned DAGSize = SUnits.size();
239 std::vector<unsigned> InDegree(DAGSize);
240 std::vector<SUnit*> WorkList;
241 WorkList.reserve(DAGSize);
243 // Initialize the data structures
244 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
245 SUnit *SU = &SUnits[i];
246 int NodeNum = SU->NodeNum;
247 unsigned Degree = SU->Preds.size();
248 InDegree[NodeNum] = Degree;
251 // Is it a node without dependencies?
253 assert(SU->Preds.empty() && "SUnit should have no predecessors");
254 // Collect leaf nodes
255 WorkList.push_back(SU);
259 // Process nodes in the topological order
260 while (!WorkList.empty()) {
261 SUnit *SU = WorkList.back();
263 unsigned &SUDepth = SU->Depth;
265 // Use dynamic programming:
266 // When current node is being processed, all of its dependencies
267 // are already processed.
268 // So, just iterate over all predecessors and take the longest path
269 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
271 unsigned PredDepth = I->Dep->Depth;
272 if (PredDepth+1 > SUDepth) {
273 SUDepth = PredDepth + 1;
277 // Update InDegrees of all nodes depending on current SUnit
278 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
281 if (!--InDegree[SU->NodeNum])
282 // If all dependencies of the node are processed already,
283 // then the longest path for the node can be computed now
284 WorkList.push_back(SU);
289 /// CalculateHeights - compute heights using algorithms for the longest
291 void ScheduleDAG::CalculateHeights() {
292 unsigned DAGSize = SUnits.size();
293 std::vector<unsigned> InDegree(DAGSize);
294 std::vector<SUnit*> WorkList;
295 WorkList.reserve(DAGSize);
297 // Initialize the data structures
298 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
299 SUnit *SU = &SUnits[i];
300 int NodeNum = SU->NodeNum;
301 unsigned Degree = SU->Succs.size();
302 InDegree[NodeNum] = Degree;
305 // Is it a node without dependencies?
307 assert(SU->Succs.empty() && "Something wrong");
308 assert(WorkList.empty() && "Should be empty");
309 // Collect leaf nodes
310 WorkList.push_back(SU);
314 // Process nodes in the topological order
315 while (!WorkList.empty()) {
316 SUnit *SU = WorkList.back();
318 unsigned &SUHeight = SU->Height;
320 // Use dynamic programming:
321 // When current node is being processed, all of its dependencies
322 // are already processed.
323 // So, just iterate over all successors and take the longest path
324 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
326 unsigned SuccHeight = I->Dep->Height;
327 if (SuccHeight+1 > SUHeight) {
328 SUHeight = SuccHeight + 1;
332 // Update InDegrees of all nodes depending on current SUnit
333 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
336 if (!--InDegree[SU->NodeNum])
337 // If all dependencies of the node are processed already,
338 // then the longest path for the node can be computed now
339 WorkList.push_back(SU);
344 /// CountResults - The results of target nodes have register or immediate
345 /// operands first, then an optional chain, and optional flag operands (which do
346 /// not go into the resulting MachineInstr).
347 unsigned ScheduleDAG::CountResults(SDNode *Node) {
348 unsigned N = Node->getNumValues();
349 while (N && Node->getValueType(N - 1) == MVT::Flag)
351 if (N && Node->getValueType(N - 1) == MVT::Other)
352 --N; // Skip over chain result.
356 /// CountOperands - The inputs to target nodes have any actual inputs first,
357 /// followed by special operands that describe memory references, then an
358 /// optional chain operand, then flag operands. Compute the number of
359 /// actual operands that will go into the resulting MachineInstr.
360 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
361 unsigned N = ComputeMemOperandsEnd(Node);
362 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
363 --N; // Ignore MemOperand nodes
367 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
369 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
370 unsigned N = Node->getNumOperands();
371 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
373 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
374 --N; // Ignore chain if it exists.
378 static const TargetRegisterClass *getInstrOperandRegClass(
379 const TargetRegisterInfo *TRI,
380 const TargetInstrInfo *TII,
381 const TargetInstrDesc &II,
383 if (Op >= II.getNumOperands()) {
384 assert(II.isVariadic() && "Invalid operand # of instruction");
387 if (II.OpInfo[Op].isLookupPtrRegClass())
388 return TII->getPointerRegClass();
389 return TRI->getRegClass(II.OpInfo[Op].RegClass);
392 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
393 unsigned InstanceNo, unsigned SrcReg,
394 DenseMap<SDOperand, unsigned> &VRBaseMap) {
396 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
397 // Just use the input register directly!
399 VRBaseMap.erase(SDOperand(Node, ResNo));
400 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
401 assert(isNew && "Node emitted out of order - early");
405 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
406 // the CopyToReg'd destination register instead of creating a new vreg.
407 bool MatchReg = true;
408 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
412 if (Use->getOpcode() == ISD::CopyToReg &&
413 Use->getOperand(2).Val == Node &&
414 Use->getOperand(2).ResNo == ResNo) {
415 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
416 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
419 } else if (DestReg != SrcReg)
422 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
423 SDOperand Op = Use->getOperand(i);
424 if (Op.Val != Node || Op.ResNo != ResNo)
426 MVT::ValueType VT = Node->getValueType(Op.ResNo);
427 if (VT != MVT::Other && VT != MVT::Flag)
436 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
437 SrcRC = TRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
439 // Figure out the register class to create for the destreg.
441 DstRC = RegInfo.getRegClass(VRBase);
443 DstRC = DAG.getTargetLoweringInfo()
444 .getRegClassFor(Node->getValueType(ResNo));
447 // If all uses are reading from the src physical register and copying the
448 // register is either impossible or very expensive, then don't create a copy.
449 if (MatchReg && SrcRC->getCopyCost() < 0) {
452 // Create the reg, emit the copy.
453 VRBase = RegInfo.createVirtualRegister(DstRC);
454 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
458 VRBaseMap.erase(SDOperand(Node, ResNo));
459 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
460 assert(isNew && "Node emitted out of order - early");
463 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
465 const TargetInstrDesc &II,
466 DenseMap<SDOperand, unsigned> &VRBaseMap) {
467 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
468 // If the specific node value is only used by a CopyToReg and the dest reg
469 // is a vreg, use the CopyToReg'd destination register instead of creating
472 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
475 if (Use->getOpcode() == ISD::CopyToReg &&
476 Use->getOperand(2).Val == Node &&
477 Use->getOperand(2).ResNo == i) {
478 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
479 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
481 MI->addOperand(MachineOperand::CreateReg(Reg, true));
487 // Create the result registers for this node and add the result regs to
488 // the machine instruction.
490 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
491 assert(RC && "Isn't a register operand!");
492 VRBase = RegInfo.createVirtualRegister(RC);
493 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
496 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
497 assert(isNew && "Node emitted out of order - early");
501 /// getVR - Return the virtual register corresponding to the specified result
502 /// of the specified node.
503 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
504 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
505 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
510 /// AddOperand - Add the specified operand to the specified machine instr. II
511 /// specifies the instruction information for the node, and IIOpNum is the
512 /// operand number (in the II) that we are adding. IIOpNum and II are used for
514 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
516 const TargetInstrDesc *II,
517 DenseMap<SDOperand, unsigned> &VRBaseMap) {
518 if (Op.isTargetOpcode()) {
519 // Note that this case is redundant with the final else block, but we
520 // include it because it is the most common and it makes the logic
522 assert(Op.getValueType() != MVT::Other &&
523 Op.getValueType() != MVT::Flag &&
524 "Chain and flag operands should occur at end of operand list!");
526 // Get/emit the operand.
527 unsigned VReg = getVR(Op, VRBaseMap);
528 const TargetInstrDesc &TID = MI->getDesc();
529 bool isOptDef = (IIOpNum < TID.getNumOperands())
530 ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
531 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
533 // Verify that it is right.
534 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
536 const TargetRegisterClass *RC =
537 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
538 assert(RC && "Don't have operand info for this instruction!");
539 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
541 cerr << "Register class of operand and regclass of use don't agree!\n";
543 cerr << "Operand = " << IIOpNum << "\n";
544 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
545 cerr << "MI = "; MI->print(cerr);
546 cerr << "VReg = " << VReg << "\n";
547 cerr << "VReg RegClass size = " << VRC->getSize()
548 << ", align = " << VRC->getAlignment() << "\n";
549 cerr << "Expected RegClass size = " << RC->getSize()
550 << ", align = " << RC->getAlignment() << "\n";
552 cerr << "Fatal error, aborting.\n";
556 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
557 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
558 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
559 const Type *FType = MVT::getTypeForValueType(Op.getValueType());
560 ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
561 MI->addOperand(MachineOperand::CreateFPImm(CFP));
562 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
563 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
564 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
565 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
566 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
567 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
568 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
569 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
570 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
571 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
572 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
573 int Offset = CP->getOffset();
574 unsigned Align = CP->getAlignment();
575 const Type *Type = CP->getType();
576 // MachineConstantPool wants an explicit alignment.
578 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
580 // Alignment of vector types. FIXME!
581 Align = TM.getTargetData()->getABITypeSize(Type);
582 Align = Log2_64(Align);
587 if (CP->isMachineConstantPoolEntry())
588 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
590 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
591 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
592 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
593 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
595 assert(Op.getValueType() != MVT::Other &&
596 Op.getValueType() != MVT::Flag &&
597 "Chain and flag operands should occur at end of operand list!");
598 unsigned VReg = getVR(Op, VRBaseMap);
599 MI->addOperand(MachineOperand::CreateReg(VReg, false));
601 // Verify that it is right. Note that the reg class of the physreg and the
602 // vreg don't necessarily need to match, but the target copy insertion has
603 // to be able to handle it. This handles things like copies from ST(0) to
604 // an FP vreg on x86.
605 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
607 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
608 "Don't have operand info for this instruction!");
614 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
615 MI->addMemOperand(MO);
618 // Returns the Register Class of a subregister
619 static const TargetRegisterClass *getSubRegisterRegClass(
620 const TargetRegisterClass *TRC,
622 // Pick the register class of the subregister
623 TargetRegisterInfo::regclass_iterator I =
624 TRC->subregclasses_begin() + SubIdx-1;
625 assert(I < TRC->subregclasses_end() &&
626 "Invalid subregister index for register class");
630 static const TargetRegisterClass *getSuperregRegisterClass(
631 const TargetRegisterClass *TRC,
634 // Pick the register class of the superegister for this type
635 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
636 E = TRC->superregclasses_end(); I != E; ++I)
637 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
639 assert(false && "Couldn't find the register class");
643 /// EmitSubregNode - Generate machine code for subreg nodes.
645 void ScheduleDAG::EmitSubregNode(SDNode *Node,
646 DenseMap<SDOperand, unsigned> &VRBaseMap) {
648 unsigned Opc = Node->getTargetOpcode();
649 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
650 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
651 // the CopyToReg'd destination register instead of creating a new vreg.
652 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
655 if (Use->getOpcode() == ISD::CopyToReg &&
656 Use->getOperand(2).Val == Node) {
657 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
658 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
665 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
667 // TODO: If the node is a use of a CopyFromReg from a physical register
668 // fold the extract into the copy now
670 // Create the extract_subreg machine instruction.
672 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
674 // Figure out the register class to create for the destreg.
675 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
676 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
677 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
680 // Grab the destination register
681 const TargetRegisterClass *DRC = RegInfo.getRegClass(VRBase);
682 assert(SRC && DRC && SRC == DRC &&
683 "Source subregister and destination must have the same class");
686 assert(SRC && "Couldn't find source register class");
687 VRBase = RegInfo.createVirtualRegister(SRC);
690 // Add def, source, and subreg index
691 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
692 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
693 MI->addOperand(MachineOperand::CreateImm(SubIdx));
695 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
696 assert((Node->getNumOperands() == 3) &&
697 "Malformed insert_subreg node");
698 SDOperand N0 = Node->getOperand(0);
699 SDOperand N1 = Node->getOperand(1);
700 SDOperand N2 = Node->getOperand(2);
701 unsigned SubReg = getVR(N1, VRBaseMap);
702 unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
704 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
705 // to allow coalescing in the allocator
707 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
708 // the CopyToReg'd destination register instead of creating a new vreg.
709 // If the CopyToReg'd destination register is physical, then fold the
710 // insert into the copy
711 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
714 if (Use->getOpcode() == ISD::CopyToReg &&
715 Use->getOperand(2).Val == Node) {
716 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
717 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
724 // Create the insert_subreg machine instruction.
726 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
728 // Figure out the register class to create for the destreg.
729 const TargetRegisterClass *TRC = 0;
731 TRC = RegInfo.getRegClass(VRBase);
733 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
734 Node->getValueType(0));
735 assert(TRC && "Couldn't determine register class for insert_subreg");
736 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
739 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
741 // If N0 is a constant then it indicates the insert is being done
742 // into a target specific constant value, not a register.
743 if (const ConstantSDNode *SD = dyn_cast<ConstantSDNode>(N0))
744 MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
746 AddOperand(MI, N0, 0, 0, VRBaseMap);
747 // Add the subregster being inserted
748 AddOperand(MI, N1, 0, 0, VRBaseMap);
749 MI->addOperand(MachineOperand::CreateImm(SubIdx));
751 assert(0 && "Node is not a subreg insert or extract");
753 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
754 assert(isNew && "Node emitted out of order - early");
757 /// EmitNode - Generate machine code for an node and needed dependencies.
759 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
760 DenseMap<SDOperand, unsigned> &VRBaseMap) {
761 // If machine instruction
762 if (Node->isTargetOpcode()) {
763 unsigned Opc = Node->getTargetOpcode();
765 // Handle subreg insert/extract specially
766 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
767 Opc == TargetInstrInfo::INSERT_SUBREG) {
768 EmitSubregNode(Node, VRBaseMap);
772 const TargetInstrDesc &II = TII->get(Opc);
774 unsigned NumResults = CountResults(Node);
775 unsigned NodeOperands = CountOperands(Node);
776 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
777 unsigned NumMIOperands = NodeOperands + NumResults;
778 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
779 II.getImplicitDefs() != 0;
781 assert((II.getNumOperands() == NumMIOperands ||
782 HasPhysRegOuts || II.isVariadic()) &&
783 "#operands for dag node doesn't match .td file!");
786 // Create the new machine instruction.
787 MachineInstr *MI = new MachineInstr(II);
789 // Add result register values for things that are defined by this
792 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
794 // Emit all of the actual operands of this instruction, adding them to the
795 // instruction as appropriate.
796 for (unsigned i = 0; i != NodeOperands; ++i)
797 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
799 // Emit all of the memory operands of this instruction
800 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
801 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
803 // Commute node if it has been determined to be profitable.
804 if (CommuteSet.count(Node)) {
805 MachineInstr *NewMI = TII->commuteInstruction(MI);
807 DOUT << "Sched: COMMUTING FAILED!\n";
809 DOUT << "Sched: COMMUTED TO: " << *NewMI;
818 if (II.usesCustomDAGSchedInsertionHook())
819 // Insert this instruction into the basic block using a target
820 // specific inserter which may returns a new basic block.
821 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
825 // Additional results must be an physical register def.
826 if (HasPhysRegOuts) {
827 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
828 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
829 if (Node->hasAnyUseOfValue(i))
830 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
834 switch (Node->getOpcode()) {
839 assert(0 && "This target-independent node should have been selected!");
840 case ISD::EntryToken: // fall thru
841 case ISD::TokenFactor:
846 case ISD::CopyToReg: {
848 SDOperand SrcVal = Node->getOperand(2);
849 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
850 SrcReg = R->getReg();
852 SrcReg = getVR(SrcVal, VRBaseMap);
854 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
855 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
858 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
859 // Get the register classes of the src/dst.
860 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
861 SrcTRC = RegInfo.getRegClass(SrcReg);
863 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcVal.getValueType(),SrcReg);
865 if (TargetRegisterInfo::isVirtualRegister(DestReg))
866 DstTRC = RegInfo.getRegClass(DestReg);
868 DstTRC = TRI->getPhysicalRegisterRegClass(
869 Node->getOperand(1).getValueType(),
871 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
874 case ISD::CopyFromReg: {
875 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
876 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
879 case ISD::INLINEASM: {
880 unsigned NumOps = Node->getNumOperands();
881 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
882 --NumOps; // Ignore the flag operand.
884 // Create the inline asm machine instruction.
886 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
888 // Add the asm string as an external symbol operand.
890 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
891 MI->addOperand(MachineOperand::CreateES(AsmStr));
893 // Add all of the operand registers to the instruction.
894 for (unsigned i = 2; i != NumOps;) {
895 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
896 unsigned NumVals = Flags >> 3;
898 MI->addOperand(MachineOperand::CreateImm(Flags));
899 ++i; // Skip the ID value.
902 default: assert(0 && "Bad flags!");
903 case 1: // Use of register.
904 for (; NumVals; --NumVals, ++i) {
905 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
906 MI->addOperand(MachineOperand::CreateReg(Reg, false));
909 case 2: // Def of register.
910 for (; NumVals; --NumVals, ++i) {
911 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
912 MI->addOperand(MachineOperand::CreateReg(Reg, true));
915 case 3: { // Immediate.
916 for (; NumVals; --NumVals, ++i) {
917 if (ConstantSDNode *CS =
918 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
919 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
920 } else if (GlobalAddressSDNode *GA =
921 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
922 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
925 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
926 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
931 case 4: // Addressing mode.
932 // The addressing mode has been selected, just add all of the
933 // operands to the machine instruction.
934 for (; NumVals; --NumVals, ++i)
935 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
945 void ScheduleDAG::EmitNoop() {
946 TII->insertNoop(*BB, BB->end());
949 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
950 DenseMap<SUnit*, unsigned> &VRBaseMap) {
951 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
953 if (I->isCtrl) continue; // ignore chain preds
955 // Copy to physical register.
956 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
957 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
958 // Find the destination physical register.
960 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
961 EE = SU->Succs.end(); II != EE; ++II) {
967 assert(I->Reg && "Unknown physical register!");
968 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
969 SU->CopyDstRC, SU->CopySrcRC);
971 // Copy from physical register.
972 assert(I->Reg && "Unknown physical register!");
973 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
974 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
975 assert(isNew && "Node emitted out of order - early");
976 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
977 SU->CopyDstRC, SU->CopySrcRC);
983 /// EmitSchedule - Emit the machine code in scheduled order.
984 void ScheduleDAG::EmitSchedule() {
985 // If this is the first basic block in the function, and if it has live ins
986 // that need to be copied into vregs, emit the copies into the top of the
987 // block before emitting the code for the block.
988 if (&MF->front() == BB) {
989 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
990 E = RegInfo.livein_end(); LI != E; ++LI)
992 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
993 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
999 // Finally, emit the code for all of the scheduled instructions.
1000 DenseMap<SDOperand, unsigned> VRBaseMap;
1001 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1002 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1003 if (SUnit *SU = Sequence[i]) {
1004 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1005 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
1007 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
1009 EmitCrossRCCopy(SU, CopyVRBaseMap);
1011 // Null SUnit* is a noop.
1017 /// dump - dump the schedule.
1018 void ScheduleDAG::dumpSchedule() const {
1019 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1020 if (SUnit *SU = Sequence[i])
1023 cerr << "**** NOOP ****\n";
1028 /// Run - perform scheduling.
1030 MachineBasicBlock *ScheduleDAG::Run() {
1035 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1036 /// a group of nodes flagged together.
1037 void SUnit::dump(const SelectionDAG *G) const {
1038 cerr << "SU(" << NodeNum << "): ";
1042 cerr << "CROSS RC COPY ";
1044 if (FlaggedNodes.size() != 0) {
1045 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1047 FlaggedNodes[i]->dump(G);
1053 void SUnit::dumpAll(const SelectionDAG *G) const {
1056 cerr << " # preds left : " << NumPredsLeft << "\n";
1057 cerr << " # succs left : " << NumSuccsLeft << "\n";
1058 cerr << " Latency : " << Latency << "\n";
1059 cerr << " Depth : " << Depth << "\n";
1060 cerr << " Height : " << Height << "\n";
1062 if (Preds.size() != 0) {
1063 cerr << " Predecessors:\n";
1064 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1070 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1076 if (Succs.size() != 0) {
1077 cerr << " Successors:\n";
1078 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1084 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";