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