Compile this:
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
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 implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "PPCTargetMachine.h"
16 #include "llvm/ADT/VectorExtras.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/TargetOptions.h"
26 using namespace llvm;
27
28 PPCTargetLowering::PPCTargetLowering(TargetMachine &TM)
29   : TargetLowering(TM) {
30     
31   // Fold away setcc operations if possible.
32   setSetCCIsExpensive();
33   setPow2DivIsCheap();
34   
35   // Use _setjmp/_longjmp instead of setjmp/longjmp.
36   setUseUnderscoreSetJmpLongJmp(true);
37     
38   // Set up the register classes.
39   addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
40   addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
41   addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
42   
43   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
44   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
45
46   // PowerPC has no intrinsics for these particular operations
47   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
48   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
49   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
50   
51   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
52   setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
53   setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
54   
55   // PowerPC has no SREM/UREM instructions
56   setOperationAction(ISD::SREM, MVT::i32, Expand);
57   setOperationAction(ISD::UREM, MVT::i32, Expand);
58   
59   // We don't support sin/cos/sqrt/fmod
60   setOperationAction(ISD::FSIN , MVT::f64, Expand);
61   setOperationAction(ISD::FCOS , MVT::f64, Expand);
62   setOperationAction(ISD::FREM , MVT::f64, Expand);
63   setOperationAction(ISD::FSIN , MVT::f32, Expand);
64   setOperationAction(ISD::FCOS , MVT::f32, Expand);
65   setOperationAction(ISD::FREM , MVT::f32, Expand);
66   
67   // If we're enabling GP optimizations, use hardware square root
68   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
69     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
70     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
71   }
72   
73   // PowerPC does not have BSWAP, CTPOP or CTTZ
74   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
75   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
76   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
77   
78   // PowerPC does not have ROTR
79   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
80   
81   // PowerPC does not have Select
82   setOperationAction(ISD::SELECT, MVT::i32, Expand);
83   setOperationAction(ISD::SELECT, MVT::f32, Expand);
84   setOperationAction(ISD::SELECT, MVT::f64, Expand);
85   
86   // PowerPC wants to turn select_cc of FP into fsel when possible.
87   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
88   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
89
90   // PowerPC wants to optimize integer setcc a bit
91   setOperationAction(ISD::SETCC, MVT::i32, Custom);
92   
93   // PowerPC does not have BRCOND* which requires SetCC
94   setOperationAction(ISD::BRCOND,       MVT::Other, Expand);
95   setOperationAction(ISD::BRCONDTWOWAY, MVT::Other, Expand);
96   
97   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
98   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
99
100   // PowerPC does not have [U|S]INT_TO_FP
101   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
102   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
103
104   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
105   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
106
107   // PowerPC does not have truncstore for i1.
108   setOperationAction(ISD::TRUNCSTORE, MVT::i1, Promote);
109
110   // Support label based line numbers.
111   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
112   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
113   // FIXME - use subtarget debug flags
114   if (!TM.getSubtarget<PPCSubtarget>().isDarwin())
115     setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
116   
117   // We want to legalize GlobalAddress and ConstantPool nodes into the 
118   // appropriate instructions to materialize the address.
119   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
120   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
121
122   // RET must be custom lowered, to meet ABI requirements
123   setOperationAction(ISD::RET               , MVT::Other, Custom);
124   
125   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
126   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
127   
128   // Use the default implementation.
129   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
130   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
131   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
132   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
133   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
134   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
135   
136   if (TM.getSubtarget<PPCSubtarget>().is64Bit()) {
137     // They also have instructions for converting between i64 and fp.
138     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
139     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
140     // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
141     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
142   } else {
143     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
144     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
145   }
146
147   if (TM.getSubtarget<PPCSubtarget>().has64BitRegs()) {
148     // 64 bit PowerPC implementations can support i64 types directly
149     addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
150     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
151     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
152   } else {
153     // 32 bit PowerPC wants to expand i64 shifts itself.
154     setOperationAction(ISD::SHL, MVT::i64, Custom);
155     setOperationAction(ISD::SRL, MVT::i64, Custom);
156     setOperationAction(ISD::SRA, MVT::i64, Custom);
157   }
158   
159   // First set operation action for all vector types to expand. Then we
160   // will selectively turn on ones that can be effectively codegen'd.
161   for (unsigned VT = (unsigned)MVT::Vector + 1;
162        VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
163     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
164     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
165     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
166     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
167   }
168
169   if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
170     addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
171     addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
172     
173     setOperationAction(ISD::ADD        , MVT::v4f32, Legal);
174     setOperationAction(ISD::SUB        , MVT::v4f32, Legal);
175     setOperationAction(ISD::MUL        , MVT::v4f32, Legal);
176     setOperationAction(ISD::LOAD       , MVT::v4f32, Legal);
177     setOperationAction(ISD::ADD        , MVT::v4i32, Legal);
178     setOperationAction(ISD::LOAD       , MVT::v4i32, Legal);
179     // FIXME: We don't support any ConstantVec's yet.  We should custom expand
180     // the ones we do!
181     setOperationAction(ISD::ConstantVec, MVT::v4f32, Expand);
182     setOperationAction(ISD::ConstantVec, MVT::v4i32, Expand);
183   }
184   
185   setSetCCResultContents(ZeroOrOneSetCCResult);
186   setStackPointerRegisterToSaveRestore(PPC::R1);
187   
188   // We have target-specific dag combine patterns for the following nodes:
189   setTargetDAGCombine(ISD::SINT_TO_FP);
190   setTargetDAGCombine(ISD::STORE);
191   
192   computeRegisterProperties();
193 }
194
195 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
196   switch (Opcode) {
197   default: return 0;
198   case PPCISD::FSEL:          return "PPCISD::FSEL";
199   case PPCISD::FCFID:         return "PPCISD::FCFID";
200   case PPCISD::FCTIDZ:        return "PPCISD::FCTIDZ";
201   case PPCISD::FCTIWZ:        return "PPCISD::FCTIWZ";
202   case PPCISD::STFIWX:        return "PPCISD::STFIWX";
203   case PPCISD::VMADDFP:       return "PPCISD::VMADDFP";
204   case PPCISD::VNMSUBFP:      return "PPCISD::VNMSUBFP";
205   case PPCISD::Hi:            return "PPCISD::Hi";
206   case PPCISD::Lo:            return "PPCISD::Lo";
207   case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
208   case PPCISD::SRL:           return "PPCISD::SRL";
209   case PPCISD::SRA:           return "PPCISD::SRA";
210   case PPCISD::SHL:           return "PPCISD::SHL";
211   case PPCISD::CALL:          return "PPCISD::CALL";
212   case PPCISD::RET_FLAG:      return "PPCISD::RET_FLAG";
213   }
214 }
215
216 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
217 static bool isFloatingPointZero(SDOperand Op) {
218   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
219     return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
220   else if (Op.getOpcode() == ISD::EXTLOAD || Op.getOpcode() == ISD::LOAD) {
221     // Maybe this has already been legalized into the constant pool?
222     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
223       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->get()))
224         return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
225   }
226   return false;
227 }
228
229 /// LowerOperation - Provide custom lowering hooks for some operations.
230 ///
231 SDOperand PPCTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
232   switch (Op.getOpcode()) {
233   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
234   case ISD::FP_TO_SINT: {
235     assert(MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
236     SDOperand Src = Op.getOperand(0);
237     if (Src.getValueType() == MVT::f32)
238       Src = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Src);
239     
240     SDOperand Tmp;
241     switch (Op.getValueType()) {
242     default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
243     case MVT::i32:
244       Tmp = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Src);
245       break;
246     case MVT::i64:
247       Tmp = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Src);
248       break;
249     }
250    
251     // Convert the FP value to an int value through memory.
252     SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Tmp);
253     if (Op.getValueType() == MVT::i32)
254       Bits = DAG.getNode(ISD::TRUNCATE, MVT::i32, Bits);
255     return Bits;
256   }
257   case ISD::SINT_TO_FP: {
258     assert(MVT::i64 == Op.getOperand(0).getValueType() && 
259            "Unhandled SINT_TO_FP type in custom expander!");
260     SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, Op.getOperand(0));
261     SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Bits);
262     if (MVT::f32 == Op.getValueType())
263       FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
264     return FP;
265   }
266   case ISD::SELECT_CC: {
267     // Turn FP only select_cc's into fsel instructions.
268     if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
269         !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
270       break;
271     
272     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
273     
274     // Cannot handle SETEQ/SETNE.
275     if (CC == ISD::SETEQ || CC == ISD::SETNE) break;
276     
277     MVT::ValueType ResVT = Op.getValueType();
278     MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
279     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
280     SDOperand TV  = Op.getOperand(2), FV  = Op.getOperand(3);
281
282     // If the RHS of the comparison is a 0.0, we don't need to do the
283     // subtraction at all.
284     if (isFloatingPointZero(RHS))
285       switch (CC) {
286       default: break;       // SETUO etc aren't handled by fsel.
287       case ISD::SETULT:
288       case ISD::SETLT:
289         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
290       case ISD::SETUGE:
291       case ISD::SETGE:
292         if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
293           LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
294         return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
295       case ISD::SETUGT:
296       case ISD::SETGT:
297         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
298       case ISD::SETULE:
299       case ISD::SETLE:
300         if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
301           LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
302         return DAG.getNode(PPCISD::FSEL, ResVT,
303                            DAG.getNode(ISD::FNEG, MVT::f64, LHS), TV, FV);
304       }
305     
306     SDOperand Cmp;
307     switch (CC) {
308     default: break;       // SETUO etc aren't handled by fsel.
309     case ISD::SETULT:
310     case ISD::SETLT:
311       Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
312       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
313         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
314       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
315     case ISD::SETUGE:
316     case ISD::SETGE:
317       Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
318       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
319         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
320       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
321     case ISD::SETUGT:
322     case ISD::SETGT:
323       Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
324       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
325         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
326       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
327     case ISD::SETULE:
328     case ISD::SETLE:
329       Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
330       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
331         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
332       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
333     }
334     break;
335   }
336   case ISD::SHL: {
337     assert(Op.getValueType() == MVT::i64 &&
338            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
339     // The generic code does a fine job expanding shift by a constant.
340     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
341     
342     // Otherwise, expand into a bunch of logical ops.  Note that these ops
343     // depend on the PPC behavior for oversized shift amounts.
344     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
345                                DAG.getConstant(0, MVT::i32));
346     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
347                                DAG.getConstant(1, MVT::i32));
348     SDOperand Amt = Op.getOperand(1);
349     
350     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
351                                  DAG.getConstant(32, MVT::i32), Amt);
352     SDOperand Tmp2 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Amt);
353     SDOperand Tmp3 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Tmp1);
354     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
355     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
356                                  DAG.getConstant(-32U, MVT::i32));
357     SDOperand Tmp6 = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Tmp5);
358     SDOperand OutHi = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
359     SDOperand OutLo = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Amt);
360     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
361   }
362   case ISD::SRL: {
363     assert(Op.getValueType() == MVT::i64 &&
364            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
365     // The generic code does a fine job expanding shift by a constant.
366     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
367     
368     // Otherwise, expand into a bunch of logical ops.  Note that these ops
369     // depend on the PPC behavior for oversized shift amounts.
370     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
371                                DAG.getConstant(0, MVT::i32));
372     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
373                                DAG.getConstant(1, MVT::i32));
374     SDOperand Amt = Op.getOperand(1);
375     
376     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
377                                  DAG.getConstant(32, MVT::i32), Amt);
378     SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
379     SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
380     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
381     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
382                                  DAG.getConstant(-32U, MVT::i32));
383     SDOperand Tmp6 = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Tmp5);
384     SDOperand OutLo = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
385     SDOperand OutHi = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Amt);
386     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
387   }    
388   case ISD::SRA: {
389     assert(Op.getValueType() == MVT::i64 &&
390            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRA!");
391     // The generic code does a fine job expanding shift by a constant.
392     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
393       
394     // Otherwise, expand into a bunch of logical ops, followed by a select_cc.
395     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
396                                DAG.getConstant(0, MVT::i32));
397     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
398                                DAG.getConstant(1, MVT::i32));
399     SDOperand Amt = Op.getOperand(1);
400     
401     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
402                                  DAG.getConstant(32, MVT::i32), Amt);
403     SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
404     SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
405     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
406     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
407                                  DAG.getConstant(-32U, MVT::i32));
408     SDOperand Tmp6 = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Tmp5);
409     SDOperand OutHi = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Amt);
410     SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, MVT::i32),
411                                       Tmp4, Tmp6, ISD::SETLE);
412     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
413   }
414   case ISD::ConstantPool: {
415     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
416     Constant *C = CP->get();
417     SDOperand CPI = DAG.getTargetConstantPool(C, MVT::i32, CP->getAlignment());
418     SDOperand Zero = DAG.getConstant(0, MVT::i32);
419     
420     if (getTargetMachine().getRelocationModel() == Reloc::Static) {
421       // Generate non-pic code that has direct accesses to the constant pool.
422       // The address of the global is just (hi(&g)+lo(&g)).
423       SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, CPI, Zero);
424       SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, CPI, Zero);
425       return DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
426     }
427     
428     // Only lower ConstantPool on Darwin.
429     if (!getTargetMachine().getSubtarget<PPCSubtarget>().isDarwin()) break;
430     SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, CPI, Zero);
431     if (getTargetMachine().getRelocationModel() == Reloc::PIC) {
432       // With PIC, the first instruction is actually "GR+hi(&G)".
433       Hi = DAG.getNode(ISD::ADD, MVT::i32,
434                        DAG.getNode(PPCISD::GlobalBaseReg, MVT::i32), Hi);
435     }
436
437     SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, CPI, Zero);
438     Lo = DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
439     return Lo;
440   }
441   case ISD::GlobalAddress: {
442     GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
443     GlobalValue *GV = GSDN->getGlobal();
444     SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32, GSDN->getOffset());
445     SDOperand Zero = DAG.getConstant(0, MVT::i32);
446
447     if (getTargetMachine().getRelocationModel() == Reloc::Static) {
448       // Generate non-pic code that has direct accesses to globals.
449       // The address of the global is just (hi(&g)+lo(&g)).
450       SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, GA, Zero);
451       SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, GA, Zero);
452       return DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
453     }
454     
455     // Only lower GlobalAddress on Darwin.
456     if (!getTargetMachine().getSubtarget<PPCSubtarget>().isDarwin()) break;
457     
458     SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, GA, Zero);
459     if (getTargetMachine().getRelocationModel() == Reloc::PIC) {
460       // With PIC, the first instruction is actually "GR+hi(&G)".
461       Hi = DAG.getNode(ISD::ADD, MVT::i32,
462                        DAG.getNode(PPCISD::GlobalBaseReg, MVT::i32), Hi);
463     }
464     
465     SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, GA, Zero);
466     Lo = DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
467                                    
468     if (!GV->hasWeakLinkage() && !GV->hasLinkOnceLinkage() &&
469         (!GV->isExternal() || GV->hasNotBeenReadFromBytecode()))
470       return Lo;
471
472     // If the global is weak or external, we have to go through the lazy
473     // resolution stub.
474     return DAG.getLoad(MVT::i32, DAG.getEntryNode(), Lo, DAG.getSrcValue(0));
475   }
476   case ISD::SETCC: {
477     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
478     
479     // If we're comparing for equality to zero, expose the fact that this is
480     // implented as a ctlz/srl pair on ppc, so that the dag combiner can
481     // fold the new nodes.
482     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
483       if (C->isNullValue() && CC == ISD::SETEQ) {
484         MVT::ValueType VT = Op.getOperand(0).getValueType();
485         SDOperand Zext = Op.getOperand(0);
486         if (VT < MVT::i32) {
487           VT = MVT::i32;
488           Zext = DAG.getNode(ISD::ZERO_EXTEND, VT, Op.getOperand(0));
489         } 
490         unsigned Log2b = Log2_32(MVT::getSizeInBits(VT));
491         SDOperand Clz = DAG.getNode(ISD::CTLZ, VT, Zext);
492         SDOperand Scc = DAG.getNode(ISD::SRL, VT, Clz,
493                                     DAG.getConstant(Log2b, getShiftAmountTy()));
494         return DAG.getNode(ISD::TRUNCATE, getSetCCResultTy(), Scc);
495       }
496       // Leave comparisons against 0 and -1 alone for now, since they're usually 
497       // optimized.  FIXME: revisit this when we can custom lower all setcc
498       // optimizations.
499       if (C->isAllOnesValue() || C->isNullValue())
500         break;
501     }
502         
503     // If we have an integer seteq/setne, turn it into a compare against zero
504     // by subtracting the rhs from the lhs, which is faster than setting a
505     // condition register, reading it back out, and masking the correct bit.
506     MVT::ValueType LHSVT = Op.getOperand(0).getValueType();
507     if (MVT::isInteger(LHSVT) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
508       MVT::ValueType VT = Op.getValueType();
509       SDOperand Sub = DAG.getNode(ISD::SUB, LHSVT, Op.getOperand(0), 
510                                   Op.getOperand(1));
511       return DAG.getSetCC(VT, Sub, DAG.getConstant(0, LHSVT), CC);
512     }
513     break;
514   }
515   case ISD::VASTART: {
516     // vastart just stores the address of the VarArgsFrameIndex slot into the
517     // memory location argument.
518     // FIXME: Replace MVT::i32 with PointerTy
519     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
520     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
521                        Op.getOperand(1), Op.getOperand(2));
522   }
523   case ISD::RET: {
524     SDOperand Copy;
525     
526     switch(Op.getNumOperands()) {
527     default:
528       assert(0 && "Do not know how to return this many arguments!");
529       abort();
530     case 1: 
531       return SDOperand(); // ret void is legal
532     case 2: {
533       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
534       unsigned ArgReg = MVT::isInteger(ArgVT) ? PPC::R3 : PPC::F1;
535       Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
536                               SDOperand());
537       break;
538     }
539     case 3:
540       Copy = DAG.getCopyToReg(Op.getOperand(0), PPC::R3, Op.getOperand(2), 
541                               SDOperand());
542       Copy = DAG.getCopyToReg(Copy, PPC::R4, Op.getOperand(1),Copy.getValue(1));
543       break;
544     }
545     return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
546   }
547   }
548   return SDOperand();
549 }
550
551 std::vector<SDOperand>
552 PPCTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
553   //
554   // add beautiful description of PPC stack frame format, or at least some docs
555   //
556   MachineFunction &MF = DAG.getMachineFunction();
557   MachineFrameInfo *MFI = MF.getFrameInfo();
558   MachineBasicBlock& BB = MF.front();
559   SSARegMap *RegMap = MF.getSSARegMap();
560   std::vector<SDOperand> ArgValues;
561   
562   unsigned ArgOffset = 24;
563   unsigned GPR_remaining = 8;
564   unsigned FPR_remaining = 13;
565   unsigned GPR_idx = 0, FPR_idx = 0;
566   static const unsigned GPR[] = {
567     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
568     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
569   };
570   static const unsigned FPR[] = {
571     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
572     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
573   };
574   
575   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
576   // the arguments start at offset 24, although they are likely to be passed
577   // in registers.
578   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
579     SDOperand newroot, argt;
580     unsigned ObjSize;
581     bool needsLoad = false;
582     bool ArgLive = !I->use_empty();
583     MVT::ValueType ObjectVT = getValueType(I->getType());
584     
585     switch (ObjectVT) {
586     default: assert(0 && "Unhandled argument type!");
587     case MVT::i1:
588     case MVT::i8:
589     case MVT::i16:
590     case MVT::i32:
591       ObjSize = 4;
592       if (!ArgLive) break;
593       if (GPR_remaining > 0) {
594         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
595         MF.addLiveIn(GPR[GPR_idx], VReg);
596         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
597         if (ObjectVT != MVT::i32) {
598           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
599                                                        : ISD::AssertZext;
600           argt = DAG.getNode(AssertOp, MVT::i32, argt, 
601                              DAG.getValueType(ObjectVT));
602           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, argt);
603         }
604       } else {
605         needsLoad = true;
606       }
607       break;
608     case MVT::i64:
609       ObjSize = 8;
610       if (!ArgLive) break;
611       if (GPR_remaining > 0) {
612         SDOperand argHi, argLo;
613         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
614         MF.addLiveIn(GPR[GPR_idx], VReg);
615         argHi = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
616         // If we have two or more remaining argument registers, then both halves
617         // of the i64 can be sourced from there.  Otherwise, the lower half will
618         // have to come off the stack.  This can happen when an i64 is preceded
619         // by 28 bytes of arguments.
620         if (GPR_remaining > 1) {
621           unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
622           MF.addLiveIn(GPR[GPR_idx+1], VReg);
623           argLo = DAG.getCopyFromReg(argHi, VReg, MVT::i32);
624         } else {
625           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
626           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
627           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
628                               DAG.getSrcValue(NULL));
629         }
630         // Build the outgoing arg thingy
631         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
632         newroot = argLo;
633       } else {
634         needsLoad = true;
635       }
636       break;
637     case MVT::f32:
638     case MVT::f64:
639       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
640       if (!ArgLive) {
641         if (FPR_remaining > 0) {
642           --FPR_remaining;
643           ++FPR_idx;
644         }        
645         break;
646       }
647       if (FPR_remaining > 0) {
648         unsigned VReg;
649         if (ObjectVT == MVT::f32)
650           VReg = RegMap->createVirtualRegister(&PPC::F4RCRegClass);
651         else
652           VReg = RegMap->createVirtualRegister(&PPC::F8RCRegClass);
653         MF.addLiveIn(FPR[FPR_idx], VReg);
654         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, ObjectVT);
655         --FPR_remaining;
656         ++FPR_idx;
657       } else {
658         needsLoad = true;
659       }
660       break;
661     }
662     
663     // We need to load the argument to a virtual register if we determined above
664     // that we ran out of physical registers of the appropriate type
665     if (needsLoad) {
666       unsigned SubregOffset = 0;
667       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
668       if (ObjectVT == MVT::i16) SubregOffset = 2;
669       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
670       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
671       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
672                         DAG.getConstant(SubregOffset, MVT::i32));
673       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
674                                    DAG.getSrcValue(NULL));
675     }
676     
677     // Every 4 bytes of argument space consumes one of the GPRs available for
678     // argument passing.
679     if (GPR_remaining > 0) {
680       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
681       GPR_remaining -= delta;
682       GPR_idx += delta;
683     }
684     ArgOffset += ObjSize;
685     if (newroot.Val)
686       DAG.setRoot(newroot.getValue(1));
687     
688     ArgValues.push_back(argt);
689   }
690   
691   // If the function takes variable number of arguments, make a frame index for
692   // the start of the first vararg value... for expansion of llvm.va_start.
693   if (F.isVarArg()) {
694     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
695     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
696     // If this function is vararg, store any remaining integer argument regs
697     // to their spots on the stack so that they may be loaded by deferencing the
698     // result of va_next.
699     std::vector<SDOperand> MemOps;
700     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
701       unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
702       MF.addLiveIn(GPR[GPR_idx], VReg);
703       SDOperand Val = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
704       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
705                                     Val, FIN, DAG.getSrcValue(NULL));
706       MemOps.push_back(Store);
707       // Increment the address by four for the next argument to store
708       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
709       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
710     }
711     if (!MemOps.empty()) {
712       MemOps.push_back(DAG.getRoot());
713       DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
714     }
715   }
716   
717   // Finally, inform the code generator which regs we return values in.
718   switch (getValueType(F.getReturnType())) {
719     default: assert(0 && "Unknown type!");
720     case MVT::isVoid: break;
721     case MVT::i1:
722     case MVT::i8:
723     case MVT::i16:
724     case MVT::i32:
725       MF.addLiveOut(PPC::R3);
726       break;
727     case MVT::i64:
728       MF.addLiveOut(PPC::R3);
729       MF.addLiveOut(PPC::R4);
730       break;
731     case MVT::f32:
732     case MVT::f64:
733       MF.addLiveOut(PPC::F1);
734       break;
735   }
736   
737   return ArgValues;
738 }
739
740 std::pair<SDOperand, SDOperand>
741 PPCTargetLowering::LowerCallTo(SDOperand Chain,
742                                const Type *RetTy, bool isVarArg,
743                                unsigned CallingConv, bool isTailCall,
744                                SDOperand Callee, ArgListTy &Args,
745                                SelectionDAG &DAG) {
746   // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
747   // SelectExpr to use to put the arguments in the appropriate registers.
748   std::vector<SDOperand> args_to_use;
749   
750   // Count how many bytes are to be pushed on the stack, including the linkage
751   // area, and parameter passing area.
752   unsigned NumBytes = 24;
753   
754   if (Args.empty()) {
755     Chain = DAG.getCALLSEQ_START(Chain,
756                                  DAG.getConstant(NumBytes, getPointerTy()));
757   } else {
758     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
759       switch (getValueType(Args[i].second)) {
760       default: assert(0 && "Unknown value type!");
761       case MVT::i1:
762       case MVT::i8:
763       case MVT::i16:
764       case MVT::i32:
765       case MVT::f32:
766         NumBytes += 4;
767         break;
768       case MVT::i64:
769       case MVT::f64:
770         NumBytes += 8;
771         break;
772       }
773     }
774         
775     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
776     // plus 32 bytes of argument space in case any called code gets funky on us.
777     // (Required by ABI to support var arg)
778     if (NumBytes < 56) NumBytes = 56;
779     
780     // Adjust the stack pointer for the new arguments...
781     // These operations are automatically eliminated by the prolog/epilog pass
782     Chain = DAG.getCALLSEQ_START(Chain,
783                                  DAG.getConstant(NumBytes, getPointerTy()));
784     
785     // Set up a copy of the stack pointer for use loading and storing any
786     // arguments that may not fit in the registers available for argument
787     // passing.
788     SDOperand StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
789     
790     // Figure out which arguments are going to go in registers, and which in
791     // memory.  Also, if this is a vararg function, floating point operations
792     // must be stored to our stack, and loaded into integer regs as well, if
793     // any integer regs are available for argument passing.
794     unsigned ArgOffset = 24;
795     unsigned GPR_remaining = 8;
796     unsigned FPR_remaining = 13;
797     
798     std::vector<SDOperand> MemOps;
799     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
800       // PtrOff will be used to store the current argument to the stack if a
801       // register cannot be found for it.
802       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
803       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
804       MVT::ValueType ArgVT = getValueType(Args[i].second);
805       
806       switch (ArgVT) {
807       default: assert(0 && "Unexpected ValueType for argument!");
808       case MVT::i1:
809       case MVT::i8:
810       case MVT::i16:
811         // Promote the integer to 32 bits.  If the input type is signed use a
812         // sign extend, otherwise use a zero extend.
813         if (Args[i].second->isSigned())
814           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
815         else
816           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
817         // FALL THROUGH
818       case MVT::i32:
819         if (GPR_remaining > 0) {
820           args_to_use.push_back(Args[i].first);
821           --GPR_remaining;
822         } else {
823           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
824                                        Args[i].first, PtrOff,
825                                        DAG.getSrcValue(NULL)));
826         }
827         ArgOffset += 4;
828         break;
829       case MVT::i64:
830         // If we have one free GPR left, we can place the upper half of the i64
831         // in it, and store the other half to the stack.  If we have two or more
832         // free GPRs, then we can pass both halves of the i64 in registers.
833         if (GPR_remaining > 0) {
834           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
835                                      Args[i].first, DAG.getConstant(1, MVT::i32));
836           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
837                                      Args[i].first, DAG.getConstant(0, MVT::i32));
838           args_to_use.push_back(Hi);
839           --GPR_remaining;
840           if (GPR_remaining > 0) {
841             args_to_use.push_back(Lo);
842             --GPR_remaining;
843           } else {
844             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
845             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
846             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
847                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
848           }
849         } else {
850           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
851                                        Args[i].first, PtrOff,
852                                        DAG.getSrcValue(NULL)));
853         }
854         ArgOffset += 8;
855         break;
856       case MVT::f32:
857       case MVT::f64:
858         if (FPR_remaining > 0) {
859           args_to_use.push_back(Args[i].first);
860           --FPR_remaining;
861           if (isVarArg) {
862             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
863                                           Args[i].first, PtrOff,
864                                           DAG.getSrcValue(NULL));
865             MemOps.push_back(Store);
866             // Float varargs are always shadowed in available integer registers
867             if (GPR_remaining > 0) {
868               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
869                                            DAG.getSrcValue(NULL));
870               MemOps.push_back(Load.getValue(1));
871               args_to_use.push_back(Load);
872               --GPR_remaining;
873             }
874             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
875               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
876               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
877               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
878                                            DAG.getSrcValue(NULL));
879               MemOps.push_back(Load.getValue(1));
880               args_to_use.push_back(Load);
881               --GPR_remaining;
882             }
883           } else {
884             // If we have any FPRs remaining, we may also have GPRs remaining.
885             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
886             // GPRs.
887             if (GPR_remaining > 0) {
888               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
889               --GPR_remaining;
890             }
891             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
892               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
893               --GPR_remaining;
894             }
895           }
896         } else {
897           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
898                                        Args[i].first, PtrOff,
899                                        DAG.getSrcValue(NULL)));
900         }
901         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
902         break;
903       }
904     }
905     if (!MemOps.empty())
906       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
907   }
908   
909   std::vector<MVT::ValueType> RetVals;
910   MVT::ValueType RetTyVT = getValueType(RetTy);
911   MVT::ValueType ActualRetTyVT = RetTyVT;
912   if (RetTyVT >= MVT::i1 && RetTyVT <= MVT::i16)
913     ActualRetTyVT = MVT::i32;   // Promote result to i32.
914     
915   if (RetTyVT == MVT::i64) {
916     RetVals.push_back(MVT::i32);
917     RetVals.push_back(MVT::i32);
918   } else if (RetTyVT != MVT::isVoid) {
919     RetVals.push_back(ActualRetTyVT);
920   }
921   RetVals.push_back(MVT::Other);
922   
923   // If the callee is a GlobalAddress node (quite common, every direct call is)
924   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
925   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
926     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
927   
928   std::vector<SDOperand> Ops;
929   Ops.push_back(Chain);
930   Ops.push_back(Callee);
931   Ops.insert(Ops.end(), args_to_use.begin(), args_to_use.end());
932   SDOperand TheCall = DAG.getNode(PPCISD::CALL, RetVals, Ops);
933   Chain = TheCall.getValue(TheCall.Val->getNumValues()-1);
934   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
935                       DAG.getConstant(NumBytes, getPointerTy()));
936   SDOperand RetVal = TheCall;
937   
938   // If the result is a small value, add a note so that we keep track of the
939   // information about whether it is sign or zero extended.
940   if (RetTyVT != ActualRetTyVT) {
941     RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext : ISD::AssertZext,
942                          MVT::i32, RetVal, DAG.getValueType(RetTyVT));
943     RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
944   } else if (RetTyVT == MVT::i64) {
945     RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, RetVal, RetVal.getValue(1));
946   }
947   
948   return std::make_pair(RetVal, Chain);
949 }
950
951 MachineBasicBlock *
952 PPCTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
953                                            MachineBasicBlock *BB) {
954   assert((MI->getOpcode() == PPC::SELECT_CC_Int ||
955           MI->getOpcode() == PPC::SELECT_CC_F4 ||
956           MI->getOpcode() == PPC::SELECT_CC_F8) &&
957          "Unexpected instr type to insert");
958   
959   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
960   // control-flow pattern.  The incoming instruction knows the destination vreg
961   // to set, the condition code register to branch on, the true/false values to
962   // select between, and a branch opcode to use.
963   const BasicBlock *LLVM_BB = BB->getBasicBlock();
964   ilist<MachineBasicBlock>::iterator It = BB;
965   ++It;
966   
967   //  thisMBB:
968   //  ...
969   //   TrueVal = ...
970   //   cmpTY ccX, r1, r2
971   //   bCC copy1MBB
972   //   fallthrough --> copy0MBB
973   MachineBasicBlock *thisMBB = BB;
974   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
975   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
976   BuildMI(BB, MI->getOperand(4).getImmedValue(), 2)
977     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
978   MachineFunction *F = BB->getParent();
979   F->getBasicBlockList().insert(It, copy0MBB);
980   F->getBasicBlockList().insert(It, sinkMBB);
981   // Update machine-CFG edges
982   BB->addSuccessor(copy0MBB);
983   BB->addSuccessor(sinkMBB);
984   
985   //  copy0MBB:
986   //   %FalseValue = ...
987   //   # fallthrough to sinkMBB
988   BB = copy0MBB;
989   
990   // Update machine-CFG edges
991   BB->addSuccessor(sinkMBB);
992   
993   //  sinkMBB:
994   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
995   //  ...
996   BB = sinkMBB;
997   BuildMI(BB, PPC::PHI, 4, MI->getOperand(0).getReg())
998     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
999     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1000
1001   delete MI;   // The pseudo instruction is gone now.
1002   return BB;
1003 }
1004
1005 SDOperand PPCTargetLowering::PerformDAGCombine(SDNode *N, 
1006                                                DAGCombinerInfo &DCI) const {
1007   TargetMachine &TM = getTargetMachine();
1008   SelectionDAG &DAG = DCI.DAG;
1009   switch (N->getOpcode()) {
1010   default: break;
1011   case ISD::SINT_TO_FP:
1012     if (TM.getSubtarget<PPCSubtarget>().is64Bit()) {
1013       // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
1014       // We allow the src/dst to be either f32/f64, but force the intermediate
1015       // type to be i64.
1016       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT && 
1017           N->getOperand(0).getValueType() == MVT::i64) {
1018         
1019         SDOperand Val = N->getOperand(0).getOperand(0);
1020         if (Val.getValueType() == MVT::f32) {
1021           Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
1022           DCI.AddToWorklist(Val.Val);
1023         }
1024           
1025         Val = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Val);
1026         DCI.AddToWorklist(Val.Val);
1027         Val = DAG.getNode(PPCISD::FCFID, MVT::f64, Val);
1028         DCI.AddToWorklist(Val.Val);
1029         if (N->getValueType(0) == MVT::f32) {
1030           Val = DAG.getNode(ISD::FP_ROUND, MVT::f32, Val);
1031           DCI.AddToWorklist(Val.Val);
1032         }
1033         return Val;
1034       }
1035     }
1036     break;
1037   case ISD::STORE:
1038     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
1039     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
1040         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
1041         N->getOperand(1).getValueType() == MVT::i32) {
1042       SDOperand Val = N->getOperand(1).getOperand(0);
1043       if (Val.getValueType() == MVT::f32) {
1044         Val = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Val);
1045         DCI.AddToWorklist(Val.Val);
1046       }
1047       Val = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Val);
1048       DCI.AddToWorklist(Val.Val);
1049
1050       Val = DAG.getNode(PPCISD::STFIWX, MVT::Other, N->getOperand(0), Val,
1051                         N->getOperand(2), N->getOperand(3));
1052       DCI.AddToWorklist(Val.Val);
1053       return Val;
1054     }
1055     break;
1056   }
1057   
1058   return SDOperand();
1059 }
1060
1061 /// getConstraintType - Given a constraint letter, return the type of
1062 /// constraint it is for this target.
1063 PPCTargetLowering::ConstraintType 
1064 PPCTargetLowering::getConstraintType(char ConstraintLetter) const {
1065   switch (ConstraintLetter) {
1066   default: break;
1067   case 'b':
1068   case 'r':
1069   case 'f':
1070   case 'v':
1071   case 'y':
1072     return C_RegisterClass;
1073   }  
1074   return TargetLowering::getConstraintType(ConstraintLetter);
1075 }
1076
1077
1078 std::vector<unsigned> PPCTargetLowering::
1079 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1080                                   MVT::ValueType VT) const {
1081   if (Constraint.size() == 1) {
1082     switch (Constraint[0]) {      // GCC RS6000 Constraint Letters
1083     default: break;  // Unknown constriant letter
1084     case 'b': 
1085       return make_vector<unsigned>(/*no R0*/ PPC::R1 , PPC::R2 , PPC::R3 ,
1086                                    PPC::R4 , PPC::R5 , PPC::R6 , PPC::R7 ,
1087                                    PPC::R8 , PPC::R9 , PPC::R10, PPC::R11, 
1088                                    PPC::R12, PPC::R13, PPC::R14, PPC::R15, 
1089                                    PPC::R16, PPC::R17, PPC::R18, PPC::R19, 
1090                                    PPC::R20, PPC::R21, PPC::R22, PPC::R23, 
1091                                    PPC::R24, PPC::R25, PPC::R26, PPC::R27, 
1092                                    PPC::R28, PPC::R29, PPC::R30, PPC::R31, 
1093                                    0);
1094     case 'r': 
1095       return make_vector<unsigned>(PPC::R0 , PPC::R1 , PPC::R2 , PPC::R3 ,
1096                                    PPC::R4 , PPC::R5 , PPC::R6 , PPC::R7 ,
1097                                    PPC::R8 , PPC::R9 , PPC::R10, PPC::R11, 
1098                                    PPC::R12, PPC::R13, PPC::R14, PPC::R15, 
1099                                    PPC::R16, PPC::R17, PPC::R18, PPC::R19, 
1100                                    PPC::R20, PPC::R21, PPC::R22, PPC::R23, 
1101                                    PPC::R24, PPC::R25, PPC::R26, PPC::R27, 
1102                                    PPC::R28, PPC::R29, PPC::R30, PPC::R31, 
1103                                    0);
1104     case 'f': 
1105       return make_vector<unsigned>(PPC::F0 , PPC::F1 , PPC::F2 , PPC::F3 ,
1106                                    PPC::F4 , PPC::F5 , PPC::F6 , PPC::F7 ,
1107                                    PPC::F8 , PPC::F9 , PPC::F10, PPC::F11, 
1108                                    PPC::F12, PPC::F13, PPC::F14, PPC::F15, 
1109                                    PPC::F16, PPC::F17, PPC::F18, PPC::F19, 
1110                                    PPC::F20, PPC::F21, PPC::F22, PPC::F23, 
1111                                    PPC::F24, PPC::F25, PPC::F26, PPC::F27, 
1112                                    PPC::F28, PPC::F29, PPC::F30, PPC::F31, 
1113                                    0);
1114     case 'v': 
1115       return make_vector<unsigned>(PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 ,
1116                                    PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
1117                                    PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, 
1118                                    PPC::V12, PPC::V13, PPC::V14, PPC::V15, 
1119                                    PPC::V16, PPC::V17, PPC::V18, PPC::V19, 
1120                                    PPC::V20, PPC::V21, PPC::V22, PPC::V23, 
1121                                    PPC::V24, PPC::V25, PPC::V26, PPC::V27, 
1122                                    PPC::V28, PPC::V29, PPC::V30, PPC::V31, 
1123                                    0);
1124     case 'y': 
1125       return make_vector<unsigned>(PPC::CR0, PPC::CR1, PPC::CR2, PPC::CR3,
1126                                    PPC::CR4, PPC::CR5, PPC::CR6, PPC::CR7,
1127                                    0);
1128     }
1129   }
1130   
1131   return std::vector<unsigned>();
1132 }
1133
1134 // isOperandValidForConstraint
1135 bool PPCTargetLowering::
1136 isOperandValidForConstraint(SDOperand Op, char Letter) {
1137   switch (Letter) {
1138   default: break;
1139   case 'I':
1140   case 'J':
1141   case 'K':
1142   case 'L':
1143   case 'M':
1144   case 'N':
1145   case 'O':
1146   case 'P': {
1147     if (!isa<ConstantSDNode>(Op)) return false;  // Must be an immediate.
1148     unsigned Value = cast<ConstantSDNode>(Op)->getValue();
1149     switch (Letter) {
1150     default: assert(0 && "Unknown constraint letter!");
1151     case 'I':  // "I" is a signed 16-bit constant.
1152       return (short)Value == (int)Value;
1153     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
1154     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
1155       return (short)Value == 0;
1156     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
1157       return (Value >> 16) == 0;
1158     case 'M':  // "M" is a constant that is greater than 31.
1159       return Value > 31;
1160     case 'N':  // "N" is a positive constant that is an exact power of two.
1161       return (int)Value > 0 && isPowerOf2_32(Value);
1162     case 'O':  // "O" is the constant zero. 
1163       return Value == 0;
1164     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
1165       return (short)-Value == (int)-Value;
1166     }
1167     break;
1168   }
1169   }
1170   
1171   // Handle standard constraint letters.
1172   return TargetLowering::isOperandValidForConstraint(Op, Letter);
1173 }