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 void ScheduleDAG::CalculateDepths() {
236 std::vector<std::pair<SUnit*, unsigned> > WorkList;
237 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
238 if (SUnits[i].Preds.empty())
239 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
241 while (!WorkList.empty()) {
242 SUnit *SU = WorkList.back().first;
243 unsigned Depth = WorkList.back().second;
245 if (SU->Depth == 0 || Depth > SU->Depth) {
247 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
249 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
254 void ScheduleDAG::CalculateHeights() {
255 std::vector<std::pair<SUnit*, unsigned> > WorkList;
256 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
257 WorkList.push_back(std::make_pair(Root, 0U));
259 while (!WorkList.empty()) {
260 SUnit *SU = WorkList.back().first;
261 unsigned Height = WorkList.back().second;
263 if (SU->Height == 0 || Height > SU->Height) {
265 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
267 WorkList.push_back(std::make_pair(I->Dep, Height+1));
272 /// CountResults - The results of target nodes have register or immediate
273 /// operands first, then an optional chain, and optional flag operands (which do
274 /// not go into the resulting MachineInstr).
275 unsigned ScheduleDAG::CountResults(SDNode *Node) {
276 unsigned N = Node->getNumValues();
277 while (N && Node->getValueType(N - 1) == MVT::Flag)
279 if (N && Node->getValueType(N - 1) == MVT::Other)
280 --N; // Skip over chain result.
284 /// CountOperands - The inputs to target nodes have any actual inputs first,
285 /// followed by special operands that describe memory references, then an
286 /// optional chain operand, then flag operands. Compute the number of
287 /// actual operands that will go into the resulting MachineInstr.
288 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
289 unsigned N = ComputeMemOperandsEnd(Node);
290 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
291 --N; // Ignore MemOperand nodes
295 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
297 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
298 unsigned N = Node->getNumOperands();
299 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
301 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
302 --N; // Ignore chain if it exists.
306 static const TargetRegisterClass *getInstrOperandRegClass(
307 const TargetRegisterInfo *TRI,
308 const TargetInstrInfo *TII,
309 const TargetInstrDesc &II,
311 if (Op >= II.getNumOperands()) {
312 assert(II.isVariadic() && "Invalid operand # of instruction");
315 if (II.OpInfo[Op].isLookupPtrRegClass())
316 return TII->getPointerRegClass();
317 return TRI->getRegClass(II.OpInfo[Op].RegClass);
320 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
321 unsigned InstanceNo, unsigned SrcReg,
322 DenseMap<SDOperand, unsigned> &VRBaseMap) {
324 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
325 // Just use the input register directly!
327 VRBaseMap.erase(SDOperand(Node, ResNo));
328 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
329 assert(isNew && "Node emitted out of order - early");
333 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
334 // the CopyToReg'd destination register instead of creating a new vreg.
335 bool MatchReg = true;
336 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
340 if (Use->getOpcode() == ISD::CopyToReg &&
341 Use->getOperand(2).Val == Node &&
342 Use->getOperand(2).ResNo == ResNo) {
343 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
344 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
347 } else if (DestReg != SrcReg)
350 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
351 SDOperand Op = Use->getOperand(i);
352 if (Op.Val != Node || Op.ResNo != ResNo)
354 MVT::ValueType VT = Node->getValueType(Op.ResNo);
355 if (VT != MVT::Other && VT != MVT::Flag)
364 const TargetRegisterClass *TRC = 0;
365 // Figure out the register class to create for the destreg.
367 TRC = RegInfo.getRegClass(VRBase);
369 TRC = TRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
371 // If all uses are reading from the src physical register and copying the
372 // register is either impossible or very expensive, then don't create a copy.
373 if (MatchReg && TRC->getCopyCost() < 0) {
376 // Create the reg, emit the copy.
377 VRBase = RegInfo.createVirtualRegister(TRC);
378 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
382 VRBaseMap.erase(SDOperand(Node, ResNo));
383 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
384 assert(isNew && "Node emitted out of order - early");
387 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
389 const TargetInstrDesc &II,
390 DenseMap<SDOperand, unsigned> &VRBaseMap) {
391 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
392 // If the specific node value is only used by a CopyToReg and the dest reg
393 // is a vreg, use the CopyToReg'd destination register instead of creating
396 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
399 if (Use->getOpcode() == ISD::CopyToReg &&
400 Use->getOperand(2).Val == Node &&
401 Use->getOperand(2).ResNo == i) {
402 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
403 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
405 MI->addOperand(MachineOperand::CreateReg(Reg, true));
411 // Create the result registers for this node and add the result regs to
412 // the machine instruction.
414 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
415 assert(RC && "Isn't a register operand!");
416 VRBase = RegInfo.createVirtualRegister(RC);
417 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
420 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
421 assert(isNew && "Node emitted out of order - early");
425 /// getVR - Return the virtual register corresponding to the specified result
426 /// of the specified node.
427 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
428 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
429 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
434 /// AddOperand - Add the specified operand to the specified machine instr. II
435 /// specifies the instruction information for the node, and IIOpNum is the
436 /// operand number (in the II) that we are adding. IIOpNum and II are used for
438 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
440 const TargetInstrDesc *II,
441 DenseMap<SDOperand, unsigned> &VRBaseMap) {
442 if (Op.isTargetOpcode()) {
443 // Note that this case is redundant with the final else block, but we
444 // include it because it is the most common and it makes the logic
446 assert(Op.getValueType() != MVT::Other &&
447 Op.getValueType() != MVT::Flag &&
448 "Chain and flag operands should occur at end of operand list!");
450 // Get/emit the operand.
451 unsigned VReg = getVR(Op, VRBaseMap);
452 const TargetInstrDesc &TID = MI->getDesc();
453 bool isOptDef = (IIOpNum < TID.getNumOperands())
454 ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
455 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
457 // Verify that it is right.
458 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
460 const TargetRegisterClass *RC =
461 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
462 assert(RC && "Don't have operand info for this instruction!");
463 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
465 cerr << "Register class of operand and regclass of use don't agree!\n";
467 cerr << "Operand = " << IIOpNum << "\n";
468 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
469 cerr << "MI = "; MI->print(cerr);
470 cerr << "VReg = " << VReg << "\n";
471 cerr << "VReg RegClass size = " << VRC->getSize()
472 << ", align = " << VRC->getAlignment() << "\n";
473 cerr << "Expected RegClass size = " << RC->getSize()
474 << ", align = " << RC->getAlignment() << "\n";
476 cerr << "Fatal error, aborting.\n";
480 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
481 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
482 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
483 const Type *FType = MVT::getTypeForValueType(Op.getValueType());
484 ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
485 MI->addOperand(MachineOperand::CreateFPImm(CFP));
486 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
487 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
488 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
489 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
490 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
491 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
492 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
493 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
494 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
495 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
496 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
497 int Offset = CP->getOffset();
498 unsigned Align = CP->getAlignment();
499 const Type *Type = CP->getType();
500 // MachineConstantPool wants an explicit alignment.
502 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
504 // Alignment of vector types. FIXME!
505 Align = TM.getTargetData()->getABITypeSize(Type);
506 Align = Log2_64(Align);
511 if (CP->isMachineConstantPoolEntry())
512 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
514 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
515 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
516 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
517 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
519 assert(Op.getValueType() != MVT::Other &&
520 Op.getValueType() != MVT::Flag &&
521 "Chain and flag operands should occur at end of operand list!");
522 unsigned VReg = getVR(Op, VRBaseMap);
523 MI->addOperand(MachineOperand::CreateReg(VReg, false));
525 // Verify that it is right.
526 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
528 const TargetRegisterClass *RC =
529 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
530 assert(RC && "Don't have operand info for this instruction!");
531 assert(RegInfo.getRegClass(VReg) == RC &&
532 "Register class of operand and regclass of use don't agree!");
538 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
539 MI->addMemOperand(MO);
542 // Returns the Register Class of a subregister
543 static const TargetRegisterClass *getSubRegisterRegClass(
544 const TargetRegisterClass *TRC,
546 // Pick the register class of the subregister
547 TargetRegisterInfo::regclass_iterator I =
548 TRC->subregclasses_begin() + SubIdx-1;
549 assert(I < TRC->subregclasses_end() &&
550 "Invalid subregister index for register class");
554 static const TargetRegisterClass *getSuperregRegisterClass(
555 const TargetRegisterClass *TRC,
558 // Pick the register class of the superegister for this type
559 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
560 E = TRC->superregclasses_end(); I != E; ++I)
561 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
563 assert(false && "Couldn't find the register class");
567 /// EmitSubregNode - Generate machine code for subreg nodes.
569 void ScheduleDAG::EmitSubregNode(SDNode *Node,
570 DenseMap<SDOperand, unsigned> &VRBaseMap) {
572 unsigned Opc = Node->getTargetOpcode();
573 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
574 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
575 // the CopyToReg'd destination register instead of creating a new vreg.
576 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
579 if (Use->getOpcode() == ISD::CopyToReg &&
580 Use->getOperand(2).Val == Node) {
581 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
582 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
589 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
591 // TODO: If the node is a use of a CopyFromReg from a physical register
592 // fold the extract into the copy now
594 // Create the extract_subreg machine instruction.
596 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
598 // Figure out the register class to create for the destreg.
599 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
600 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
601 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
604 // Grab the destination register
605 const TargetRegisterClass *DRC = 0;
606 DRC = RegInfo.getRegClass(VRBase);
607 assert(SRC && DRC && SRC == DRC &&
608 "Source subregister and destination must have the same class");
611 assert(SRC && "Couldn't find source register class");
612 VRBase = RegInfo.createVirtualRegister(SRC);
615 // Add def, source, and subreg index
616 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
617 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
618 MI->addOperand(MachineOperand::CreateImm(SubIdx));
620 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
621 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
622 "Malformed insert_subreg node");
623 bool isUndefInput = (Node->getNumOperands() == 2);
628 SubReg = getVR(Node->getOperand(0), VRBaseMap);
629 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
631 SubReg = getVR(Node->getOperand(1), VRBaseMap);
632 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
635 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
636 // to allow coalescing in the allocator
638 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
639 // the CopyToReg'd destination register instead of creating a new vreg.
640 // If the CopyToReg'd destination register is physical, then fold the
641 // insert into the copy
642 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
645 if (Use->getOpcode() == ISD::CopyToReg &&
646 Use->getOperand(2).Val == Node) {
647 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
648 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
655 // Create the insert_subreg machine instruction.
657 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
659 // Figure out the register class to create for the destreg.
660 const TargetRegisterClass *TRC = 0;
662 TRC = RegInfo.getRegClass(VRBase);
664 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
665 Node->getValueType(0));
666 assert(TRC && "Couldn't determine register class for insert_subreg");
667 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
670 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
671 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
673 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
674 MI->addOperand(MachineOperand::CreateImm(SubIdx));
676 assert(0 && "Node is not a subreg insert or extract");
678 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
679 assert(isNew && "Node emitted out of order - early");
682 /// EmitNode - Generate machine code for an node and needed dependencies.
684 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
685 DenseMap<SDOperand, unsigned> &VRBaseMap) {
686 // If machine instruction
687 if (Node->isTargetOpcode()) {
688 unsigned Opc = Node->getTargetOpcode();
690 // Handle subreg insert/extract specially
691 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
692 Opc == TargetInstrInfo::INSERT_SUBREG) {
693 EmitSubregNode(Node, VRBaseMap);
697 const TargetInstrDesc &II = TII->get(Opc);
699 unsigned NumResults = CountResults(Node);
700 unsigned NodeOperands = CountOperands(Node);
701 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
702 unsigned NumMIOperands = NodeOperands + NumResults;
703 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
704 II.getImplicitDefs() != 0;
706 assert((II.getNumOperands() == NumMIOperands ||
707 HasPhysRegOuts || II.isVariadic()) &&
708 "#operands for dag node doesn't match .td file!");
711 // Create the new machine instruction.
712 MachineInstr *MI = new MachineInstr(II);
714 // Add result register values for things that are defined by this
717 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
719 // Emit all of the actual operands of this instruction, adding them to the
720 // instruction as appropriate.
721 for (unsigned i = 0; i != NodeOperands; ++i)
722 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
724 // Emit all of the memory operands of this instruction
725 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
726 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
728 // Commute node if it has been determined to be profitable.
729 if (CommuteSet.count(Node)) {
730 MachineInstr *NewMI = TII->commuteInstruction(MI);
732 DOUT << "Sched: COMMUTING FAILED!\n";
734 DOUT << "Sched: COMMUTED TO: " << *NewMI;
743 if (II.usesCustomDAGSchedInsertionHook())
744 // Insert this instruction into the basic block using a target
745 // specific inserter which may returns a new basic block.
746 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
750 // Additional results must be an physical register def.
751 if (HasPhysRegOuts) {
752 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
753 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
754 if (Node->hasAnyUseOfValue(i))
755 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
759 switch (Node->getOpcode()) {
764 assert(0 && "This target-independent node should have been selected!");
765 case ISD::EntryToken: // fall thru
766 case ISD::TokenFactor:
771 case ISD::CopyToReg: {
773 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
776 InReg = getVR(Node->getOperand(2), VRBaseMap);
777 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
778 if (InReg != DestReg) {// Coalesced away the copy?
779 const TargetRegisterClass *TRC = 0;
780 // Get the target register class
781 if (TargetRegisterInfo::isVirtualRegister(InReg))
782 TRC = RegInfo.getRegClass(InReg);
785 TRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
787 TII->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
791 case ISD::CopyFromReg: {
792 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
793 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
796 case ISD::INLINEASM: {
797 unsigned NumOps = Node->getNumOperands();
798 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
799 --NumOps; // Ignore the flag operand.
801 // Create the inline asm machine instruction.
803 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
805 // Add the asm string as an external symbol operand.
807 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
808 MI->addOperand(MachineOperand::CreateES(AsmStr));
810 // Add all of the operand registers to the instruction.
811 for (unsigned i = 2; i != NumOps;) {
812 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
813 unsigned NumVals = Flags >> 3;
815 MI->addOperand(MachineOperand::CreateImm(Flags));
816 ++i; // Skip the ID value.
819 default: assert(0 && "Bad flags!");
820 case 1: // Use of register.
821 for (; NumVals; --NumVals, ++i) {
822 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
823 MI->addOperand(MachineOperand::CreateReg(Reg, false));
826 case 2: // Def of register.
827 for (; NumVals; --NumVals, ++i) {
828 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
829 MI->addOperand(MachineOperand::CreateReg(Reg, true));
832 case 3: { // Immediate.
833 for (; NumVals; --NumVals, ++i) {
834 if (ConstantSDNode *CS =
835 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
836 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
837 } else if (GlobalAddressSDNode *GA =
838 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
839 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
842 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
843 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
848 case 4: // Addressing mode.
849 // The addressing mode has been selected, just add all of the
850 // operands to the machine instruction.
851 for (; NumVals; --NumVals, ++i)
852 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
862 void ScheduleDAG::EmitNoop() {
863 TII->insertNoop(*BB, BB->end());
866 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
867 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
869 if (I->isCtrl) continue; // ignore chain preds
871 // Copy to physical register.
872 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
873 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
874 // Find the destination physical register.
876 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
877 EE = SU->Succs.end(); II != EE; ++II) {
883 assert(I->Reg && "Unknown physical register!");
884 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
885 SU->CopyDstRC, SU->CopySrcRC);
887 // Copy from physical register.
888 assert(I->Reg && "Unknown physical register!");
889 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
890 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
891 assert(isNew && "Node emitted out of order - early");
892 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
893 SU->CopyDstRC, SU->CopySrcRC);
899 /// EmitSchedule - Emit the machine code in scheduled order.
900 void ScheduleDAG::EmitSchedule() {
901 // If this is the first basic block in the function, and if it has live ins
902 // that need to be copied into vregs, emit the copies into the top of the
903 // block before emitting the code for the block.
904 if (&MF->front() == BB) {
905 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
906 E = RegInfo.livein_end(); LI != E; ++LI)
908 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
909 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
915 // Finally, emit the code for all of the scheduled instructions.
916 DenseMap<SDOperand, unsigned> VRBaseMap;
917 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
918 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
919 if (SUnit *SU = Sequence[i]) {
920 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
921 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
923 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
925 EmitCrossRCCopy(SU, CopyVRBaseMap);
927 // Null SUnit* is a noop.
933 /// dump - dump the schedule.
934 void ScheduleDAG::dumpSchedule() const {
935 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
936 if (SUnit *SU = Sequence[i])
939 cerr << "**** NOOP ****\n";
944 /// Run - perform scheduling.
946 MachineBasicBlock *ScheduleDAG::Run() {
951 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
952 /// a group of nodes flagged together.
953 void SUnit::dump(const SelectionDAG *G) const {
954 cerr << "SU(" << NodeNum << "): ";
958 cerr << "CROSS RC COPY ";
960 if (FlaggedNodes.size() != 0) {
961 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
963 FlaggedNodes[i]->dump(G);
969 void SUnit::dumpAll(const SelectionDAG *G) const {
972 cerr << " # preds left : " << NumPredsLeft << "\n";
973 cerr << " # succs left : " << NumSuccsLeft << "\n";
974 cerr << " Latency : " << Latency << "\n";
975 cerr << " Depth : " << Depth << "\n";
976 cerr << " Height : " << Height << "\n";
978 if (Preds.size() != 0) {
979 cerr << " Predecessors:\n";
980 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
986 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
992 if (Succs.size() != 0) {
993 cerr << " Successors:\n";
994 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1000 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";