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