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