Fix build failure of povray
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --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 PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include <iostream>
32 #include <set>
33 using namespace llvm;
34
35 namespace {
36   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
37     
38   //===--------------------------------------------------------------------===//
39   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
40   /// instructions for SelectionDAG operations.
41   ///
42   class PPCDAGToDAGISel : public SelectionDAGISel {
43     PPCTargetMachine &TM;
44     PPCTargetLowering PPCLowering;
45     unsigned GlobalBaseReg;
46   public:
47     PPCDAGToDAGISel(PPCTargetMachine &tm)
48       : SelectionDAGISel(PPCLowering), TM(tm),
49         PPCLowering(*TM.getTargetLowering()) {}
50     
51     virtual bool runOnFunction(Function &Fn) {
52       // Make sure we re-emit a set of the global base reg if necessary
53       GlobalBaseReg = 0;
54       SelectionDAGISel::runOnFunction(Fn);
55       
56       InsertVRSaveCode(Fn);
57       return true;
58     }
59    
60     /// getI32Imm - Return a target constant with the specified value, of type
61     /// i32.
62     inline SDOperand getI32Imm(unsigned Imm) {
63       return CurDAG->getTargetConstant(Imm, MVT::i32);
64     }
65
66     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
67     /// base register.  Return the virtual register that holds this value.
68     SDOperand getGlobalBaseReg();
69     
70     // Select - Convert the specified operand from a target-independent to a
71     // target-specific node if it hasn't already been changed.
72     void Select(SDOperand &Result, SDOperand Op);
73     
74     SDNode *SelectBitfieldInsert(SDNode *N);
75
76     /// SelectCC - Select a comparison of the specified values with the
77     /// specified condition code, returning the CR# of the expression.
78     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
79
80     /// SelectAddrImm - Returns true if the address N can be represented by
81     /// a base register plus a signed 16-bit displacement [r+imm].
82     bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
83       
84     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
85     /// represented as an indexed [r+r] operation.  Returns false if it can
86     /// be represented by [r+imm], which are preferred.
87     bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
88     
89     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
90     /// represented as an indexed [r+r] operation.
91     bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
92
93     /// SelectAddrImmShift - Returns true if the address N can be represented by
94     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
95     /// for use by STD and friends.
96     bool SelectAddrImmShift(SDOperand N, SDOperand &Disp, SDOperand &Base);
97     
98     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
99     /// inline asm expressions.
100     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
101                                               char ConstraintCode,
102                                               std::vector<SDOperand> &OutOps,
103                                               SelectionDAG &DAG) {
104       SDOperand Op0, Op1;
105       switch (ConstraintCode) {
106       default: return true;
107       case 'm':   // memory
108         if (!SelectAddrIdx(Op, Op0, Op1))
109           SelectAddrImm(Op, Op0, Op1);
110         break;
111       case 'o':   // offsetable
112         if (!SelectAddrImm(Op, Op0, Op1)) {
113           Select(Op0, Op);     // r+0.
114           Op1 = getI32Imm(0);
115         }
116         break;
117       case 'v':   // not offsetable
118         SelectAddrIdxOnly(Op, Op0, Op1);
119         break;
120       }
121       
122       OutOps.push_back(Op0);
123       OutOps.push_back(Op1);
124       return false;
125     }
126     
127     SDOperand BuildSDIVSequence(SDNode *N);
128     SDOperand BuildUDIVSequence(SDNode *N);
129     
130     /// InstructionSelectBasicBlock - This callback is invoked by
131     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
132     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
133     
134     void InsertVRSaveCode(Function &Fn);
135
136     virtual const char *getPassName() const {
137       return "PowerPC DAG->DAG Pattern Instruction Selection";
138     } 
139     
140     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
141     /// this target when scheduling the DAG.
142     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
143       // Should use subtarget info to pick the right hazard recognizer.  For
144       // now, always return a PPC970 recognizer.
145       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
146       assert(II && "No InstrInfo?");
147       return new PPCHazardRecognizer970(*II); 
148     }
149
150 // Include the pieces autogenerated from the target description.
151 #include "PPCGenDAGISel.inc"
152     
153 private:
154     SDOperand SelectSETCC(SDOperand Op);
155   };
156 }
157
158 /// InstructionSelectBasicBlock - This callback is invoked by
159 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
160 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
161   DEBUG(BB->dump());
162   
163   // The selection process is inherently a bottom-up recursive process (users
164   // select their uses before themselves).  Given infinite stack space, we
165   // could just start selecting on the root and traverse the whole graph.  In
166   // practice however, this causes us to run out of stack space on large basic
167   // blocks.  To avoid this problem, select the entry node, then all its uses,
168   // iteratively instead of recursively.
169   std::vector<SDOperand> Worklist;
170   Worklist.push_back(DAG.getEntryNode());
171   
172   // Note that we can do this in the PPC target (scanning forward across token
173   // chain edges) because no nodes ever get folded across these edges.  On a
174   // target like X86 which supports load/modify/store operations, this would
175   // have to be more careful.
176   while (!Worklist.empty()) {
177     SDOperand Node = Worklist.back();
178     Worklist.pop_back();
179     
180     // Chose from the least deep of the top two nodes.
181     if (!Worklist.empty() &&
182         Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
183       std::swap(Worklist.back(), Node);
184     
185     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
186          Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
187         CodeGenMap.count(Node)) continue;
188     
189     for (SDNode::use_iterator UI = Node.Val->use_begin(),
190          E = Node.Val->use_end(); UI != E; ++UI) {
191       // Scan the values.  If this use has a value that is a token chain, add it
192       // to the worklist.
193       SDNode *User = *UI;
194       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
195         if (User->getValueType(i) == MVT::Other) {
196           Worklist.push_back(SDOperand(User, i));
197           break; 
198         }
199     }
200
201     // Finally, legalize this node.
202     SDOperand Dummy;
203     Select(Dummy, Node);
204   }
205     
206   // Select target instructions for the DAG.
207   DAG.setRoot(SelectRoot(DAG.getRoot()));
208   assert(InFlightSet.empty() && "ISel InFlightSet has not been emptied!");
209   CodeGenMap.clear();
210   HandleMap.clear();
211   ReplaceMap.clear();
212   DAG.RemoveDeadNodes();
213   
214   // Emit machine code to BB.
215   ScheduleAndEmitDAG(DAG);
216 }
217
218 /// InsertVRSaveCode - Once the entire function has been instruction selected,
219 /// all virtual registers are created and all machine instructions are built,
220 /// check to see if we need to save/restore VRSAVE.  If so, do it.
221 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
222   // Check to see if this function uses vector registers, which means we have to
223   // save and restore the VRSAVE register and update it with the regs we use.  
224   //
225   // In this case, there will be virtual registers of vector type type created
226   // by the scheduler.  Detect them now.
227   MachineFunction &Fn = MachineFunction::get(&F);
228   SSARegMap *RegMap = Fn.getSSARegMap();
229   bool HasVectorVReg = false;
230   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
231        e = RegMap->getLastVirtReg()+1; i != e; ++i)
232     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
233       HasVectorVReg = true;
234       break;
235     }
236   if (!HasVectorVReg) return;  // nothing to do.
237       
238   // If we have a vector register, we want to emit code into the entry and exit
239   // blocks to save and restore the VRSAVE register.  We do this here (instead
240   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
241   //
242   // 1. This (trivially) reduces the load on the register allocator, by not
243   //    having to represent the live range of the VRSAVE register.
244   // 2. This (more significantly) allows us to create a temporary virtual
245   //    register to hold the saved VRSAVE value, allowing this temporary to be
246   //    register allocated, instead of forcing it to be spilled to the stack.
247
248   // Create two vregs - one to hold the VRSAVE register that is live-in to the
249   // function and one for the value after having bits or'd into it.
250   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
251   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
252   
253   MachineBasicBlock &EntryBB = *Fn.begin();
254   // Emit the following code into the entry block:
255   // InVRSAVE = MFVRSAVE
256   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
257   // MTVRSAVE UpdatedVRSAVE
258   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
259   BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
260   BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
261   BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
262   
263   // Find all return blocks, outputting a restore in each epilog.
264   const TargetInstrInfo &TII = *TM.getInstrInfo();
265   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
266     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
267       IP = BB->end(); --IP;
268       
269       // Skip over all terminator instructions, which are part of the return
270       // sequence.
271       MachineBasicBlock::iterator I2 = IP;
272       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
273         IP = I2;
274       
275       // Emit: MTVRSAVE InVRSave
276       BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
277     }        
278   }
279 }
280
281
282 /// getGlobalBaseReg - Output the instructions required to put the
283 /// base address to use for accessing globals into a register.
284 ///
285 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
286   if (!GlobalBaseReg) {
287     // Insert the set of GlobalBaseReg into the first MBB of the function
288     MachineBasicBlock &FirstMBB = BB->getParent()->front();
289     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
290     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
291     // FIXME: when we get to LP64, we will need to create the appropriate
292     // type of register here.
293     GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
294     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
295     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
296   }
297   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
298 }
299
300
301 // isIntImmediate - This method tests to see if a constant operand.
302 // If so Imm will receive the 32 bit value.
303 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
304   if (N->getOpcode() == ISD::Constant) {
305     Imm = cast<ConstantSDNode>(N)->getValue();
306     return true;
307   }
308   return false;
309 }
310
311 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
312 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
313 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
314 // not, since all 1s are not contiguous.
315 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
316   if (isShiftedMask_32(Val)) {
317     // look for the first non-zero bit
318     MB = CountLeadingZeros_32(Val);
319     // look for the first zero bit after the run of ones
320     ME = CountLeadingZeros_32((Val - 1) ^ Val);
321     return true;
322   } else {
323     Val = ~Val; // invert mask
324     if (isShiftedMask_32(Val)) {
325       // effectively look for the first zero bit
326       ME = CountLeadingZeros_32(Val) - 1;
327       // effectively look for the first one bit after the run of zeros
328       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
329       return true;
330     }
331   }
332   // no run present
333   return false;
334 }
335
336 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
337 // and mask opcode and mask operation.
338 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
339                             unsigned &SH, unsigned &MB, unsigned &ME) {
340   // Don't even go down this path for i64, since different logic will be
341   // necessary for rldicl/rldicr/rldimi.
342   if (N->getValueType(0) != MVT::i32)
343     return false;
344
345   unsigned Shift  = 32;
346   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
347   unsigned Opcode = N->getOpcode();
348   if (N->getNumOperands() != 2 ||
349       !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
350     return false;
351   
352   if (Opcode == ISD::SHL) {
353     // apply shift left to mask if it comes first
354     if (IsShiftMask) Mask = Mask << Shift;
355     // determine which bits are made indeterminant by shift
356     Indeterminant = ~(0xFFFFFFFFu << Shift);
357   } else if (Opcode == ISD::SRL) { 
358     // apply shift right to mask if it comes first
359     if (IsShiftMask) Mask = Mask >> Shift;
360     // determine which bits are made indeterminant by shift
361     Indeterminant = ~(0xFFFFFFFFu >> Shift);
362     // adjust for the left rotate
363     Shift = 32 - Shift;
364   } else {
365     return false;
366   }
367   
368   // if the mask doesn't intersect any Indeterminant bits
369   if (Mask && !(Mask & Indeterminant)) {
370     SH = Shift & 31;
371     // make sure the mask is still a mask (wrap arounds may not be)
372     return isRunOfOnes(Mask, MB, ME);
373   }
374   return false;
375 }
376
377 // isOpcWithIntImmediate - This method tests to see if the node is a specific
378 // opcode and that it has a immediate integer right operand.
379 // If so Imm will receive the 32 bit value.
380 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
381   return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
382 }
383
384 // isIntImmediate - This method tests to see if a constant operand.
385 // If so Imm will receive the 32 bit value.
386 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
387   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
388     Imm = (unsigned)CN->getSignExtended();
389     return true;
390   }
391   return false;
392 }
393
394 /// SelectBitfieldInsert - turn an or of two masked values into
395 /// the rotate left word immediate then mask insert (rlwimi) instruction.
396 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
397   SDOperand Op0 = N->getOperand(0);
398   SDOperand Op1 = N->getOperand(1);
399   
400   uint64_t LKZ, LKO, RKZ, RKO;
401   TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
402   TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
403   
404   unsigned TargetMask = LKZ;
405   unsigned InsertMask = RKZ;
406   
407   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
408     unsigned Op0Opc = Op0.getOpcode();
409     unsigned Op1Opc = Op1.getOpcode();
410     unsigned Value, SH = 0;
411     TargetMask = ~TargetMask;
412     InsertMask = ~InsertMask;
413
414     // If the LHS has a foldable shift and the RHS does not, then swap it to the
415     // RHS so that we can fold the shift into the insert.
416     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
417       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
418           Op0.getOperand(0).getOpcode() == ISD::SRL) {
419         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
420             Op1.getOperand(0).getOpcode() != ISD::SRL) {
421           std::swap(Op0, Op1);
422           std::swap(Op0Opc, Op1Opc);
423           std::swap(TargetMask, InsertMask);
424         }
425       }
426     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
427       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
428           Op1.getOperand(0).getOpcode() != ISD::SRL) {
429         std::swap(Op0, Op1);
430         std::swap(Op0Opc, Op1Opc);
431         std::swap(TargetMask, InsertMask);
432       }
433     }
434     
435     unsigned MB, ME;
436     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
437       SDOperand Tmp1, Tmp2, Tmp3;
438       bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
439
440       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
441           isIntImmediate(Op1.getOperand(1), Value)) {
442         Op1 = Op1.getOperand(0);
443         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
444       }
445       if (Op1Opc == ISD::AND) {
446         unsigned SHOpc = Op1.getOperand(0).getOpcode();
447         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
448             isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
449           Op1 = Op1.getOperand(0).getOperand(0);
450           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
451         } else {
452           Op1 = Op1.getOperand(0);
453         }
454       }
455       
456       Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
457       Select(Tmp1, Tmp3);
458       Select(Tmp2, Op1);
459       SH &= 31;
460       return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
461                                    getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
462     }
463   }
464   return 0;
465 }
466
467 /// SelectAddrImm - Returns true if the address N can be represented by
468 /// a base register plus a signed 16-bit displacement [r+imm].
469 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp, 
470                                     SDOperand &Base) {
471   // If this can be more profitably realized as r+r, fail.
472   if (SelectAddrIdx(N, Disp, Base))
473     return false;
474
475   if (N.getOpcode() == ISD::ADD) {
476     unsigned imm = 0;
477     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
478       Disp = getI32Imm(imm & 0xFFFF);
479       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
480         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
481       } else {
482         Base = N.getOperand(0);
483       }
484       return true; // [r+i]
485     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
486       // Match LOAD (ADD (X, Lo(G))).
487       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
488              && "Cannot handle constant offsets yet!");
489       Disp = N.getOperand(1).getOperand(0);  // The global address.
490       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
491              Disp.getOpcode() == ISD::TargetConstantPool ||
492              Disp.getOpcode() == ISD::TargetJumpTable);
493       Base = N.getOperand(0);
494       return true;  // [&g+r]
495     }
496   } else if (N.getOpcode() == ISD::OR) {
497     unsigned imm = 0;
498     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
499       // If this is an or of disjoint bitfields, we can codegen this as an add
500       // (for better address arithmetic) if the LHS and RHS of the OR are
501       // provably disjoint.
502       uint64_t LHSKnownZero, LHSKnownOne;
503       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
504                                     LHSKnownZero, LHSKnownOne);
505       if ((LHSKnownZero|~imm) == ~0U) {
506         // If all of the bits are known zero on the LHS or RHS, the add won't
507         // carry.
508         Base = N.getOperand(0);
509         Disp = getI32Imm(imm & 0xFFFF);
510         return true;
511       }
512     }
513   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
514     // Loading from a constant address.
515     int Addr = (int)CN->getValue();
516     
517     // If this address fits entirely in a 16-bit sext immediate field, codegen
518     // this as "d, 0"
519     if (Addr == (short)Addr) {
520       Disp = getI32Imm(Addr);
521       Base = CurDAG->getRegister(PPC::R0, MVT::i32);
522       return true;
523     }
524     
525     // Otherwise, break this down into an LIS + disp.
526     Disp = getI32Imm((short)Addr);
527     Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
528     return true;
529   }
530   
531   Disp = getI32Imm(0);
532   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
533     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
534   else
535     Base = N;
536   return true;      // [r+0]
537 }
538
539 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
540 /// represented as an indexed [r+r] operation.  Returns false if it can
541 /// be represented by [r+imm], which are preferred.
542 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base, 
543                                     SDOperand &Index) {
544   unsigned imm = 0;
545   if (N.getOpcode() == ISD::ADD) {
546     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
547       return false;    // r+i
548     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
549       return false;    // r+i
550     
551     Base = N.getOperand(0);
552     Index = N.getOperand(1);
553     return true;
554   } else if (N.getOpcode() == ISD::OR) {
555     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
556       return false;    // r+i can fold it if we can.
557     
558     // If this is an or of disjoint bitfields, we can codegen this as an add
559     // (for better address arithmetic) if the LHS and RHS of the OR are provably
560     // disjoint.
561     uint64_t LHSKnownZero, LHSKnownOne;
562     uint64_t RHSKnownZero, RHSKnownOne;
563     PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
564                                   LHSKnownZero, LHSKnownOne);
565     
566     if (LHSKnownZero) {
567       PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
568                                     RHSKnownZero, RHSKnownOne);
569       // If all of the bits are known zero on the LHS or RHS, the add won't
570       // carry.
571       if ((LHSKnownZero | RHSKnownZero) == ~0U) {
572         Base = N.getOperand(0);
573         Index = N.getOperand(1);
574         return true;
575       }
576     }
577   }
578   
579   return false;
580 }
581
582 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
583 /// represented as an indexed [r+r] operation.
584 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base, 
585                                         SDOperand &Index) {
586   // Check to see if we can easily represent this as an [r+r] address.  This
587   // will fail if it thinks that the address is more profitably represented as
588   // reg+imm, e.g. where imm = 0.
589   if (SelectAddrIdx(N, Base, Index))
590     return true;
591   
592   // If the operand is an addition, always emit this as [r+r], since this is
593   // better (for code size, and execution, as the memop does the add for free)
594   // than emitting an explicit add.
595   if (N.getOpcode() == ISD::ADD) {
596     Base = N.getOperand(0);
597     Index = N.getOperand(1);
598     return true;
599   }
600   
601   // Otherwise, do it the hard way, using R0 as the base register.
602   Base = CurDAG->getRegister(PPC::R0, MVT::i32);
603   Index = N;
604   return true;
605 }
606
607 /// SelectAddrImmShift - Returns true if the address N can be represented by
608 /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
609 /// for use by STD and friends.
610 bool PPCDAGToDAGISel::SelectAddrImmShift(SDOperand N, SDOperand &Disp, 
611                                          SDOperand &Base) {
612   // If this can be more profitably realized as r+r, fail.
613   if (SelectAddrIdx(N, Disp, Base))
614     return false;
615   
616   if (N.getOpcode() == ISD::ADD) {
617     unsigned imm = 0;
618     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm) &&
619         (imm & 3) == 0) {
620       Disp = getI32Imm((imm & 0xFFFF) >> 2);
621       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
622         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
623       } else {
624         Base = N.getOperand(0);
625       }
626       return true; // [r+i]
627     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
628       // Match LOAD (ADD (X, Lo(G))).
629       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
630              && "Cannot handle constant offsets yet!");
631       Disp = N.getOperand(1).getOperand(0);  // The global address.
632       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
633              Disp.getOpcode() == ISD::TargetConstantPool ||
634              Disp.getOpcode() == ISD::TargetJumpTable);
635       Base = N.getOperand(0);
636       return true;  // [&g+r]
637     }
638   } else if (N.getOpcode() == ISD::OR) {
639     unsigned imm = 0;
640     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm) &&
641         (imm & 3) == 0) {
642       // If this is an or of disjoint bitfields, we can codegen this as an add
643       // (for better address arithmetic) if the LHS and RHS of the OR are
644       // provably disjoint.
645       uint64_t LHSKnownZero, LHSKnownOne;
646       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
647                                     LHSKnownZero, LHSKnownOne);
648       if ((LHSKnownZero|~imm) == ~0U) {
649         // If all of the bits are known zero on the LHS or RHS, the add won't
650         // carry.
651         Base = N.getOperand(0);
652         Disp = getI32Imm((imm & 0xFFFF) >> 2);
653         return true;
654       }
655     }
656   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
657     // Loading from a constant address.
658     int Addr = (int)CN->getValue();
659     if ((Addr & 3) == 0) {
660       // If this address fits entirely in a 16-bit sext immediate field, codegen
661       // this as "d, 0"
662       if (Addr == (short)Addr) {
663         Disp = getI32Imm(Addr >> 2);
664         Base = CurDAG->getRegister(PPC::R0, MVT::i32);
665         return true;
666       }
667       
668       // Otherwise, break this down into an LIS + disp.
669       Disp = getI32Imm((short)Addr >> 2);
670       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
671       return true;
672     }
673   }
674   
675   Disp = getI32Imm(0);
676   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
677     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
678   else
679     Base = N;
680   return true;      // [r+0]
681 }
682
683
684 /// SelectCC - Select a comparison of the specified values with the specified
685 /// condition code, returning the CR# of the expression.
686 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
687                                     ISD::CondCode CC) {
688   // Always select the LHS.
689   Select(LHS, LHS);
690
691   // Use U to determine whether the SETCC immediate range is signed or not.
692   if (MVT::isInteger(LHS.getValueType())) {
693     bool U = ISD::isUnsignedIntSetCC(CC);
694     unsigned Imm;
695     if (isIntImmediate(RHS, Imm) && 
696         ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
697       return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
698                                     MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
699     Select(RHS, RHS);
700     return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
701                                            LHS, RHS), 0);
702   } else if (LHS.getValueType() == MVT::f32) {
703     Select(RHS, RHS);
704     return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
705   } else {
706     Select(RHS, RHS);
707     return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
708   }
709 }
710
711 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
712 /// to Condition.
713 static unsigned getBCCForSetCC(ISD::CondCode CC) {
714   switch (CC) {
715   default: assert(0 && "Unknown condition!"); abort();
716   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
717   case ISD::SETUEQ:
718   case ISD::SETEQ:  return PPC::BEQ;
719   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
720   case ISD::SETUNE:
721   case ISD::SETNE:  return PPC::BNE;
722   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
723   case ISD::SETULT:
724   case ISD::SETLT:  return PPC::BLT;
725   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
726   case ISD::SETULE:
727   case ISD::SETLE:  return PPC::BLE;
728   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
729   case ISD::SETUGT:
730   case ISD::SETGT:  return PPC::BGT;
731   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
732   case ISD::SETUGE:
733   case ISD::SETGE:  return PPC::BGE;
734     
735   case ISD::SETO:   return PPC::BUN;
736   case ISD::SETUO:  return PPC::BNU;
737   }
738   return 0;
739 }
740
741 /// getCRIdxForSetCC - Return the index of the condition register field
742 /// associated with the SetCC condition, and whether or not the field is
743 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
744 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
745   switch (CC) {
746   default: assert(0 && "Unknown condition!"); abort();
747   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
748   case ISD::SETULT:
749   case ISD::SETLT:  Inv = false;  return 0;
750   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
751   case ISD::SETUGE:
752   case ISD::SETGE:  Inv = true;   return 0;
753   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
754   case ISD::SETUGT:
755   case ISD::SETGT:  Inv = false;  return 1;
756   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
757   case ISD::SETULE:
758   case ISD::SETLE:  Inv = true;   return 1;
759   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
760   case ISD::SETUEQ:
761   case ISD::SETEQ:  Inv = false;  return 2;
762   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
763   case ISD::SETUNE:
764   case ISD::SETNE:  Inv = true;   return 2;
765   case ISD::SETO:   Inv = true;   return 3;
766   case ISD::SETUO:  Inv = false;  return 3;
767   }
768   return 0;
769 }
770
771 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
772   SDNode *N = Op.Val;
773   unsigned Imm;
774   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
775   if (isIntImmediate(N->getOperand(1), Imm)) {
776     // We can codegen setcc op, imm very efficiently compared to a brcond.
777     // Check for those cases here.
778     // setcc op, 0
779     if (Imm == 0) {
780       SDOperand Op;
781       Select(Op, N->getOperand(0));
782       switch (CC) {
783       default: break;
784       case ISD::SETEQ:
785         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
786         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
787                                     getI32Imm(5), getI32Imm(31));
788       case ISD::SETNE: {
789         SDOperand AD =
790           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
791                                           Op, getI32Imm(~0U)), 0);
792         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
793                                     AD.getValue(1));
794       }
795       case ISD::SETLT:
796         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
797                                     getI32Imm(31), getI32Imm(31));
798       case ISD::SETGT: {
799         SDOperand T =
800           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
801         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
802         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
803                                     getI32Imm(31), getI32Imm(31));
804       }
805       }
806     } else if (Imm == ~0U) {        // setcc op, -1
807       SDOperand Op;
808       Select(Op, N->getOperand(0));
809       switch (CC) {
810       default: break;
811       case ISD::SETEQ:
812         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
813                                              Op, getI32Imm(1)), 0);
814         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
815                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
816                                                               getI32Imm(0)), 0),
817                                     Op.getValue(1));
818       case ISD::SETNE: {
819         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
820         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
821                                            Op, getI32Imm(~0U));
822         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
823                                     Op, SDOperand(AD, 1));
824       }
825       case ISD::SETLT: {
826         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
827                                                        getI32Imm(1)), 0);
828         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
829                                                        Op), 0);
830         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
831                                     getI32Imm(31), getI32Imm(31));
832       }
833       case ISD::SETGT:
834         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
835                                              getI32Imm(1), getI32Imm(31),
836                                              getI32Imm(31)), 0);
837         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
838       }
839     }
840   }
841   
842   bool Inv;
843   unsigned Idx = getCRIdxForSetCC(CC, Inv);
844   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
845   SDOperand IntCR;
846   
847   // Force the ccreg into CR7.
848   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
849   
850   SDOperand InFlag(0, 0);  // Null incoming flag value.
851   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
852                                InFlag).getValue(1);
853   
854   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
855     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
856                                             CCReg), 0);
857   else
858     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
859   
860   if (!Inv) {
861     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
862                                 getI32Imm((32-(3-Idx)) & 31),
863                                 getI32Imm(31), getI32Imm(31));
864   } else {
865     SDOperand Tmp =
866       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
867                                       getI32Imm((32-(3-Idx)) & 31),
868                                       getI32Imm(31),getI32Imm(31)), 0);
869     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
870   }
871 }
872
873
874 // Select - Convert the specified operand from a target-independent to a
875 // target-specific node if it hasn't already been changed.
876 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
877   SDNode *N = Op.Val;
878   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
879       N->getOpcode() < PPCISD::FIRST_NUMBER) {
880     Result = Op;
881     return;   // Already selected.
882   }
883
884   // If this has already been converted, use it.
885   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
886   if (CGMI != CodeGenMap.end()) {
887     Result = CGMI->second;
888     return;
889   }
890   
891   switch (N->getOpcode()) {
892   default: break;
893   case ISD::SETCC:
894     Result = SelectSETCC(Op);
895     return;
896   case PPCISD::GlobalBaseReg:
897     Result = getGlobalBaseReg();
898     return;
899     
900   case ISD::FrameIndex: {
901     int FI = cast<FrameIndexSDNode>(N)->getIndex();
902     if (N->hasOneUse()) {
903       Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
904                                     CurDAG->getTargetFrameIndex(FI, MVT::i32),
905                                     getI32Imm(0));
906       return;
907     }
908     Result = CodeGenMap[Op] = 
909       SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
910                                       CurDAG->getTargetFrameIndex(FI, MVT::i32),
911                                       getI32Imm(0)), 0);
912     return;
913   }
914
915   case PPCISD::MFCR: {
916     SDOperand InFlag;
917     Select(InFlag, N->getOperand(1));
918     // Use MFOCRF if supported.
919     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
920       Result = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
921                                                N->getOperand(0), InFlag), 0);
922     else
923       Result = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag), 0);
924     CodeGenMap[Op] = Result;
925     return;
926   }
927     
928   case ISD::SDIV: {
929     // FIXME: since this depends on the setting of the carry flag from the srawi
930     //        we should really be making notes about that for the scheduler.
931     // FIXME: It sure would be nice if we could cheaply recognize the 
932     //        srl/add/sra pattern the dag combiner will generate for this as
933     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
934     unsigned Imm;
935     if (isIntImmediate(N->getOperand(1), Imm)) {
936       SDOperand N0;
937       Select(N0, N->getOperand(0));
938       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
939         SDNode *Op =
940           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
941                                 N0, getI32Imm(Log2_32(Imm)));
942         Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
943                                       SDOperand(Op, 0), SDOperand(Op, 1));
944       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
945         SDNode *Op =
946           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
947                                 N0, getI32Imm(Log2_32(-Imm)));
948         SDOperand PT =
949           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
950                                           SDOperand(Op, 0), SDOperand(Op, 1)),
951                     0);
952         Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
953       }
954       return;
955     }
956     
957     // Other cases are autogenerated.
958     break;
959   }
960   case ISD::AND: {
961     unsigned Imm, Imm2;
962     // If this is an and of a value rotated between 0 and 31 bits and then and'd
963     // with a mask, emit rlwinm
964     if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
965                                                   isShiftedMask_32(~Imm))) {
966       SDOperand Val;
967       unsigned SH, MB, ME;
968       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
969         Select(Val, N->getOperand(0).getOperand(0));
970       } else if (Imm == 0) {
971         // AND X, 0 -> 0, not "rlwinm 32".
972         Select(Result, N->getOperand(1));
973         return ;
974       } else {        
975         Select(Val, N->getOperand(0));
976         isRunOfOnes(Imm, MB, ME);
977         SH = 0;
978       }
979       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
980                                     getI32Imm(SH), getI32Imm(MB),
981                                     getI32Imm(ME));
982       return;
983     }
984     // ISD::OR doesn't get all the bitfield insertion fun.
985     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
986     if (isIntImmediate(N->getOperand(1), Imm) && 
987         N->getOperand(0).getOpcode() == ISD::OR &&
988         isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
989       unsigned MB, ME;
990       Imm = ~(Imm^Imm2);
991       if (isRunOfOnes(Imm, MB, ME)) {
992         SDOperand Tmp1, Tmp2;
993         Select(Tmp1, N->getOperand(0).getOperand(0));
994         Select(Tmp2, N->getOperand(0).getOperand(1));
995         Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
996                                                  Tmp1, Tmp2,
997                                                  getI32Imm(0), getI32Imm(MB),
998                                                  getI32Imm(ME)), 0);
999         return;
1000       }
1001     }
1002     
1003     // Other cases are autogenerated.
1004     break;
1005   }
1006   case ISD::OR:
1007     if (SDNode *I = SelectBitfieldInsert(N)) {
1008       Result = CodeGenMap[Op] = SDOperand(I, 0);
1009       return;
1010     }
1011       
1012     // Other cases are autogenerated.
1013     break;
1014   case ISD::SHL: {
1015     unsigned Imm, SH, MB, ME;
1016     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1017         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1018       SDOperand Val;
1019       Select(Val, N->getOperand(0).getOperand(0));
1020       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1021                                     Val, getI32Imm(SH), getI32Imm(MB),
1022                                     getI32Imm(ME));
1023       return;
1024     }
1025     
1026     // Other cases are autogenerated.
1027     break;
1028   }
1029   case ISD::SRL: {
1030     unsigned Imm, SH, MB, ME;
1031     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1032         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
1033       SDOperand Val;
1034       Select(Val, N->getOperand(0).getOperand(0));
1035       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1036                                     Val, getI32Imm(SH), getI32Imm(MB),
1037                                     getI32Imm(ME));
1038       return;
1039     }
1040     
1041     // Other cases are autogenerated.
1042     break;
1043   }
1044   case ISD::SELECT_CC: {
1045     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1046     
1047     // handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1048     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1049       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1050         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1051           if (N1C->isNullValue() && N3C->isNullValue() &&
1052               N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1053             SDOperand LHS;
1054             Select(LHS, N->getOperand(0));
1055             SDNode *Tmp =
1056               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1057                                     LHS, getI32Imm(~0U));
1058             Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1059                                           SDOperand(Tmp, 0), LHS,
1060                                           SDOperand(Tmp, 1));
1061             return;
1062           }
1063
1064     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1065     unsigned BROpc = getBCCForSetCC(CC);
1066
1067     bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1068     unsigned SelectCCOp;
1069     if (MVT::isInteger(N->getValueType(0)))
1070       SelectCCOp = PPC::SELECT_CC_Int;
1071     else if (N->getValueType(0) == MVT::f32)
1072       SelectCCOp = PPC::SELECT_CC_F4;
1073     else if (N->getValueType(0) == MVT::f64)
1074       SelectCCOp = PPC::SELECT_CC_F8;
1075     else
1076       SelectCCOp = PPC::SELECT_CC_VRRC;
1077
1078     SDOperand N2, N3;
1079     Select(N2, N->getOperand(2));
1080     Select(N3, N->getOperand(3));
1081     Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1082                                   N2, N3, getI32Imm(BROpc));
1083     return;
1084   }
1085   case ISD::BR_CC: {
1086     SDOperand Chain;
1087     Select(Chain, N->getOperand(0));
1088     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1089     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1090     Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, 
1091                                   CondCode, getI32Imm(getBCCForSetCC(CC)), 
1092                                   N->getOperand(4), Chain);
1093     return;
1094   }
1095   case ISD::BRIND: {
1096     SDOperand Chain, Target;
1097     Select(Chain, N->getOperand(0));
1098     Select(Target,N->getOperand(1));
1099     Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Target,
1100                                             Chain), 0);
1101     Result = CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
1102     return;
1103   }
1104   }
1105   
1106   SelectCode(Result, Op);
1107 }
1108
1109
1110 /// createPPCISelDag - This pass converts a legalized DAG into a 
1111 /// PowerPC-specific DAG, ready for instruction scheduling.
1112 ///
1113 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1114   return new PPCDAGToDAGISel(TM);
1115 }
1116