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