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