PPCISelDAGToDAG.cpp revision e6ec9f20c9df6387b68874e4c49035d3c9c5527f
1//===-- PPC32ISelDAGToDAG.cpp - PPC32 pattern matching inst selector ------===//
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 defines a pattern matching instruction selector for 32 bit PowerPC,
11// converting from a legalized dag to a PPC dag.
12//
13//===----------------------------------------------------------------------===//
14
15#include "PowerPC.h"
16#include "PPC32TargetMachine.h"
17#include "PPC32ISelLowering.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/SSARegMap.h"
21#include "llvm/CodeGen/SelectionDAG.h"
22#include "llvm/CodeGen/SelectionDAGISel.h"
23#include "llvm/Target/TargetOptions.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Constants.h"
26#include "llvm/GlobalValue.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/MathExtras.h"
29using namespace llvm;
30
31namespace {
32  Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
33  Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
34
35  //===--------------------------------------------------------------------===//
36  /// PPC32DAGToDAGISel - PPC32 specific code to select PPC32 machine
37  /// instructions for SelectionDAG operations.
38  ///
39  class PPC32DAGToDAGISel : public SelectionDAGISel {
40    PPC32TargetLowering PPC32Lowering;
41    unsigned GlobalBaseReg;
42  public:
43    PPC32DAGToDAGISel(TargetMachine &TM)
44      : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) {}
45
46    virtual bool runOnFunction(Function &Fn) {
47      // Make sure we re-emit a set of the global base reg if necessary
48      GlobalBaseReg = 0;
49      return SelectionDAGISel::runOnFunction(Fn);
50    }
51
52    /// getI32Imm - Return a target constant with the specified value, of type
53    /// i32.
54    inline SDOperand getI32Imm(unsigned Imm) {
55      return CurDAG->getTargetConstant(Imm, MVT::i32);
56    }
57
58    /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
59    /// base register.  Return the virtual register that holds this value.
60    SDOperand getGlobalBaseReg();
61
62    // Select - Convert the specified operand from a target-independent to a
63    // target-specific node if it hasn't already been changed.
64    SDOperand Select(SDOperand Op);
65    SDOperand SelectCode(SDOperand Op);
66
67    SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
68                                   unsigned OCHi, unsigned OCLo,
69                                   bool IsArithmetic = false,
70                                   bool Negate = false);
71    SDNode *SelectBitfieldInsert(SDNode *N);
72
73    /// SelectCC - Select a comparison of the specified values with the
74    /// specified condition code, returning the CR# of the expression.
75    SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
76
77    /// SelectAddr - Given the specified address, return the two operands for a
78    /// load/store instruction, and return true if it should be an indexed [r+r]
79    /// operation.
80    bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
81
82    SDOperand BuildSDIVSequence(SDNode *N);
83    SDOperand BuildUDIVSequence(SDNode *N);
84
85    /// InstructionSelectBasicBlock - This callback is invoked by
86    /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
87    virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
88      DEBUG(BB->dump());
89      // Select target instructions for the DAG.
90      DAG.setRoot(Select(DAG.getRoot()));
91      DAG.RemoveDeadNodes();
92
93      // Emit machine code to BB.
94      ScheduleAndEmitDAG(DAG);
95    }
96
97    virtual const char *getPassName() const {
98      return "PowerPC DAG->DAG Pattern Instruction Selection";
99    }
100  };
101}
102
103#include "PPC32GenDAGISel.inc"
104
105/// getGlobalBaseReg - Output the instructions required to put the
106/// base address to use for accessing globals into a register.
107///
108SDOperand PPC32DAGToDAGISel::getGlobalBaseReg() {
109  if (!GlobalBaseReg) {
110    // Insert the set of GlobalBaseReg into the first MBB of the function
111    MachineBasicBlock &FirstMBB = BB->getParent()->front();
112    MachineBasicBlock::iterator MBBI = FirstMBB.begin();
113    SSARegMap *RegMap = BB->getParent()->getSSARegMap();
114    GlobalBaseReg = RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
115    BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
116    BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
117  }
118  return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
119}
120
121
122// isIntImmediate - This method tests to see if a constant operand.
123// If so Imm will receive the 32 bit value.
124static bool isIntImmediate(SDNode *N, unsigned& Imm) {
125  if (N->getOpcode() == ISD::Constant) {
126    Imm = cast<ConstantSDNode>(N)->getValue();
127    return true;
128  }
129  return false;
130}
131
132// isOprShiftImm - Returns true if the specified operand is a shift opcode with
133// a immediate shift count less than 32.
134static bool isOprShiftImm(SDNode *N, unsigned& Opc, unsigned& SH) {
135  Opc = N->getOpcode();
136  return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
137    isIntImmediate(N->getOperand(1).Val, SH) && SH < 32;
138}
139
140// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
141// any number of 0s on either side.  The 1s are allowed to wrap from LSB to
142// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
143// not, since all 1s are not contiguous.
144static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
145  if (isShiftedMask_32(Val)) {
146    // look for the first non-zero bit
147    MB = CountLeadingZeros_32(Val);
148    // look for the first zero bit after the run of ones
149    ME = CountLeadingZeros_32((Val - 1) ^ Val);
150    return true;
151  } else {
152    Val = ~Val; // invert mask
153    if (isShiftedMask_32(Val)) {
154      // effectively look for the first zero bit
155      ME = CountLeadingZeros_32(Val) - 1;
156      // effectively look for the first one bit after the run of zeros
157      MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
158      return true;
159    }
160  }
161  // no run present
162  return false;
163}
164
165// isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
166// and mask opcode and mask operation.
167static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
168                            unsigned &SH, unsigned &MB, unsigned &ME) {
169  unsigned Shift  = 32;
170  unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
171  unsigned Opcode = N->getOpcode();
172  if (N->getNumOperands() != 2 ||
173      !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
174    return false;
175
176  if (Opcode == ISD::SHL) {
177    // apply shift left to mask if it comes first
178    if (IsShiftMask) Mask = Mask << Shift;
179    // determine which bits are made indeterminant by shift
180    Indeterminant = ~(0xFFFFFFFFu << Shift);
181  } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) {
182    // apply shift right to mask if it comes first
183    if (IsShiftMask) Mask = Mask >> Shift;
184    // determine which bits are made indeterminant by shift
185    Indeterminant = ~(0xFFFFFFFFu >> Shift);
186    // adjust for the left rotate
187    Shift = 32 - Shift;
188  } else {
189    return false;
190  }
191
192  // if the mask doesn't intersect any Indeterminant bits
193  if (Mask && !(Mask & Indeterminant)) {
194    SH = Shift;
195    // make sure the mask is still a mask (wrap arounds may not be)
196    return isRunOfOnes(Mask, MB, ME);
197  }
198  return false;
199}
200
201// isOpcWithIntImmediate - This method tests to see if the node is a specific
202// opcode and that it has a immediate integer right operand.
203// If so Imm will receive the 32 bit value.
204static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
205  return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
206}
207
208// isOprNot - Returns true if the specified operand is an xor with immediate -1.
209static bool isOprNot(SDNode *N) {
210  unsigned Imm;
211  return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
212}
213
214// Immediate constant composers.
215// Lo16 - grabs the lo 16 bits from a 32 bit constant.
216// Hi16 - grabs the hi 16 bits from a 32 bit constant.
217// HA16 - computes the hi bits required if the lo bits are add/subtracted in
218// arithmethically.
219static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
220static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
221static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }
222
223// isIntImmediate - This method tests to see if a constant operand.
224// If so Imm will receive the 32 bit value.
225static bool isIntImmediate(SDOperand N, unsigned& Imm) {
226  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
227    Imm = (unsigned)CN->getSignExtended();
228    return true;
229  }
230  return false;
231}
232
233/// SelectBitfieldInsert - turn an or of two masked values into
234/// the rotate left word immediate then mask insert (rlwimi) instruction.
235/// Returns true on success, false if the caller still needs to select OR.
236///
237/// Patterns matched:
238/// 1. or shl, and   5. or and, and
239/// 2. or and, shl   6. or shl, shr
240/// 3. or shr, and   7. or shr, shl
241/// 4. or and, shr
242SDNode *PPC32DAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
243  bool IsRotate = false;
244  unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
245  unsigned Value;
246
247  SDOperand Op0 = N->getOperand(0);
248  SDOperand Op1 = N->getOperand(1);
249
250  unsigned Op0Opc = Op0.getOpcode();
251  unsigned Op1Opc = Op1.getOpcode();
252
253  // Verify that we have the correct opcodes
254  if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
255    return false;
256  if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
257    return false;
258
259  // Generate Mask value for Target
260  if (isIntImmediate(Op0.getOperand(1), Value)) {
261    switch(Op0Opc) {
262    case ISD::SHL: TgtMask <<= Value; break;
263    case ISD::SRL: TgtMask >>= Value; break;
264    case ISD::AND: TgtMask &= Value; break;
265    }
266  } else {
267    return 0;
268  }
269
270  // Generate Mask value for Insert
271  if (!isIntImmediate(Op1.getOperand(1), Value))
272    return 0;
273
274  switch(Op1Opc) {
275  case ISD::SHL:
276    SH = Value;
277    InsMask <<= SH;
278    if (Op0Opc == ISD::SRL) IsRotate = true;
279    break;
280  case ISD::SRL:
281    SH = Value;
282    InsMask >>= SH;
283    SH = 32-SH;
284    if (Op0Opc == ISD::SHL) IsRotate = true;
285    break;
286  case ISD::AND:
287    InsMask &= Value;
288    break;
289  }
290
291  // If both of the inputs are ANDs and one of them has a logical shift by
292  // constant as its input, make that AND the inserted value so that we can
293  // combine the shift into the rotate part of the rlwimi instruction
294  bool IsAndWithShiftOp = false;
295  if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
296    if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
297        Op1.getOperand(0).getOpcode() == ISD::SRL) {
298      if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
299        SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
300        IsAndWithShiftOp = true;
301      }
302    } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
303               Op0.getOperand(0).getOpcode() == ISD::SRL) {
304      if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
305        std::swap(Op0, Op1);
306        std::swap(TgtMask, InsMask);
307        SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
308        IsAndWithShiftOp = true;
309      }
310    }
311  }
312
313  // Verify that the Target mask and Insert mask together form a full word mask
314  // and that the Insert mask is a run of set bits (which implies both are runs
315  // of set bits).  Given that, Select the arguments and generate the rlwimi
316  // instruction.
317  unsigned MB, ME;
318  if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
319    bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
320    bool Op0IsAND = Op0Opc == ISD::AND;
321    // Check for rotlwi / rotrwi here, a special case of bitfield insert
322    // where both bitfield halves are sourced from the same value.
323    if (IsRotate && fullMask &&
324        N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
325      Op0 = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32,
326                                  Select(N->getOperand(0).getOperand(0)),
327                                  getI32Imm(SH), getI32Imm(0), getI32Imm(31));
328      return Op0.Val;
329    }
330    SDOperand Tmp1 = (Op0IsAND && fullMask) ? Select(Op0.getOperand(0))
331                                            : Select(Op0);
332    SDOperand Tmp2 = IsAndWithShiftOp ? Select(Op1.getOperand(0).getOperand(0))
333                                      : Select(Op1.getOperand(0));
334    Op0 = CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
335                                getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
336    return Op0.Val;
337  }
338  return 0;
339}
340
341// SelectIntImmediateExpr - Choose code for integer operations with an immediate
342// operand.
343SDNode *PPC32DAGToDAGISel::SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
344                                                  unsigned OCHi, unsigned OCLo,
345                                                  bool IsArithmetic,
346                                                  bool Negate) {
347  // Check to make sure this is a constant.
348  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS);
349  // Exit if not a constant.
350  if (!CN) return 0;
351  // Extract immediate.
352  unsigned C = (unsigned)CN->getValue();
353  // Negate if required (ISD::SUB).
354  if (Negate) C = -C;
355  // Get the hi and lo portions of constant.
356  unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
357  unsigned Lo = Lo16(C);
358
359  // If two instructions are needed and usage indicates it would be better to
360  // load immediate into a register, bail out.
361  if (Hi && Lo && CN->use_size() > 2) return false;
362
363  // Select the first operand.
364  SDOperand Opr0 = Select(LHS);
365
366  if (Lo)  // Add in the lo-part.
367    Opr0 = CurDAG->getTargetNode(OCLo, MVT::i32, Opr0, getI32Imm(Lo));
368  if (Hi)  // Add in the hi-part.
369    Opr0 = CurDAG->getTargetNode(OCHi, MVT::i32, Opr0, getI32Imm(Hi));
370  return Opr0.Val;
371}
372
373/// SelectAddr - Given the specified address, return the two operands for a
374/// load/store instruction, and return true if it should be an indexed [r+r]
375/// operation.
376bool PPC32DAGToDAGISel::SelectAddr(SDOperand Addr, SDOperand &Op1,
377                                   SDOperand &Op2) {
378  unsigned imm = 0;
379  if (Addr.getOpcode() == ISD::ADD) {
380    if (isIntImmediate(Addr.getOperand(1), imm) && isInt16(imm)) {
381      Op1 = getI32Imm(Lo16(imm));
382      if (FrameIndexSDNode *FI =
383            dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
384        ++FrameOff;
385        Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
386      } else {
387        Op2 = Select(Addr.getOperand(0));
388      }
389      return false;
390    } else {
391      Op1 = Select(Addr.getOperand(0));
392      Op2 = Select(Addr.getOperand(1));
393      return true;   // [r+r]
394    }
395  }
396
397  // Now check if we're dealing with a global, and whether or not we should emit
398  // an optimized load or store for statics.
399  if (GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Addr)) {
400    GlobalValue *GV = GN->getGlobal();
401    if (!GV->hasWeakLinkage() && !GV->isExternal()) {
402      Op1 = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
403      if (PICEnabled)
404        Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),
405                                    Op1);
406      else
407        Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
408      return false;
409    }
410  } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Addr)) {
411    Op1 = getI32Imm(0);
412    Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
413    return false;
414  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Addr)) {
415    Op1 = Addr;
416    if (PICEnabled)
417      Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),Op1);
418    else
419      Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
420    return false;
421  }
422  Op1 = getI32Imm(0);
423  Op2 = Select(Addr);
424  return false;
425}
426
427/// SelectCC - Select a comparison of the specified values with the specified
428/// condition code, returning the CR# of the expression.
429SDOperand PPC32DAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
430                                      ISD::CondCode CC) {
431  // Always select the LHS.
432  LHS = Select(LHS);
433
434  // Use U to determine whether the SETCC immediate range is signed or not.
435  if (MVT::isInteger(LHS.getValueType())) {
436    bool U = ISD::isUnsignedIntSetCC(CC);
437    unsigned Imm;
438    if (isIntImmediate(RHS, Imm) &&
439        ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
440      return CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI, MVT::i32,
441                                   LHS, getI32Imm(Lo16(Imm)));
442    return CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
443                                 LHS, Select(RHS));
444  } else {
445    return CurDAG->getTargetNode(PPC::FCMPU, MVT::i32, LHS, Select(RHS));
446  }
447}
448
449/// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
450/// to Condition.
451static unsigned getBCCForSetCC(ISD::CondCode CC) {
452  switch (CC) {
453  default: assert(0 && "Unknown condition!"); abort();
454  case ISD::SETEQ:  return PPC::BEQ;
455  case ISD::SETNE:  return PPC::BNE;
456  case ISD::SETULT:
457  case ISD::SETLT:  return PPC::BLT;
458  case ISD::SETULE:
459  case ISD::SETLE:  return PPC::BLE;
460  case ISD::SETUGT:
461  case ISD::SETGT:  return PPC::BGT;
462  case ISD::SETUGE:
463  case ISD::SETGE:  return PPC::BGE;
464  }
465  return 0;
466}
467
468/// getCRIdxForSetCC - Return the index of the condition register field
469/// associated with the SetCC condition, and whether or not the field is
470/// treated as inverted.  That is, lt = 0; ge = 0 inverted.
471static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
472  switch (CC) {
473  default: assert(0 && "Unknown condition!"); abort();
474  case ISD::SETULT:
475  case ISD::SETLT:  Inv = false;  return 0;
476  case ISD::SETUGE:
477  case ISD::SETGE:  Inv = true;   return 0;
478  case ISD::SETUGT:
479  case ISD::SETGT:  Inv = false;  return 1;
480  case ISD::SETULE:
481  case ISD::SETLE:  Inv = true;   return 1;
482  case ISD::SETEQ:  Inv = false;  return 2;
483  case ISD::SETNE:  Inv = true;   return 2;
484  }
485  return 0;
486}
487
488// Structure used to return the necessary information to codegen an SDIV as
489// a multiply.
490struct ms {
491  int m; // magic number
492  int s; // shift amount
493};
494
495struct mu {
496  unsigned int m; // magic number
497  int a;          // add indicator
498  int s;          // shift amount
499};
500
501/// magic - calculate the magic numbers required to codegen an integer sdiv as
502/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
503/// or -1.
504static struct ms magic(int d) {
505  int p;
506  unsigned int ad, anc, delta, q1, r1, q2, r2, t;
507  const unsigned int two31 = 0x80000000U;
508  struct ms mag;
509
510  ad = abs(d);
511  t = two31 + ((unsigned int)d >> 31);
512  anc = t - 1 - t%ad;   // absolute value of nc
513  p = 31;               // initialize p
514  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
515  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
516  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
517  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
518  do {
519    p = p + 1;
520    q1 = 2*q1;        // update q1 = 2p/abs(nc)
521    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
522    if (r1 >= anc) {  // must be unsigned comparison
523      q1 = q1 + 1;
524      r1 = r1 - anc;
525    }
526    q2 = 2*q2;        // update q2 = 2p/abs(d)
527    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
528    if (r2 >= ad) {   // must be unsigned comparison
529      q2 = q2 + 1;
530      r2 = r2 - ad;
531    }
532    delta = ad - r2;
533  } while (q1 < delta || (q1 == delta && r1 == 0));
534
535  mag.m = q2 + 1;
536  if (d < 0) mag.m = -mag.m; // resulting magic number
537  mag.s = p - 32;            // resulting shift
538  return mag;
539}
540
541/// magicu - calculate the magic numbers required to codegen an integer udiv as
542/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
543static struct mu magicu(unsigned d)
544{
545  int p;
546  unsigned int nc, delta, q1, r1, q2, r2;
547  struct mu magu;
548  magu.a = 0;               // initialize "add" indicator
549  nc = - 1 - (-d)%d;
550  p = 31;                   // initialize p
551  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
552  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
553  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
554  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
555  do {
556    p = p + 1;
557    if (r1 >= nc - r1 ) {
558      q1 = 2*q1 + 1;  // update q1
559      r1 = 2*r1 - nc; // update r1
560    }
561    else {
562      q1 = 2*q1; // update q1
563      r1 = 2*r1; // update r1
564    }
565    if (r2 + 1 >= d - r2) {
566      if (q2 >= 0x7FFFFFFF) magu.a = 1;
567      q2 = 2*q2 + 1;     // update q2
568      r2 = 2*r2 + 1 - d; // update r2
569    }
570    else {
571      if (q2 >= 0x80000000) magu.a = 1;
572      q2 = 2*q2;     // update q2
573      r2 = 2*r2 + 1; // update r2
574    }
575    delta = d - 1 - r2;
576  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
577  magu.m = q2 + 1; // resulting magic number
578  magu.s = p - 32;  // resulting shift
579  return magu;
580}
581
582/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
583/// return a DAG expression to select that will generate the same value by
584/// multiplying by a magic number.  See:
585/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
586SDOperand PPC32DAGToDAGISel::BuildSDIVSequence(SDNode *N) {
587  int d = (int)cast<ConstantSDNode>(N->getOperand(1))->getValue();
588  ms magics = magic(d);
589  // Multiply the numerator (operand 0) by the magic value
590  SDOperand Q = CurDAG->getNode(ISD::MULHS, MVT::i32, N->getOperand(0),
591                                CurDAG->getConstant(magics.m, MVT::i32));
592  // If d > 0 and m < 0, add the numerator
593  if (d > 0 && magics.m < 0)
594    Q = CurDAG->getNode(ISD::ADD, MVT::i32, Q, N->getOperand(0));
595  // If d < 0 and m > 0, subtract the numerator.
596  if (d < 0 && magics.m > 0)
597    Q = CurDAG->getNode(ISD::SUB, MVT::i32, Q, N->getOperand(0));
598  // Shift right algebraic if shift value is nonzero
599  if (magics.s > 0)
600    Q = CurDAG->getNode(ISD::SRA, MVT::i32, Q,
601                        CurDAG->getConstant(magics.s, MVT::i32));
602  // Extract the sign bit and add it to the quotient
603  SDOperand T =
604    CurDAG->getNode(ISD::SRL, MVT::i32, Q, CurDAG->getConstant(31, MVT::i32));
605  return CurDAG->getNode(ISD::ADD, MVT::i32, Q, T);
606}
607
608/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
609/// return a DAG expression to select that will generate the same value by
610/// multiplying by a magic number.  See:
611/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
612SDOperand PPC32DAGToDAGISel::BuildUDIVSequence(SDNode *N) {
613  unsigned d = (unsigned)cast<ConstantSDNode>(N->getOperand(1))->getValue();
614  mu magics = magicu(d);
615  // Multiply the numerator (operand 0) by the magic value
616  SDOperand Q = CurDAG->getNode(ISD::MULHU, MVT::i32, N->getOperand(0),
617                                CurDAG->getConstant(magics.m, MVT::i32));
618  if (magics.a == 0) {
619    return CurDAG->getNode(ISD::SRL, MVT::i32, Q,
620                           CurDAG->getConstant(magics.s, MVT::i32));
621  } else {
622    SDOperand NPQ = CurDAG->getNode(ISD::SUB, MVT::i32, N->getOperand(0), Q);
623    NPQ = CurDAG->getNode(ISD::SRL, MVT::i32, NPQ,
624                           CurDAG->getConstant(1, MVT::i32));
625    NPQ = CurDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
626    return CurDAG->getNode(ISD::SRL, MVT::i32, NPQ,
627                           CurDAG->getConstant(magics.s-1, MVT::i32));
628  }
629}
630
631// Select - Convert the specified operand from a target-independent to a
632// target-specific node if it hasn't already been changed.
633SDOperand PPC32DAGToDAGISel::Select(SDOperand Op) {
634  SDNode *N = Op.Val;
635  if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
636      N->getOpcode() < PPCISD::FIRST_NUMBER)
637    return Op;   // Already selected.
638
639  switch (N->getOpcode()) {
640  default: break;
641  case ISD::TokenFactor: {
642    SDOperand New;
643    if (N->getNumOperands() == 2) {
644      SDOperand Op0 = Select(N->getOperand(0));
645      SDOperand Op1 = Select(N->getOperand(1));
646      New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
647    } else {
648      std::vector<SDOperand> Ops;
649      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
650        Ops.push_back(Select(N->getOperand(i)));
651      New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
652    }
653
654    if (New.Val != N) {
655      CurDAG->ReplaceAllUsesWith(Op, New);
656      N = New.Val;
657    }
658    return SDOperand(N, 0);
659  }
660  case ISD::CopyFromReg: {
661    SDOperand Chain = Select(N->getOperand(0));
662    if (Chain == N->getOperand(0)) return Op; // No change
663    SDOperand New = CurDAG->getCopyFromReg(Chain,
664         cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
665    return New.getValue(Op.ResNo);
666  }
667  case ISD::CopyToReg: {
668    SDOperand Chain = Select(N->getOperand(0));
669    SDOperand Reg = N->getOperand(1);
670    SDOperand Val = Select(N->getOperand(2));
671    if (Chain != N->getOperand(0) || Val != N->getOperand(2)) {
672      SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
673                                      Chain, Reg, Val);
674      CurDAG->ReplaceAllUsesWith(Op, New);
675      N = New.Val;
676    }
677    return SDOperand(N, 0);
678  }
679  case ISD::Constant: {
680    assert(N->getValueType(0) == MVT::i32);
681    unsigned v = (unsigned)cast<ConstantSDNode>(N)->getValue();
682
683    // NOTE: This doesn't use SelectNodeTo, because doing that will prevent
684    // folding shared immediates into other the second instruction that
685    // uses it.
686    if (isInt16(v))
687      return CurDAG->getTargetNode(PPC::LI, MVT::i32, getI32Imm(v));
688
689    unsigned Hi = Hi16(v);
690    unsigned Lo = Lo16(v);
691
692    if (!Lo)
693      return CurDAG->getTargetNode(PPC::LIS, MVT::i32, getI32Imm(Hi));
694
695    SDOperand Top = CurDAG->getTargetNode(PPC::LIS, MVT::i32, getI32Imm(Hi));
696    return CurDAG->getTargetNode(PPC::ORI, MVT::i32, Top, getI32Imm(Lo));
697  }
698  case ISD::UNDEF:
699    if (N->getValueType(0) == MVT::i32)
700      CurDAG->SelectNodeTo(N, PPC::IMPLICIT_DEF_GPR, MVT::i32);
701    else
702      CurDAG->SelectNodeTo(N, PPC::IMPLICIT_DEF_FP, N->getValueType(0));
703    return SDOperand(N, 0);
704  case ISD::FrameIndex: {
705    int FI = cast<FrameIndexSDNode>(N)->getIndex();
706    CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
707                         CurDAG->getTargetFrameIndex(FI, MVT::i32),
708                         getI32Imm(0));
709    return SDOperand(N, 0);
710  }
711  case ISD::ConstantPool: {
712    Constant *C = cast<ConstantPoolSDNode>(N)->get();
713    SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(C, MVT::i32);
714    if (PICEnabled)
715      Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPI);
716    else
717      Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPI);
718    CurDAG->SelectNodeTo(N, PPC::LA, MVT::i32, Tmp, CPI);
719    return SDOperand(N, 0);
720  }
721  case ISD::GlobalAddress: {
722    GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
723    SDOperand Tmp;
724    SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
725    if (PICEnabled)
726      Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(), GA);
727    else
728      Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, GA);
729
730    if (GV->hasWeakLinkage() || GV->isExternal())
731      CurDAG->SelectNodeTo(N, PPC::LWZ, MVT::i32, GA, Tmp);
732    else
733      CurDAG->SelectNodeTo(N, PPC::LA, MVT::i32, Tmp, GA);
734    return SDOperand(N, 0);
735  }
736  case ISD::DYNAMIC_STACKALLOC: {
737    // FIXME: We are currently ignoring the requested alignment for handling
738    // greater than the stack alignment.  This will need to be revisited at some
739    // point.  Align = N.getOperand(2);
740    if (!isa<ConstantSDNode>(N->getOperand(2)) ||
741        cast<ConstantSDNode>(N->getOperand(2))->getValue() != 0) {
742      std::cerr << "Cannot allocate stack object with greater alignment than"
743                << " the stack alignment yet!";
744      abort();
745    }
746    SDOperand Chain = Select(N->getOperand(0));
747    SDOperand Amt   = Select(N->getOperand(1));
748
749    SDOperand R1Reg = CurDAG->getRegister(PPC::R1, MVT::i32);
750
751    SDOperand R1Val = CurDAG->getCopyFromReg(Chain, PPC::R1, MVT::i32);
752    Chain = R1Val.getValue(1);
753
754    // Subtract the amount (guaranteed to be a multiple of the stack alignment)
755    // from the stack pointer, giving us the result pointer.
756    SDOperand Result = CurDAG->getTargetNode(PPC::SUBF, MVT::i32, Amt, R1Val);
757
758    // Copy this result back into R1.
759    Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R1Reg, Result);
760
761    // Copy this result back out of R1 to make sure we're not using the stack
762    // space without decrementing the stack pointer.
763    Result = CurDAG->getCopyFromReg(Chain, PPC::R1, MVT::i32);
764
765    // Finally, replace the DYNAMIC_STACKALLOC with the copyfromreg.
766    CurDAG->ReplaceAllUsesWith(N, Result.Val);
767    return SDOperand(Result.Val, Op.ResNo);
768  }
769  case ISD::SIGN_EXTEND_INREG:
770    switch(cast<VTSDNode>(N->getOperand(1))->getVT()) {
771    default: assert(0 && "Illegal type in SIGN_EXTEND_INREG"); break;
772    case MVT::i16:
773      CurDAG->SelectNodeTo(N, PPC::EXTSH, MVT::i32, Select(N->getOperand(0)));
774      break;
775    case MVT::i8:
776      CurDAG->SelectNodeTo(N, PPC::EXTSB, MVT::i32, Select(N->getOperand(0)));
777      break;
778    }
779    return SDOperand(N, 0);
780  case ISD::CTLZ:
781    assert(N->getValueType(0) == MVT::i32);
782    CurDAG->SelectNodeTo(N, PPC::CNTLZW, MVT::i32, Select(N->getOperand(0)));
783    return SDOperand(N, 0);
784  case PPCISD::FSEL:
785    CurDAG->SelectNodeTo(N, PPC::FSEL, N->getValueType(0),
786                         Select(N->getOperand(0)),
787                         Select(N->getOperand(1)),
788                         Select(N->getOperand(2)));
789    return SDOperand(N, 0);
790  case PPCISD::FCFID:
791    CurDAG->SelectNodeTo(N, PPC::FCFID, N->getValueType(0),
792                         Select(N->getOperand(0)));
793    return SDOperand(N, 0);
794  case PPCISD::FCTIDZ:
795    CurDAG->SelectNodeTo(N, PPC::FCTIDZ, N->getValueType(0),
796                         Select(N->getOperand(0)));
797    return SDOperand(N, 0);
798  case PPCISD::FCTIWZ:
799    CurDAG->SelectNodeTo(N, PPC::FCTIWZ, N->getValueType(0),
800                         Select(N->getOperand(0)));
801    return SDOperand(N, 0);
802  case ISD::ADD: {
803    MVT::ValueType Ty = N->getValueType(0);
804    if (Ty == MVT::i32) {
805      if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
806                                             PPC::ADDIS, PPC::ADDI, true)) {
807        CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
808        N = I;
809      } else {
810        CurDAG->SelectNodeTo(N, PPC::ADD, MVT::i32, Select(N->getOperand(0)),
811                             Select(N->getOperand(1)));
812      }
813      return SDOperand(N, 0);
814    }
815
816    if (!NoExcessFPPrecision) {  // Match FMA ops
817      if (N->getOperand(0).getOpcode() == ISD::MUL &&
818          N->getOperand(0).Val->hasOneUse()) {
819        ++FusedFP; // Statistic
820        CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS, Ty,
821                             Select(N->getOperand(0).getOperand(0)),
822                             Select(N->getOperand(0).getOperand(1)),
823                             Select(N->getOperand(1)));
824        return SDOperand(N, 0);
825      } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
826                 N->getOperand(1).hasOneUse()) {
827        ++FusedFP; // Statistic
828        CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS, Ty,
829                             Select(N->getOperand(1).getOperand(0)),
830                             Select(N->getOperand(1).getOperand(1)),
831                             Select(N->getOperand(0)));
832        return SDOperand(N, 0);
833      }
834    }
835
836    CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FADD : PPC::FADDS, Ty,
837                         Select(N->getOperand(0)), Select(N->getOperand(1)));
838    return SDOperand(N, 0);
839  }
840  case ISD::SUB: {
841    MVT::ValueType Ty = N->getValueType(0);
842    if (Ty == MVT::i32) {
843      unsigned Imm;
844      if (isIntImmediate(N->getOperand(0), Imm) && isInt16(Imm)) {
845        if (0 == Imm)
846          CurDAG->SelectNodeTo(N, PPC::NEG, Ty, Select(N->getOperand(1)));
847        else
848          CurDAG->SelectNodeTo(N, PPC::SUBFIC, Ty, Select(N->getOperand(1)),
849                               getI32Imm(Lo16(Imm)));
850        return SDOperand(N, 0);
851      }
852      if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
853                                          PPC::ADDIS, PPC::ADDI, true, true)) {
854        CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
855        N = I;
856      } else {
857        CurDAG->SelectNodeTo(N, PPC::SUBF, Ty, Select(N->getOperand(1)),
858                             Select(N->getOperand(0)));
859      }
860      return SDOperand(N, 0);
861    }
862
863    if (!NoExcessFPPrecision) {  // Match FMA ops
864      if (N->getOperand(0).getOpcode() == ISD::MUL &&
865          N->getOperand(0).Val->hasOneUse()) {
866        ++FusedFP; // Statistic
867        CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS, Ty,
868                             Select(N->getOperand(0).getOperand(0)),
869                             Select(N->getOperand(0).getOperand(1)),
870                             Select(N->getOperand(1)));
871        return SDOperand(N, 0);
872      } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
873                 N->getOperand(1).Val->hasOneUse()) {
874        ++FusedFP; // Statistic
875        CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS, Ty,
876                             Select(N->getOperand(1).getOperand(0)),
877                             Select(N->getOperand(1).getOperand(1)),
878                             Select(N->getOperand(0)));
879        return SDOperand(N, 0);
880      }
881    }
882    CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FSUB : PPC::FSUBS, Ty,
883                         Select(N->getOperand(0)),
884                         Select(N->getOperand(1)));
885    return SDOperand(N, 0);
886  }
887  case ISD::MUL: {
888    unsigned Imm, Opc;
889    if (isIntImmediate(N->getOperand(1), Imm) && isInt16(Imm)) {
890      CurDAG->SelectNodeTo(N, PPC::MULLI, MVT::i32,
891                           Select(N->getOperand(0)), getI32Imm(Lo16(Imm)));
892      return SDOperand(N, 0);
893    }
894    switch (N->getValueType(0)) {
895      default: assert(0 && "Unhandled multiply type!");
896      case MVT::i32: Opc = PPC::MULLW; break;
897      case MVT::f32: Opc = PPC::FMULS; break;
898      case MVT::f64: Opc = PPC::FMUL;  break;
899    }
900    CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), Select(N->getOperand(0)),
901                         Select(N->getOperand(1)));
902    return SDOperand(N, 0);
903  }
904  case ISD::SDIV: {
905    unsigned Imm;
906    if (isIntImmediate(N->getOperand(1), Imm)) {
907      if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
908        SDOperand Op =
909          CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
910                                Select(N->getOperand(0)),
911                                getI32Imm(Log2_32(Imm)));
912        CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
913                             Op.getValue(0), Op.getValue(1));
914        return SDOperand(N, 0);
915      } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
916        SDOperand Op =
917          CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
918                                Select(N->getOperand(0)),
919                                getI32Imm(Log2_32(-Imm)));
920        SDOperand PT =
921          CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, Op.getValue(0),
922                                Op.getValue(1));
923        CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
924        return SDOperand(N, 0);
925      } else if (Imm) {
926        SDOperand Result = Select(BuildSDIVSequence(N));
927        assert(Result.ResNo == 0);
928        CurDAG->ReplaceAllUsesWith(Op, Result);
929        N = Result.Val;
930        return SDOperand(N, 0);
931      }
932    }
933
934    unsigned Opc;
935    switch (N->getValueType(0)) {
936    default: assert(0 && "Unknown type to ISD::SDIV");
937    case MVT::i32: Opc = PPC::DIVW; break;
938    case MVT::f32: Opc = PPC::FDIVS; break;
939    case MVT::f64: Opc = PPC::FDIV; break;
940    }
941    CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), Select(N->getOperand(0)),
942                         Select(N->getOperand(1)));
943    return SDOperand(N, 0);
944  }
945  case ISD::UDIV: {
946    // If this is a divide by constant, we can emit code using some magic
947    // constants to implement it as a multiply instead.
948    unsigned Imm;
949    if (isIntImmediate(N->getOperand(1), Imm) && Imm) {
950      SDOperand Result = Select(BuildUDIVSequence(N));
951      assert(Result.ResNo == 0);
952      CurDAG->ReplaceAllUsesWith(Op, Result);
953      N = Result.Val;
954      return SDOperand(N, 0);
955    }
956
957    CurDAG->SelectNodeTo(N, PPC::DIVWU, MVT::i32, Select(N->getOperand(0)),
958                         Select(N->getOperand(1)));
959    return SDOperand(N, 0);
960  }
961  case ISD::MULHS:
962    assert(N->getValueType(0) == MVT::i32);
963    CurDAG->SelectNodeTo(N, PPC::MULHW, MVT::i32, Select(N->getOperand(0)),
964                         Select(N->getOperand(1)));
965    return SDOperand(N, 0);
966  case ISD::MULHU:
967    assert(N->getValueType(0) == MVT::i32);
968    CurDAG->SelectNodeTo(N, PPC::MULHWU, MVT::i32, Select(N->getOperand(0)),
969                         Select(N->getOperand(1)));
970    return SDOperand(N, 0);
971  case ISD::AND: {
972    unsigned Imm;
973    // If this is an and of a value rotated between 0 and 31 bits and then and'd
974    // with a mask, emit rlwinm
975    if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
976                                                  isShiftedMask_32(~Imm))) {
977      SDOperand Val;
978      unsigned SH, MB, ME;
979      if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
980        Val = Select(N->getOperand(0).getOperand(0));
981      } else {
982        Val = Select(N->getOperand(0));
983        isRunOfOnes(Imm, MB, ME);
984        SH = 0;
985      }
986      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val, getI32Imm(SH),
987                           getI32Imm(MB), getI32Imm(ME));
988      return SDOperand(N, 0);
989    }
990    // Finally, check for the case where we are being asked to select
991    // and (not(a), b) or and (a, not(b)) which can be selected as andc.
992    if (isOprNot(N->getOperand(0).Val))
993      CurDAG->SelectNodeTo(N, PPC::ANDC, MVT::i32, Select(N->getOperand(1)),
994                           Select(N->getOperand(0).getOperand(0)));
995    else if (isOprNot(N->getOperand(1).Val))
996      CurDAG->SelectNodeTo(N, PPC::ANDC, MVT::i32, Select(N->getOperand(0)),
997                           Select(N->getOperand(1).getOperand(0)));
998    else
999      CurDAG->SelectNodeTo(N, PPC::AND, MVT::i32, Select(N->getOperand(0)),
1000                           Select(N->getOperand(1)));
1001    return SDOperand(N, 0);
1002  }
1003  case ISD::OR:
1004    if (SDNode *I = SelectBitfieldInsert(N)) {
1005      CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
1006      N = I;
1007      return SDOperand(N, 0);
1008    }
1009    if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0),
1010                                           N->getOperand(1),
1011                                           PPC::ORIS, PPC::ORI)) {
1012      CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
1013      N = I;
1014      return SDOperand(N, 0);
1015    }
1016    // Finally, check for the case where we are being asked to select
1017    // 'or (not(a), b)' or 'or (a, not(b))' which can be selected as orc.
1018    if (isOprNot(N->getOperand(0).Val))
1019      CurDAG->SelectNodeTo(N, PPC::ORC, MVT::i32, Select(N->getOperand(1)),
1020                           Select(N->getOperand(0).getOperand(0)));
1021    else if (isOprNot(N->getOperand(1).Val))
1022      CurDAG->SelectNodeTo(N, PPC::ORC, MVT::i32, Select(N->getOperand(0)),
1023                           Select(N->getOperand(1).getOperand(0)));
1024    else
1025      CurDAG->SelectNodeTo(N, PPC::OR, MVT::i32, Select(N->getOperand(0)),
1026                           Select(N->getOperand(1)));
1027    return SDOperand(N, 0);
1028  case ISD::XOR:
1029    // Check whether or not this node is a logical 'not'.  This is represented
1030    // by llvm as a xor with the constant value -1 (all bits set).  If this is a
1031    // 'not', then fold 'or' into 'nor', and so forth for the supported ops.
1032    if (isOprNot(N)) {
1033      unsigned Opc;
1034      SDOperand Val = Select(N->getOperand(0));
1035      switch (Val.isTargetOpcode() ? Val.getTargetOpcode() : 0) {
1036      default:        Opc = 0;          break;
1037      case PPC::OR:   Opc = PPC::NOR;   break;
1038      case PPC::AND:  Opc = PPC::NAND;  break;
1039      case PPC::XOR:  Opc = PPC::EQV;   break;
1040      }
1041      if (Opc)
1042        CurDAG->SelectNodeTo(N, Opc, MVT::i32, Val.getOperand(0),
1043                             Val.getOperand(1));
1044      else
1045        CurDAG->SelectNodeTo(N, PPC::NOR, MVT::i32, Val, Val);
1046      return SDOperand(N, 0);
1047    }
1048    // If this is a xor with an immediate other than -1, then codegen it as high
1049    // and low 16 bit immediate xors.
1050    if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0),
1051                                           N->getOperand(1),
1052                                           PPC::XORIS, PPC::XORI)) {
1053      CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
1054      N = I;
1055      return SDOperand(N, 0);
1056    }
1057    // Finally, check for the case where we are being asked to select
1058    // xor (not(a), b) which is equivalent to not(xor a, b), which is eqv
1059    if (isOprNot(N->getOperand(0).Val))
1060      CurDAG->SelectNodeTo(N, PPC::EQV, MVT::i32,
1061                           Select(N->getOperand(0).getOperand(0)),
1062                           Select(N->getOperand(1)));
1063    else
1064      CurDAG->SelectNodeTo(N, PPC::XOR, MVT::i32, Select(N->getOperand(0)),
1065                           Select(N->getOperand(1)));
1066    return SDOperand(N, 0);
1067  case ISD::SHL: {
1068    unsigned Imm, SH, MB, ME;
1069    if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1070        isRotateAndMask(N, Imm, true, SH, MB, ME))
1071      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1072                           Select(N->getOperand(0).getOperand(0)),
1073                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1074    else if (isIntImmediate(N->getOperand(1), Imm))
1075      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Select(N->getOperand(0)),
1076                           getI32Imm(Imm), getI32Imm(0), getI32Imm(31-Imm));
1077    else
1078      CurDAG->SelectNodeTo(N, PPC::SLW, MVT::i32, Select(N->getOperand(0)),
1079                           Select(N->getOperand(1)));
1080    return SDOperand(N, 0);
1081  }
1082  case ISD::SRL: {
1083    unsigned Imm, SH, MB, ME;
1084    if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1085        isRotateAndMask(N, Imm, true, SH, MB, ME))
1086      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1087                           Select(N->getOperand(0).getOperand(0)),
1088                           getI32Imm(SH & 0x1F), getI32Imm(MB), getI32Imm(ME));
1089    else if (isIntImmediate(N->getOperand(1), Imm))
1090      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Select(N->getOperand(0)),
1091                           getI32Imm((32-Imm) & 0x1F), getI32Imm(Imm),
1092                           getI32Imm(31));
1093    else
1094      CurDAG->SelectNodeTo(N, PPC::SRW, MVT::i32, Select(N->getOperand(0)),
1095                           Select(N->getOperand(1)));
1096    return SDOperand(N, 0);
1097  }
1098  case ISD::SRA: {
1099    unsigned Imm, SH, MB, ME;
1100    if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1101        isRotateAndMask(N, Imm, true, SH, MB, ME))
1102      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1103                           Select(N->getOperand(0).getOperand(0)),
1104                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1105    else if (isIntImmediate(N->getOperand(1), Imm))
1106      CurDAG->SelectNodeTo(N, PPC::SRAWI, MVT::i32, Select(N->getOperand(0)),
1107                           getI32Imm(Imm));
1108    else
1109      CurDAG->SelectNodeTo(N, PPC::SRAW, MVT::i32, Select(N->getOperand(0)),
1110                           Select(N->getOperand(1)));
1111    return SDOperand(N, 0);
1112  }
1113  case ISD::FABS:
1114    CurDAG->SelectNodeTo(N, PPC::FABS, N->getValueType(0),
1115                         Select(N->getOperand(0)));
1116    return SDOperand(N, 0);
1117  case ISD::FP_EXTEND:
1118    assert(MVT::f64 == N->getValueType(0) &&
1119           MVT::f32 == N->getOperand(0).getValueType() && "Illegal FP_EXTEND");
1120    // We need to emit an FMR to make sure that the result has the right value
1121    // type.
1122    CurDAG->SelectNodeTo(N, PPC::FMR, MVT::f64, Select(N->getOperand(0)));
1123    return SDOperand(N, 0);
1124  case ISD::FP_ROUND:
1125    assert(MVT::f32 == N->getValueType(0) &&
1126           MVT::f64 == N->getOperand(0).getValueType() && "Illegal FP_ROUND");
1127    CurDAG->SelectNodeTo(N, PPC::FRSP, MVT::f32, Select(N->getOperand(0)));
1128    return SDOperand(N, 0);
1129  case ISD::FNEG: {
1130    SDOperand Val = Select(N->getOperand(0));
1131    MVT::ValueType Ty = N->getValueType(0);
1132    if (Val.Val->hasOneUse()) {
1133      unsigned Opc;
1134      switch (Val.isTargetOpcode() ? Val.getTargetOpcode() : 0) {
1135      default:          Opc = 0;            break;
1136      case PPC::FABS:   Opc = PPC::FNABS;   break;
1137      case PPC::FMADD:  Opc = PPC::FNMADD;  break;
1138      case PPC::FMADDS: Opc = PPC::FNMADDS; break;
1139      case PPC::FMSUB:  Opc = PPC::FNMSUB;  break;
1140      case PPC::FMSUBS: Opc = PPC::FNMSUBS; break;
1141      }
1142      // If we inverted the opcode, then emit the new instruction with the
1143      // inverted opcode and the original instruction's operands.  Otherwise,
1144      // fall through and generate a fneg instruction.
1145      if (Opc) {
1146        if (PPC::FNABS == Opc)
1147          CurDAG->SelectNodeTo(N, Opc, Ty, Val.getOperand(0));
1148        else
1149          CurDAG->SelectNodeTo(N, Opc, Ty, Val.getOperand(0),
1150                               Val.getOperand(1), Val.getOperand(2));
1151        return SDOperand(N, 0);
1152      }
1153    }
1154    CurDAG->SelectNodeTo(N, PPC::FNEG, Ty, Val);
1155    return SDOperand(N, 0);
1156  }
1157  case ISD::FSQRT: {
1158    MVT::ValueType Ty = N->getValueType(0);
1159    CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FSQRT : PPC::FSQRTS, Ty,
1160                         Select(N->getOperand(0)));
1161    return SDOperand(N, 0);
1162  }
1163
1164  case ISD::ADD_PARTS: {
1165    SDOperand LHSL = Select(N->getOperand(0));
1166    SDOperand LHSH = Select(N->getOperand(1));
1167
1168    unsigned Imm;
1169    bool ME = false, ZE = false;
1170    if (isIntImmediate(N->getOperand(3), Imm)) {
1171      ME = (signed)Imm == -1;
1172      ZE = Imm == 0;
1173    }
1174
1175    std::vector<SDOperand> Result;
1176    SDOperand CarryFromLo;
1177    if (isIntImmediate(N->getOperand(2), Imm) &&
1178        ((signed)Imm >= -32768 || (signed)Imm < 32768)) {
1179      // Codegen the low 32 bits of the add.  Interestingly, there is no
1180      // shifted form of add immediate carrying.
1181      CarryFromLo = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1182                                          LHSL, getI32Imm(Imm));
1183    } else {
1184      CarryFromLo = CurDAG->getTargetNode(PPC::ADDC, MVT::i32, MVT::Flag,
1185                                          LHSL, Select(N->getOperand(2)));
1186    }
1187    CarryFromLo = CarryFromLo.getValue(1);
1188
1189    // Codegen the high 32 bits, adding zero, minus one, or the full value
1190    // along with the carry flag produced by addc/addic.
1191    SDOperand ResultHi;
1192    if (ZE)
1193      ResultHi = CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, LHSH, CarryFromLo);
1194    else if (ME)
1195      ResultHi = CurDAG->getTargetNode(PPC::ADDME, MVT::i32, LHSH, CarryFromLo);
1196    else
1197      ResultHi = CurDAG->getTargetNode(PPC::ADDE, MVT::i32, LHSH,
1198                                       Select(N->getOperand(3)), CarryFromLo);
1199    Result.push_back(CarryFromLo.getValue(0));
1200    Result.push_back(ResultHi);
1201    CurDAG->ReplaceAllUsesWith(N, Result);
1202    return Result[Op.ResNo];
1203  }
1204  case ISD::SUB_PARTS: {
1205    SDOperand LHSL = Select(N->getOperand(0));
1206    SDOperand LHSH = Select(N->getOperand(1));
1207    SDOperand RHSL = Select(N->getOperand(2));
1208    SDOperand RHSH = Select(N->getOperand(3));
1209
1210    std::vector<SDOperand> Result;
1211    Result.push_back(CurDAG->getTargetNode(PPC::SUBFC, MVT::i32, MVT::Flag,
1212                                           RHSL, LHSL));
1213    Result.push_back(CurDAG->getTargetNode(PPC::SUBFE, MVT::i32, RHSH, LHSH,
1214                                           Result[0].getValue(1)));
1215    CurDAG->ReplaceAllUsesWith(N, Result);
1216    return Result[Op.ResNo];
1217  }
1218
1219  case ISD::LOAD:
1220  case ISD::EXTLOAD:
1221  case ISD::ZEXTLOAD:
1222  case ISD::SEXTLOAD: {
1223    SDOperand Op1, Op2;
1224    bool isIdx = SelectAddr(N->getOperand(1), Op1, Op2);
1225
1226    MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
1227      N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
1228    unsigned Opc;
1229    switch (TypeBeingLoaded) {
1230    default: N->dump(); assert(0 && "Cannot load this type!");
1231    case MVT::i1:
1232    case MVT::i8:  Opc = isIdx ? PPC::LBZX : PPC::LBZ; break;
1233    case MVT::i16:
1234      if (N->getOpcode() == ISD::SEXTLOAD) { // SEXT load?
1235        Opc = isIdx ? PPC::LHAX : PPC::LHA;
1236      } else {
1237        Opc = isIdx ? PPC::LHZX : PPC::LHZ;
1238      }
1239      break;
1240    case MVT::i32: Opc = isIdx ? PPC::LWZX : PPC::LWZ; break;
1241    case MVT::f32: Opc = isIdx ? PPC::LFSX : PPC::LFS; break;
1242    case MVT::f64: Opc = isIdx ? PPC::LFDX : PPC::LFD; break;
1243    }
1244
1245    CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), MVT::Other,
1246                         Op1, Op2, Select(N->getOperand(0)));
1247    return SDOperand(N, Op.ResNo);
1248  }
1249
1250  case ISD::TRUNCSTORE:
1251  case ISD::STORE: {
1252    SDOperand AddrOp1, AddrOp2;
1253    bool isIdx = SelectAddr(N->getOperand(2), AddrOp1, AddrOp2);
1254
1255    unsigned Opc;
1256    if (N->getOpcode() == ISD::STORE) {
1257      switch (N->getOperand(1).getValueType()) {
1258      default: assert(0 && "unknown Type in store");
1259      case MVT::i32: Opc = isIdx ? PPC::STWX  : PPC::STW; break;
1260      case MVT::f64: Opc = isIdx ? PPC::STFDX : PPC::STFD; break;
1261      case MVT::f32: Opc = isIdx ? PPC::STFSX : PPC::STFS; break;
1262      }
1263    } else { //ISD::TRUNCSTORE
1264      switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
1265      default: assert(0 && "unknown Type in store");
1266      case MVT::i8:  Opc = isIdx ? PPC::STBX : PPC::STB; break;
1267      case MVT::i16: Opc = isIdx ? PPC::STHX : PPC::STH; break;
1268      }
1269    }
1270
1271    CurDAG->SelectNodeTo(N, Opc, MVT::Other, Select(N->getOperand(1)),
1272                         AddrOp1, AddrOp2, Select(N->getOperand(0)));
1273    return SDOperand(N, 0);
1274  }
1275
1276  case ISD::SETCC: {
1277    unsigned Imm;
1278    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1279    if (isIntImmediate(N->getOperand(1), Imm)) {
1280      // We can codegen setcc op, imm very efficiently compared to a brcond.
1281      // Check for those cases here.
1282      // setcc op, 0
1283      if (Imm == 0) {
1284        SDOperand Op = Select(N->getOperand(0));
1285        switch (CC) {
1286        default: assert(0 && "Unhandled SetCC condition"); abort();
1287        case ISD::SETEQ:
1288          Op = CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op);
1289          CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
1290                               getI32Imm(5), getI32Imm(31));
1291          break;
1292        case ISD::SETNE: {
1293          SDOperand AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1294                                               Op, getI32Imm(~0U));
1295          CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
1296          break;
1297        }
1298        case ISD::SETLT:
1299          CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
1300                               getI32Imm(31), getI32Imm(31));
1301          break;
1302        case ISD::SETGT: {
1303          SDOperand T = CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op);
1304          T = CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op);;
1305          CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
1306                               getI32Imm(31), getI32Imm(31));
1307          break;
1308        }
1309        }
1310        return SDOperand(N, 0);
1311      } else if (Imm == ~0U) {        // setcc op, -1
1312        SDOperand Op = Select(N->getOperand(0));
1313        switch (CC) {
1314        default: assert(0 && "Unhandled SetCC condition"); abort();
1315        case ISD::SETEQ:
1316          Op = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1317                                     Op, getI32Imm(1));
1318          CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1319                               CurDAG->getTargetNode(PPC::LI, MVT::i32,
1320                                                     getI32Imm(0)),
1321                               Op.getValue(1));
1322          break;
1323        case ISD::SETNE: {
1324          Op = CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op);
1325          SDOperand AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1326                                                Op, getI32Imm(~0U));
1327          CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
1328          break;
1329        }
1330        case ISD::SETLT: {
1331          SDOperand AD = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
1332                                               getI32Imm(1));
1333          SDOperand AN = CurDAG->getTargetNode(PPC::AND, MVT::i32, AD, Op);
1334          CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
1335                               getI32Imm(31), getI32Imm(31));
1336          break;
1337        }
1338        case ISD::SETGT:
1339          Op = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
1340                                     getI32Imm(31), getI32Imm(31));
1341          CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
1342          break;
1343        }
1344        return SDOperand(N, 0);
1345      }
1346    }
1347
1348    bool Inv;
1349    unsigned Idx = getCRIdxForSetCC(CC, Inv);
1350    SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1351    SDOperand IntCR;
1352
1353    // Force the ccreg into CR7.
1354    SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
1355
1356    std::vector<MVT::ValueType> VTs;
1357    VTs.push_back(MVT::Other);
1358    VTs.push_back(MVT::Flag);    // NONSTANDARD CopyToReg node: defines a flag
1359    std::vector<SDOperand> Ops;
1360    Ops.push_back(CurDAG->getEntryNode());
1361    Ops.push_back(CR7Reg);
1362    Ops.push_back(CCReg);
1363    CCReg = CurDAG->getNode(ISD::CopyToReg, VTs, Ops).getValue(1);
1364
1365    if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
1366      IntCR = CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg, CCReg);
1367    else
1368      IntCR = CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg);
1369
1370    if (!Inv) {
1371      CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
1372                           getI32Imm(32-(3-Idx)), getI32Imm(31), getI32Imm(31));
1373    } else {
1374      SDOperand Tmp =
1375      CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
1376                            getI32Imm(32-(3-Idx)), getI32Imm(31),getI32Imm(31));
1377      CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
1378    }
1379
1380    return SDOperand(N, 0);
1381  }
1382
1383  case ISD::SELECT_CC: {
1384    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1385
1386    // handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1387    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1388      if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1389        if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1390          if (N1C->isNullValue() && N3C->isNullValue() &&
1391              N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1392            SDOperand LHS = Select(N->getOperand(0));
1393            SDOperand Tmp =
1394              CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1395                                    LHS, getI32Imm(~0U));
1396            CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, Tmp, LHS,
1397                                 Tmp.getValue(1));
1398            return SDOperand(N, 0);
1399          }
1400
1401    SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1402    unsigned BROpc = getBCCForSetCC(CC);
1403
1404    bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1405    unsigned SelectCCOp = isFP ? PPC::SELECT_CC_FP : PPC::SELECT_CC_Int;
1406    CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1407                         Select(N->getOperand(2)), Select(N->getOperand(3)),
1408                         getI32Imm(BROpc));
1409    return SDOperand(N, 0);
1410  }
1411
1412  case ISD::CALLSEQ_START:
1413  case ISD::CALLSEQ_END: {
1414    unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1415    unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
1416                       PPC::ADJCALLSTACKDOWN : PPC::ADJCALLSTACKUP;
1417    CurDAG->SelectNodeTo(N, Opc, MVT::Other,
1418                         getI32Imm(Amt), Select(N->getOperand(0)));
1419    return SDOperand(N, 0);
1420  }
1421  case ISD::CALL:
1422  case ISD::TAILCALL: {
1423    SDOperand Chain = Select(N->getOperand(0));
1424
1425    unsigned CallOpcode;
1426    std::vector<SDOperand> CallOperands;
1427
1428    if (GlobalAddressSDNode *GASD =
1429        dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
1430      CallOpcode = PPC::CALLpcrel;
1431      CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
1432                                                            MVT::i32));
1433    } else if (ExternalSymbolSDNode *ESSDN =
1434               dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
1435      CallOpcode = PPC::CALLpcrel;
1436      CallOperands.push_back(N->getOperand(1));
1437    } else {
1438      // Copy the callee address into the CTR register.
1439      SDOperand Callee = Select(N->getOperand(1));
1440      Chain = CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee, Chain);
1441
1442      // Copy the callee address into R12 on darwin.
1443      SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
1444      Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
1445
1446      CallOperands.push_back(getI32Imm(20));  // Information to encode indcall
1447      CallOperands.push_back(getI32Imm(0));   // Information to encode indcall
1448      CallOperands.push_back(R12);
1449      CallOpcode = PPC::CALLindirect;
1450    }
1451
1452    unsigned GPR_idx = 0, FPR_idx = 0;
1453    static const unsigned GPR[] = {
1454      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1455      PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1456    };
1457    static const unsigned FPR[] = {
1458      PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1459      PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1460    };
1461
1462    SDOperand InFlag;  // Null incoming flag value.
1463
1464    for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
1465      unsigned DestReg = 0;
1466      MVT::ValueType RegTy = N->getOperand(i).getValueType();
1467      if (RegTy == MVT::i32) {
1468        assert(GPR_idx < 8 && "Too many int args");
1469        DestReg = GPR[GPR_idx++];
1470      } else {
1471        assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
1472               "Unpromoted integer arg?");
1473        assert(FPR_idx < 13 && "Too many fp args");
1474        DestReg = FPR[FPR_idx++];
1475      }
1476
1477      if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
1478        SDOperand Val = Select(N->getOperand(i));
1479        Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
1480        InFlag = Chain.getValue(1);
1481        CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
1482      }
1483    }
1484
1485    // Finally, once everything is in registers to pass to the call, emit the
1486    // call itself.
1487    if (InFlag.Val)
1488      CallOperands.push_back(InFlag);   // Strong dep on register copies.
1489    else
1490      CallOperands.push_back(Chain);    // Weak dep on whatever occurs before
1491    Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
1492                                  CallOperands);
1493
1494    std::vector<SDOperand> CallResults;
1495
1496    // If the call has results, copy the values out of the ret val registers.
1497    switch (N->getValueType(0)) {
1498    default: assert(0 && "Unexpected ret value!");
1499    case MVT::Other: break;
1500    case MVT::i32:
1501      if (N->getValueType(1) == MVT::i32) {
1502        Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32,
1503                                       Chain.getValue(1)).getValue(1);
1504        CallResults.push_back(Chain.getValue(0));
1505        Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
1506                                       Chain.getValue(1)).getValue(1);
1507        CallResults.push_back(Chain.getValue(0));
1508      } else {
1509        Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
1510                                       Chain.getValue(1)).getValue(1);
1511        CallResults.push_back(Chain.getValue(0));
1512      }
1513      break;
1514    case MVT::f32:
1515    case MVT::f64:
1516      Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
1517                                     Chain.getValue(1)).getValue(1);
1518      CallResults.push_back(Chain.getValue(0));
1519      break;
1520    }
1521
1522    CallResults.push_back(Chain);
1523    CurDAG->ReplaceAllUsesWith(N, CallResults);
1524    return CallResults[Op.ResNo];
1525  }
1526  case ISD::RET: {
1527    SDOperand Chain = Select(N->getOperand(0));     // Token chain.
1528
1529    if (N->getNumOperands() == 2) {
1530      SDOperand Val = Select(N->getOperand(1));
1531      if (N->getOperand(1).getValueType() == MVT::i32) {
1532        Chain = CurDAG->getCopyToReg(Chain, PPC::R3, Val);
1533      } else {
1534        assert(MVT::isFloatingPoint(N->getOperand(1).getValueType()));
1535        Chain = CurDAG->getCopyToReg(Chain, PPC::F1, Val);
1536      }
1537    } else if (N->getNumOperands() > 1) {
1538      assert(N->getOperand(1).getValueType() == MVT::i32 &&
1539             N->getOperand(2).getValueType() == MVT::i32 &&
1540             N->getNumOperands() == 3 && "Unknown two-register ret value!");
1541      Chain = CurDAG->getCopyToReg(Chain, PPC::R4, Select(N->getOperand(1)));
1542      Chain = CurDAG->getCopyToReg(Chain, PPC::R3, Select(N->getOperand(2)));
1543    }
1544
1545    // Finally, select this to a blr (return) instruction.
1546    CurDAG->SelectNodeTo(N, PPC::BLR, MVT::Other, Chain);
1547    return SDOperand(N, 0);
1548  }
1549  case ISD::BR:
1550    CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, N->getOperand(1),
1551                         Select(N->getOperand(0)));
1552    return SDOperand(N, 0);
1553  case ISD::BR_CC:
1554  case ISD::BRTWOWAY_CC: {
1555    SDOperand Chain = Select(N->getOperand(0));
1556    MachineBasicBlock *Dest =
1557      cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1558    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1559    SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1560    unsigned Opc = getBCCForSetCC(CC);
1561
1562    // If this is a two way branch, then grab the fallthrough basic block
1563    // argument and build a PowerPC branch pseudo-op, suitable for long branch
1564    // conversion if necessary by the branch selection pass.  Otherwise, emit a
1565    // standard conditional branch.
1566    if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1567      MachineBasicBlock *Fallthrough =
1568        cast<BasicBlockSDNode>(N->getOperand(5))->getBasicBlock();
1569      SDOperand CB = CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1570                                           CondCode, getI32Imm(Opc),
1571                                           N->getOperand(4), N->getOperand(5),
1572                                           Chain);
1573      CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, N->getOperand(5), CB);
1574    } else {
1575      // Iterate to the next basic block
1576      ilist<MachineBasicBlock>::iterator It = BB;
1577      ++It;
1578
1579      // If the fallthrough path is off the end of the function, which would be
1580      // undefined behavior, set it to be the same as the current block because
1581      // we have nothing better to set it to, and leaving it alone will cause
1582      // the PowerPC Branch Selection pass to crash.
1583      if (It == BB->getParent()->end()) It = Dest;
1584      CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, CondCode,
1585                           getI32Imm(Opc), N->getOperand(4),
1586                           CurDAG->getBasicBlock(It), Chain);
1587    }
1588    return SDOperand(N, 0);
1589  }
1590  }
1591
1592  return SelectCode(Op);
1593}
1594
1595
1596/// createPPC32ISelDag - This pass converts a legalized DAG into a
1597/// PowerPC-specific DAG, ready for instruction scheduling.
1598///
1599FunctionPass *llvm::createPPC32ISelDag(TargetMachine &TM) {
1600  return new PPC32DAGToDAGISel(TM);
1601}
1602
1603