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