Remove a bunch more SparcV9 specific stuff
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Support/MathExtras.h"
24 using namespace llvm;
25
26
27 /// CountResults - The results of target nodes have register or immediate
28 /// operands first, then an optional chain, and optional flag operands (which do
29 /// not go into the machine instrs.)
30 static unsigned CountResults(SDNode *Node) {
31   unsigned N = Node->getNumValues();
32   while (N && Node->getValueType(N - 1) == MVT::Flag)
33     --N;
34   if (N && Node->getValueType(N - 1) == MVT::Other)
35     --N;    // Skip over chain result.
36   return N;
37 }
38
39 /// CountOperands  The inputs to target nodes have any actual inputs first,
40 /// followed by an optional chain operand, then flag operands.  Compute the
41 /// number of actual operands that  will go into the machine instr.
42 static unsigned CountOperands(SDNode *Node) {
43   unsigned N = Node->getNumOperands();
44   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
45     --N;
46   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
47     --N; // Ignore chain if it exists.
48   return N;
49 }
50
51 static unsigned CreateVirtualRegisters(MachineInstr *MI,
52                                        unsigned NumResults,
53                                        SSARegMap *RegMap,
54                                        const TargetInstrDescriptor &II) {
55   // Create the result registers for this node and add the result regs to
56   // the machine instruction.
57   const TargetOperandInfo *OpInfo = II.OpInfo;
58   unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
59   MI->addRegOperand(ResultReg, MachineOperand::Def);
60   for (unsigned i = 1; i != NumResults; ++i) {
61     assert(OpInfo[i].RegClass && "Isn't a register operand!");
62     MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
63                       MachineOperand::Def);
64   }
65   return ResultReg;
66 }
67
68 /// getVR - Return the virtual register corresponding to the specified result
69 /// of the specified node.
70 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
71   std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
72   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
73   return I->second + Op.ResNo;
74 }
75
76
77 /// AddOperand - Add the specified operand to the specified machine instr.  II
78 /// specifies the instruction information for the node, and IIOpNum is the
79 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
80 /// assertions only.
81 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
82                              unsigned IIOpNum,
83                              const TargetInstrDescriptor *II,
84                              std::map<SDNode*, unsigned> &VRBaseMap) {
85   if (Op.isTargetOpcode()) {
86     // Note that this case is redundant with the final else block, but we
87     // include it because it is the most common and it makes the logic
88     // simpler here.
89     assert(Op.getValueType() != MVT::Other &&
90            Op.getValueType() != MVT::Flag &&
91            "Chain and flag operands should occur at end of operand list!");
92     
93     // Get/emit the operand.
94     unsigned VReg = getVR(Op, VRBaseMap);
95     MI->addRegOperand(VReg, MachineOperand::Use);
96     
97     // Verify that it is right.
98     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
99     if (II) {
100       assert(II->OpInfo[IIOpNum].RegClass &&
101              "Don't have operand info for this instruction!");
102       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
103              "Register class of operand and regclass of use don't agree!");
104     }
105   } else if (ConstantSDNode *C =
106              dyn_cast<ConstantSDNode>(Op)) {
107     MI->addZeroExtImm64Operand(C->getValue());
108   } else if (RegisterSDNode*R =
109              dyn_cast<RegisterSDNode>(Op)) {
110     MI->addRegOperand(R->getReg(), MachineOperand::Use);
111   } else if (GlobalAddressSDNode *TGA =
112              dyn_cast<GlobalAddressSDNode>(Op)) {
113     MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
114   } else if (BasicBlockSDNode *BB =
115              dyn_cast<BasicBlockSDNode>(Op)) {
116     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
117   } else if (FrameIndexSDNode *FI =
118              dyn_cast<FrameIndexSDNode>(Op)) {
119     MI->addFrameIndexOperand(FI->getIndex());
120   } else if (JumpTableSDNode *JT =
121              dyn_cast<JumpTableSDNode>(Op)) {
122     MI->addJumpTableIndexOperand(JT->getIndex());
123   } else if (ConstantPoolSDNode *CP = 
124              dyn_cast<ConstantPoolSDNode>(Op)) {
125     int Offset = CP->getOffset();
126     unsigned Align = CP->getAlignment();
127     // MachineConstantPool wants an explicit alignment.
128     if (Align == 0) {
129       if (CP->get()->getType() == Type::DoubleTy)
130         Align = 3;  // always 8-byte align doubles.
131       else {
132         Align = TM.getTargetData()
133           ->getTypeAlignmentShift(CP->get()->getType());
134         if (Align == 0) {
135           // Alignment of packed types.  FIXME!
136           Align = TM.getTargetData()->getTypeSize(CP->get()->getType());
137           Align = Log2_64(Align);
138         }
139       }
140     }
141     
142     unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
143     MI->addConstantPoolIndexOperand(Idx, Offset);
144   } else if (ExternalSymbolSDNode *ES = 
145              dyn_cast<ExternalSymbolSDNode>(Op)) {
146     MI->addExternalSymbolOperand(ES->getSymbol());
147   } else {
148     assert(Op.getValueType() != MVT::Other &&
149            Op.getValueType() != MVT::Flag &&
150            "Chain and flag operands should occur at end of operand list!");
151     unsigned VReg = getVR(Op, VRBaseMap);
152     MI->addRegOperand(VReg, MachineOperand::Use);
153     
154     // Verify that it is right.
155     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
156     if (II) {
157       assert(II->OpInfo[IIOpNum].RegClass &&
158              "Don't have operand info for this instruction!");
159       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
160              "Register class of operand and regclass of use don't agree!");
161     }
162   }
163   
164 }
165
166
167 /// EmitNode - Generate machine code for an node and needed dependencies.
168 ///
169 void ScheduleDAG::EmitNode(SDNode *Node, 
170                            std::map<SDNode*, unsigned> &VRBaseMap) {
171   unsigned VRBase = 0;                 // First virtual register for node
172   
173   // If machine instruction
174   if (Node->isTargetOpcode()) {
175     unsigned Opc = Node->getTargetOpcode();
176     const TargetInstrDescriptor &II = TII->get(Opc);
177
178     unsigned NumResults = CountResults(Node);
179     unsigned NodeOperands = CountOperands(Node);
180     unsigned NumMIOperands = NodeOperands + NumResults;
181 #ifndef NDEBUG
182     assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
183            "#operands for dag node doesn't match .td file!"); 
184 #endif
185
186     // Create the new machine instruction.
187     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
188     
189     // Add result register values for things that are defined by this
190     // instruction.
191     
192     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
193     // the CopyToReg'd destination register instead of creating a new vreg.
194     if (NumResults == 1) {
195       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
196            UI != E; ++UI) {
197         SDNode *Use = *UI;
198         if (Use->getOpcode() == ISD::CopyToReg && 
199             Use->getOperand(2).Val == Node) {
200           unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
201           if (MRegisterInfo::isVirtualRegister(Reg)) {
202             VRBase = Reg;
203             MI->addRegOperand(Reg, MachineOperand::Def);
204             break;
205           }
206         }
207       }
208     }
209     
210     // Otherwise, create new virtual registers.
211     if (NumResults && VRBase == 0)
212       VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
213     
214     // Emit all of the actual operands of this instruction, adding them to the
215     // instruction as appropriate.
216     for (unsigned i = 0; i != NodeOperands; ++i)
217       AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
218     
219     // Now that we have emitted all operands, emit this instruction itself.
220     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
221       BB->insert(BB->end(), MI);
222     } else {
223       // Insert this instruction into the end of the basic block, potentially
224       // taking some custom action.
225       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
226     }
227   } else {
228     switch (Node->getOpcode()) {
229     default:
230       Node->dump(); 
231       assert(0 && "This target-independent node should have been selected!");
232     case ISD::EntryToken: // fall thru
233     case ISD::TokenFactor:
234       break;
235     case ISD::CopyToReg: {
236       unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
237       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
238       if (InReg != DestReg)   // Coalesced away the copy?
239         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
240                           RegMap->getRegClass(InReg));
241       break;
242     }
243     case ISD::CopyFromReg: {
244       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
245       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
246         VRBase = SrcReg;  // Just use the input register directly!
247         break;
248       }
249
250       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
251       // the CopyToReg'd destination register instead of creating a new vreg.
252       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
253            UI != E; ++UI) {
254         SDNode *Use = *UI;
255         if (Use->getOpcode() == ISD::CopyToReg && 
256             Use->getOperand(2).Val == Node) {
257           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
258           if (MRegisterInfo::isVirtualRegister(DestReg)) {
259             VRBase = DestReg;
260             break;
261           }
262         }
263       }
264
265       // Figure out the register class to create for the destreg.
266       const TargetRegisterClass *TRC = 0;
267       if (VRBase) {
268         TRC = RegMap->getRegClass(VRBase);
269       } else {
270
271         // Pick the register class of the right type that contains this physreg.
272         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
273              E = MRI->regclass_end(); I != E; ++I)
274           if ((*I)->hasType(Node->getValueType(0)) &&
275               (*I)->contains(SrcReg)) {
276             TRC = *I;
277             break;
278           }
279         assert(TRC && "Couldn't find register class for reg copy!");
280       
281         // Create the reg, emit the copy.
282         VRBase = RegMap->createVirtualRegister(TRC);
283       }
284       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
285       break;
286     }
287     case ISD::INLINEASM: {
288       unsigned NumOps = Node->getNumOperands();
289       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
290         --NumOps;  // Ignore the flag operand.
291       
292       // Create the inline asm machine instruction.
293       MachineInstr *MI =
294         new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
295
296       // Add the asm string as an external symbol operand.
297       const char *AsmStr =
298         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
299       MI->addExternalSymbolOperand(AsmStr);
300       
301       // Add all of the operand registers to the instruction.
302       for (unsigned i = 2; i != NumOps;) {
303         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
304         unsigned NumVals = Flags >> 3;
305         
306         MI->addZeroExtImm64Operand(Flags);
307         ++i;  // Skip the ID value.
308         
309         switch (Flags & 7) {
310         default: assert(0 && "Bad flags!");
311         case 1:  // Use of register.
312           for (; NumVals; --NumVals, ++i) {
313             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
314             MI->addRegOperand(Reg, MachineOperand::Use);
315           }
316           break;
317         case 2:   // Def of register.
318           for (; NumVals; --NumVals, ++i) {
319             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
320             MI->addRegOperand(Reg, MachineOperand::Def);
321           }
322           break;
323         case 3: { // Immediate.
324           assert(NumVals == 1 && "Unknown immediate value!");
325           uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
326           MI->addZeroExtImm64Operand(Val);
327           ++i;
328           break;
329         }
330         case 4:  // Addressing mode.
331           // The addressing mode has been selected, just add all of the
332           // operands to the machine instruction.
333           for (; NumVals; --NumVals, ++i)
334             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
335           break;
336         }
337       }
338       break;
339     }
340     }
341   }
342
343   assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
344   VRBaseMap[Node] = VRBase;
345 }
346
347 void ScheduleDAG::EmitNoop() {
348   TII->insertNoop(*BB, BB->end());
349 }
350
351 /// Run - perform scheduling.
352 ///
353 MachineBasicBlock *ScheduleDAG::Run() {
354   TII = TM.getInstrInfo();
355   MRI = TM.getRegisterInfo();
356   RegMap = BB->getParent()->getSSARegMap();
357   ConstPool = BB->getParent()->getConstantPool();
358
359   Schedule();
360   return BB;
361 }
362
363