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