blob: 21c12d3993f0af3c1689cbe8b2036e6abb7754da [file] [log] [blame]
Dan Gohman94b8d7e2008-09-03 16:01:59 +00001//===---- ScheduleDAGEmit.cpp - Emit routines for the ScheduleDAG class ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the Emit routines for the ScheduleDAG class, which creates
11// MachineInstrs according to the computed schedule.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "pre-RA-sched"
16#include "llvm/CodeGen/ScheduleDAG.h"
17#include "llvm/CodeGen/MachineConstantPool.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetLowering.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/MathExtras.h"
29using namespace llvm;
30
31STATISTIC(NumCommutes, "Number of instructions commuted");
32
33namespace {
34 static cl::opt<bool>
35 SchedLiveInCopies("schedule-livein-copies",
36 cl::desc("Schedule copies of livein registers"),
37 cl::init(false));
38}
39
40/// getInstrOperandRegClass - Return register class of the operand of an
41/// instruction of the specified TargetInstrDesc.
42static const TargetRegisterClass*
43getInstrOperandRegClass(const TargetRegisterInfo *TRI,
44 const TargetInstrInfo *TII, const TargetInstrDesc &II,
45 unsigned Op) {
46 if (Op >= II.getNumOperands()) {
47 assert(II.isVariadic() && "Invalid operand # of instruction");
48 return NULL;
49 }
50 if (II.OpInfo[Op].isLookupPtrRegClass())
51 return TII->getPointerRegClass();
52 return TRI->getRegClass(II.OpInfo[Op].RegClass);
53}
54
55/// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
56/// implicit physical register output.
57void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
58 bool IsClone, unsigned SrcReg,
59 DenseMap<SDValue, unsigned> &VRBaseMap) {
60 unsigned VRBase = 0;
61 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
62 // Just use the input register directly!
63 SDValue Op(Node, ResNo);
64 if (IsClone)
65 VRBaseMap.erase(Op);
66 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
67 isNew = isNew; // Silence compiler warning.
68 assert(isNew && "Node emitted out of order - early");
69 return;
70 }
71
72 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
73 // the CopyToReg'd destination register instead of creating a new vreg.
74 bool MatchReg = true;
75 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
76 UI != E; ++UI) {
77 SDNode *User = *UI;
78 bool Match = true;
79 if (User->getOpcode() == ISD::CopyToReg &&
80 User->getOperand(2).getNode() == Node &&
81 User->getOperand(2).getResNo() == ResNo) {
82 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
83 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
84 VRBase = DestReg;
85 Match = false;
86 } else if (DestReg != SrcReg)
87 Match = false;
88 } else {
89 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
90 SDValue Op = User->getOperand(i);
91 if (Op.getNode() != Node || Op.getResNo() != ResNo)
92 continue;
93 MVT VT = Node->getValueType(Op.getResNo());
94 if (VT != MVT::Other && VT != MVT::Flag)
95 Match = false;
96 }
97 }
98 MatchReg &= Match;
99 if (VRBase)
100 break;
101 }
102
103 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
104 SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, Node->getValueType(ResNo));
105
106 // Figure out the register class to create for the destreg.
107 if (VRBase) {
108 DstRC = MRI.getRegClass(VRBase);
109 } else {
110 DstRC = TLI->getRegClassFor(Node->getValueType(ResNo));
111 }
112
113 // If all uses are reading from the src physical register and copying the
114 // register is either impossible or very expensive, then don't create a copy.
115 if (MatchReg && SrcRC->getCopyCost() < 0) {
116 VRBase = SrcReg;
117 } else {
118 // Create the reg, emit the copy.
119 VRBase = MRI.createVirtualRegister(DstRC);
120 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
121 }
122
123 SDValue Op(Node, ResNo);
124 if (IsClone)
125 VRBaseMap.erase(Op);
126 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
127 isNew = isNew; // Silence compiler warning.
128 assert(isNew && "Node emitted out of order - early");
129}
130
131/// getDstOfCopyToRegUse - If the only use of the specified result number of
132/// node is a CopyToReg, return its destination register. Return 0 otherwise.
133unsigned ScheduleDAG::getDstOfOnlyCopyToRegUse(SDNode *Node,
134 unsigned ResNo) const {
135 if (!Node->hasOneUse())
136 return 0;
137
138 SDNode *User = *Node->use_begin();
139 if (User->getOpcode() == ISD::CopyToReg &&
140 User->getOperand(2).getNode() == Node &&
141 User->getOperand(2).getResNo() == ResNo) {
142 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
143 if (TargetRegisterInfo::isVirtualRegister(Reg))
144 return Reg;
145 }
146 return 0;
147}
148
149void ScheduleDAG::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
150 const TargetInstrDesc &II,
151 DenseMap<SDValue, unsigned> &VRBaseMap) {
152 assert(Node->getMachineOpcode() != TargetInstrInfo::IMPLICIT_DEF &&
153 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
154
155 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
156 // If the specific node value is only used by a CopyToReg and the dest reg
157 // is a vreg, use the CopyToReg'd destination register instead of creating
158 // a new vreg.
159 unsigned VRBase = 0;
160 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
161 UI != E; ++UI) {
162 SDNode *User = *UI;
163 if (User->getOpcode() == ISD::CopyToReg &&
164 User->getOperand(2).getNode() == Node &&
165 User->getOperand(2).getResNo() == i) {
166 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
167 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
168 VRBase = Reg;
169 MI->addOperand(MachineOperand::CreateReg(Reg, true));
170 break;
171 }
172 }
173 }
174
175 // Create the result registers for this node and add the result regs to
176 // the machine instruction.
177 if (VRBase == 0) {
178 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
179 assert(RC && "Isn't a register operand!");
180 VRBase = MRI.createVirtualRegister(RC);
181 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
182 }
183
184 SDValue Op(Node, i);
185 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
186 isNew = isNew; // Silence compiler warning.
187 assert(isNew && "Node emitted out of order - early");
188 }
189}
190
191/// getVR - Return the virtual register corresponding to the specified result
192/// of the specified node.
193unsigned ScheduleDAG::getVR(SDValue Op,
194 DenseMap<SDValue, unsigned> &VRBaseMap) {
195 if (Op.isMachineOpcode() &&
196 Op.getMachineOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
197 // Add an IMPLICIT_DEF instruction before every use.
198 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
199 // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
200 // does not include operand register class info.
201 if (!VReg) {
202 const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
203 VReg = MRI.createVirtualRegister(RC);
204 }
205 BuildMI(BB, TII->get(TargetInstrInfo::IMPLICIT_DEF), VReg);
206 return VReg;
207 }
208
209 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
210 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
211 return I->second;
212}
213
214
215/// AddOperand - Add the specified operand to the specified machine instr. II
216/// specifies the instruction information for the node, and IIOpNum is the
217/// operand number (in the II) that we are adding. IIOpNum and II are used for
218/// assertions only.
219void ScheduleDAG::AddOperand(MachineInstr *MI, SDValue Op,
220 unsigned IIOpNum,
221 const TargetInstrDesc *II,
222 DenseMap<SDValue, unsigned> &VRBaseMap) {
223 if (Op.isMachineOpcode()) {
224 // Note that this case is redundant with the final else block, but we
225 // include it because it is the most common and it makes the logic
226 // simpler here.
227 assert(Op.getValueType() != MVT::Other &&
228 Op.getValueType() != MVT::Flag &&
229 "Chain and flag operands should occur at end of operand list!");
230 // Get/emit the operand.
231 unsigned VReg = getVR(Op, VRBaseMap);
232 const TargetInstrDesc &TID = MI->getDesc();
233 bool isOptDef = IIOpNum < TID.getNumOperands() &&
234 TID.OpInfo[IIOpNum].isOptionalDef();
235 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
236
237 // Verify that it is right.
238 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
239#ifndef NDEBUG
240 if (II) {
241 // There may be no register class for this operand if it is a variadic
242 // argument (RC will be NULL in this case). In this case, we just assume
243 // the regclass is ok.
244 const TargetRegisterClass *RC =
245 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
246 assert((RC || II->isVariadic()) && "Expected reg class info!");
247 const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
248 if (RC && VRC != RC) {
249 cerr << "Register class of operand and regclass of use don't agree!\n";
250 cerr << "Operand = " << IIOpNum << "\n";
251 cerr << "Op->Val = "; Op.getNode()->dump(&DAG); cerr << "\n";
252 cerr << "MI = "; MI->print(cerr);
253 cerr << "VReg = " << VReg << "\n";
254 cerr << "VReg RegClass size = " << VRC->getSize()
255 << ", align = " << VRC->getAlignment() << "\n";
256 cerr << "Expected RegClass size = " << RC->getSize()
257 << ", align = " << RC->getAlignment() << "\n";
258 cerr << "Fatal error, aborting.\n";
259 abort();
260 }
261 }
262#endif
263 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
264 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
265 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
266 ConstantFP *CFP = ConstantFP::get(F->getValueAPF());
267 MI->addOperand(MachineOperand::CreateFPImm(CFP));
268 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
269 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
270 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
271 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
272 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
273 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
274 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
275 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
276 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
277 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
278 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
279 int Offset = CP->getOffset();
280 unsigned Align = CP->getAlignment();
281 const Type *Type = CP->getType();
282 // MachineConstantPool wants an explicit alignment.
283 if (Align == 0) {
284 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
285 if (Align == 0) {
286 // Alignment of vector types. FIXME!
287 Align = TM.getTargetData()->getABITypeSize(Type);
288 Align = Log2_64(Align);
289 }
290 }
291
292 unsigned Idx;
293 if (CP->isMachineConstantPoolEntry())
294 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
295 else
296 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
297 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
298 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
299 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
300 } else {
301 assert(Op.getValueType() != MVT::Other &&
302 Op.getValueType() != MVT::Flag &&
303 "Chain and flag operands should occur at end of operand list!");
304 unsigned VReg = getVR(Op, VRBaseMap);
305 MI->addOperand(MachineOperand::CreateReg(VReg, false));
306
307 // Verify that it is right. Note that the reg class of the physreg and the
308 // vreg don't necessarily need to match, but the target copy insertion has
309 // to be able to handle it. This handles things like copies from ST(0) to
310 // an FP vreg on x86.
311 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
312 if (II && !II->isVariadic()) {
313 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
314 "Don't have operand info for this instruction!");
315 }
316 }
317}
318
319void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO) {
320 MI->addMemOperand(*MF, MO);
321}
322
323/// getSubRegisterRegClass - Returns the register class of specified register
324/// class' "SubIdx"'th sub-register class.
325static const TargetRegisterClass*
326getSubRegisterRegClass(const TargetRegisterClass *TRC, unsigned SubIdx) {
327 // Pick the register class of the subregister
328 TargetRegisterInfo::regclass_iterator I =
329 TRC->subregclasses_begin() + SubIdx-1;
330 assert(I < TRC->subregclasses_end() &&
331 "Invalid subregister index for register class");
332 return *I;
333}
334
335/// getSuperRegisterRegClass - Returns the register class of a superreg A whose
336/// "SubIdx"'th sub-register class is the specified register class and whose
337/// type matches the specified type.
338static const TargetRegisterClass*
339getSuperRegisterRegClass(const TargetRegisterClass *TRC,
340 unsigned SubIdx, MVT VT) {
341 // Pick the register class of the superegister for this type
342 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
343 E = TRC->superregclasses_end(); I != E; ++I)
344 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
345 return *I;
346 assert(false && "Couldn't find the register class");
347 return 0;
348}
349
350/// EmitSubregNode - Generate machine code for subreg nodes.
351///
352void ScheduleDAG::EmitSubregNode(SDNode *Node,
353 DenseMap<SDValue, unsigned> &VRBaseMap) {
354 unsigned VRBase = 0;
355 unsigned Opc = Node->getMachineOpcode();
356
357 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
358 // the CopyToReg'd destination register instead of creating a new vreg.
359 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
360 UI != E; ++UI) {
361 SDNode *User = *UI;
362 if (User->getOpcode() == ISD::CopyToReg &&
363 User->getOperand(2).getNode() == Node) {
364 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
365 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
366 VRBase = DestReg;
367 break;
368 }
369 }
370 }
371
372 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
373 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
374
375 // Create the extract_subreg machine instruction.
376 MachineInstr *MI = BuildMI(*MF, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
377
378 // Figure out the register class to create for the destreg.
379 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
380 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
381 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
382
383 if (VRBase) {
384 // Grab the destination register
385#ifndef NDEBUG
386 const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
387 assert(SRC && DRC && SRC == DRC &&
388 "Source subregister and destination must have the same class");
389#endif
390 } else {
391 // Create the reg
392 assert(SRC && "Couldn't find source register class");
393 VRBase = MRI.createVirtualRegister(SRC);
394 }
395
396 // Add def, source, and subreg index
397 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
398 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
399 MI->addOperand(MachineOperand::CreateImm(SubIdx));
400 BB->push_back(MI);
401 } else if (Opc == TargetInstrInfo::INSERT_SUBREG ||
402 Opc == TargetInstrInfo::SUBREG_TO_REG) {
403 SDValue N0 = Node->getOperand(0);
404 SDValue N1 = Node->getOperand(1);
405 SDValue N2 = Node->getOperand(2);
406 unsigned SubReg = getVR(N1, VRBaseMap);
407 unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
408
409
410 // Figure out the register class to create for the destreg.
411 const TargetRegisterClass *TRC = 0;
412 if (VRBase) {
413 TRC = MRI.getRegClass(VRBase);
414 } else {
415 TRC = getSuperRegisterRegClass(MRI.getRegClass(SubReg), SubIdx,
416 Node->getValueType(0));
417 assert(TRC && "Couldn't determine register class for insert_subreg");
418 VRBase = MRI.createVirtualRegister(TRC); // Create the reg
419 }
420
421 // Create the insert_subreg or subreg_to_reg machine instruction.
422 MachineInstr *MI = BuildMI(*MF, TII->get(Opc));
423 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
424
425 // If creating a subreg_to_reg, then the first input operand
426 // is an implicit value immediate, otherwise it's a register
427 if (Opc == TargetInstrInfo::SUBREG_TO_REG) {
428 const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
429 MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
430 } else
431 AddOperand(MI, N0, 0, 0, VRBaseMap);
432 // Add the subregster being inserted
433 AddOperand(MI, N1, 0, 0, VRBaseMap);
434 MI->addOperand(MachineOperand::CreateImm(SubIdx));
435 BB->push_back(MI);
436 } else
437 assert(0 && "Node is not insert_subreg, extract_subreg, or subreg_to_reg");
438
439 SDValue Op(Node, 0);
440 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
441 isNew = isNew; // Silence compiler warning.
442 assert(isNew && "Node emitted out of order - early");
443}
444
445/// EmitNode - Generate machine code for an node and needed dependencies.
446///
447void ScheduleDAG::EmitNode(SDNode *Node, bool IsClone,
448 DenseMap<SDValue, unsigned> &VRBaseMap) {
449 // If machine instruction
450 if (Node->isMachineOpcode()) {
451 unsigned Opc = Node->getMachineOpcode();
452
453 // Handle subreg insert/extract specially
454 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
455 Opc == TargetInstrInfo::INSERT_SUBREG ||
456 Opc == TargetInstrInfo::SUBREG_TO_REG) {
457 EmitSubregNode(Node, VRBaseMap);
458 return;
459 }
460
461 if (Opc == TargetInstrInfo::IMPLICIT_DEF)
462 // We want a unique VR for each IMPLICIT_DEF use.
463 return;
464
465 const TargetInstrDesc &II = TII->get(Opc);
466 unsigned NumResults = CountResults(Node);
467 unsigned NodeOperands = CountOperands(Node);
468 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
469 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
470 II.getImplicitDefs() != 0;
471#ifndef NDEBUG
472 unsigned NumMIOperands = NodeOperands + NumResults;
473 assert((II.getNumOperands() == NumMIOperands ||
474 HasPhysRegOuts || II.isVariadic()) &&
475 "#operands for dag node doesn't match .td file!");
476#endif
477
478 // Create the new machine instruction.
479 MachineInstr *MI = BuildMI(*MF, II);
480
481 // Add result register values for things that are defined by this
482 // instruction.
483 if (NumResults)
484 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
485
486 // Emit all of the actual operands of this instruction, adding them to the
487 // instruction as appropriate.
488 for (unsigned i = 0; i != NodeOperands; ++i)
489 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
490
491 // Emit all of the memory operands of this instruction
492 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
493 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
494
495 // Commute node if it has been determined to be profitable.
496 if (CommuteSet.count(Node)) {
497 MachineInstr *NewMI = TII->commuteInstruction(MI);
498 if (NewMI == 0)
499 DOUT << "Sched: COMMUTING FAILED!\n";
500 else {
501 DOUT << "Sched: COMMUTED TO: " << *NewMI;
502 if (MI != NewMI) {
503 MF->DeleteMachineInstr(MI);
504 MI = NewMI;
505 }
506 ++NumCommutes;
507 }
508 }
509
510 if (II.usesCustomDAGSchedInsertionHook())
511 // Insert this instruction into the basic block using a target
512 // specific inserter which may returns a new basic block.
513 BB = TLI->EmitInstrWithCustomInserter(MI, BB);
514 else
515 BB->push_back(MI);
516
517 // Additional results must be an physical register def.
518 if (HasPhysRegOuts) {
519 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
520 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
521 if (Node->hasAnyUseOfValue(i))
522 EmitCopyFromReg(Node, i, IsClone, Reg, VRBaseMap);
523 }
524 }
525 return;
526 }
527
528 switch (Node->getOpcode()) {
529 default:
530#ifndef NDEBUG
531 Node->dump(&DAG);
532#endif
533 assert(0 && "This target-independent node should have been selected!");
534 break;
535 case ISD::EntryToken:
536 assert(0 && "EntryToken should have been excluded from the schedule!");
537 break;
538 case ISD::TokenFactor: // fall thru
539 break;
540 case ISD::CopyToReg: {
541 unsigned SrcReg;
542 SDValue SrcVal = Node->getOperand(2);
543 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
544 SrcReg = R->getReg();
545 else
546 SrcReg = getVR(SrcVal, VRBaseMap);
547
548 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
549 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
550 break;
551
552 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
553 // Get the register classes of the src/dst.
554 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
555 SrcTRC = MRI.getRegClass(SrcReg);
556 else
557 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
558
559 if (TargetRegisterInfo::isVirtualRegister(DestReg))
560 DstTRC = MRI.getRegClass(DestReg);
561 else
562 DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
563 Node->getOperand(1).getValueType());
564 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
565 break;
566 }
567 case ISD::CopyFromReg: {
568 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
569 EmitCopyFromReg(Node, 0, IsClone, SrcReg, VRBaseMap);
570 break;
571 }
572 case ISD::INLINEASM: {
573 unsigned NumOps = Node->getNumOperands();
574 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
575 --NumOps; // Ignore the flag operand.
576
577 // Create the inline asm machine instruction.
578 MachineInstr *MI = BuildMI(*MF, TII->get(TargetInstrInfo::INLINEASM));
579
580 // Add the asm string as an external symbol operand.
581 const char *AsmStr =
582 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
583 MI->addOperand(MachineOperand::CreateES(AsmStr));
584
585 // Add all of the operand registers to the instruction.
586 for (unsigned i = 2; i != NumOps;) {
587 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
588 unsigned NumVals = Flags >> 3;
589
590 MI->addOperand(MachineOperand::CreateImm(Flags));
591 ++i; // Skip the ID value.
592
593 switch (Flags & 7) {
594 default: assert(0 && "Bad flags!");
595 case 2: // Def of register.
596 for (; NumVals; --NumVals, ++i) {
597 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
598 MI->addOperand(MachineOperand::CreateReg(Reg, true));
599 }
600 break;
601 case 1: // Use of register.
602 case 3: // Immediate.
603 case 4: // Addressing mode.
604 // The addressing mode has been selected, just add all of the
605 // operands to the machine instruction.
606 for (; NumVals; --NumVals, ++i)
607 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
608 break;
609 }
610 }
611 BB->push_back(MI);
612 break;
613 }
614 }
615}
616
617void ScheduleDAG::EmitNoop() {
618 TII->insertNoop(*BB, BB->end());
619}
620
621void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
622 DenseMap<SUnit*, unsigned> &VRBaseMap) {
623 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
624 I != E; ++I) {
625 if (I->isCtrl) continue; // ignore chain preds
626 if (!I->Dep->Node) {
627 // Copy to physical register.
628 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
629 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
630 // Find the destination physical register.
631 unsigned Reg = 0;
632 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
633 EE = SU->Succs.end(); II != EE; ++II) {
634 if (I->Reg) {
635 Reg = I->Reg;
636 break;
637 }
638 }
639 assert(I->Reg && "Unknown physical register!");
640 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
641 SU->CopyDstRC, SU->CopySrcRC);
642 } else {
643 // Copy from physical register.
644 assert(I->Reg && "Unknown physical register!");
645 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
646 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
647 isNew = isNew; // Silence compiler warning.
648 assert(isNew && "Node emitted out of order - early");
649 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
650 SU->CopyDstRC, SU->CopySrcRC);
651 }
652 break;
653 }
654}
655
656/// EmitLiveInCopy - Emit a copy for a live in physical register. If the
657/// physical register has only a single copy use, then coalesced the copy
658/// if possible.
659void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
660 MachineBasicBlock::iterator &InsertPos,
661 unsigned VirtReg, unsigned PhysReg,
662 const TargetRegisterClass *RC,
663 DenseMap<MachineInstr*, unsigned> &CopyRegMap){
664 unsigned NumUses = 0;
665 MachineInstr *UseMI = NULL;
666 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
667 UE = MRI.use_end(); UI != UE; ++UI) {
668 UseMI = &*UI;
669 if (++NumUses > 1)
670 break;
671 }
672
673 // If the number of uses is not one, or the use is not a move instruction,
674 // don't coalesce. Also, only coalesce away a virtual register to virtual
675 // register copy.
676 bool Coalesced = false;
677 unsigned SrcReg, DstReg;
678 if (NumUses == 1 &&
679 TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
680 TargetRegisterInfo::isVirtualRegister(DstReg)) {
681 VirtReg = DstReg;
682 Coalesced = true;
683 }
684
685 // Now find an ideal location to insert the copy.
686 MachineBasicBlock::iterator Pos = InsertPos;
687 while (Pos != MBB->begin()) {
688 MachineInstr *PrevMI = prior(Pos);
689 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
690 // copyRegToReg might emit multiple instructions to do a copy.
691 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
692 if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
693 // This is what the BB looks like right now:
694 // r1024 = mov r0
695 // ...
696 // r1 = mov r1024
697 //
698 // We want to insert "r1025 = mov r1". Inserting this copy below the
699 // move to r1024 makes it impossible for that move to be coalesced.
700 //
701 // r1025 = mov r1
702 // r1024 = mov r0
703 // ...
704 // r1 = mov 1024
705 // r2 = mov 1025
706 break; // Woot! Found a good location.
707 --Pos;
708 }
709
710 TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
711 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
712 if (Coalesced) {
713 if (&*InsertPos == UseMI) ++InsertPos;
714 MBB->erase(UseMI);
715 }
716}
717
718/// EmitLiveInCopies - If this is the first basic block in the function,
719/// and if it has live ins that need to be copied into vregs, emit the
720/// copies into the top of the block.
721void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
722 DenseMap<MachineInstr*, unsigned> CopyRegMap;
723 MachineBasicBlock::iterator InsertPos = MBB->begin();
724 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
725 E = MRI.livein_end(); LI != E; ++LI)
726 if (LI->second) {
727 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
728 EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
729 }
730}
731
732/// EmitSchedule - Emit the machine code in scheduled order.
733MachineBasicBlock *ScheduleDAG::EmitSchedule() {
734 bool isEntryBB = &MF->front() == BB;
735
736 if (isEntryBB && !SchedLiveInCopies) {
737 // If this is the first basic block in the function, and if it has live ins
738 // that need to be copied into vregs, emit the copies into the top of the
739 // block before emitting the code for the block.
740 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
741 E = MRI.livein_end(); LI != E; ++LI)
742 if (LI->second) {
743 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
744 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
745 LI->first, RC, RC);
746 }
747 }
748
749 // Finally, emit the code for all of the scheduled instructions.
750 DenseMap<SDValue, unsigned> VRBaseMap;
751 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
752 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
753 SUnit *SU = Sequence[i];
754 if (!SU) {
755 // Null SUnit* is a noop.
756 EmitNoop();
757 continue;
758 }
759 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
760 EmitNode(SU->FlaggedNodes[j], SU->OrigNode != SU, VRBaseMap);
761 if (!SU->Node)
762 EmitCrossRCCopy(SU, CopyVRBaseMap);
763 else
764 EmitNode(SU->Node, SU->OrigNode != SU, VRBaseMap);
765 }
766
767 if (isEntryBB && SchedLiveInCopies)
768 EmitLiveInCopies(MF->begin());
769
770 return BB;
771}