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/Type.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
30 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
31 const TargetMachine &tm)
32 : DAG(dag), BB(bb), TM(tm), RegInfo(BB->getParent()->getRegInfo()) {
33 TII = TM.getInstrInfo();
34 MF = &DAG.getMachineFunction();
35 MRI = TM.getRegisterInfo();
36 ConstPool = BB->getParent()->getConstantPool();
39 /// CheckForPhysRegDependency - Check if the dependency between def and use of
40 /// a specified operand is a physical register dependency. If so, returns the
41 /// register and the cost of copying the register.
42 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
43 const MRegisterInfo *MRI,
44 const TargetInstrInfo *TII,
45 unsigned &PhysReg, int &Cost) {
46 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
49 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
50 if (MRegisterInfo::isVirtualRegister(Reg))
53 unsigned ResNo = Use->getOperand(2).ResNo;
54 if (Def->isTargetOpcode()) {
55 const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
56 if (ResNo >= II.getNumDefs() &&
57 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
59 const TargetRegisterClass *RC =
60 MRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
61 Cost = RC->getCopyCost();
66 SUnit *ScheduleDAG::Clone(SUnit *Old) {
67 SUnit *SU = NewSUnit(Old->Node);
68 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
69 SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
70 SU->InstanceNo = SUnitMap[Old->Node].size();
71 SU->Latency = Old->Latency;
72 SU->isTwoAddress = Old->isTwoAddress;
73 SU->isCommutable = Old->isCommutable;
74 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
75 SUnitMap[Old->Node].push_back(SU);
80 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
81 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
82 /// together nodes with a single SUnit.
83 void ScheduleDAG::BuildSchedUnits() {
84 // Reserve entries in the vector for each of the SUnits we are creating. This
85 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
87 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
89 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
90 E = DAG.allnodes_end(); NI != E; ++NI) {
91 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
94 // If this node has already been processed, stop now.
95 if (SUnitMap[NI].size()) continue;
97 SUnit *NodeSUnit = NewSUnit(NI);
99 // See if anything is flagged to this node, if so, add them to flagged
100 // nodes. Nodes can have at most one flag input and one flag output. Flags
101 // are required the be the last operand and result of a node.
103 // Scan up, adding flagged preds to FlaggedNodes.
105 if (N->getNumOperands() &&
106 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
108 N = N->getOperand(N->getNumOperands()-1).Val;
109 NodeSUnit->FlaggedNodes.push_back(N);
110 SUnitMap[N].push_back(NodeSUnit);
111 } while (N->getNumOperands() &&
112 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
113 std::reverse(NodeSUnit->FlaggedNodes.begin(),
114 NodeSUnit->FlaggedNodes.end());
117 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
118 // have a user of the flag operand.
120 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
121 SDOperand FlagVal(N, N->getNumValues()-1);
123 // There are either zero or one users of the Flag result.
124 bool HasFlagUse = false;
125 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
127 if (FlagVal.isOperand(*UI)) {
129 NodeSUnit->FlaggedNodes.push_back(N);
130 SUnitMap[N].push_back(NodeSUnit);
134 if (!HasFlagUse) break;
137 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
140 SUnitMap[N].push_back(NodeSUnit);
142 ComputeLatency(NodeSUnit);
145 // Pass 2: add the preds, succs, etc.
146 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
147 SUnit *SU = &SUnits[su];
148 SDNode *MainNode = SU->Node;
150 if (MainNode->isTargetOpcode()) {
151 unsigned Opc = MainNode->getTargetOpcode();
152 const TargetInstrDesc &TID = TII->get(Opc);
153 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
154 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
155 SU->isTwoAddress = true;
159 if (TID.isCommutable())
160 SU->isCommutable = true;
163 // Find all predecessors and successors of the group.
164 // Temporarily add N to make code simpler.
165 SU->FlaggedNodes.push_back(MainNode);
167 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
168 SDNode *N = SU->FlaggedNodes[n];
169 if (N->isTargetOpcode() &&
170 TII->get(N->getTargetOpcode()).getImplicitDefs() &&
171 CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
172 SU->hasPhysRegDefs = true;
174 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
175 SDNode *OpN = N->getOperand(i).Val;
176 if (isPassiveNode(OpN)) continue; // Not scheduled.
177 SUnit *OpSU = SUnitMap[OpN].front();
178 assert(OpSU && "Node has no SUnit!");
179 if (OpSU == SU) continue; // In the same group.
181 MVT::ValueType OpVT = N->getOperand(i).getValueType();
182 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
183 bool isChain = OpVT == MVT::Other;
185 unsigned PhysReg = 0;
187 // Determine if this is a physical register dependency.
188 CheckForPhysRegDependency(OpN, N, i, MRI, TII, PhysReg, Cost);
189 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
193 // Remove MainNode from FlaggedNodes again.
194 SU->FlaggedNodes.pop_back();
200 void ScheduleDAG::ComputeLatency(SUnit *SU) {
201 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
203 // Compute the latency for the node. We use the sum of the latencies for
204 // all nodes flagged together into this SUnit.
205 if (InstrItins.isEmpty()) {
206 // No latency information.
210 if (SU->Node->isTargetOpcode()) {
211 unsigned SchedClass =
212 TII->get(SU->Node->getTargetOpcode()).getSchedClass();
213 InstrStage *S = InstrItins.begin(SchedClass);
214 InstrStage *E = InstrItins.end(SchedClass);
216 SU->Latency += S->Cycles;
218 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
219 SDNode *FNode = SU->FlaggedNodes[i];
220 if (FNode->isTargetOpcode()) {
221 unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
222 InstrStage *S = InstrItins.begin(SchedClass);
223 InstrStage *E = InstrItins.end(SchedClass);
225 SU->Latency += S->Cycles;
231 void ScheduleDAG::CalculateDepths() {
232 std::vector<std::pair<SUnit*, unsigned> > WorkList;
233 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
234 if (SUnits[i].Preds.empty())
235 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
237 while (!WorkList.empty()) {
238 SUnit *SU = WorkList.back().first;
239 unsigned Depth = WorkList.back().second;
241 if (SU->Depth == 0 || Depth > SU->Depth) {
243 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
245 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
250 void ScheduleDAG::CalculateHeights() {
251 std::vector<std::pair<SUnit*, unsigned> > WorkList;
252 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
253 WorkList.push_back(std::make_pair(Root, 0U));
255 while (!WorkList.empty()) {
256 SUnit *SU = WorkList.back().first;
257 unsigned Height = WorkList.back().second;
259 if (SU->Height == 0 || Height > SU->Height) {
261 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
263 WorkList.push_back(std::make_pair(I->Dep, Height+1));
268 /// CountResults - The results of target nodes have register or immediate
269 /// operands first, then an optional chain, and optional flag operands (which do
270 /// not go into the machine instrs.)
271 unsigned ScheduleDAG::CountResults(SDNode *Node) {
272 unsigned N = Node->getNumValues();
273 while (N && Node->getValueType(N - 1) == MVT::Flag)
275 if (N && Node->getValueType(N - 1) == MVT::Other)
276 --N; // Skip over chain result.
280 /// CountOperands - The inputs to target nodes have any actual inputs first,
281 /// followed by optional memory operands chain operand, then flag operands.
282 /// Compute the number of actual operands that will go into the machine istr.
283 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
284 unsigned N = Node->getNumOperands();
285 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
287 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
288 --N; // Ignore chain if it exists.
289 while (N && MemOperandSDNode::classof(Node->getOperand(N - 1).Val))
290 --N; // Ignore MemOperand nodes
294 /// CountMemOperands - Find the index of the last MemOperandSDNode operand
295 unsigned ScheduleDAG::CountMemOperands(SDNode *Node) {
296 unsigned N = Node->getNumOperands();
297 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
299 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
300 --N; // Ignore chain if it exists.
304 static const TargetRegisterClass *getInstrOperandRegClass(
305 const MRegisterInfo *MRI,
306 const TargetInstrInfo *TII,
307 const TargetInstrDesc &II,
309 if (Op >= II.getNumOperands()) {
310 assert(II.isVariadic() && "Invalid operand # of instruction");
313 if (II.OpInfo[Op].isLookupPtrRegClass())
314 return TII->getPointerRegClass();
315 return MRI->getRegClass(II.OpInfo[Op].RegClass);
318 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
319 unsigned InstanceNo, unsigned SrcReg,
320 DenseMap<SDOperand, unsigned> &VRBaseMap) {
322 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
323 // Just use the input register directly!
325 VRBaseMap.erase(SDOperand(Node, ResNo));
326 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
327 assert(isNew && "Node emitted out of order - early");
331 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
332 // the CopyToReg'd destination register instead of creating a new vreg.
333 bool MatchReg = true;
334 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
338 if (Use->getOpcode() == ISD::CopyToReg &&
339 Use->getOperand(2).Val == Node &&
340 Use->getOperand(2).ResNo == ResNo) {
341 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
342 if (MRegisterInfo::isVirtualRegister(DestReg)) {
345 } else if (DestReg != SrcReg)
348 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
349 SDOperand Op = Use->getOperand(i);
350 if (Op.Val != Node || Op.ResNo != ResNo)
352 MVT::ValueType VT = Node->getValueType(Op.ResNo);
353 if (VT != MVT::Other && VT != MVT::Flag)
362 const TargetRegisterClass *TRC = 0;
363 // Figure out the register class to create for the destreg.
365 TRC = RegInfo.getRegClass(VRBase);
367 TRC = MRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
369 // If all uses are reading from the src physical register and copying the
370 // register is either impossible or very expensive, then don't create a copy.
371 if (MatchReg && TRC->getCopyCost() < 0) {
374 // Create the reg, emit the copy.
375 VRBase = RegInfo.createVirtualRegister(TRC);
376 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
380 VRBaseMap.erase(SDOperand(Node, ResNo));
381 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
382 assert(isNew && "Node emitted out of order - early");
385 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
387 const TargetInstrDesc &II,
388 DenseMap<SDOperand, unsigned> &VRBaseMap) {
389 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
390 // If the specific node value is only used by a CopyToReg and the dest reg
391 // is a vreg, use the CopyToReg'd destination register instead of creating
394 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
397 if (Use->getOpcode() == ISD::CopyToReg &&
398 Use->getOperand(2).Val == Node &&
399 Use->getOperand(2).ResNo == i) {
400 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
401 if (MRegisterInfo::isVirtualRegister(Reg)) {
403 MI->addOperand(MachineOperand::CreateReg(Reg, true));
409 // Create the result registers for this node and add the result regs to
410 // the machine instruction.
412 const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, II, i);
413 assert(RC && "Isn't a register operand!");
414 VRBase = RegInfo.createVirtualRegister(RC);
415 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
418 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
419 assert(isNew && "Node emitted out of order - early");
423 /// getVR - Return the virtual register corresponding to the specified result
424 /// of the specified node.
425 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
426 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
427 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
432 /// AddOperand - Add the specified operand to the specified machine instr. II
433 /// specifies the instruction information for the node, and IIOpNum is the
434 /// operand number (in the II) that we are adding. IIOpNum and II are used for
436 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
438 const TargetInstrDesc *II,
439 DenseMap<SDOperand, unsigned> &VRBaseMap) {
440 if (Op.isTargetOpcode()) {
441 // Note that this case is redundant with the final else block, but we
442 // include it because it is the most common and it makes the logic
444 assert(Op.getValueType() != MVT::Other &&
445 Op.getValueType() != MVT::Flag &&
446 "Chain and flag operands should occur at end of operand list!");
448 // Get/emit the operand.
449 unsigned VReg = getVR(Op, VRBaseMap);
450 const TargetInstrDesc &TID = MI->getDesc();
451 bool isOptDef = (IIOpNum < TID.getNumOperands())
452 ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
453 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
455 // Verify that it is right.
456 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
458 const TargetRegisterClass *RC =
459 getInstrOperandRegClass(MRI, TII, *II, IIOpNum);
460 assert(RC && "Don't have operand info for this instruction!");
461 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
463 cerr << "Register class of operand and regclass of use don't agree!\n";
465 cerr << "Operand = " << IIOpNum << "\n";
466 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
467 cerr << "MI = "; MI->print(cerr);
468 cerr << "VReg = " << VReg << "\n";
469 cerr << "VReg RegClass size = " << VRC->getSize()
470 << ", align = " << VRC->getAlignment() << "\n";
471 cerr << "Expected RegClass size = " << RC->getSize()
472 << ", align = " << RC->getAlignment() << "\n";
474 cerr << "Fatal error, aborting.\n";
478 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
479 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
480 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
481 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
482 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
483 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
484 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
485 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
486 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
487 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
488 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
489 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
490 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
491 int Offset = CP->getOffset();
492 unsigned Align = CP->getAlignment();
493 const Type *Type = CP->getType();
494 // MachineConstantPool wants an explicit alignment.
496 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
498 // Alignment of vector types. FIXME!
499 Align = TM.getTargetData()->getABITypeSize(Type);
500 Align = Log2_64(Align);
505 if (CP->isMachineConstantPoolEntry())
506 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
508 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
509 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
510 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
511 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
513 assert(Op.getValueType() != MVT::Other &&
514 Op.getValueType() != MVT::Flag &&
515 "Chain and flag operands should occur at end of operand list!");
516 unsigned VReg = getVR(Op, VRBaseMap);
517 MI->addOperand(MachineOperand::CreateReg(VReg, false));
519 // Verify that it is right.
520 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
522 const TargetRegisterClass *RC =
523 getInstrOperandRegClass(MRI, TII, *II, IIOpNum);
524 assert(RC && "Don't have operand info for this instruction!");
525 assert(RegInfo.getRegClass(VReg) == RC &&
526 "Register class of operand and regclass of use don't agree!");
532 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
533 MI->addMemOperand(MO);
536 // Returns the Register Class of a subregister
537 static const TargetRegisterClass *getSubRegisterRegClass(
538 const TargetRegisterClass *TRC,
540 // Pick the register class of the subregister
541 MRegisterInfo::regclass_iterator I = TRC->subregclasses_begin() + SubIdx-1;
542 assert(I < TRC->subregclasses_end() &&
543 "Invalid subregister index for register class");
547 static const TargetRegisterClass *getSuperregRegisterClass(
548 const TargetRegisterClass *TRC,
551 // Pick the register class of the superegister for this type
552 for (MRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
553 E = TRC->superregclasses_end(); I != E; ++I)
554 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
556 assert(false && "Couldn't find the register class");
560 /// EmitSubregNode - Generate machine code for subreg nodes.
562 void ScheduleDAG::EmitSubregNode(SDNode *Node,
563 DenseMap<SDOperand, unsigned> &VRBaseMap) {
565 unsigned Opc = Node->getTargetOpcode();
566 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
567 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
568 // the CopyToReg'd destination register instead of creating a new vreg.
569 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
572 if (Use->getOpcode() == ISD::CopyToReg &&
573 Use->getOperand(2).Val == Node) {
574 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
575 if (MRegisterInfo::isVirtualRegister(DestReg)) {
582 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
584 // TODO: If the node is a use of a CopyFromReg from a physical register
585 // fold the extract into the copy now
587 // Create the extract_subreg machine instruction.
589 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
591 // Figure out the register class to create for the destreg.
592 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
593 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
594 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
597 // Grab the destination register
598 const TargetRegisterClass *DRC = 0;
599 DRC = RegInfo.getRegClass(VRBase);
601 "Source subregister and destination must have the same class");
604 VRBase = RegInfo.createVirtualRegister(SRC);
607 // Add def, source, and subreg index
608 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
609 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
610 MI->addOperand(MachineOperand::CreateImm(SubIdx));
612 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
613 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
614 "Malformed insert_subreg node");
615 bool isUndefInput = (Node->getNumOperands() == 2);
620 SubReg = getVR(Node->getOperand(0), VRBaseMap);
621 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
623 SubReg = getVR(Node->getOperand(1), VRBaseMap);
624 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
627 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
628 // to allow coalescing in the allocator
630 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
631 // the CopyToReg'd destination register instead of creating a new vreg.
632 // If the CopyToReg'd destination register is physical, then fold the
633 // insert into the copy
634 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
637 if (Use->getOpcode() == ISD::CopyToReg &&
638 Use->getOperand(2).Val == Node) {
639 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
640 if (MRegisterInfo::isVirtualRegister(DestReg)) {
647 // Create the insert_subreg machine instruction.
649 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
651 // Figure out the register class to create for the destreg.
652 const TargetRegisterClass *TRC = 0;
654 TRC = RegInfo.getRegClass(VRBase);
656 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
657 Node->getValueType(0));
658 assert(TRC && "Couldn't determine register class for insert_subreg");
659 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
662 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
663 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
665 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
666 MI->addOperand(MachineOperand::CreateImm(SubIdx));
668 assert(0 && "Node is not a subreg insert or extract");
670 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
671 assert(isNew && "Node emitted out of order - early");
674 /// EmitNode - Generate machine code for an node and needed dependencies.
676 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
677 DenseMap<SDOperand, unsigned> &VRBaseMap) {
678 // If machine instruction
679 if (Node->isTargetOpcode()) {
680 unsigned Opc = Node->getTargetOpcode();
682 // Handle subreg insert/extract specially
683 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
684 Opc == TargetInstrInfo::INSERT_SUBREG) {
685 EmitSubregNode(Node, VRBaseMap);
689 const TargetInstrDesc &II = TII->get(Opc);
691 unsigned NumResults = CountResults(Node);
692 unsigned NodeOperands = CountOperands(Node);
693 unsigned NodeMemOperands = CountMemOperands(Node);
694 unsigned NumMIOperands = NodeOperands + NumResults;
695 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
696 II.getImplicitDefs() != 0;
698 assert((II.getNumOperands() == NumMIOperands ||
699 HasPhysRegOuts || II.isVariadic()) &&
700 "#operands for dag node doesn't match .td file!");
703 // Create the new machine instruction.
704 MachineInstr *MI = new MachineInstr(II);
706 // Add result register values for things that are defined by this
709 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
711 // Emit all of the actual operands of this instruction, adding them to the
712 // instruction as appropriate.
713 for (unsigned i = 0; i != NodeOperands; ++i)
714 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
716 // Emit all of the memory operands of this instruction
717 for (unsigned i = NodeOperands; i != NodeMemOperands; ++i)
718 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
720 // Commute node if it has been determined to be profitable.
721 if (CommuteSet.count(Node)) {
722 MachineInstr *NewMI = TII->commuteInstruction(MI);
724 DOUT << "Sched: COMMUTING FAILED!\n";
726 DOUT << "Sched: COMMUTED TO: " << *NewMI;
734 // Now that we have emitted all operands, emit this instruction itself.
735 if (Opc == TargetInstrInfo::LABEL &&
736 !BB->empty() && &MF->front() == BB) {
737 // If we are inserting a LABEL and this happens to be the first label in
738 // the entry block, it is the "function start" label. Make sure there are
739 // no other instructions before it.
740 unsigned NumLabels = 0;
741 MachineBasicBlock::iterator MBBI = BB->begin();
742 while (MBBI != BB->end()) {
743 if (MBBI->getOpcode() == TargetInstrInfo::LABEL) {
750 BB->insert(BB->begin(), MI);
753 } else if (II.usesCustomDAGSchedInsertionHook())
754 // Insert this instruction into the basic block using a target
755 // specific inserter which may returns a new basic block.
756 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
760 // Additional results must be an physical register def.
761 if (HasPhysRegOuts) {
762 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
763 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
764 if (Node->hasAnyUseOfValue(i))
765 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
769 switch (Node->getOpcode()) {
774 assert(0 && "This target-independent node should have been selected!");
775 case ISD::EntryToken: // fall thru
776 case ISD::TokenFactor:
780 case ISD::CopyToReg: {
782 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
785 InReg = getVR(Node->getOperand(2), VRBaseMap);
786 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
787 if (InReg != DestReg) {// Coalesced away the copy?
788 const TargetRegisterClass *TRC = 0;
789 // Get the target register class
790 if (MRegisterInfo::isVirtualRegister(InReg))
791 TRC = RegInfo.getRegClass(InReg);
794 MRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
796 TII->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
800 case ISD::CopyFromReg: {
801 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
802 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
805 case ISD::INLINEASM: {
806 unsigned NumOps = Node->getNumOperands();
807 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
808 --NumOps; // Ignore the flag operand.
810 // Create the inline asm machine instruction.
812 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
814 // Add the asm string as an external symbol operand.
816 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
817 MI->addOperand(MachineOperand::CreateES(AsmStr));
819 // Add all of the operand registers to the instruction.
820 for (unsigned i = 2; i != NumOps;) {
821 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
822 unsigned NumVals = Flags >> 3;
824 MI->addOperand(MachineOperand::CreateImm(Flags));
825 ++i; // Skip the ID value.
828 default: assert(0 && "Bad flags!");
829 case 1: // Use of register.
830 for (; NumVals; --NumVals, ++i) {
831 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
832 MI->addOperand(MachineOperand::CreateReg(Reg, false));
835 case 2: // Def of register.
836 for (; NumVals; --NumVals, ++i) {
837 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
838 MI->addOperand(MachineOperand::CreateReg(Reg, true));
841 case 3: { // Immediate.
842 for (; NumVals; --NumVals, ++i) {
843 if (ConstantSDNode *CS =
844 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
845 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
846 } else if (GlobalAddressSDNode *GA =
847 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
848 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
851 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
852 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
857 case 4: // Addressing mode.
858 // The addressing mode has been selected, just add all of the
859 // operands to the machine instruction.
860 for (; NumVals; --NumVals, ++i)
861 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
871 void ScheduleDAG::EmitNoop() {
872 TII->insertNoop(*BB, BB->end());
875 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
876 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
878 if (I->isCtrl) continue; // ignore chain preds
880 // Copy to physical register.
881 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
882 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
883 // Find the destination physical register.
885 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
886 EE = SU->Succs.end(); II != EE; ++II) {
892 assert(I->Reg && "Unknown physical register!");
893 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
894 SU->CopyDstRC, SU->CopySrcRC);
896 // Copy from physical register.
897 assert(I->Reg && "Unknown physical register!");
898 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
899 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
900 assert(isNew && "Node emitted out of order - early");
901 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
902 SU->CopyDstRC, SU->CopySrcRC);
908 /// EmitSchedule - Emit the machine code in scheduled order.
909 void ScheduleDAG::EmitSchedule() {
910 // If this is the first basic block in the function, and if it has live ins
911 // that need to be copied into vregs, emit the copies into the top of the
912 // block before emitting the code for the block.
913 if (&MF->front() == BB) {
914 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
915 E = RegInfo.livein_end(); LI != E; ++LI)
917 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
918 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
924 // Finally, emit the code for all of the scheduled instructions.
925 DenseMap<SDOperand, unsigned> VRBaseMap;
926 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
927 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
928 if (SUnit *SU = Sequence[i]) {
929 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
930 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
932 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
934 EmitCrossRCCopy(SU, CopyVRBaseMap);
936 // Null SUnit* is a noop.
942 /// dump - dump the schedule.
943 void ScheduleDAG::dumpSchedule() const {
944 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
945 if (SUnit *SU = Sequence[i])
948 cerr << "**** NOOP ****\n";
953 /// Run - perform scheduling.
955 MachineBasicBlock *ScheduleDAG::Run() {
960 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
961 /// a group of nodes flagged together.
962 void SUnit::dump(const SelectionDAG *G) const {
963 cerr << "SU(" << NodeNum << "): ";
967 cerr << "CROSS RC COPY ";
969 if (FlaggedNodes.size() != 0) {
970 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
972 FlaggedNodes[i]->dump(G);
978 void SUnit::dumpAll(const SelectionDAG *G) const {
981 cerr << " # preds left : " << NumPredsLeft << "\n";
982 cerr << " # succs left : " << NumSuccsLeft << "\n";
983 cerr << " Latency : " << Latency << "\n";
984 cerr << " Depth : " << Depth << "\n";
985 cerr << " Height : " << Height << "\n";
987 if (Preds.size() != 0) {
988 cerr << " Predecessors:\n";
989 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
995 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1001 if (Succs.size() != 0) {
1002 cerr << " Successors:\n";
1003 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1009 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";