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