Change the arg lowering code to use copyfromreg from vregs associated
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPC32ISelLowering.cpp - PPC32 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 PPC32ISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPC32ISelLowering.h"
15 #include "PPC32TargetMachine.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 using namespace llvm;
24
25 PPC32TargetLowering::PPC32TargetLowering(TargetMachine &TM)
26   : TargetLowering(TM) {
27     
28   // Fold away setcc operations if possible.
29   setSetCCIsExpensive();
30   
31   // Set up the register classes.
32   addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
33   addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
34   addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
35   
36   // PowerPC has no intrinsics for these particular operations
37   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
38   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
39   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
40   
41   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
42   setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
43   setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
44   
45   // PowerPC has no SREM/UREM instructions
46   setOperationAction(ISD::SREM, MVT::i32, Expand);
47   setOperationAction(ISD::UREM, MVT::i32, Expand);
48   
49   // We don't support sin/cos/sqrt/fmod
50   setOperationAction(ISD::FSIN , MVT::f64, Expand);
51   setOperationAction(ISD::FCOS , MVT::f64, Expand);
52   setOperationAction(ISD::SREM , MVT::f64, Expand);
53   setOperationAction(ISD::FSIN , MVT::f32, Expand);
54   setOperationAction(ISD::FCOS , MVT::f32, Expand);
55   setOperationAction(ISD::SREM , MVT::f32, Expand);
56   
57   // If we're enabling GP optimizations, use hardware square root
58   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
59     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
60     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
61   }
62   
63   // PowerPC does not have CTPOP or CTTZ
64   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
65   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
66   
67   // PowerPC does not have Select
68   setOperationAction(ISD::SELECT, MVT::i32, Expand);
69   setOperationAction(ISD::SELECT, MVT::f32, Expand);
70   setOperationAction(ISD::SELECT, MVT::f64, Expand);
71   
72   // PowerPC wants to turn select_cc of FP into fsel when possible.
73   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
74   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
75   
76   // PowerPC wants to expand i64 shifts itself.
77   setOperationAction(ISD::SHL, MVT::i64, Custom);
78   setOperationAction(ISD::SRL, MVT::i64, Custom);
79   setOperationAction(ISD::SRA, MVT::i64, Custom);
80
81   // PowerPC does not have BRCOND* which requires SetCC
82   setOperationAction(ISD::BRCOND,       MVT::Other, Expand);
83   setOperationAction(ISD::BRCONDTWOWAY, MVT::Other, Expand);
84   
85   // PowerPC does not have FP_TO_UINT
86   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
87   
88   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
89   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
90
91   // PowerPC does not have [U|S]INT_TO_FP
92   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
93   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
94
95   // PowerPC does not have truncstore for i1.
96   setOperationAction(ISD::TRUNCSTORE, MVT::i1, Promote);
97   
98   // 64 bit PowerPC implementations have instructions to facilitate conversion
99   // between i64 and fp.
100   if (TM.getSubtarget<PPCSubtarget>().is64Bit()) {
101     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
102     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
103   }
104   
105   setSetCCResultContents(ZeroOrOneSetCCResult);
106   
107   computeRegisterProperties();
108 }
109
110 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
111 static bool isFloatingPointZero(SDOperand Op) {
112   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
113     return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
114   else if (Op.getOpcode() == ISD::EXTLOAD || Op.getOpcode() == ISD::LOAD) {
115     // Maybe this has already been legalized into the constant pool?
116     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
117       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->get()))
118         return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
119   }
120   return false;
121 }
122
123 /// LowerOperation - Provide custom lowering hooks for some operations.
124 ///
125 SDOperand PPC32TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
126   switch (Op.getOpcode()) {
127   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
128   case ISD::FP_TO_SINT: {
129     assert(MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
130     switch (Op.getValueType()) {
131     default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
132     case MVT::i32:
133       Op = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Op.getOperand(0));
134       break;
135     case MVT::i64:
136       Op = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Op.getOperand(0));
137       break;
138     }
139    
140     int FrameIdx =
141       DAG.getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
142     SDOperand FI = DAG.getFrameIndex(FrameIdx, MVT::i32);
143     SDOperand ST = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
144                                Op, FI, DAG.getSrcValue(0));
145     if (Op.getOpcode() == PPCISD::FCTIDZ) {
146       Op = DAG.getLoad(MVT::i64, ST, FI, DAG.getSrcValue(0));
147     } else {
148       FI = DAG.getNode(ISD::ADD, MVT::i32, FI, DAG.getConstant(4, MVT::i32));
149       Op = DAG.getLoad(MVT::i32, ST, FI, DAG.getSrcValue(0));
150     }
151     return Op;
152   }
153   case ISD::SINT_TO_FP: {
154     assert(MVT::i64 == Op.getOperand(0).getValueType() && 
155            "Unhandled SINT_TO_FP type in custom expander!");
156     int FrameIdx =
157       DAG.getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
158     SDOperand FI = DAG.getFrameIndex(FrameIdx, MVT::i32);
159     SDOperand ST = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
160                                Op.getOperand(0), FI, DAG.getSrcValue(0));
161     SDOperand LD = DAG.getLoad(MVT::f64, ST, FI, DAG.getSrcValue(0));
162     SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, LD);
163     if (MVT::f32 == Op.getValueType())
164       FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
165     return FP;
166   }
167   case ISD::SELECT_CC: {
168     // Turn FP only select_cc's into fsel instructions.
169     if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
170         !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
171       break;
172     
173     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
174     
175     // Cannot handle SETEQ/SETNE.
176     if (CC == ISD::SETEQ || CC == ISD::SETNE) break;
177     
178     MVT::ValueType ResVT = Op.getValueType();
179     MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
180     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
181     SDOperand TV  = Op.getOperand(2), FV  = Op.getOperand(3);
182
183     // If the RHS of the comparison is a 0.0, we don't need to do the
184     // subtraction at all.
185     if (isFloatingPointZero(RHS))
186       switch (CC) {
187       default: assert(0 && "Invalid FSEL condition"); abort();
188       case ISD::SETULT:
189       case ISD::SETLT:
190         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
191       case ISD::SETUGE:
192       case ISD::SETGE:
193         return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
194       case ISD::SETUGT:
195       case ISD::SETGT:
196         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
197       case ISD::SETULE:
198       case ISD::SETLE:
199         return DAG.getNode(PPCISD::FSEL, ResVT,
200                            DAG.getNode(ISD::FNEG, ResVT, LHS), TV, FV);
201       }
202     
203     switch (CC) {
204     default: assert(0 && "Invalid FSEL condition"); abort();
205     case ISD::SETULT:
206     case ISD::SETLT:
207       return DAG.getNode(PPCISD::FSEL, ResVT,
208                          DAG.getNode(ISD::SUB, CmpVT, LHS, RHS), FV, TV);
209     case ISD::SETUGE:
210     case ISD::SETGE:
211       return DAG.getNode(PPCISD::FSEL, ResVT,
212                          DAG.getNode(ISD::SUB, CmpVT, LHS, RHS), TV, FV);
213     case ISD::SETUGT:
214     case ISD::SETGT:
215       return DAG.getNode(PPCISD::FSEL, ResVT,
216                          DAG.getNode(ISD::SUB, CmpVT, RHS, LHS), FV, TV);
217     case ISD::SETULE:
218     case ISD::SETLE:
219       return DAG.getNode(PPCISD::FSEL, ResVT,
220                          DAG.getNode(ISD::SUB, CmpVT, RHS, LHS), TV, FV);
221     }
222     break;
223   }
224   case ISD::SHL: {
225     assert(Op.getValueType() == MVT::i64 &&
226            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
227     // The generic code does a fine job expanding shift by a constant.
228     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
229     
230     // Otherwise, expand into a bunch of logical ops.  Note that these ops
231     // depend on the PPC behavior for oversized shift amounts.
232     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
233                                DAG.getConstant(0, MVT::i32));
234     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
235                                DAG.getConstant(1, MVT::i32));
236     SDOperand Amt = Op.getOperand(1);
237     
238     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
239                                  DAG.getConstant(32, MVT::i32), Amt);
240     SDOperand Tmp2 = DAG.getNode(ISD::SHL, MVT::i32, Hi, Amt);
241     SDOperand Tmp3 = DAG.getNode(ISD::SRL, MVT::i32, Lo, Tmp1);
242     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
243     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
244                                  DAG.getConstant(-32U, MVT::i32));
245     SDOperand Tmp6 = DAG.getNode(ISD::SHL, MVT::i32, Lo, Tmp5);
246     SDOperand OutHi = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
247     SDOperand OutLo = DAG.getNode(ISD::SHL, MVT::i32, Lo, Amt);
248     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
249   }
250   case ISD::SRL: {
251     assert(Op.getValueType() == MVT::i64 &&
252            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
253     // The generic code does a fine job expanding shift by a constant.
254     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
255     
256     // Otherwise, expand into a bunch of logical ops.  Note that these ops
257     // depend on the PPC behavior for oversized shift amounts.
258     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
259                                DAG.getConstant(0, MVT::i32));
260     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
261                                DAG.getConstant(1, MVT::i32));
262     SDOperand Amt = Op.getOperand(1);
263     
264     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
265                                  DAG.getConstant(32, MVT::i32), Amt);
266     SDOperand Tmp2 = DAG.getNode(ISD::SRL, MVT::i32, Lo, Amt);
267     SDOperand Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, Hi, Tmp1);
268     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
269     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
270                                  DAG.getConstant(-32U, MVT::i32));
271     SDOperand Tmp6 = DAG.getNode(ISD::SRL, MVT::i32, Hi, Tmp5);
272     SDOperand OutLo = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
273     SDOperand OutHi = DAG.getNode(ISD::SRL, MVT::i32, Hi, Amt);
274     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
275   }    
276   case ISD::SRA: {
277     assert(Op.getValueType() == MVT::i64 &&
278            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRA!");
279     // The generic code does a fine job expanding shift by a constant.
280     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
281       
282     // Otherwise, expand into a bunch of logical ops, followed by a select_cc.
283     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
284                                DAG.getConstant(0, MVT::i32));
285     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
286                                DAG.getConstant(1, MVT::i32));
287     SDOperand Amt = Op.getOperand(1);
288     
289     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
290                                  DAG.getConstant(32, MVT::i32), Amt);
291     SDOperand Tmp2 = DAG.getNode(ISD::SRL, MVT::i32, Lo, Amt);
292     SDOperand Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, Hi, Tmp1);
293     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
294     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
295                                  DAG.getConstant(-32U, MVT::i32));
296     SDOperand Tmp6 = DAG.getNode(ISD::SRA, MVT::i32, Hi, Tmp5);
297     SDOperand OutHi = DAG.getNode(ISD::SRA, MVT::i32, Hi, Amt);
298     SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, MVT::i32),
299                                       Tmp4, Tmp6, ISD::SETLE);
300     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
301   }
302   }
303   return SDOperand();
304 }
305
306 std::vector<SDOperand>
307 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
308   //
309   // add beautiful description of PPC stack frame format, or at least some docs
310   //
311   MachineFunction &MF = DAG.getMachineFunction();
312   MachineFrameInfo *MFI = MF.getFrameInfo();
313   MachineBasicBlock& BB = MF.front();
314   SSARegMap *RegMap = MF.getSSARegMap();
315   std::vector<SDOperand> ArgValues;
316   
317   unsigned ArgOffset = 24;
318   unsigned GPR_remaining = 8;
319   unsigned FPR_remaining = 13;
320   unsigned GPR_idx = 0, FPR_idx = 0;
321   static const unsigned GPR[] = {
322     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
323     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
324   };
325   static const unsigned FPR[] = {
326     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
327     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
328   };
329   
330   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
331   // the arguments start at offset 24, although they are likely to be passed
332   // in registers.
333   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
334     SDOperand newroot, argt;
335     unsigned ObjSize;
336     bool needsLoad = false;
337     bool ArgLive = !I->use_empty();
338     MVT::ValueType ObjectVT = getValueType(I->getType());
339     
340     switch (ObjectVT) {
341     default: assert(0 && "Unhandled argument type!");
342     case MVT::i1:
343     case MVT::i8:
344     case MVT::i16:
345     case MVT::i32:
346       ObjSize = 4;
347       if (!ArgLive) break;
348       if (GPR_remaining > 0) {
349         unsigned VReg = RegMap->createVirtualRegister(&PPC32::GPRCRegClass);
350         MF.addLiveIn(GPR[GPR_idx], VReg);
351         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
352         if (ObjectVT != MVT::i32) {
353           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
354                                                        : ISD::AssertZext;
355           argt = DAG.getNode(AssertOp, MVT::i32, argt, 
356                              DAG.getValueType(ObjectVT));
357           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, argt);
358         }
359       } else {
360         needsLoad = true;
361       }
362       break;
363     case MVT::i64: ObjSize = 8;
364       if (!ArgLive) break;
365       if (GPR_remaining > 0) {
366         SDOperand argHi, argLo;
367         unsigned VReg = RegMap->createVirtualRegister(&PPC32::GPRCRegClass);
368         MF.addLiveIn(GPR[GPR_idx], VReg);
369         argHi = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
370         // If we have two or more remaining argument registers, then both halves
371         // of the i64 can be sourced from there.  Otherwise, the lower half will
372         // have to come off the stack.  This can happen when an i64 is preceded
373         // by 28 bytes of arguments.
374         if (GPR_remaining > 1) {
375           unsigned VReg = RegMap->createVirtualRegister(&PPC32::GPRCRegClass);
376           MF.addLiveIn(GPR[GPR_idx+1], VReg);
377           argLo = DAG.getCopyFromReg(argHi, VReg, MVT::i32);
378         } else {
379           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
380           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
381           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
382                               DAG.getSrcValue(NULL));
383         }
384         // Build the outgoing arg thingy
385         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
386         newroot = argLo;
387       } else {
388         needsLoad = true;
389       }
390       break;
391     case MVT::f32:
392     case MVT::f64:
393       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
394       if (!ArgLive) break;
395       if (FPR_remaining > 0) {
396         unsigned VReg = RegMap->createVirtualRegister(&PPC32::FPRCRegClass);
397         MF.addLiveIn(FPR[FPR_idx], VReg);
398         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, ObjectVT);
399         --FPR_remaining;
400         ++FPR_idx;
401       } else {
402         needsLoad = true;
403       }
404       break;
405     }
406     
407     // We need to load the argument to a virtual register if we determined above
408     // that we ran out of physical registers of the appropriate type
409     if (needsLoad) {
410       unsigned SubregOffset = 0;
411       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
412       if (ObjectVT == MVT::i16) SubregOffset = 2;
413       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
414       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
415       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
416                         DAG.getConstant(SubregOffset, MVT::i32));
417       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
418                                    DAG.getSrcValue(NULL));
419     }
420     
421     // Every 4 bytes of argument space consumes one of the GPRs available for
422     // argument passing.
423     if (GPR_remaining > 0) {
424       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
425       GPR_remaining -= delta;
426       GPR_idx += delta;
427     }
428     ArgOffset += ObjSize;
429     if (newroot.Val)
430       DAG.setRoot(newroot.getValue(1));
431     
432     ArgValues.push_back(argt);
433   }
434   
435   // If the function takes variable number of arguments, make a frame index for
436   // the start of the first vararg value... for expansion of llvm.va_start.
437   if (F.isVarArg()) {
438     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
439     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
440     // If this function is vararg, store any remaining integer argument regs
441     // to their spots on the stack so that they may be loaded by deferencing the
442     // result of va_next.
443     std::vector<SDOperand> MemOps;
444     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
445       unsigned VReg = RegMap->createVirtualRegister(&PPC32::GPRCRegClass);
446       MF.addLiveIn(GPR[GPR_idx], VReg);
447       SDOperand Val = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
448       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
449                                     Val, FIN, DAG.getSrcValue(NULL));
450       MemOps.push_back(Store);
451       // Increment the address by four for the next argument to store
452       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
453       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
454     }
455     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
456   }
457   
458   // Finally, inform the code generator which regs we return values in.
459   switch (getValueType(F.getReturnType())) {
460     default: assert(0 && "Unknown type!");
461     case MVT::isVoid: break;
462     case MVT::i1:
463     case MVT::i8:
464     case MVT::i16:
465     case MVT::i32:
466       MF.addLiveOut(PPC::R3);
467       break;
468     case MVT::i64:
469       MF.addLiveOut(PPC::R3);
470       MF.addLiveOut(PPC::R4);
471       break;
472     case MVT::f32:
473     case MVT::f64:
474       MF.addLiveOut(PPC::F1);
475       break;
476   }
477   
478   return ArgValues;
479 }
480
481 std::pair<SDOperand, SDOperand>
482 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
483                                  const Type *RetTy, bool isVarArg,
484                                  unsigned CallingConv, bool isTailCall,
485                                  SDOperand Callee, ArgListTy &Args,
486                                  SelectionDAG &DAG) {
487   // args_to_use will accumulate outgoing args for the ISD::CALL case in
488   // SelectExpr to use to put the arguments in the appropriate registers.
489   std::vector<SDOperand> args_to_use;
490   
491   // Count how many bytes are to be pushed on the stack, including the linkage
492   // area, and parameter passing area.
493   unsigned NumBytes = 24;
494   
495   if (Args.empty()) {
496     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
497                         DAG.getConstant(NumBytes, getPointerTy()));
498   } else {
499     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
500       switch (getValueType(Args[i].second)) {
501       default: assert(0 && "Unknown value type!");
502       case MVT::i1:
503       case MVT::i8:
504       case MVT::i16:
505       case MVT::i32:
506       case MVT::f32:
507         NumBytes += 4;
508         break;
509       case MVT::i64:
510       case MVT::f64:
511         NumBytes += 8;
512         break;
513       }
514     }
515         
516     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
517     // plus 32 bytes of argument space in case any called code gets funky on us.
518     // (Required by ABI to support var arg)
519     if (NumBytes < 56) NumBytes = 56;
520     
521     // Adjust the stack pointer for the new arguments...
522     // These operations are automatically eliminated by the prolog/epilog pass
523     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
524                         DAG.getConstant(NumBytes, getPointerTy()));
525     
526     // Set up a copy of the stack pointer for use loading and storing any
527     // arguments that may not fit in the registers available for argument
528     // passing.
529     SDOperand StackPtr = DAG.getCopyFromReg(DAG.getEntryNode(),
530                                             PPC::R1, MVT::i32);
531     
532     // Figure out which arguments are going to go in registers, and which in
533     // memory.  Also, if this is a vararg function, floating point operations
534     // must be stored to our stack, and loaded into integer regs as well, if
535     // any integer regs are available for argument passing.
536     unsigned ArgOffset = 24;
537     unsigned GPR_remaining = 8;
538     unsigned FPR_remaining = 13;
539     
540     std::vector<SDOperand> MemOps;
541     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
542       // PtrOff will be used to store the current argument to the stack if a
543       // register cannot be found for it.
544       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
545       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
546       MVT::ValueType ArgVT = getValueType(Args[i].second);
547       
548       switch (ArgVT) {
549       default: assert(0 && "Unexpected ValueType for argument!");
550       case MVT::i1:
551       case MVT::i8:
552       case MVT::i16:
553         // Promote the integer to 32 bits.  If the input type is signed use a
554         // sign extend, otherwise use a zero extend.
555         if (Args[i].second->isSigned())
556           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
557         else
558           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
559         // FALL THROUGH
560       case MVT::i32:
561         if (GPR_remaining > 0) {
562           args_to_use.push_back(Args[i].first);
563           --GPR_remaining;
564         } else {
565           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
566                                        Args[i].first, PtrOff,
567                                        DAG.getSrcValue(NULL)));
568         }
569         ArgOffset += 4;
570         break;
571       case MVT::i64:
572         // If we have one free GPR left, we can place the upper half of the i64
573         // in it, and store the other half to the stack.  If we have two or more
574         // free GPRs, then we can pass both halves of the i64 in registers.
575         if (GPR_remaining > 0) {
576           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
577                                      Args[i].first, DAG.getConstant(1, MVT::i32));
578           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
579                                      Args[i].first, DAG.getConstant(0, MVT::i32));
580           args_to_use.push_back(Hi);
581           --GPR_remaining;
582           if (GPR_remaining > 0) {
583             args_to_use.push_back(Lo);
584             --GPR_remaining;
585           } else {
586             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
587             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
588             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
589                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
590           }
591         } else {
592           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
593                                        Args[i].first, PtrOff,
594                                        DAG.getSrcValue(NULL)));
595         }
596         ArgOffset += 8;
597         break;
598       case MVT::f32:
599       case MVT::f64:
600         if (FPR_remaining > 0) {
601           args_to_use.push_back(Args[i].first);
602           --FPR_remaining;
603           if (isVarArg) {
604             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
605                                           Args[i].first, PtrOff,
606                                           DAG.getSrcValue(NULL));
607             MemOps.push_back(Store);
608             // Float varargs are always shadowed in available integer registers
609             if (GPR_remaining > 0) {
610               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
611                                            DAG.getSrcValue(NULL));
612               MemOps.push_back(Load);
613               args_to_use.push_back(Load);
614               --GPR_remaining;
615             }
616             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
617               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
618               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
619               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
620                                            DAG.getSrcValue(NULL));
621               MemOps.push_back(Load);
622               args_to_use.push_back(Load);
623               --GPR_remaining;
624             }
625           } else {
626             // If we have any FPRs remaining, we may also have GPRs remaining.
627             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
628             // GPRs.
629             if (GPR_remaining > 0) {
630               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
631               --GPR_remaining;
632             }
633             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
634               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
635               --GPR_remaining;
636             }
637           }
638         } else {
639           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
640                                        Args[i].first, PtrOff,
641                                        DAG.getSrcValue(NULL)));
642         }
643         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
644         break;
645       }
646     }
647     if (!MemOps.empty())
648       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
649   }
650   
651   std::vector<MVT::ValueType> RetVals;
652   MVT::ValueType RetTyVT = getValueType(RetTy);
653   MVT::ValueType ActualRetTyVT = RetTyVT;
654   if (RetTyVT >= MVT::i1 && RetTyVT <= MVT::i16)
655     ActualRetTyVT = MVT::i32;   // Promote result to i32.
656     
657   if (RetTyVT != MVT::isVoid)
658     RetVals.push_back(ActualRetTyVT);
659   RetVals.push_back(MVT::Other);
660   
661   SDOperand TheCall = SDOperand(DAG.getCall(RetVals,
662                                             Chain, Callee, args_to_use), 0);
663   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
664   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
665                       DAG.getConstant(NumBytes, getPointerTy()));
666   SDOperand RetVal = TheCall;
667   
668   // If the result is a small value, add a note so that we keep track of the
669   // information about whether it is sign or zero extended.
670   if (RetTyVT != ActualRetTyVT) {
671     RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext : ISD::AssertZext,
672                          MVT::i32, RetVal, DAG.getValueType(RetTyVT));
673     RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
674   }
675   
676   return std::make_pair(RetVal, Chain);
677 }
678
679 SDOperand PPC32TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
680                                             Value *VAListV, SelectionDAG &DAG) {
681   // vastart just stores the address of the VarArgsFrameIndex slot into the
682   // memory location argument.
683   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
684   return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
685                      DAG.getSrcValue(VAListV));
686 }
687
688 std::pair<SDOperand,SDOperand>
689 PPC32TargetLowering::LowerVAArg(SDOperand Chain,
690                                 SDOperand VAListP, Value *VAListV,
691                                 const Type *ArgTy, SelectionDAG &DAG) {
692   MVT::ValueType ArgVT = getValueType(ArgTy);
693   
694   SDOperand VAList =
695     DAG.getLoad(MVT::i32, Chain, VAListP, DAG.getSrcValue(VAListV));
696   SDOperand Result = DAG.getLoad(ArgVT, Chain, VAList, DAG.getSrcValue(NULL));
697   unsigned Amt;
698   if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
699     Amt = 4;
700   else {
701     assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
702            "Other types should have been promoted for varargs!");
703     Amt = 8;
704   }
705   VAList = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
706                        DAG.getConstant(Amt, VAList.getValueType()));
707   Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
708                       VAList, VAListP, DAG.getSrcValue(VAListV));
709   return std::make_pair(Result, Chain);
710 }
711
712
713 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
714 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
715                         SelectionDAG &DAG) {
716   assert(0 && "LowerFrameReturnAddress unimplemented");
717   abort();
718 }
719
720 MachineBasicBlock *
721 PPC32TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
722                                              MachineBasicBlock *BB) {
723   assert((MI->getOpcode() == PPC::SELECT_CC_Int ||
724           MI->getOpcode() == PPC::SELECT_CC_FP) &&
725          "Unexpected instr type to insert");
726   
727   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
728   // control-flow pattern.  The incoming instruction knows the destination vreg
729   // to set, the condition code register to branch on, the true/false values to
730   // select between, and a branch opcode to use.
731   const BasicBlock *LLVM_BB = BB->getBasicBlock();
732   ilist<MachineBasicBlock>::iterator It = BB;
733   ++It;
734   
735   //  thisMBB:
736   //  ...
737   //   TrueVal = ...
738   //   cmpTY ccX, r1, r2
739   //   bCC copy1MBB
740   //   fallthrough --> copy0MBB
741   MachineBasicBlock *thisMBB = BB;
742   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
743   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
744   BuildMI(BB, MI->getOperand(4).getImmedValue(), 2)
745     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
746   MachineFunction *F = BB->getParent();
747   F->getBasicBlockList().insert(It, copy0MBB);
748   F->getBasicBlockList().insert(It, sinkMBB);
749   // Update machine-CFG edges
750   BB->addSuccessor(copy0MBB);
751   BB->addSuccessor(sinkMBB);
752   
753   //  copy0MBB:
754   //   %FalseValue = ...
755   //   # fallthrough to sinkMBB
756   BB = copy0MBB;
757   
758   // Update machine-CFG edges
759   BB->addSuccessor(sinkMBB);
760   
761   //  sinkMBB:
762   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
763   //  ...
764   BB = sinkMBB;
765   BuildMI(BB, PPC::PHI, 4, MI->getOperand(0).getReg())
766     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
767     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
768
769   delete MI;   // The pseudo instruction is gone now.
770   return BB;
771 }
772