Fully implement frame index, so that we can pass the address of alloca's
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPC32ISelDAGToDAG.cpp - PPC32 pattern matching inst selector ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for 32 bit PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PowerPC.h"
16 #include "PPC32TargetMachine.h"
17 #include "PPC32ISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/GlobalValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 using namespace llvm;
29
30 namespace {
31   Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
32   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
33     
34   //===--------------------------------------------------------------------===//
35   /// PPC32DAGToDAGISel - PPC32 specific code to select PPC32 machine
36   /// instructions for SelectionDAG operations.
37   ///
38   class PPC32DAGToDAGISel : public SelectionDAGISel {
39     PPC32TargetLowering PPC32Lowering;
40     unsigned GlobalBaseReg;
41   public:
42     PPC32DAGToDAGISel(TargetMachine &TM)
43       : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) {}
44     
45     virtual bool runOnFunction(Function &Fn) {
46       // Make sure we re-emit a set of the global base reg if necessary
47       GlobalBaseReg = 0;
48       return SelectionDAGISel::runOnFunction(Fn);
49     }
50    
51     /// getI32Imm - Return a target constant with the specified value, of type
52     /// i32.
53     inline SDOperand getI32Imm(unsigned Imm) {
54       return CurDAG->getTargetConstant(Imm, MVT::i32);
55     }
56
57     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
58     /// base register.  Return the virtual register that holds this value.
59     SDOperand getGlobalBaseReg();
60     
61     // Select - Convert the specified operand from a target-independent to a
62     // target-specific node if it hasn't already been changed.
63     SDOperand Select(SDOperand Op);
64     
65     SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
66                                    unsigned OCHi, unsigned OCLo,
67                                    bool IsArithmetic = false,
68                                    bool Negate = false);
69     SDNode *SelectBitfieldInsert(SDNode *N);
70
71     /// SelectCC - Select a comparison of the specified values with the
72     /// specified condition code, returning the CR# of the expression.
73     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
74
75     /// SelectAddr - Given the specified address, return the two operands for a
76     /// load/store instruction, and return true if it should be an indexed [r+r]
77     /// operation.
78     bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
79
80     /// InstructionSelectBasicBlock - This callback is invoked by
81     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
82     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
83       DEBUG(BB->dump());
84       // Select target instructions for the DAG.
85       Select(DAG.getRoot());
86       DAG.RemoveDeadNodes();
87       
88       // Emit machine code to BB. 
89       ScheduleAndEmitDAG(DAG);
90     }
91  
92     virtual const char *getPassName() const {
93       return "PowerPC DAG->DAG Pattern Instruction Selection";
94     } 
95   };
96 }
97
98 /// getGlobalBaseReg - Output the instructions required to put the
99 /// base address to use for accessing globals into a register.
100 ///
101 SDOperand PPC32DAGToDAGISel::getGlobalBaseReg() {
102   if (!GlobalBaseReg) {
103     // Insert the set of GlobalBaseReg into the first MBB of the function
104     MachineBasicBlock &FirstMBB = BB->getParent()->front();
105     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
106     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
107     GlobalBaseReg = RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
108     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
109     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
110   }
111   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
112 }
113
114
115 // isIntImmediate - This method tests to see if a constant operand.
116 // If so Imm will receive the 32 bit value.
117 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
118   if (N->getOpcode() == ISD::Constant) {
119     Imm = cast<ConstantSDNode>(N)->getValue();
120     return true;
121   }
122   return false;
123 }
124
125 // isOprShiftImm - Returns true if the specified operand is a shift opcode with
126 // a immediate shift count less than 32.
127 static bool isOprShiftImm(SDNode *N, unsigned& Opc, unsigned& SH) {
128   Opc = N->getOpcode();
129   return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
130     isIntImmediate(N->getOperand(1).Val, SH) && SH < 32;
131 }
132
133 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
134 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
135 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
136 // not, since all 1s are not contiguous.
137 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
138   if (isShiftedMask_32(Val)) {
139     // look for the first non-zero bit
140     MB = CountLeadingZeros_32(Val);
141     // look for the first zero bit after the run of ones
142     ME = CountLeadingZeros_32((Val - 1) ^ Val);
143     return true;
144   } else if (isShiftedMask_32(Val = ~Val)) { // invert mask
145                                              // effectively look for the first zero bit
146     ME = CountLeadingZeros_32(Val) - 1;
147     // effectively look for the first one bit after the run of zeros
148     MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
149     return true;
150   }
151   // no run present
152   return false;
153 }
154
155 // isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
156 // and mask opcode and mask operation.
157 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
158                             unsigned &SH, unsigned &MB, unsigned &ME) {
159   unsigned Shift  = 32;
160   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
161   unsigned Opcode = N->getOpcode();
162   if (!isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
163     return false;
164   
165   if (Opcode == ISD::SHL) {
166     // apply shift left to mask if it comes first
167     if (IsShiftMask) Mask = Mask << Shift;
168     // determine which bits are made indeterminant by shift
169     Indeterminant = ~(0xFFFFFFFFu << Shift);
170   } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) { 
171     // apply shift right to mask if it comes first
172     if (IsShiftMask) Mask = Mask >> Shift;
173     // determine which bits are made indeterminant by shift
174     Indeterminant = ~(0xFFFFFFFFu >> Shift);
175     // adjust for the left rotate
176     Shift = 32 - Shift;
177   } else {
178     return false;
179   }
180   
181   // if the mask doesn't intersect any Indeterminant bits
182   if (Mask && !(Mask & Indeterminant)) {
183     SH = Shift;
184     // make sure the mask is still a mask (wrap arounds may not be)
185     return isRunOfOnes(Mask, MB, ME);
186   }
187   return false;
188 }
189
190 // isOpcWithIntImmediate - This method tests to see if the node is a specific
191 // opcode and that it has a immediate integer right operand.
192 // If so Imm will receive the 32 bit value.
193 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
194   return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
195 }
196
197 // isOprNot - Returns true if the specified operand is an xor with immediate -1.
198 static bool isOprNot(SDNode *N) {
199   unsigned Imm;
200   return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
201 }
202
203 // Immediate constant composers.
204 // Lo16 - grabs the lo 16 bits from a 32 bit constant.
205 // Hi16 - grabs the hi 16 bits from a 32 bit constant.
206 // HA16 - computes the hi bits required if the lo bits are add/subtracted in
207 // arithmethically.
208 static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
209 static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
210 static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }
211
212 // isIntImmediate - This method tests to see if a constant operand.
213 // If so Imm will receive the 32 bit value.
214 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
215   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
216     Imm = (unsigned)CN->getSignExtended();
217     return true;
218   }
219   return false;
220 }
221
222 /// SelectBitfieldInsert - turn an or of two masked values into
223 /// the rotate left word immediate then mask insert (rlwimi) instruction.
224 /// Returns true on success, false if the caller still needs to select OR.
225 ///
226 /// Patterns matched:
227 /// 1. or shl, and   5. or and, and
228 /// 2. or and, shl   6. or shl, shr
229 /// 3. or shr, and   7. or shr, shl
230 /// 4. or and, shr
231 SDNode *PPC32DAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
232   bool IsRotate = false;
233   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
234   unsigned Value;
235   
236   SDOperand Op0 = N->getOperand(0);
237   SDOperand Op1 = N->getOperand(1);
238   
239   unsigned Op0Opc = Op0.getOpcode();
240   unsigned Op1Opc = Op1.getOpcode();
241   
242   // Verify that we have the correct opcodes
243   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
244     return false;
245   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
246     return false;
247   
248   // Generate Mask value for Target
249   if (isIntImmediate(Op0.getOperand(1), Value)) {
250     switch(Op0Opc) {
251       case ISD::SHL: TgtMask <<= Value; break;
252       case ISD::SRL: TgtMask >>= Value; break;
253       case ISD::AND: TgtMask &= Value; break;
254     }
255   } else {
256     return 0;
257   }
258   
259   // Generate Mask value for Insert
260   if (isIntImmediate(Op1.getOperand(1), Value)) {
261     switch(Op1Opc) {
262       case ISD::SHL:
263         SH = Value;
264         InsMask <<= SH;
265         if (Op0Opc == ISD::SRL) IsRotate = true;
266           break;
267       case ISD::SRL:
268         SH = Value;
269         InsMask >>= SH;
270         SH = 32-SH;
271         if (Op0Opc == ISD::SHL) IsRotate = true;
272           break;
273       case ISD::AND:
274         InsMask &= Value;
275         break;
276     }
277   } else {
278     return 0;
279   }
280   
281   // If both of the inputs are ANDs and one of them has a logical shift by
282   // constant as its input, make that AND the inserted value so that we can
283   // combine the shift into the rotate part of the rlwimi instruction
284   bool IsAndWithShiftOp = false;
285   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
286     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
287         Op1.getOperand(0).getOpcode() == ISD::SRL) {
288       if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
289         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
290         IsAndWithShiftOp = true;
291       }
292     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
293                Op0.getOperand(0).getOpcode() == ISD::SRL) {
294       if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
295         std::swap(Op0, Op1);
296         std::swap(TgtMask, InsMask);
297         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
298         IsAndWithShiftOp = true;
299       }
300     }
301   }
302   
303   // Verify that the Target mask and Insert mask together form a full word mask
304   // and that the Insert mask is a run of set bits (which implies both are runs
305   // of set bits).  Given that, Select the arguments and generate the rlwimi
306   // instruction.
307   unsigned MB, ME;
308   if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
309     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
310     bool Op0IsAND = Op0Opc == ISD::AND;
311     // Check for rotlwi / rotrwi here, a special case of bitfield insert
312     // where both bitfield halves are sourced from the same value.
313     if (IsRotate && fullMask &&
314         N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
315       Op0 = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32,
316                                   Select(N->getOperand(0).getOperand(0)),
317                                   getI32Imm(SH), getI32Imm(0), getI32Imm(31));
318       return Op0.Val;
319     }
320     SDOperand Tmp1 = (Op0IsAND && fullMask) ? Select(Op0.getOperand(0))
321                                             : Select(Op0);
322     SDOperand Tmp2 = IsAndWithShiftOp ? Select(Op1.getOperand(0).getOperand(0)) 
323                                       : Select(Op1.getOperand(0));
324     Op0 = CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
325                                 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
326     return Op0.Val;
327   }
328   return 0;
329 }
330
331 // SelectIntImmediateExpr - Choose code for integer operations with an immediate
332 // operand.
333 SDNode *PPC32DAGToDAGISel::SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
334                                                   unsigned OCHi, unsigned OCLo,
335                                                   bool IsArithmetic,
336                                                   bool Negate) {
337   // Check to make sure this is a constant.
338   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS);
339   // Exit if not a constant.
340   if (!CN) return 0;
341   // Extract immediate.
342   unsigned C = (unsigned)CN->getValue();
343   // Negate if required (ISD::SUB).
344   if (Negate) C = -C;
345   // Get the hi and lo portions of constant.
346   unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
347   unsigned Lo = Lo16(C);
348
349   // If two instructions are needed and usage indicates it would be better to
350   // load immediate into a register, bail out.
351   if (Hi && Lo && CN->use_size() > 2) return false;
352
353   // Select the first operand.
354   SDOperand Opr0 = Select(LHS);
355
356   if (Lo)  // Add in the lo-part.
357     Opr0 = CurDAG->getTargetNode(OCLo, MVT::i32, Opr0, getI32Imm(Lo));
358   if (Hi)  // Add in the hi-part.
359     Opr0 = CurDAG->getTargetNode(OCHi, MVT::i32, Opr0, getI32Imm(Hi));
360   return Opr0.Val;
361 }
362
363 /// SelectAddr - Given the specified address, return the two operands for a
364 /// load/store instruction, and return true if it should be an indexed [r+r]
365 /// operation.
366 bool PPC32DAGToDAGISel::SelectAddr(SDOperand Addr, SDOperand &Op1,
367                                    SDOperand &Op2) {
368   unsigned imm = 0;
369   if (Addr.getOpcode() == ISD::ADD) {
370     if (isIntImmediate(Addr.getOperand(1), imm) && isInt16(imm)) {
371       Op1 = getI32Imm(Lo16(imm));
372       if (FrameIndexSDNode *FI =
373             dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
374         ++FrameOff;
375         Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
376       } else {
377         Op2 = Select(Addr.getOperand(0));
378       }
379       return false;
380     } else {
381       Op1 = Select(Addr.getOperand(0));
382       Op2 = Select(Addr.getOperand(1));
383       return true;   // [r+r]
384     }
385   }
386
387   // Now check if we're dealing with a global, and whether or not we should emit
388   // an optimized load or store for statics.
389   if (GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Addr)) {
390     GlobalValue *GV = GN->getGlobal();
391     if (!GV->hasWeakLinkage() && !GV->isExternal()) {
392       Op1 = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
393       if (PICEnabled)
394         Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),
395                                     Op1);
396       else
397         Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
398       return false;
399     }
400   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Addr)) {
401     Op1 = getI32Imm(0);
402     Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
403     return false;
404   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Addr)) {
405     Op1 = Addr;
406     if (PICEnabled)
407       Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),Op1);
408     else
409       Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
410     return false;
411   }
412   Op1 = getI32Imm(0);
413   Op2 = Select(Addr);
414   return false;
415 }
416
417 /// SelectCC - Select a comparison of the specified values with the specified
418 /// condition code, returning the CR# of the expression.
419 SDOperand PPC32DAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
420                                       ISD::CondCode CC) {
421   // Always select the LHS.
422   LHS = Select(LHS);
423
424   // Use U to determine whether the SETCC immediate range is signed or not.
425   if (MVT::isInteger(LHS.getValueType())) {
426     bool U = ISD::isUnsignedIntSetCC(CC);
427     unsigned Imm;
428     if (isIntImmediate(RHS, Imm) && 
429         ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
430       return CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI, MVT::i32,
431                                    LHS, getI32Imm(Lo16(Imm)));
432     return CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
433                                  LHS, Select(RHS));
434   } else {
435     return CurDAG->getTargetNode(PPC::FCMPU, MVT::i32, LHS, Select(RHS));
436   }
437 }
438
439 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
440 /// to Condition.
441 static unsigned getBCCForSetCC(ISD::CondCode CC) {
442   switch (CC) {
443   default: assert(0 && "Unknown condition!"); abort();
444   case ISD::SETEQ:  return PPC::BEQ;
445   case ISD::SETNE:  return PPC::BNE;
446   case ISD::SETULT:
447   case ISD::SETLT:  return PPC::BLT;
448   case ISD::SETULE:
449   case ISD::SETLE:  return PPC::BLE;
450   case ISD::SETUGT:
451   case ISD::SETGT:  return PPC::BGT;
452   case ISD::SETUGE:
453   case ISD::SETGE:  return PPC::BGE;
454   }
455   return 0;
456 }
457
458
459 // Select - Convert the specified operand from a target-independent to a
460 // target-specific node if it hasn't already been changed.
461 SDOperand PPC32DAGToDAGISel::Select(SDOperand Op) {
462   SDNode *N = Op.Val;
463   if (N->getOpcode() >= ISD::BUILTIN_OP_END)
464     return Op;   // Already selected.
465   
466   switch (N->getOpcode()) {
467   default:
468     std::cerr << "Cannot yet select: ";
469     N->dump();
470     std::cerr << "\n";
471     abort();
472   case ISD::EntryToken:       // These leaves remain the same.
473     return Op;
474   case ISD::TokenFactor: {
475     SDOperand New;
476     if (N->getNumOperands() == 2) {
477       SDOperand Op0 = Select(N->getOperand(0));
478       SDOperand Op1 = Select(N->getOperand(1));
479       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
480     } else {
481       std::vector<SDOperand> Ops;
482       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
483         Ops.push_back(Select(N->getOperand(i)));
484       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
485     }
486     
487     if (New.Val != N) {
488       CurDAG->ReplaceAllUsesWith(N, New.Val);
489       N = New.Val;
490     }
491     break;
492   }
493   case ISD::CopyFromReg: {
494     SDOperand Chain = Select(N->getOperand(0));
495     if (Chain == N->getOperand(0)) return Op; // No change
496     SDOperand New = CurDAG->getCopyFromReg(Chain,
497          cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
498     return New.getValue(Op.ResNo);
499   }
500   case ISD::CopyToReg: {
501     SDOperand Chain = Select(N->getOperand(0));
502     SDOperand Reg = N->getOperand(1);
503     SDOperand Val = Select(N->getOperand(2));
504     if (Chain != N->getOperand(0) || Val != N->getOperand(2)) {
505       SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
506                                       Chain, Reg, Val);
507       CurDAG->ReplaceAllUsesWith(N, New.Val);
508       N = New.Val;
509     }
510     break;    
511   }
512   case ISD::Constant: {
513     assert(N->getValueType(0) == MVT::i32);
514     unsigned v = (unsigned)cast<ConstantSDNode>(N)->getValue();
515     unsigned Hi = HA16(v);
516     unsigned Lo = Lo16(v);
517     if (Hi && Lo) {
518       SDOperand Top = CurDAG->getTargetNode(PPC::LIS, MVT::i32, 
519                                             getI32Imm(v >> 16));
520       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORI, Top, getI32Imm(v & 0xFFFF));
521     } else if (Lo) {
522       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LI, getI32Imm(v));
523     } else {
524       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LIS, getI32Imm(v >> 16));
525     }
526     break;
527   }
528   case ISD::UNDEF:
529     if (N->getValueType(0) == MVT::i32)
530       CurDAG->SelectNodeTo(N, MVT::i32, PPC::IMPLICIT_DEF_GPR);
531     else
532       CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::IMPLICIT_DEF_FP);
533     break;
534   case ISD::FrameIndex: {
535     int FI = cast<FrameIndexSDNode>(N)->getIndex();
536     CurDAG->SelectNodeTo(N, MVT::i32, PPC::ADDI,
537                          CurDAG->getTargetFrameIndex(FI, MVT::i32),
538                          getI32Imm(0));
539     break;
540   }
541   case ISD::GlobalAddress: {
542     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
543     SDOperand Tmp;
544     SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
545     if (PICEnabled)
546       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(), GA);
547     else
548       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, GA);
549
550     if (GV->hasWeakLinkage() || GV->isExternal())
551       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LWZ, GA, Tmp);
552     else
553       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LA, Tmp, GA);
554     break;
555   }
556   case ISD::SIGN_EXTEND_INREG:
557     switch(cast<VTSDNode>(N->getOperand(1))->getVT()) {
558     default: assert(0 && "Illegal type in SIGN_EXTEND_INREG"); break;
559     case MVT::i16:
560       CurDAG->SelectNodeTo(N, MVT::i32, PPC::EXTSH, Select(N->getOperand(0)));
561       break;
562     case MVT::i8:
563       CurDAG->SelectNodeTo(N, MVT::i32, PPC::EXTSB, Select(N->getOperand(0)));
564       break;
565     }
566     break;
567   case ISD::CTLZ:
568     assert(N->getValueType(0) == MVT::i32);
569     CurDAG->SelectNodeTo(N, MVT::i32, PPC::CNTLZW, Select(N->getOperand(0)));
570     break;
571   case ISD::ADD: {
572     MVT::ValueType Ty = N->getValueType(0);
573     if (Ty == MVT::i32) {
574       if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
575                                              PPC::ADDIS, PPC::ADDI, true)) {
576         CurDAG->ReplaceAllUsesWith(N, I);
577         N = I;
578       } else {
579         CurDAG->SelectNodeTo(N, Ty, PPC::ADD, Select(N->getOperand(0)),
580                              Select(N->getOperand(1)));
581       }
582       break;
583     }
584     
585     if (!NoExcessFPPrecision) {  // Match FMA ops
586       if (N->getOperand(0).getOpcode() == ISD::MUL &&
587           N->getOperand(0).Val->hasOneUse()) {
588         ++FusedFP; // Statistic
589         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS,
590                              Select(N->getOperand(0).getOperand(0)),
591                              Select(N->getOperand(0).getOperand(1)),
592                              Select(N->getOperand(1)));
593         break;
594       } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
595                  N->getOperand(1).hasOneUse()) {
596         ++FusedFP; // Statistic
597         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS,
598                              Select(N->getOperand(1).getOperand(0)),
599                              Select(N->getOperand(1).getOperand(1)),
600                              Select(N->getOperand(0)));
601         break;
602       }
603     }
604     
605     CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FADD : PPC::FADDS,
606                          Select(N->getOperand(0)), Select(N->getOperand(1)));
607     break;
608   }
609   case ISD::SUB: {
610     MVT::ValueType Ty = N->getValueType(0);
611     if (Ty == MVT::i32) {
612       unsigned Imm;
613       if (isIntImmediate(N->getOperand(0), Imm) && isInt16(Imm)) {
614         if (0 == Imm)
615           CurDAG->SelectNodeTo(N, Ty, PPC::NEG, Select(N->getOperand(1)));
616         else
617           CurDAG->SelectNodeTo(N, Ty, PPC::SUBFIC, Select(N->getOperand(1)),
618                                getI32Imm(Lo16(Imm)));
619         break;
620       }
621       if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
622                                           PPC::ADDIS, PPC::ADDI, true, true)) {
623         CurDAG->ReplaceAllUsesWith(N, I);
624         N = I;
625       } else {
626         CurDAG->SelectNodeTo(N, Ty, PPC::SUBF, Select(N->getOperand(1)),
627                              Select(N->getOperand(0)));
628       }
629       break;
630     }
631     
632     if (!NoExcessFPPrecision) {  // Match FMA ops
633       if (N->getOperand(0).getOpcode() == ISD::MUL &&
634           N->getOperand(0).Val->hasOneUse()) {
635         ++FusedFP; // Statistic
636         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS,
637                              Select(N->getOperand(0).getOperand(0)),
638                              Select(N->getOperand(0).getOperand(1)),
639                              Select(N->getOperand(1)));
640         break;
641       } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
642                  N->getOperand(1).Val->hasOneUse()) {
643         ++FusedFP; // Statistic
644         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS,
645                              Select(N->getOperand(1).getOperand(0)),
646                              Select(N->getOperand(1).getOperand(1)),
647                              Select(N->getOperand(0)));
648         break;
649       }
650     }
651     CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FSUB : PPC::FSUBS,
652                          Select(N->getOperand(0)),
653                          Select(N->getOperand(1)));
654     break;
655   }
656   case ISD::MUL: {
657     unsigned Imm, Opc;
658     if (isIntImmediate(N->getOperand(1), Imm) && isInt16(Imm)) {
659       CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::MULLI, 
660                            Select(N->getOperand(0)), getI32Imm(Lo16(Imm)));
661       break;
662     } 
663     switch (N->getValueType(0)) {
664       default: assert(0 && "Unhandled multiply type!");
665       case MVT::i32: Opc = PPC::MULLW; break;
666       case MVT::f32: Opc = PPC::FMULS; break;
667       case MVT::f64: Opc = PPC::FMUL;  break;
668     }
669     CurDAG->SelectNodeTo(N, N->getValueType(0), Opc, Select(N->getOperand(0)), 
670                          Select(N->getOperand(1)));
671     break;
672   }
673   case ISD::MULHS:
674     assert(N->getValueType(0) == MVT::i32);
675     CurDAG->SelectNodeTo(N, MVT::i32, PPC::MULHW, Select(N->getOperand(0)), 
676                          Select(N->getOperand(1)));
677     break;
678   case ISD::MULHU:
679     assert(N->getValueType(0) == MVT::i32);
680     CurDAG->SelectNodeTo(N, MVT::i32, PPC::MULHWU, Select(N->getOperand(0)),
681                          Select(N->getOperand(1)));
682     break;
683   case ISD::AND: {
684     unsigned Imm;
685     // If this is an and of a value rotated between 0 and 31 bits and then and'd
686     // with a mask, emit rlwinm
687     if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
688                                                   isShiftedMask_32(~Imm))) {
689       SDOperand Val;
690       unsigned SH, MB, ME;
691       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
692         Val = Select(N->getOperand(0).getOperand(0));
693       } else {
694         Val = Select(N->getOperand(0));
695         isRunOfOnes(Imm, MB, ME);
696         SH = 0;
697       }
698       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Val, getI32Imm(SH),
699                            getI32Imm(MB), getI32Imm(ME));
700       break;
701     }
702     // If this is an and with an immediate that isn't a mask, then codegen it as
703     // high and low 16 bit immediate ands.
704     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
705                                            N->getOperand(1),
706                                            PPC::ANDISo, PPC::ANDIo)) {
707       CurDAG->ReplaceAllUsesWith(N, I); 
708       N = I;
709       break;
710     }
711     // Finally, check for the case where we are being asked to select
712     // and (not(a), b) or and (a, not(b)) which can be selected as andc.
713     if (isOprNot(N->getOperand(0).Val))
714       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ANDC, Select(N->getOperand(1)),
715                            Select(N->getOperand(0).getOperand(0)));
716     else if (isOprNot(N->getOperand(1).Val))
717       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ANDC, Select(N->getOperand(0)),
718                            Select(N->getOperand(1).getOperand(0)));
719     else
720       CurDAG->SelectNodeTo(N, MVT::i32, PPC::AND, Select(N->getOperand(0)),
721                            Select(N->getOperand(1)));
722     break;
723   }
724   case ISD::OR:
725     if (SDNode *I = SelectBitfieldInsert(N)) {
726       CurDAG->ReplaceAllUsesWith(N, I);
727       N = I;
728       break;
729     }
730     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
731                                            N->getOperand(1),
732                                            PPC::ORIS, PPC::ORI)) {
733       CurDAG->ReplaceAllUsesWith(N, I); 
734       N = I;
735       break;
736     }
737     // Finally, check for the case where we are being asked to select
738     // 'or (not(a), b)' or 'or (a, not(b))' which can be selected as orc.
739     if (isOprNot(N->getOperand(0).Val))
740       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORC, Select(N->getOperand(1)),
741                            Select(N->getOperand(0).getOperand(0)));
742     else if (isOprNot(N->getOperand(1).Val))
743       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORC, Select(N->getOperand(0)),
744                            Select(N->getOperand(1).getOperand(0)));
745     else
746       CurDAG->SelectNodeTo(N, MVT::i32, PPC::OR, Select(N->getOperand(0)),
747                            Select(N->getOperand(1)));
748     break;
749   case ISD::XOR:
750     // Check whether or not this node is a logical 'not'.  This is represented
751     // by llvm as a xor with the constant value -1 (all bits set).  If this is a
752     // 'not', then fold 'or' into 'nor', and so forth for the supported ops.
753     if (isOprNot(N)) {
754       unsigned Opc;
755       SDOperand Val = Select(N->getOperand(0));
756       switch (Val.getTargetOpcode()) {
757       default:        Opc = 0;          break;
758       case PPC::OR:   Opc = PPC::NOR;   break;
759       case PPC::AND:  Opc = PPC::NAND;  break;
760       case PPC::XOR:  Opc = PPC::EQV;   break;
761       }
762       if (Opc)
763         CurDAG->SelectNodeTo(N, MVT::i32, Opc, Val.getOperand(0),
764                              Val.getOperand(1));
765       else
766         CurDAG->SelectNodeTo(N, MVT::i32, PPC::NOR, Val, Val);
767       break;
768     }
769     // If this is a xor with an immediate other than -1, then codegen it as high
770     // and low 16 bit immediate xors.
771     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
772                                            N->getOperand(1),
773                                            PPC::XORIS, PPC::XORI)) {
774       CurDAG->ReplaceAllUsesWith(N, I); 
775       N = I;
776       break;
777     }
778     // Finally, check for the case where we are being asked to select
779     // xor (not(a), b) which is equivalent to not(xor a, b), which is eqv
780     if (isOprNot(N->getOperand(0).Val))
781       CurDAG->SelectNodeTo(N, MVT::i32, PPC::EQV, 
782                            Select(N->getOperand(0).getOperand(0)),
783                            Select(N->getOperand(1)));
784     else
785       CurDAG->SelectNodeTo(N, MVT::i32, PPC::XOR, Select(N->getOperand(0)),
786                            Select(N->getOperand(1)));
787     break;
788   case ISD::SHL: {
789     unsigned Imm, SH, MB, ME;
790     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
791         isRotateAndMask(N, Imm, true, SH, MB, ME))
792       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, 
793                            Select(N->getOperand(0).getOperand(0)),
794                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
795     else if (isIntImmediate(N->getOperand(1), Imm))
796       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Select(N->getOperand(0)),
797                            getI32Imm(Imm), getI32Imm(0), getI32Imm(31-Imm));
798     else
799       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SLW, Select(N->getOperand(0)),
800                            Select(N->getOperand(1)));
801     break;
802   }
803   case ISD::SRL: {
804     unsigned Imm, SH, MB, ME;
805     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
806         isRotateAndMask(N, Imm, true, SH, MB, ME))
807       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, 
808                            Select(N->getOperand(0).getOperand(0)),
809                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
810     else if (isIntImmediate(N->getOperand(1), Imm))
811       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Select(N->getOperand(0)),
812                            getI32Imm(32-Imm), getI32Imm(Imm), getI32Imm(31));
813     else
814       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRW, Select(N->getOperand(0)),
815                            Select(N->getOperand(1)));
816     break;
817   }
818   case ISD::SRA: {
819     unsigned Imm, SH, MB, ME;
820     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
821         isRotateAndMask(N, Imm, true, SH, MB, ME))
822       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, 
823                            Select(N->getOperand(0).getOperand(0)),
824                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
825     else if (isIntImmediate(N->getOperand(1), Imm))
826       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRAWI, Select(N->getOperand(0)), 
827                            getI32Imm(Imm));
828     else
829       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRAW, Select(N->getOperand(0)),
830                            Select(N->getOperand(1)));
831     break;
832   }
833   case ISD::FABS:
834     CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::FABS, 
835                          Select(N->getOperand(0)));
836     break;
837   case ISD::FP_EXTEND:
838     assert(MVT::f64 == N->getValueType(0) && 
839            MVT::f32 == N->getOperand(0).getValueType() && "Illegal FP_EXTEND");
840     CurDAG->SelectNodeTo(N, MVT::f64, PPC::FMR, Select(N->getOperand(0)));
841     break;
842   case ISD::FP_ROUND:
843     assert(MVT::f32 == N->getValueType(0) && 
844            MVT::f64 == N->getOperand(0).getValueType() && "Illegal FP_ROUND");
845     CurDAG->SelectNodeTo(N, MVT::f32, PPC::FRSP, Select(N->getOperand(0)));
846     break;
847   case ISD::FNEG: {
848     SDOperand Val = Select(N->getOperand(0));
849     MVT::ValueType Ty = N->getValueType(0);
850     if (Val.Val->hasOneUse()) {
851       unsigned Opc;
852       switch (Val.getTargetOpcode()) {
853       default:          Opc = 0;            break;
854       case PPC::FABS:   Opc = PPC::FNABS;   break;
855       case PPC::FMADD:  Opc = PPC::FNMADD;  break;
856       case PPC::FMADDS: Opc = PPC::FNMADDS; break;
857       case PPC::FMSUB:  Opc = PPC::FNMSUB;  break;
858       case PPC::FMSUBS: Opc = PPC::FNMSUBS; break;
859       }
860       // If we inverted the opcode, then emit the new instruction with the
861       // inverted opcode and the original instruction's operands.  Otherwise, 
862       // fall through and generate a fneg instruction.
863       if (Opc) {
864         if (PPC::FNABS == Opc)
865           CurDAG->SelectNodeTo(N, Ty, Opc, Val.getOperand(0));
866         else
867           CurDAG->SelectNodeTo(N, Ty, Opc, Val.getOperand(0),
868                                Val.getOperand(1), Val.getOperand(2));
869         break;
870       }
871     }
872     CurDAG->SelectNodeTo(N, Ty, PPC::FNEG, Val);
873     break;
874   }
875   case ISD::FSQRT: {
876     MVT::ValueType Ty = N->getValueType(0);
877     CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FSQRT : PPC::FSQRTS,
878                          Select(N->getOperand(0)));
879     break;
880   }
881   case ISD::LOAD:
882   case ISD::EXTLOAD:
883   case ISD::ZEXTLOAD:
884   case ISD::SEXTLOAD: {
885     SDOperand Op1, Op2;
886     bool isIdx = SelectAddr(N->getOperand(1), Op1, Op2);
887
888     MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
889       N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
890     unsigned Opc;
891     switch (TypeBeingLoaded) {
892     default: N->dump(); assert(0 && "Cannot load this type!");
893     case MVT::i1:
894     case MVT::i8:  Opc = isIdx ? PPC::LBZX : PPC::LBZ; break;
895     case MVT::i16:
896       if (N->getOpcode() == ISD::SEXTLOAD) { // SEXT load?
897         Opc = isIdx ? PPC::LHAX : PPC::LHA;
898       } else {
899         Opc = isIdx ? PPC::LHZX : PPC::LHZ;
900       }
901       break;
902     case MVT::i32: Opc = isIdx ? PPC::LWZX : PPC::LWZ; break;
903     case MVT::f32: Opc = isIdx ? PPC::LFSX : PPC::LFS; break;
904     case MVT::f64: Opc = isIdx ? PPC::LFDX : PPC::LFD; break;
905     }
906
907     CurDAG->SelectNodeTo(N, N->getValueType(0), MVT::Other, Opc,
908                          Op1, Op2, Select(N->getOperand(0)));
909     break;
910   }
911
912   case ISD::TRUNCSTORE:
913   case ISD::STORE: {
914     SDOperand AddrOp1, AddrOp2;
915     bool isIdx = SelectAddr(N->getOperand(2), AddrOp1, AddrOp2);
916
917     unsigned Opc;
918     if (N->getOpcode() == ISD::STORE) {
919       switch (N->getOperand(1).getValueType()) {
920       default: assert(0 && "unknown Type in store");
921       case MVT::i32: Opc = isIdx ? PPC::STWX  : PPC::STW; break;
922       case MVT::f64: Opc = isIdx ? PPC::STFDX : PPC::STFD; break;
923       case MVT::f32: Opc = isIdx ? PPC::STFSX : PPC::STFS; break;
924       }
925     } else { //ISD::TRUNCSTORE
926       switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
927       default: assert(0 && "unknown Type in store");
928       case MVT::i1:
929       case MVT::i8:  Opc = isIdx ? PPC::STBX : PPC::STB; break;
930       case MVT::i16: Opc = isIdx ? PPC::STHX : PPC::STH; break;
931       }
932     }
933     
934     CurDAG->SelectNodeTo(N, MVT::Other, Opc, Select(N->getOperand(1)),
935                          AddrOp1, AddrOp2, Select(N->getOperand(0)));
936     break;
937   }
938
939   case ISD::CALLSEQ_START:
940   case ISD::CALLSEQ_END: {
941     unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
942     unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
943                        PPC::ADJCALLSTACKDOWN : PPC::ADJCALLSTACKUP;
944     CurDAG->SelectNodeTo(N, MVT::Other, Opc, 
945                          getI32Imm(Amt), Select(N->getOperand(0)));
946     break;
947   }
948   case ISD::CALL:
949   case ISD::TAILCALL: {
950     SDOperand Chain = Select(N->getOperand(0));
951
952     unsigned CallOpcode;
953     std::vector<SDOperand> CallOperands;
954     
955     if (GlobalAddressSDNode *GASD =
956         dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
957       CallOpcode = PPC::CALLpcrel;
958       CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
959                                                             MVT::i32));
960     } else if (ExternalSymbolSDNode *ESSDN =
961                dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
962       CallOpcode = PPC::CALLpcrel;
963       CallOperands.push_back(N->getOperand(1));
964     } else {
965       // Copy the callee address into the CTR register.
966       SDOperand Callee = Select(N->getOperand(1));
967       Chain = CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee, Chain);
968
969       // Copy the callee address into R12 on darwin.
970       SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
971       Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, R12, Callee, Chain);
972       
973       CallOperands.push_back(getI32Imm(20));  // Information to encode indcall
974       CallOperands.push_back(getI32Imm(0));   // Information to encode indcall
975       CallOperands.push_back(R12);
976       CallOpcode = PPC::CALLindirect;
977     }
978     
979     unsigned GPR_idx = 0, FPR_idx = 0;
980     static const unsigned GPR[] = {
981       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
982       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
983     };
984     static const unsigned FPR[] = {
985       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
986       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
987     };
988     
989     for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i)
990       if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
991         unsigned DestReg = 0;
992         MVT::ValueType RegTy;
993         if (N->getOperand(i).getValueType() == MVT::i32) {
994           assert(GPR_idx < 8 && "Too many int args");
995           DestReg = GPR[GPR_idx++];
996           RegTy = MVT::i32;
997         } else {
998           assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
999                  "Unpromoted integer arg?");
1000           assert(FPR_idx < 13 && "Too many fp args");
1001           DestReg = FPR[FPR_idx++];
1002           RegTy = MVT::f64;   // Even if this is really f32!
1003         }
1004         
1005         SDOperand Reg = CurDAG->getRegister(DestReg, RegTy);
1006         Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, Reg,
1007                                 Select(N->getOperand(i)));
1008         CallOperands.push_back(Reg);
1009       }
1010
1011     // Finally, once everything is in registers to pass to the call, emit the
1012     // call itself.
1013     CallOperands.push_back(Chain);
1014     Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, CallOperands);
1015     
1016     std::vector<SDOperand> CallResults;
1017     
1018     // If the call has results, copy the values out of the ret val registers.
1019     switch (N->getValueType(0)) {
1020     default: assert(0 && "Unexpected ret value!");
1021     case MVT::Other: break;
1022     case MVT::i32:
1023       if (N->getValueType(1) == MVT::i32) {
1024         Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32).getValue(1);
1025         CallResults.push_back(Chain.getValue(0));
1026         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1027         CallResults.push_back(Chain.getValue(0));
1028       } else {
1029         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1030         CallResults.push_back(Chain.getValue(0));
1031       }
1032       break;
1033     case MVT::f32:
1034     case MVT::f64:
1035       Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, MVT::f64).getValue(1);
1036       CallResults.push_back(Chain.getValue(0));
1037       break;
1038     }
1039     
1040     CallResults.push_back(Chain);
1041     CurDAG->ReplaceAllUsesWith(N, CallResults);
1042     return CallResults[Op.ResNo];
1043   }
1044   case ISD::RET: {
1045     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
1046
1047     if (N->getNumOperands() > 1) {
1048       SDOperand Val = Select(N->getOperand(1));
1049       switch (N->getOperand(1).getValueType()) {
1050       default: assert(0 && "Unknown return type!");
1051       case MVT::f64:
1052       case MVT::f32:
1053         Chain = CurDAG->getCopyToReg(Chain, PPC::F1, Val);
1054         break;
1055       case MVT::i32:
1056         Chain = CurDAG->getCopyToReg(Chain, PPC::R3, Val);
1057         break;
1058       }
1059
1060       if (N->getNumOperands() > 2) {
1061         assert(N->getOperand(1).getValueType() == MVT::i32 &&
1062                N->getOperand(2).getValueType() == MVT::i32 &&
1063                N->getNumOperands() == 2 && "Unknown two-register ret value!");
1064         Val = Select(N->getOperand(2));
1065         Chain = CurDAG->getCopyToReg(Chain, PPC::R4, Val);
1066       }
1067     }
1068
1069     // Finally, select this to a blr (return) instruction.
1070     CurDAG->SelectNodeTo(N, MVT::Other, PPC::BLR, Chain);
1071     break;
1072   }
1073   case ISD::BR:
1074     CurDAG->SelectNodeTo(N, MVT::Other, PPC::B, N->getOperand(1),
1075                          Select(N->getOperand(0)));
1076     break;
1077   case ISD::BR_CC:
1078   case ISD::BRTWOWAY_CC: {
1079     SDOperand Chain = Select(N->getOperand(0));
1080     MachineBasicBlock *Dest =
1081       cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1082     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1083     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1084     unsigned Opc = getBCCForSetCC(CC);
1085
1086     // If this is a two way branch, then grab the fallthrough basic block
1087     // argument and build a PowerPC branch pseudo-op, suitable for long branch
1088     // conversion if necessary by the branch selection pass.  Otherwise, emit a
1089     // standard conditional branch.
1090     if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1091       MachineBasicBlock *Fallthrough =
1092         cast<BasicBlockSDNode>(N->getOperand(5))->getBasicBlock();
1093       SDOperand CB = CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1094                                            CondCode, getI32Imm(Opc),
1095                                            N->getOperand(4), N->getOperand(5),
1096                                            Chain);
1097       CurDAG->SelectNodeTo(N, MVT::Other, PPC::B, N->getOperand(5), CB);
1098     } else {
1099       // Iterate to the next basic block
1100       ilist<MachineBasicBlock>::iterator It = BB;
1101       ++It;
1102
1103       // If the fallthrough path is off the end of the function, which would be
1104       // undefined behavior, set it to be the same as the current block because
1105       // we have nothing better to set it to, and leaving it alone will cause
1106       // the PowerPC Branch Selection pass to crash.
1107       if (It == BB->getParent()->end()) It = Dest;
1108       CurDAG->SelectNodeTo(N, MVT::Other, PPC::COND_BRANCH, CondCode,
1109                            getI32Imm(Opc), N->getOperand(4),
1110                            CurDAG->getBasicBlock(It), Chain);
1111     }
1112     break;
1113   }
1114   }
1115   return SDOperand(N, Op.ResNo);
1116 }
1117
1118
1119 /// createPPC32ISelDag - This pass converts a legalized DAG into a 
1120 /// PowerPC-specific DAG, ready for instruction scheduling.
1121 ///
1122 FunctionPass *llvm::createPPC32ISelDag(TargetMachine &TM) {
1123   return new PPC32DAGToDAGISel(TM);
1124 }
1125