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/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
31 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
32 const TargetMachine &tm)
33 : DAG(dag), BB(bb), TM(tm), RegInfo(BB->getParent()->getRegInfo()) {
34 TII = TM.getInstrInfo();
35 MF = &DAG.getMachineFunction();
36 TRI = TM.getRegisterInfo();
37 ConstPool = BB->getParent()->getConstantPool();
40 /// CheckForPhysRegDependency - Check if the dependency between def and use of
41 /// a specified operand is a physical register dependency. If so, returns the
42 /// register and the cost of copying the register.
43 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
44 const TargetRegisterInfo *TRI,
45 const TargetInstrInfo *TII,
46 unsigned &PhysReg, int &Cost) {
47 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
50 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
51 if (TargetRegisterInfo::isVirtualRegister(Reg))
54 unsigned ResNo = Use->getOperand(2).ResNo;
55 if (Def->isTargetOpcode()) {
56 const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
57 if (ResNo >= II.getNumDefs() &&
58 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
60 const TargetRegisterClass *RC =
61 TRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
62 Cost = RC->getCopyCost();
67 SUnit *ScheduleDAG::Clone(SUnit *Old) {
68 SUnit *SU = NewSUnit(Old->Node);
69 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
70 SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
71 SU->InstanceNo = SUnitMap[Old->Node].size();
72 SU->Latency = Old->Latency;
73 SU->isTwoAddress = Old->isTwoAddress;
74 SU->isCommutable = Old->isCommutable;
75 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
76 SUnitMap[Old->Node].push_back(SU);
81 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
82 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
83 /// together nodes with a single SUnit.
84 void ScheduleDAG::BuildSchedUnits() {
85 // Reserve entries in the vector for each of the SUnits we are creating. This
86 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
88 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
90 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
91 E = DAG.allnodes_end(); NI != E; ++NI) {
92 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
95 // If this node has already been processed, stop now.
96 if (SUnitMap[NI].size()) continue;
98 SUnit *NodeSUnit = NewSUnit(NI);
100 // See if anything is flagged to this node, if so, add them to flagged
101 // nodes. Nodes can have at most one flag input and one flag output. Flags
102 // are required the be the last operand and result of a node.
104 // Scan up, adding flagged preds to FlaggedNodes.
106 if (N->getNumOperands() &&
107 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
109 N = N->getOperand(N->getNumOperands()-1).Val;
110 NodeSUnit->FlaggedNodes.push_back(N);
111 SUnitMap[N].push_back(NodeSUnit);
112 } while (N->getNumOperands() &&
113 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
114 std::reverse(NodeSUnit->FlaggedNodes.begin(),
115 NodeSUnit->FlaggedNodes.end());
118 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
119 // have a user of the flag operand.
121 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
122 SDOperand FlagVal(N, N->getNumValues()-1);
124 // There are either zero or one users of the Flag result.
125 bool HasFlagUse = false;
126 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
128 if (FlagVal.isOperand(*UI)) {
130 NodeSUnit->FlaggedNodes.push_back(N);
131 SUnitMap[N].push_back(NodeSUnit);
135 if (!HasFlagUse) break;
138 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
141 SUnitMap[N].push_back(NodeSUnit);
143 ComputeLatency(NodeSUnit);
146 // Pass 2: add the preds, succs, etc.
147 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
148 SUnit *SU = &SUnits[su];
149 SDNode *MainNode = SU->Node;
151 if (MainNode->isTargetOpcode()) {
152 unsigned Opc = MainNode->getTargetOpcode();
153 const TargetInstrDesc &TID = TII->get(Opc);
154 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
155 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
156 SU->isTwoAddress = true;
160 if (TID.isCommutable())
161 SU->isCommutable = true;
164 // Find all predecessors and successors of the group.
165 // Temporarily add N to make code simpler.
166 SU->FlaggedNodes.push_back(MainNode);
168 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
169 SDNode *N = SU->FlaggedNodes[n];
170 if (N->isTargetOpcode() &&
171 TII->get(N->getTargetOpcode()).getImplicitDefs() &&
172 CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
173 SU->hasPhysRegDefs = true;
175 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
176 SDNode *OpN = N->getOperand(i).Val;
177 if (isPassiveNode(OpN)) continue; // Not scheduled.
178 SUnit *OpSU = SUnitMap[OpN].front();
179 assert(OpSU && "Node has no SUnit!");
180 if (OpSU == SU) continue; // In the same group.
182 MVT::ValueType OpVT = N->getOperand(i).getValueType();
183 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
184 bool isChain = OpVT == MVT::Other;
186 unsigned PhysReg = 0;
188 // Determine if this is a physical register dependency.
189 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
190 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
194 // Remove MainNode from FlaggedNodes again.
195 SU->FlaggedNodes.pop_back();
201 void ScheduleDAG::ComputeLatency(SUnit *SU) {
202 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
204 // Compute the latency for the node. We use the sum of the latencies for
205 // all nodes flagged together into this SUnit.
206 if (InstrItins.isEmpty()) {
207 // No latency information.
211 if (SU->Node->isTargetOpcode()) {
212 unsigned SchedClass =
213 TII->get(SU->Node->getTargetOpcode()).getSchedClass();
214 InstrStage *S = InstrItins.begin(SchedClass);
215 InstrStage *E = InstrItins.end(SchedClass);
217 SU->Latency += S->Cycles;
219 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
220 SDNode *FNode = SU->FlaggedNodes[i];
221 if (FNode->isTargetOpcode()) {
222 unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
223 InstrStage *S = InstrItins.begin(SchedClass);
224 InstrStage *E = InstrItins.end(SchedClass);
226 SU->Latency += S->Cycles;
232 void ScheduleDAG::CalculateDepths() {
233 std::vector<std::pair<SUnit*, unsigned> > WorkList;
234 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
235 if (SUnits[i].Preds.empty())
236 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
238 while (!WorkList.empty()) {
239 SUnit *SU = WorkList.back().first;
240 unsigned Depth = WorkList.back().second;
242 if (SU->Depth == 0 || Depth > SU->Depth) {
244 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
246 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
251 void ScheduleDAG::CalculateHeights() {
252 std::vector<std::pair<SUnit*, unsigned> > WorkList;
253 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
254 WorkList.push_back(std::make_pair(Root, 0U));
256 while (!WorkList.empty()) {
257 SUnit *SU = WorkList.back().first;
258 unsigned Height = WorkList.back().second;
260 if (SU->Height == 0 || Height > SU->Height) {
262 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
264 WorkList.push_back(std::make_pair(I->Dep, Height+1));
269 /// CountResults - The results of target nodes have register or immediate
270 /// operands first, then an optional chain, and optional flag operands (which do
271 /// not go into the resulting MachineInstr).
272 unsigned ScheduleDAG::CountResults(SDNode *Node) {
273 unsigned N = Node->getNumValues();
274 while (N && Node->getValueType(N - 1) == MVT::Flag)
276 if (N && Node->getValueType(N - 1) == MVT::Other)
277 --N; // Skip over chain result.
281 /// CountOperands - The inputs to target nodes have any actual inputs first,
282 /// followed by special operands that describe memory references, then an
283 /// optional chain operand, then flag operands. Compute the number of
284 /// actual operands that will go into the resulting MachineInstr.
285 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
286 unsigned N = ComputeMemOperandsEnd(Node);
287 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
288 --N; // Ignore MemOperand nodes
292 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
294 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
295 unsigned N = Node->getNumOperands();
296 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
298 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
299 --N; // Ignore chain if it exists.
303 static const TargetRegisterClass *getInstrOperandRegClass(
304 const TargetRegisterInfo *TRI,
305 const TargetInstrInfo *TII,
306 const TargetInstrDesc &II,
308 if (Op >= II.getNumOperands()) {
309 assert(II.isVariadic() && "Invalid operand # of instruction");
312 if (II.OpInfo[Op].isLookupPtrRegClass())
313 return TII->getPointerRegClass();
314 return TRI->getRegClass(II.OpInfo[Op].RegClass);
317 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
318 unsigned InstanceNo, unsigned SrcReg,
319 DenseMap<SDOperand, unsigned> &VRBaseMap) {
321 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
322 // Just use the input register directly!
324 VRBaseMap.erase(SDOperand(Node, ResNo));
325 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
326 assert(isNew && "Node emitted out of order - early");
330 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
331 // the CopyToReg'd destination register instead of creating a new vreg.
332 bool MatchReg = true;
333 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
337 if (Use->getOpcode() == ISD::CopyToReg &&
338 Use->getOperand(2).Val == Node &&
339 Use->getOperand(2).ResNo == ResNo) {
340 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
341 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
344 } else if (DestReg != SrcReg)
347 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
348 SDOperand Op = Use->getOperand(i);
349 if (Op.Val != Node || Op.ResNo != ResNo)
351 MVT::ValueType VT = Node->getValueType(Op.ResNo);
352 if (VT != MVT::Other && VT != MVT::Flag)
361 const TargetRegisterClass *TRC = 0;
362 // Figure out the register class to create for the destreg.
364 TRC = RegInfo.getRegClass(VRBase);
366 TRC = TRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
368 // If all uses are reading from the src physical register and copying the
369 // register is either impossible or very expensive, then don't create a copy.
370 if (MatchReg && TRC->getCopyCost() < 0) {
373 // Create the reg, emit the copy.
374 VRBase = RegInfo.createVirtualRegister(TRC);
375 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
379 VRBaseMap.erase(SDOperand(Node, ResNo));
380 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
381 assert(isNew && "Node emitted out of order - early");
384 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
386 const TargetInstrDesc &II,
387 DenseMap<SDOperand, unsigned> &VRBaseMap) {
388 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
389 // If the specific node value is only used by a CopyToReg and the dest reg
390 // is a vreg, use the CopyToReg'd destination register instead of creating
393 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
396 if (Use->getOpcode() == ISD::CopyToReg &&
397 Use->getOperand(2).Val == Node &&
398 Use->getOperand(2).ResNo == i) {
399 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
400 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
402 MI->addOperand(MachineOperand::CreateReg(Reg, true));
408 // Create the result registers for this node and add the result regs to
409 // the machine instruction.
411 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
412 assert(RC && "Isn't a register operand!");
413 VRBase = RegInfo.createVirtualRegister(RC);
414 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
417 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
418 assert(isNew && "Node emitted out of order - early");
422 /// getVR - Return the virtual register corresponding to the specified result
423 /// of the specified node.
424 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
425 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
426 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
431 /// AddOperand - Add the specified operand to the specified machine instr. II
432 /// specifies the instruction information for the node, and IIOpNum is the
433 /// operand number (in the II) that we are adding. IIOpNum and II are used for
435 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
437 const TargetInstrDesc *II,
438 DenseMap<SDOperand, unsigned> &VRBaseMap) {
439 if (Op.isTargetOpcode()) {
440 // Note that this case is redundant with the final else block, but we
441 // include it because it is the most common and it makes the logic
443 assert(Op.getValueType() != MVT::Other &&
444 Op.getValueType() != MVT::Flag &&
445 "Chain and flag operands should occur at end of operand list!");
447 // Get/emit the operand.
448 unsigned VReg = getVR(Op, VRBaseMap);
449 const TargetInstrDesc &TID = MI->getDesc();
450 bool isOptDef = (IIOpNum < TID.getNumOperands())
451 ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
452 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
454 // Verify that it is right.
455 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
457 const TargetRegisterClass *RC =
458 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
459 assert(RC && "Don't have operand info for this instruction!");
460 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
462 cerr << "Register class of operand and regclass of use don't agree!\n";
464 cerr << "Operand = " << IIOpNum << "\n";
465 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
466 cerr << "MI = "; MI->print(cerr);
467 cerr << "VReg = " << VReg << "\n";
468 cerr << "VReg RegClass size = " << VRC->getSize()
469 << ", align = " << VRC->getAlignment() << "\n";
470 cerr << "Expected RegClass size = " << RC->getSize()
471 << ", align = " << RC->getAlignment() << "\n";
473 cerr << "Fatal error, aborting.\n";
477 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
478 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
479 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
480 const Type *FType = MVT::getTypeForValueType(Op.getValueType());
481 ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
482 MI->addOperand(MachineOperand::CreateFPImm(CFP));
483 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
484 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
485 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
486 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
487 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
488 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
489 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
490 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
491 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
492 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
493 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
494 int Offset = CP->getOffset();
495 unsigned Align = CP->getAlignment();
496 const Type *Type = CP->getType();
497 // MachineConstantPool wants an explicit alignment.
499 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
501 // Alignment of vector types. FIXME!
502 Align = TM.getTargetData()->getABITypeSize(Type);
503 Align = Log2_64(Align);
508 if (CP->isMachineConstantPoolEntry())
509 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
511 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
512 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
513 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
514 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
516 assert(Op.getValueType() != MVT::Other &&
517 Op.getValueType() != MVT::Flag &&
518 "Chain and flag operands should occur at end of operand list!");
519 unsigned VReg = getVR(Op, VRBaseMap);
520 MI->addOperand(MachineOperand::CreateReg(VReg, false));
522 // Verify that it is right.
523 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
525 const TargetRegisterClass *RC =
526 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
527 assert(RC && "Don't have operand info for this instruction!");
528 assert(RegInfo.getRegClass(VReg) == RC &&
529 "Register class of operand and regclass of use don't agree!");
535 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
536 MI->addMemOperand(MO);
539 // Returns the Register Class of a subregister
540 static const TargetRegisterClass *getSubRegisterRegClass(
541 const TargetRegisterClass *TRC,
543 // Pick the register class of the subregister
544 TargetRegisterInfo::regclass_iterator I =
545 TRC->subregclasses_begin() + SubIdx-1;
546 assert(I < TRC->subregclasses_end() &&
547 "Invalid subregister index for register class");
551 static const TargetRegisterClass *getSuperregRegisterClass(
552 const TargetRegisterClass *TRC,
555 // Pick the register class of the superegister for this type
556 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
557 E = TRC->superregclasses_end(); I != E; ++I)
558 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
560 assert(false && "Couldn't find the register class");
564 /// EmitSubregNode - Generate machine code for subreg nodes.
566 void ScheduleDAG::EmitSubregNode(SDNode *Node,
567 DenseMap<SDOperand, unsigned> &VRBaseMap) {
569 unsigned Opc = Node->getTargetOpcode();
570 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
571 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
572 // the CopyToReg'd destination register instead of creating a new vreg.
573 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
576 if (Use->getOpcode() == ISD::CopyToReg &&
577 Use->getOperand(2).Val == Node) {
578 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
579 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
586 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
588 // TODO: If the node is a use of a CopyFromReg from a physical register
589 // fold the extract into the copy now
591 // Create the extract_subreg machine instruction.
593 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
595 // Figure out the register class to create for the destreg.
596 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
597 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
598 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
601 // Grab the destination register
602 const TargetRegisterClass *DRC = 0;
603 DRC = RegInfo.getRegClass(VRBase);
604 assert(SRC && DRC && SRC == DRC &&
605 "Source subregister and destination must have the same class");
608 assert(SRC && "Couldn't find source register class");
609 VRBase = RegInfo.createVirtualRegister(SRC);
612 // Add def, source, and subreg index
613 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
614 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
615 MI->addOperand(MachineOperand::CreateImm(SubIdx));
617 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
618 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
619 "Malformed insert_subreg node");
620 bool isUndefInput = (Node->getNumOperands() == 2);
625 SubReg = getVR(Node->getOperand(0), VRBaseMap);
626 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
628 SubReg = getVR(Node->getOperand(1), VRBaseMap);
629 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
632 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
633 // to allow coalescing in the allocator
635 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
636 // the CopyToReg'd destination register instead of creating a new vreg.
637 // If the CopyToReg'd destination register is physical, then fold the
638 // insert into the copy
639 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
642 if (Use->getOpcode() == ISD::CopyToReg &&
643 Use->getOperand(2).Val == Node) {
644 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
645 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
652 // Create the insert_subreg machine instruction.
654 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
656 // Figure out the register class to create for the destreg.
657 const TargetRegisterClass *TRC = 0;
659 TRC = RegInfo.getRegClass(VRBase);
661 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
662 Node->getValueType(0));
663 assert(TRC && "Couldn't determine register class for insert_subreg");
664 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
667 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
668 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
670 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
671 MI->addOperand(MachineOperand::CreateImm(SubIdx));
673 assert(0 && "Node is not a subreg insert or extract");
675 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
676 assert(isNew && "Node emitted out of order - early");
679 /// EmitNode - Generate machine code for an node and needed dependencies.
681 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
682 DenseMap<SDOperand, unsigned> &VRBaseMap) {
683 // If machine instruction
684 if (Node->isTargetOpcode()) {
685 unsigned Opc = Node->getTargetOpcode();
687 // Handle subreg insert/extract specially
688 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
689 Opc == TargetInstrInfo::INSERT_SUBREG) {
690 EmitSubregNode(Node, VRBaseMap);
694 const TargetInstrDesc &II = TII->get(Opc);
696 unsigned NumResults = CountResults(Node);
697 unsigned NodeOperands = CountOperands(Node);
698 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
699 unsigned NumMIOperands = NodeOperands + NumResults;
700 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
701 II.getImplicitDefs() != 0;
703 assert((II.getNumOperands() == NumMIOperands ||
704 HasPhysRegOuts || II.isVariadic()) &&
705 "#operands for dag node doesn't match .td file!");
708 // Create the new machine instruction.
709 MachineInstr *MI = new MachineInstr(II);
711 // Add result register values for things that are defined by this
714 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
716 // Emit all of the actual operands of this instruction, adding them to the
717 // instruction as appropriate.
718 for (unsigned i = 0; i != NodeOperands; ++i)
719 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
721 // Emit all of the memory operands of this instruction
722 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
723 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
725 // Commute node if it has been determined to be profitable.
726 if (CommuteSet.count(Node)) {
727 MachineInstr *NewMI = TII->commuteInstruction(MI);
729 DOUT << "Sched: COMMUTING FAILED!\n";
731 DOUT << "Sched: COMMUTED TO: " << *NewMI;
739 if (II.usesCustomDAGSchedInsertionHook())
740 // Insert this instruction into the basic block using a target
741 // specific inserter which may returns a new basic block.
742 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
746 // Additional results must be an physical register def.
747 if (HasPhysRegOuts) {
748 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
749 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
750 if (Node->hasAnyUseOfValue(i))
751 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
755 switch (Node->getOpcode()) {
760 assert(0 && "This target-independent node should have been selected!");
761 case ISD::EntryToken: // fall thru
762 case ISD::TokenFactor:
767 case ISD::CopyToReg: {
769 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
772 InReg = getVR(Node->getOperand(2), VRBaseMap);
773 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
774 if (InReg != DestReg) {// Coalesced away the copy?
775 const TargetRegisterClass *TRC = 0;
776 // Get the target register class
777 if (TargetRegisterInfo::isVirtualRegister(InReg))
778 TRC = RegInfo.getRegClass(InReg);
781 TRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
783 TII->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
787 case ISD::CopyFromReg: {
788 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
789 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
792 case ISD::INLINEASM: {
793 unsigned NumOps = Node->getNumOperands();
794 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
795 --NumOps; // Ignore the flag operand.
797 // Create the inline asm machine instruction.
799 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
801 // Add the asm string as an external symbol operand.
803 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
804 MI->addOperand(MachineOperand::CreateES(AsmStr));
806 // Add all of the operand registers to the instruction.
807 for (unsigned i = 2; i != NumOps;) {
808 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
809 unsigned NumVals = Flags >> 3;
811 MI->addOperand(MachineOperand::CreateImm(Flags));
812 ++i; // Skip the ID value.
815 default: assert(0 && "Bad flags!");
816 case 1: // Use of register.
817 for (; NumVals; --NumVals, ++i) {
818 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
819 MI->addOperand(MachineOperand::CreateReg(Reg, false));
822 case 2: // Def of register.
823 for (; NumVals; --NumVals, ++i) {
824 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
825 MI->addOperand(MachineOperand::CreateReg(Reg, true));
828 case 3: { // Immediate.
829 for (; NumVals; --NumVals, ++i) {
830 if (ConstantSDNode *CS =
831 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
832 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
833 } else if (GlobalAddressSDNode *GA =
834 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
835 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
838 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
839 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
844 case 4: // Addressing mode.
845 // The addressing mode has been selected, just add all of the
846 // operands to the machine instruction.
847 for (; NumVals; --NumVals, ++i)
848 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
858 void ScheduleDAG::EmitNoop() {
859 TII->insertNoop(*BB, BB->end());
862 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
863 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
865 if (I->isCtrl) continue; // ignore chain preds
867 // Copy to physical register.
868 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
869 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
870 // Find the destination physical register.
872 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
873 EE = SU->Succs.end(); II != EE; ++II) {
879 assert(I->Reg && "Unknown physical register!");
880 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
881 SU->CopyDstRC, SU->CopySrcRC);
883 // Copy from physical register.
884 assert(I->Reg && "Unknown physical register!");
885 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
886 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
887 assert(isNew && "Node emitted out of order - early");
888 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
889 SU->CopyDstRC, SU->CopySrcRC);
895 /// EmitSchedule - Emit the machine code in scheduled order.
896 void ScheduleDAG::EmitSchedule() {
897 // If this is the first basic block in the function, and if it has live ins
898 // that need to be copied into vregs, emit the copies into the top of the
899 // block before emitting the code for the block.
900 if (&MF->front() == BB) {
901 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
902 E = RegInfo.livein_end(); LI != E; ++LI)
904 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
905 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
911 // Finally, emit the code for all of the scheduled instructions.
912 DenseMap<SDOperand, unsigned> VRBaseMap;
913 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
914 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
915 if (SUnit *SU = Sequence[i]) {
916 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
917 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
919 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
921 EmitCrossRCCopy(SU, CopyVRBaseMap);
923 // Null SUnit* is a noop.
929 /// dump - dump the schedule.
930 void ScheduleDAG::dumpSchedule() const {
931 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
932 if (SUnit *SU = Sequence[i])
935 cerr << "**** NOOP ****\n";
940 /// Run - perform scheduling.
942 MachineBasicBlock *ScheduleDAG::Run() {
947 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
948 /// a group of nodes flagged together.
949 void SUnit::dump(const SelectionDAG *G) const {
950 cerr << "SU(" << NodeNum << "): ";
954 cerr << "CROSS RC COPY ";
956 if (FlaggedNodes.size() != 0) {
957 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
959 FlaggedNodes[i]->dump(G);
965 void SUnit::dumpAll(const SelectionDAG *G) const {
968 cerr << " # preds left : " << NumPredsLeft << "\n";
969 cerr << " # succs left : " << NumSuccsLeft << "\n";
970 cerr << " Latency : " << Latency << "\n";
971 cerr << " Depth : " << Depth << "\n";
972 cerr << " Height : " << Height << "\n";
974 if (Preds.size() != 0) {
975 cerr << " Predecessors:\n";
976 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
982 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
988 if (Succs.size() != 0) {
989 cerr << " Successors:\n";
990 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
996 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";