Add an isTailCall flag to LowerCallTo
[oota-llvm.git] / lib / Target / PowerPC / PPCISelPattern.cpp
1 //===-- PPC32ISelPattern.cpp - A pattern matching inst selector for PPC32 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for 32 bit PowerPC.
11 // Magic number generation for integer divide from the PowerPC Compiler Writer's
12 // Guide, section 3.2.3.5
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "PowerPC.h"
17 #include "PowerPCInstrBuilder.h"
18 #include "PowerPCInstrInfo.h"
19 #include "PPC32TargetMachine.h"
20 #include "llvm/Constants.h"                   // FIXME: REMOVE
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineConstantPool.h" // FIXME: REMOVE
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include <set>
35 #include <algorithm>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 //  PPC32TargetLowering - PPC32 Implementation of the TargetLowering interface
40 namespace {
41   class PPC32TargetLowering : public TargetLowering {
42     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
43     int ReturnAddrIndex;              // FrameIndex for return slot.
44   public:
45     PPC32TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
46       // Fold away setcc operations if possible.
47       setSetCCIsExpensive();
48
49       // Set up the register classes.
50       addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
51       addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
52       addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
53
54       // PowerPC has no intrinsics for these particular operations
55       setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
56       setOperationAction(ISD::MEMSET, MVT::Other, Expand);
57       setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
58
59       // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
60       setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
61       setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
62
63       // PowerPC has no SREM/UREM instructions
64       setOperationAction(ISD::SREM, MVT::i32, Expand);
65       setOperationAction(ISD::UREM, MVT::i32, Expand);
66
67       // We don't support sin/cos/sqrt/fmod
68       setOperationAction(ISD::FSIN , MVT::f64, Expand);
69       setOperationAction(ISD::FCOS , MVT::f64, Expand);
70       setOperationAction(ISD::FSQRT, MVT::f64, Expand);
71       setOperationAction(ISD::SREM , MVT::f64, Expand);
72       setOperationAction(ISD::FSIN , MVT::f32, Expand);
73       setOperationAction(ISD::FCOS , MVT::f32, Expand);
74       setOperationAction(ISD::FSQRT, MVT::f32, Expand);
75       setOperationAction(ISD::SREM , MVT::f32, Expand);
76
77       //PowerPC does not have CTPOP or CTTZ
78       setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
79       setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
80
81       setSetCCResultContents(ZeroOrOneSetCCResult);
82       addLegalFPImmediate(+0.0); // Necessary for FSEL
83       addLegalFPImmediate(-0.0); //
84
85       computeRegisterProperties();
86     }
87
88     /// LowerArguments - This hook must be implemented to indicate how we should
89     /// lower the arguments for the specified function, into the specified DAG.
90     virtual std::vector<SDOperand>
91     LowerArguments(Function &F, SelectionDAG &DAG);
92
93     /// LowerCallTo - This hook lowers an abstract call to a function into an
94     /// actual call.
95     virtual std::pair<SDOperand, SDOperand>
96     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
97                 bool isTailCall, SDOperand Callee, ArgListTy &Args,
98                 SelectionDAG &DAG);
99
100     virtual std::pair<SDOperand, SDOperand>
101     LowerVAStart(SDOperand Chain, SelectionDAG &DAG);
102
103     virtual std::pair<SDOperand,SDOperand>
104     LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
105                    const Type *ArgTy, SelectionDAG &DAG);
106
107     virtual std::pair<SDOperand, SDOperand>
108     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
109                             SelectionDAG &DAG);
110   };
111 }
112
113
114 std::vector<SDOperand>
115 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
116   //
117   // add beautiful description of PPC stack frame format, or at least some docs
118   //
119   MachineFunction &MF = DAG.getMachineFunction();
120   MachineFrameInfo *MFI = MF.getFrameInfo();
121   MachineBasicBlock& BB = MF.front();
122   std::vector<SDOperand> ArgValues;
123
124   // Due to the rather complicated nature of the PowerPC ABI, rather than a
125   // fixed size array of physical args, for the sake of simplicity let the STL
126   // handle tracking them for us.
127   std::vector<unsigned> argVR, argPR, argOp;
128   unsigned ArgOffset = 24;
129   unsigned GPR_remaining = 8;
130   unsigned FPR_remaining = 13;
131   unsigned GPR_idx = 0, FPR_idx = 0;
132   static const unsigned GPR[] = {
133     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
134     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
135   };
136   static const unsigned FPR[] = {
137     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
138     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
139   };
140
141   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
142   // the arguments start at offset 24, although they are likely to be passed
143   // in registers.
144   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
145     SDOperand newroot, argt;
146     unsigned ObjSize;
147     bool needsLoad = false;
148     bool ArgLive = !I->use_empty();
149     MVT::ValueType ObjectVT = getValueType(I->getType());
150
151     switch (ObjectVT) {
152     default: assert(0 && "Unhandled argument type!");
153     case MVT::i1:
154     case MVT::i8:
155     case MVT::i16:
156     case MVT::i32:
157       ObjSize = 4;
158       if (!ArgLive) break;
159       if (GPR_remaining > 0) {
160         MF.addLiveIn(GPR[GPR_idx]);
161         argt = newroot = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32,
162                                             DAG.getRoot());
163         if (ObjectVT != MVT::i32)
164           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, newroot);
165       } else {
166         needsLoad = true;
167       }
168       break;
169       case MVT::i64: ObjSize = 8;
170       if (!ArgLive) break;
171       if (GPR_remaining > 0) {
172         SDOperand argHi, argLo;
173         MF.addLiveIn(GPR[GPR_idx]);
174         argHi = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
175         // If we have two or more remaining argument registers, then both halves
176         // of the i64 can be sourced from there.  Otherwise, the lower half will
177         // have to come off the stack.  This can happen when an i64 is preceded
178         // by 28 bytes of arguments.
179         if (GPR_remaining > 1) {
180           MF.addLiveIn(GPR[GPR_idx+1]);
181           argLo = DAG.getCopyFromReg(GPR[GPR_idx+1], MVT::i32, argHi);
182         } else {
183           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
184           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
185           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN, DAG.getSrcValue(NULL));
186         }
187         // Build the outgoing arg thingy
188         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
189         newroot = argLo;
190       } else {
191         needsLoad = true;
192       }
193       break;
194       case MVT::f32:
195       case MVT::f64:
196       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
197       if (!ArgLive) break;
198       if (FPR_remaining > 0) {
199         MF.addLiveIn(FPR[FPR_idx]);
200         argt = newroot = DAG.getCopyFromReg(FPR[FPR_idx], ObjectVT,
201                                             DAG.getRoot());
202         --FPR_remaining;
203         ++FPR_idx;
204       } else {
205         needsLoad = true;
206       }
207       break;
208     }
209
210     // We need to load the argument to a virtual register if we determined above
211     // that we ran out of physical registers of the appropriate type
212     if (needsLoad) {
213       unsigned SubregOffset = 0;
214       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
215       if (ObjectVT == MVT::i16) SubregOffset = 2;
216       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
217       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
218       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
219                         DAG.getConstant(SubregOffset, MVT::i32));
220       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN, DAG.getSrcValue(NULL));
221     }
222
223     // Every 4 bytes of argument space consumes one of the GPRs available for
224     // argument passing.
225     if (GPR_remaining > 0) {
226       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
227       GPR_remaining -= delta;
228       GPR_idx += delta;
229     }
230     ArgOffset += ObjSize;
231     if (newroot.Val)
232       DAG.setRoot(newroot.getValue(1));
233
234     ArgValues.push_back(argt);
235   }
236
237   // If the function takes variable number of arguments, make a frame index for
238   // the start of the first vararg value... for expansion of llvm.va_start.
239   if (F.isVarArg()) {
240     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
241     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
242     // If this function is vararg, store any remaining integer argument regs
243     // to their spots on the stack so that they may be loaded by deferencing the
244     // result of va_next.
245     std::vector<SDOperand> MemOps;
246     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
247       MF.addLiveIn(GPR[GPR_idx]);
248       SDOperand Val = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, DAG.getRoot());
249       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
250                                     Val, FIN, DAG.getSrcValue(NULL));
251       MemOps.push_back(Store);
252       // Increment the address by four for the next argument to store
253       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
254       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
255     }
256     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
257   }
258
259   // Finally, inform the code generator which regs we return values in.
260   switch (getValueType(F.getReturnType())) {
261   default: assert(0 && "Unknown type!");
262   case MVT::isVoid: break;
263   case MVT::i1:
264   case MVT::i8:
265   case MVT::i16:
266   case MVT::i32:
267     MF.addLiveOut(PPC::R3);
268     break;
269   case MVT::i64:
270     MF.addLiveOut(PPC::R3);
271     MF.addLiveOut(PPC::R4);
272     break;
273   case MVT::f32:
274   case MVT::f64:
275     MF.addLiveOut(PPC::F1);
276     break;
277   }
278
279   return ArgValues;
280 }
281
282 std::pair<SDOperand, SDOperand>
283 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
284                                  const Type *RetTy, bool isVarArg,
285                                  unsigned CallingConv, bool isTailCall, 
286                                  SDOperand Callee, ArgListTy &Args,
287                                  SelectionDAG &DAG) {
288   // args_to_use will accumulate outgoing args for the ISD::CALL case in
289   // SelectExpr to use to put the arguments in the appropriate registers.
290   std::vector<SDOperand> args_to_use;
291
292   // Count how many bytes are to be pushed on the stack, including the linkage
293   // area, and parameter passing area.
294   unsigned NumBytes = 24;
295
296   if (Args.empty()) {
297     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
298                         DAG.getConstant(NumBytes, getPointerTy()));
299   } else {
300     for (unsigned i = 0, e = Args.size(); i != e; ++i)
301       switch (getValueType(Args[i].second)) {
302       default: assert(0 && "Unknown value type!");
303       case MVT::i1:
304       case MVT::i8:
305       case MVT::i16:
306       case MVT::i32:
307       case MVT::f32:
308         NumBytes += 4;
309         break;
310       case MVT::i64:
311       case MVT::f64:
312         NumBytes += 8;
313         break;
314       }
315
316     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
317     // plus 32 bytes of argument space in case any called code gets funky on us.
318     if (NumBytes < 56) NumBytes = 56;
319
320     // Adjust the stack pointer for the new arguments...
321     // These operations are automatically eliminated by the prolog/epilog pass
322     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
323                         DAG.getConstant(NumBytes, getPointerTy()));
324
325     // Set up a copy of the stack pointer for use loading and storing any
326     // arguments that may not fit in the registers available for argument
327     // passing.
328     SDOperand StackPtr = DAG.getCopyFromReg(PPC::R1, MVT::i32,
329                                             DAG.getEntryNode());
330
331     // Figure out which arguments are going to go in registers, and which in
332     // memory.  Also, if this is a vararg function, floating point operations
333     // must be stored to our stack, and loaded into integer regs as well, if
334     // any integer regs are available for argument passing.
335     unsigned ArgOffset = 24;
336     unsigned GPR_remaining = 8;
337     unsigned FPR_remaining = 13;
338
339     std::vector<SDOperand> MemOps;
340     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
341       // PtrOff will be used to store the current argument to the stack if a
342       // register cannot be found for it.
343       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
344       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
345       MVT::ValueType ArgVT = getValueType(Args[i].second);
346
347       switch (ArgVT) {
348       default: assert(0 && "Unexpected ValueType for argument!");
349       case MVT::i1:
350       case MVT::i8:
351       case MVT::i16:
352         // Promote the integer to 32 bits.  If the input type is signed use a
353         // sign extend, otherwise use a zero extend.
354         if (Args[i].second->isSigned())
355           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
356         else
357           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
358         // FALL THROUGH
359       case MVT::i32:
360         if (GPR_remaining > 0) {
361           args_to_use.push_back(Args[i].first);
362           --GPR_remaining;
363         } else {
364           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
365                                        Args[i].first, PtrOff, DAG.getSrcValue(NULL)));
366         }
367         ArgOffset += 4;
368         break;
369       case MVT::i64:
370         // If we have one free GPR left, we can place the upper half of the i64
371         // in it, and store the other half to the stack.  If we have two or more
372         // free GPRs, then we can pass both halves of the i64 in registers.
373         if (GPR_remaining > 0) {
374           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
375             Args[i].first, DAG.getConstant(1, MVT::i32));
376           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
377             Args[i].first, DAG.getConstant(0, MVT::i32));
378           args_to_use.push_back(Hi);
379           --GPR_remaining;
380           if (GPR_remaining > 0) {
381             args_to_use.push_back(Lo);
382             --GPR_remaining;
383           } else {
384             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
385             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
386             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
387                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
388           }
389         } else {
390           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
391                                        Args[i].first, PtrOff, DAG.getSrcValue(NULL)));
392         }
393         ArgOffset += 8;
394         break;
395       case MVT::f32:
396       case MVT::f64:
397         if (FPR_remaining > 0) {
398           args_to_use.push_back(Args[i].first);
399           --FPR_remaining;
400           if (isVarArg) {
401             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
402                                           Args[i].first, PtrOff, DAG.getSrcValue(NULL));
403             MemOps.push_back(Store);
404             // Float varargs are always shadowed in available integer registers
405             if (GPR_remaining > 0) {
406               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff, DAG.getSrcValue(NULL));
407               MemOps.push_back(Load);
408               args_to_use.push_back(Load);
409               --GPR_remaining;
410             }
411             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
412               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
413               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
414               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff, DAG.getSrcValue(NULL));
415               MemOps.push_back(Load);
416               args_to_use.push_back(Load);
417               --GPR_remaining;
418             }
419           } else {
420             // If we have any FPRs remaining, we may also have GPRs remaining.
421             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
422             // GPRs.
423             if (GPR_remaining > 0) {
424               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
425               --GPR_remaining;
426             }
427             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
428               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
429               --GPR_remaining;
430             }
431           }
432         } else {
433           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
434                                        Args[i].first, PtrOff, DAG.getSrcValue(NULL)));
435         }
436         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
437         break;
438       }
439     }
440     if (!MemOps.empty())
441       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
442   }
443
444   std::vector<MVT::ValueType> RetVals;
445   MVT::ValueType RetTyVT = getValueType(RetTy);
446   if (RetTyVT != MVT::isVoid)
447     RetVals.push_back(RetTyVT);
448   RetVals.push_back(MVT::Other);
449
450   SDOperand TheCall = SDOperand(DAG.getCall(RetVals,
451                                             Chain, Callee, args_to_use), 0);
452   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
453   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
454                       DAG.getConstant(NumBytes, getPointerTy()));
455   return std::make_pair(TheCall, Chain);
456 }
457
458 std::pair<SDOperand, SDOperand>
459 PPC32TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
460   //vastart just returns the address of the VarArgsFrameIndex slot.
461   return std::make_pair(DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32), Chain);
462 }
463
464 std::pair<SDOperand,SDOperand> PPC32TargetLowering::
465 LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
466                const Type *ArgTy, SelectionDAG &DAG) {
467   MVT::ValueType ArgVT = getValueType(ArgTy);
468   SDOperand Result;
469   if (!isVANext) {
470     Result = DAG.getLoad(ArgVT, DAG.getEntryNode(), VAList, DAG.getSrcValue(NULL));
471   } else {
472     unsigned Amt;
473     if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
474       Amt = 4;
475     else {
476       assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
477              "Other types should have been promoted for varargs!");
478       Amt = 8;
479     }
480     Result = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
481                          DAG.getConstant(Amt, VAList.getValueType()));
482   }
483   return std::make_pair(Result, Chain);
484 }
485
486
487 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
488 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
489                         SelectionDAG &DAG) {
490   assert(0 && "LowerFrameReturnAddress unimplemented");
491   abort();
492 }
493
494 namespace {
495 Statistic<>Recorded("ppc-codegen", "Number of recording ops emitted");
496 Statistic<>FusedFP("ppc-codegen", "Number of fused fp operations");
497 Statistic<>MultiBranch("ppc-codegen", "Number of setcc logical ops collapsed");
498 //===--------------------------------------------------------------------===//
499 /// ISel - PPC32 specific code to select PPC32 machine instructions for
500 /// SelectionDAG operations.
501 //===--------------------------------------------------------------------===//
502 class ISel : public SelectionDAGISel {
503   PPC32TargetLowering PPC32Lowering;
504   SelectionDAG *ISelDAG;  // Hack to support us having a dag->dag transform
505                           // for sdiv and udiv until it is put into the future
506                           // dag combiner.
507
508   /// ExprMap - As shared expressions are codegen'd, we keep track of which
509   /// vreg the value is produced in, so we only emit one copy of each compiled
510   /// tree.
511   std::map<SDOperand, unsigned> ExprMap;
512
513   unsigned GlobalBaseReg;
514   bool GlobalBaseInitialized;
515   bool RecordSuccess;
516 public:
517   ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM),
518                             ISelDAG(0) {}
519
520   /// runOnFunction - Override this function in order to reset our per-function
521   /// variables.
522   virtual bool runOnFunction(Function &Fn) {
523     // Make sure we re-emit a set of the global base reg if necessary
524     GlobalBaseInitialized = false;
525     return SelectionDAGISel::runOnFunction(Fn);
526   }
527
528   /// InstructionSelectBasicBlock - This callback is invoked by
529   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
530   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
531     DEBUG(BB->dump());
532     // Codegen the basic block.
533     ISelDAG = &DAG;
534     Select(DAG.getRoot());
535
536     // Clear state used for selection.
537     ExprMap.clear();
538     ISelDAG = 0;
539   }
540
541   // dag -> dag expanders for integer divide by constant
542   SDOperand BuildSDIVSequence(SDOperand N);
543   SDOperand BuildUDIVSequence(SDOperand N);
544
545   unsigned getGlobalBaseReg();
546   unsigned getConstDouble(double floatVal, unsigned Result);
547   void MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result);
548   bool SelectBitfieldInsert(SDOperand OR, unsigned Result);
549   unsigned FoldIfWideZeroExtend(SDOperand N);
550   unsigned SelectCC(SDOperand CC, unsigned &Opc, bool &Inv, unsigned &Idx);
551   unsigned SelectCCExpr(SDOperand N, unsigned& Opc, bool &Inv, unsigned &Idx);
552   unsigned SelectExpr(SDOperand N, bool Recording=false);
553   unsigned SelectExprFP(SDOperand N, unsigned Result);
554   void Select(SDOperand N);
555
556   bool SelectAddr(SDOperand N, unsigned& Reg, int& offset);
557   void SelectBranchCC(SDOperand N);
558 };
559
560 /// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
561 /// returns zero when the input is not exactly a power of two.
562 static unsigned ExactLog2(unsigned Val) {
563   if (Val == 0 || (Val & (Val-1))) return 0;
564   unsigned Count = 0;
565   while (Val != 1) {
566     Val >>= 1;
567     ++Count;
568   }
569   return Count;
570 }
571
572 // IsRunOfOnes - returns true if Val consists of one contiguous run of 1's with
573 // any number of 0's on either side.  the 1's are allowed to wrap from LSB to
574 // MSB.  so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
575 // not, since all 1's are not contiguous.
576 static bool IsRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
577   bool isRun = true;
578   MB = 0;
579   ME = 0;
580
581   // look for first set bit
582   int i = 0;
583   for (; i < 32; i++) {
584     if ((Val & (1 << (31 - i))) != 0) {
585       MB = i;
586       ME = i;
587       break;
588     }
589   }
590
591   // look for last set bit
592   for (; i < 32; i++) {
593     if ((Val & (1 << (31 - i))) == 0)
594       break;
595     ME = i;
596   }
597
598   // look for next set bit
599   for (; i < 32; i++) {
600     if ((Val & (1 << (31 - i))) != 0)
601       break;
602   }
603
604   // if we exhausted all the bits, we found a match at this point for 0*1*0*
605   if (i == 32)
606     return true;
607
608   // since we just encountered more 1's, if it doesn't wrap around to the
609   // most significant bit of the word, then we did not find a match to 1*0*1* so
610   // exit.
611   if (MB != 0)
612     return false;
613
614   // look for last set bit
615   for (MB = i; i < 32; i++) {
616     if ((Val & (1 << (31 - i))) == 0)
617       break;
618   }
619
620   // if we exhausted all the bits, then we found a match for 1*0*1*, otherwise,
621   // the value is not a run of ones.
622   if (i == 32)
623     return true;
624   return false;
625 }
626
627 /// getImmediateForOpcode - This method returns a value indicating whether
628 /// the ConstantSDNode N can be used as an immediate to Opcode.  The return
629 /// values are either 0, 1 or 2.  0 indicates that either N is not a
630 /// ConstantSDNode, or is not suitable for use by that opcode.
631 /// Return value codes for turning into an enum someday:
632 /// 1: constant may be used in normal immediate form.
633 /// 2: constant may be used in shifted immediate form.
634 /// 3: log base 2 of the constant may be used.
635 /// 4: constant is suitable for integer division conversion
636 /// 5: constant is a bitfield mask
637 ///
638 static unsigned getImmediateForOpcode(SDOperand N, unsigned Opcode,
639                                       unsigned& Imm, bool U = false) {
640   if (N.getOpcode() != ISD::Constant) return 0;
641
642   int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
643
644   switch(Opcode) {
645   default: return 0;
646   case ISD::ADD:
647     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
648     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
649     break;
650   case ISD::AND: {
651     unsigned MB, ME;
652     if (IsRunOfOnes(v, MB, ME)) { Imm = MB << 16 | ME & 0xFFFF; return 5; }
653     if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
654     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
655     break;
656   }
657   case ISD::XOR:
658   case ISD::OR:
659     if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
660     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
661     break;
662   case ISD::MUL:
663     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
664     break;
665   case ISD::SUB:
666     // handle subtract-from separately from subtract, since subi is really addi
667     if (U && v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
668     if (!U && v <= 32768 && v >= -32767) { Imm = (-v) & 0xFFFF; return 1; }
669     break;
670   case ISD::SETCC:
671     if (U && (v >= 0 && v <= 65535)) { Imm = v & 0xFFFF; return 1; }
672     if (!U && (v <= 32767 && v >= -32768)) { Imm = v & 0xFFFF; return 1; }
673     break;
674   case ISD::SDIV:
675     if ((Imm = ExactLog2(v))) { return 3; }
676     if ((Imm = ExactLog2(-v))) { Imm = -Imm; return 3; }
677     if (v <= -2 || v >= 2) { return 4; }
678     break;
679   case ISD::UDIV:
680     if (v > 1) { return 4; }
681     break;
682   }
683   return 0;
684 }
685
686 /// NodeHasRecordingVariant - If SelectExpr can always produce code for
687 /// NodeOpcode that also sets CR0 as a side effect, return true.  Otherwise,
688 /// return false.
689 static bool NodeHasRecordingVariant(unsigned NodeOpcode) {
690   switch(NodeOpcode) {
691   default: return false;
692   case ISD::AND:
693   case ISD::OR:
694     return true;
695   }
696 }
697
698 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
699 /// to Condition.  If the Condition is unordered or unsigned, the bool argument
700 /// U is set to true, otherwise it is set to false.
701 static unsigned getBCCForSetCC(unsigned Condition, bool& U) {
702   U = false;
703   switch (Condition) {
704   default: assert(0 && "Unknown condition!"); abort();
705   case ISD::SETEQ:  return PPC::BEQ;
706   case ISD::SETNE:  return PPC::BNE;
707   case ISD::SETULT: U = true;
708   case ISD::SETLT:  return PPC::BLT;
709   case ISD::SETULE: U = true;
710   case ISD::SETLE:  return PPC::BLE;
711   case ISD::SETUGT: U = true;
712   case ISD::SETGT:  return PPC::BGT;
713   case ISD::SETUGE: U = true;
714   case ISD::SETGE:  return PPC::BGE;
715   }
716   return 0;
717 }
718
719 /// getCROpForOp - Return the condition register opcode (or inverted opcode)
720 /// associated with the SelectionDAG opcode.
721 static unsigned getCROpForSetCC(unsigned Opcode, bool Inv1, bool Inv2) {
722   switch (Opcode) {
723   default: assert(0 && "Unknown opcode!"); abort();
724   case ISD::AND:
725     if (Inv1 && Inv2) return PPC::CRNOR; // De Morgan's Law
726     if (!Inv1 && !Inv2) return PPC::CRAND;
727     if (Inv1 ^ Inv2) return PPC::CRANDC;
728   case ISD::OR:
729     if (Inv1 && Inv2) return PPC::CRNAND; // De Morgan's Law
730     if (!Inv1 && !Inv2) return PPC::CROR;
731     if (Inv1 ^ Inv2) return PPC::CRORC;
732   }
733   return 0;
734 }
735
736 /// getCRIdxForSetCC - Return the index of the condition register field
737 /// associated with the SetCC condition, and whether or not the field is
738 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
739 static unsigned getCRIdxForSetCC(unsigned Condition, bool& Inv) {
740   switch (Condition) {
741   default: assert(0 && "Unknown condition!"); abort();
742   case ISD::SETULT:
743   case ISD::SETLT:  Inv = false;  return 0;
744   case ISD::SETUGE:
745   case ISD::SETGE:  Inv = true;   return 0;
746   case ISD::SETUGT:
747   case ISD::SETGT:  Inv = false;  return 1;
748   case ISD::SETULE:
749   case ISD::SETLE:  Inv = true;   return 1;
750   case ISD::SETEQ:  Inv = false;  return 2;
751   case ISD::SETNE:  Inv = true;   return 2;
752   }
753   return 0;
754 }
755
756 /// IndexedOpForOp - Return the indexed variant for each of the PowerPC load
757 /// and store immediate instructions.
758 static unsigned IndexedOpForOp(unsigned Opcode) {
759   switch(Opcode) {
760   default: assert(0 && "Unknown opcode!"); abort();
761   case PPC::LBZ: return PPC::LBZX;  case PPC::STB: return PPC::STBX;
762   case PPC::LHZ: return PPC::LHZX;  case PPC::STH: return PPC::STHX;
763   case PPC::LHA: return PPC::LHAX;  case PPC::STW: return PPC::STWX;
764   case PPC::LWZ: return PPC::LWZX;  case PPC::STFS: return PPC::STFSX;
765   case PPC::LFS: return PPC::LFSX;  case PPC::STFD: return PPC::STFDX;
766   case PPC::LFD: return PPC::LFDX;
767   }
768   return 0;
769 }
770
771 // Structure used to return the necessary information to codegen an SDIV as
772 // a multiply.
773 struct ms {
774   int m; // magic number
775   int s; // shift amount
776 };
777
778 struct mu {
779   unsigned int m; // magic number
780   int a;          // add indicator
781   int s;          // shift amount
782 };
783
784 /// magic - calculate the magic numbers required to codegen an integer sdiv as
785 /// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
786 /// or -1.
787 static struct ms magic(int d) {
788   int p;
789   unsigned int ad, anc, delta, q1, r1, q2, r2, t;
790   const unsigned int two31 = 2147483648U; // 2^31
791   struct ms mag;
792
793   ad = abs(d);
794   t = two31 + ((unsigned int)d >> 31);
795   anc = t - 1 - t%ad;   // absolute value of nc
796   p = 31;               // initialize p
797   q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
798   r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
799   q2 = two31/ad;        // initialize q2 = 2p/abs(d)
800   r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
801   do {
802     p = p + 1;
803     q1 = 2*q1;        // update q1 = 2p/abs(nc)
804     r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
805     if (r1 >= anc) {  // must be unsigned comparison
806       q1 = q1 + 1;
807       r1 = r1 - anc;
808     }
809     q2 = 2*q2;        // update q2 = 2p/abs(d)
810     r2 = 2*r2;        // update r2 = rem(2p/abs(d))
811     if (r2 >= ad) {   // must be unsigned comparison
812       q2 = q2 + 1;
813       r2 = r2 - ad;
814     }
815     delta = ad - r2;
816   } while (q1 < delta || (q1 == delta && r1 == 0));
817
818   mag.m = q2 + 1;
819   if (d < 0) mag.m = -mag.m; // resulting magic number
820   mag.s = p - 32;            // resulting shift
821   return mag;
822 }
823
824 /// magicu - calculate the magic numbers required to codegen an integer udiv as
825 /// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
826 static struct mu magicu(unsigned d)
827 {
828   int p;
829   unsigned int nc, delta, q1, r1, q2, r2;
830   struct mu magu;
831   magu.a = 0;               // initialize "add" indicator
832   nc = - 1 - (-d)%d;
833   p = 31;                   // initialize p
834   q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
835   r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
836   q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
837   r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
838   do {
839     p = p + 1;
840     if (r1 >= nc - r1 ) {
841       q1 = 2*q1 + 1;  // update q1
842       r1 = 2*r1 - nc; // update r1
843     }
844     else {
845       q1 = 2*q1; // update q1
846       r1 = 2*r1; // update r1
847     }
848     if (r2 + 1 >= d - r2) {
849       if (q2 >= 0x7FFFFFFF) magu.a = 1;
850       q2 = 2*q2 + 1;     // update q2
851       r2 = 2*r2 + 1 - d; // update r2
852     }
853     else {
854       if (q2 >= 0x80000000) magu.a = 1;
855       q2 = 2*q2;     // update q2
856       r2 = 2*r2 + 1; // update r2
857     }
858     delta = d - 1 - r2;
859   } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
860   magu.m = q2 + 1; // resulting magic number
861   magu.s = p - 32;  // resulting shift
862   return magu;
863 }
864 }
865
866 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
867 /// return a DAG expression to select that will generate the same value by
868 /// multiplying by a magic number.  See:
869 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
870 SDOperand ISel::BuildSDIVSequence(SDOperand N) {
871   int d = (int)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
872   ms magics = magic(d);
873   // Multiply the numerator (operand 0) by the magic value
874   SDOperand Q = ISelDAG->getNode(ISD::MULHS, MVT::i32, N.getOperand(0),
875                                  ISelDAG->getConstant(magics.m, MVT::i32));
876   // If d > 0 and m < 0, add the numerator
877   if (d > 0 && magics.m < 0)
878     Q = ISelDAG->getNode(ISD::ADD, MVT::i32, Q, N.getOperand(0));
879   // If d < 0 and m > 0, subtract the numerator.
880   if (d < 0 && magics.m > 0)
881     Q = ISelDAG->getNode(ISD::SUB, MVT::i32, Q, N.getOperand(0));
882   // Shift right algebraic if shift value is nonzero
883   if (magics.s > 0)
884     Q = ISelDAG->getNode(ISD::SRA, MVT::i32, Q,
885                          ISelDAG->getConstant(magics.s, MVT::i32));
886   // Extract the sign bit and add it to the quotient
887   SDOperand T =
888     ISelDAG->getNode(ISD::SRL, MVT::i32, Q, ISelDAG->getConstant(31, MVT::i32));
889   return ISelDAG->getNode(ISD::ADD, MVT::i32, Q, T);
890 }
891
892 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
893 /// return a DAG expression to select that will generate the same value by
894 /// multiplying by a magic number.  See:
895 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
896 SDOperand ISel::BuildUDIVSequence(SDOperand N) {
897   unsigned d =
898     (unsigned)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
899   mu magics = magicu(d);
900   // Multiply the numerator (operand 0) by the magic value
901   SDOperand Q = ISelDAG->getNode(ISD::MULHU, MVT::i32, N.getOperand(0),
902                                  ISelDAG->getConstant(magics.m, MVT::i32));
903   if (magics.a == 0) {
904     Q = ISelDAG->getNode(ISD::SRL, MVT::i32, Q,
905                          ISelDAG->getConstant(magics.s, MVT::i32));
906   } else {
907     SDOperand NPQ = ISelDAG->getNode(ISD::SUB, MVT::i32, N.getOperand(0), Q);
908     NPQ = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
909                            ISelDAG->getConstant(1, MVT::i32));
910     NPQ = ISelDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
911     Q = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
912                            ISelDAG->getConstant(magics.s-1, MVT::i32));
913   }
914   return Q;
915 }
916
917 /// getGlobalBaseReg - Output the instructions required to put the
918 /// base address to use for accessing globals into a register.
919 ///
920 unsigned ISel::getGlobalBaseReg() {
921   if (!GlobalBaseInitialized) {
922     // Insert the set of GlobalBaseReg into the first MBB of the function
923     MachineBasicBlock &FirstMBB = BB->getParent()->front();
924     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
925     GlobalBaseReg = MakeReg(MVT::i32);
926     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
927     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
928     GlobalBaseInitialized = true;
929   }
930   return GlobalBaseReg;
931 }
932
933 /// getConstDouble - Loads a floating point value into a register, via the
934 /// Constant Pool.  Optionally takes a register in which to load the value.
935 unsigned ISel::getConstDouble(double doubleVal, unsigned Result=0) {
936   unsigned Tmp1 = MakeReg(MVT::i32);
937   if (0 == Result) Result = MakeReg(MVT::f64);
938   MachineConstantPool *CP = BB->getParent()->getConstantPool();
939   ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, doubleVal);
940   unsigned CPI = CP->getConstantPoolIndex(CFP);
941   BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
942     .addConstantPoolIndex(CPI);
943   BuildMI(BB, PPC::LFD, 2, Result).addConstantPoolIndex(CPI).addReg(Tmp1);
944   return Result;
945 }
946
947 /// MoveCRtoGPR - Move CCReg[Idx] to the least significant bit of Result.  If
948 /// Inv is true, then invert the result.
949 void ISel::MoveCRtoGPR(unsigned CCReg, bool Inv, unsigned Idx, unsigned Result){
950   unsigned IntCR = MakeReg(MVT::i32);
951   BuildMI(BB, PPC::MCRF, 1, PPC::CR7).addReg(CCReg);
952   BuildMI(BB, PPC::MFCR, 1, IntCR).addReg(PPC::CR7);
953   if (Inv) {
954     unsigned Tmp1 = MakeReg(MVT::i32);
955     BuildMI(BB, PPC::RLWINM, 4, Tmp1).addReg(IntCR).addImm(32-(3-Idx))
956       .addImm(31).addImm(31);
957     BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(1);
958   } else {
959     BuildMI(BB, PPC::RLWINM, 4, Result).addReg(IntCR).addImm(32-(3-Idx))
960       .addImm(31).addImm(31);
961   }
962 }
963
964 /// SelectBitfieldInsert - turn an or of two masked values into
965 /// the rotate left word immediate then mask insert (rlwimi) instruction.
966 /// Returns true on success, false if the caller still needs to select OR.
967 ///
968 /// Patterns matched:
969 /// 1. or shl, and   5. or and, and
970 /// 2. or and, shl   6. or shl, shr
971 /// 3. or shr, and   7. or shr, shl
972 /// 4. or and, shr
973 bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
974   bool IsRotate = false;
975   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, Amount = 0;
976   unsigned Op0Opc = OR.getOperand(0).getOpcode();
977   unsigned Op1Opc = OR.getOperand(1).getOpcode();
978
979   // Verify that we have the correct opcodes
980   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
981     return false;
982   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
983     return false;
984
985   // Generate Mask value for Target
986   if (ConstantSDNode *CN =
987       dyn_cast<ConstantSDNode>(OR.getOperand(0).getOperand(1).Val)) {
988     switch(Op0Opc) {
989     case ISD::SHL: TgtMask <<= (unsigned)CN->getValue(); break;
990     case ISD::SRL: TgtMask >>= (unsigned)CN->getValue(); break;
991     case ISD::AND: TgtMask &= (unsigned)CN->getValue(); break;
992     }
993   } else {
994     return false;
995   }
996
997   // Generate Mask value for Insert
998   if (ConstantSDNode *CN =
999       dyn_cast<ConstantSDNode>(OR.getOperand(1).getOperand(1).Val)) {
1000     switch(Op1Opc) {
1001     case ISD::SHL:
1002       Amount = CN->getValue();
1003       InsMask <<= Amount;
1004       if (Op0Opc == ISD::SRL) IsRotate = true;
1005       break;
1006     case ISD::SRL:
1007       Amount = CN->getValue();
1008       InsMask >>= Amount;
1009       Amount = 32-Amount;
1010       if (Op0Opc == ISD::SHL) IsRotate = true;
1011       break;
1012     case ISD::AND:
1013       InsMask &= (unsigned)CN->getValue();
1014       break;
1015     }
1016   } else {
1017     return false;
1018   }
1019
1020   // Verify that the Target mask and Insert mask together form a full word mask
1021   // and that the Insert mask is a run of set bits (which implies both are runs
1022   // of set bits).  Given that, Select the arguments and generate the rlwimi
1023   // instruction.
1024   unsigned MB, ME;
1025   if (((TgtMask ^ InsMask) == 0xFFFFFFFF) && IsRunOfOnes(InsMask, MB, ME)) {
1026     unsigned Tmp1, Tmp2;
1027     // Check for rotlwi / rotrwi here, a special case of bitfield insert
1028     // where both bitfield halves are sourced from the same value.
1029     if (IsRotate &&
1030         OR.getOperand(0).getOperand(0) == OR.getOperand(1).getOperand(0)) {
1031       Tmp1 = SelectExpr(OR.getOperand(0).getOperand(0));
1032       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Amount)
1033         .addImm(0).addImm(31);
1034       return true;
1035     }
1036     if (Op0Opc == ISD::AND)
1037       Tmp1 = SelectExpr(OR.getOperand(0).getOperand(0));
1038     else
1039       Tmp1 = SelectExpr(OR.getOperand(0));
1040     Tmp2 = SelectExpr(OR.getOperand(1).getOperand(0));
1041     BuildMI(BB, PPC::RLWIMI, 5, Result).addReg(Tmp1).addReg(Tmp2)
1042       .addImm(Amount).addImm(MB).addImm(ME);
1043     return true;
1044   }
1045   return false;
1046 }
1047
1048 /// FoldIfWideZeroExtend - 32 bit PowerPC implicit masks shift amounts to the
1049 /// low six bits.  If the shift amount is an ISD::AND node with a mask that is
1050 /// wider than the implicit mask, then we can get rid of the AND and let the
1051 /// shift do the mask.
1052 unsigned ISel::FoldIfWideZeroExtend(SDOperand N) {
1053   unsigned C;
1054   if (N.getOpcode() == ISD::AND &&
1055       5 == getImmediateForOpcode(N.getOperand(1), ISD::AND, C) && // isMask
1056       31 == (C & 0xFFFF) && // ME
1057       26 >= (C >> 16))      // MB
1058     return SelectExpr(N.getOperand(0));
1059   else
1060     return SelectExpr(N);
1061 }
1062
1063 unsigned ISel::SelectCC(SDOperand CC, unsigned& Opc, bool &Inv, unsigned& Idx) {
1064   unsigned Result, Tmp1, Tmp2;
1065   bool AlreadySelected = false;
1066   static const unsigned CompareOpcodes[] =
1067     { PPC::FCMPU, PPC::FCMPU, PPC::CMPW, PPC::CMPLW };
1068
1069   // Allocate a condition register for this expression
1070   Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);
1071
1072   // If the first operand to the select is a SETCC node, then we can fold it
1073   // into the branch that selects which value to return.
1074   if (SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(CC.Val)) {
1075     bool U;
1076     Opc = getBCCForSetCC(SetCC->getCondition(), U);
1077     Idx = getCRIdxForSetCC(SetCC->getCondition(), Inv);
1078
1079     // Pass the optional argument U to getImmediateForOpcode for SETCC,
1080     // so that it knows whether the SETCC immediate range is signed or not.
1081     if (1 == getImmediateForOpcode(SetCC->getOperand(1), ISD::SETCC,
1082                                    Tmp2, U)) {
1083       // For comparisons against zero, we can implicity set CR0 if a recording
1084       // variant (e.g. 'or.' instead of 'or') of the instruction that defines
1085       // operand zero of the SetCC node is available.
1086       if (0 == Tmp2 &&
1087           NodeHasRecordingVariant(SetCC->getOperand(0).getOpcode()) &&
1088           SetCC->getOperand(0).Val->hasOneUse()) {
1089         RecordSuccess = false;
1090         Tmp1 = SelectExpr(SetCC->getOperand(0), true);
1091         if (RecordSuccess) {
1092           ++Recorded;
1093           BuildMI(BB, PPC::MCRF, 1, Result).addReg(PPC::CR0);
1094           return Result;
1095         }
1096         AlreadySelected = true;
1097       }
1098       // If we could not implicitly set CR0, then emit a compare immediate
1099       // instead.
1100       if (!AlreadySelected) Tmp1 = SelectExpr(SetCC->getOperand(0));
1101       if (U)
1102         BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1103       else
1104         BuildMI(BB, PPC::CMPWI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1105     } else {
1106       bool IsInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1107       unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
1108       Tmp1 = SelectExpr(SetCC->getOperand(0));
1109       Tmp2 = SelectExpr(SetCC->getOperand(1));
1110       BuildMI(BB, CompareOpc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1111     }
1112   } else {
1113     if (PPCCRopts)
1114       return SelectCCExpr(CC, Opc, Inv, Idx);
1115     // If this isn't a SetCC, then select the value and compare it against zero,
1116     // treating it as if it were a boolean.
1117     Opc = PPC::BNE;
1118     Idx = getCRIdxForSetCC(ISD::SETNE, Inv);
1119     Tmp1 = SelectExpr(CC);
1120     BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(0);
1121   }
1122   return Result;
1123 }
1124
1125 unsigned ISel::SelectCCExpr(SDOperand N, unsigned& Opc, bool &Inv,
1126                             unsigned &Idx) {
1127   bool Inv0, Inv1;
1128   unsigned Idx0, Idx1, CROpc, Opc1, Tmp1, Tmp2;
1129
1130   // Allocate a condition register for this expression
1131   unsigned Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);
1132
1133   // Check for the operations we support:
1134   switch(N.getOpcode()) {
1135   default:
1136     Opc = PPC::BNE;
1137     Idx = getCRIdxForSetCC(ISD::SETNE, Inv);
1138     Tmp1 = SelectExpr(N);
1139     BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(0);
1140     break;
1141   case ISD::OR:
1142   case ISD::AND:
1143     ++MultiBranch;
1144     Tmp1 = SelectCCExpr(N.getOperand(0), Opc, Inv0, Idx0);
1145     Tmp2 = SelectCCExpr(N.getOperand(1), Opc1, Inv1, Idx1);
1146     CROpc = getCROpForSetCC(N.getOpcode(), Inv0, Inv1);
1147     if (Inv0 && !Inv1) {
1148       std::swap(Tmp1, Tmp2);
1149       std::swap(Idx0, Idx1);
1150       Opc = Opc1;
1151     }
1152     if (Inv0 && Inv1) Opc = PPC32InstrInfo::invertPPCBranchOpcode(Opc);
1153     BuildMI(BB, CROpc, 5, Result).addImm(Idx0).addReg(Tmp1).addImm(Idx0)
1154       .addReg(Tmp2).addImm(Idx1);
1155     Inv = false;
1156     Idx = Idx0;
1157     break;
1158   case ISD::SETCC:
1159     Tmp1 = SelectCC(N, Opc, Inv, Idx);
1160     Result = Tmp1;
1161     break;
1162   }
1163   return Result;
1164 }
1165
1166 /// Check to see if the load is a constant offset from a base register
1167 bool ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
1168 {
1169   unsigned imm = 0, opcode = N.getOpcode();
1170   if (N.getOpcode() == ISD::ADD) {
1171     Reg = SelectExpr(N.getOperand(0));
1172     if (1 == getImmediateForOpcode(N.getOperand(1), opcode, imm)) {
1173       offset = imm;
1174       return false;
1175     }
1176     offset = SelectExpr(N.getOperand(1));
1177     return true;
1178   }
1179   Reg = SelectExpr(N);
1180   offset = 0;
1181   return false;
1182 }
1183
1184 void ISel::SelectBranchCC(SDOperand N)
1185 {
1186   MachineBasicBlock *Dest =
1187     cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
1188
1189   bool Inv;
1190   unsigned Opc, CCReg, Idx;
1191   Select(N.getOperand(0));  //chain
1192   CCReg = SelectCC(N.getOperand(1), Opc, Inv, Idx);
1193
1194   // Iterate to the next basic block, unless we're already at the end of the
1195   ilist<MachineBasicBlock>::iterator It = BB, E = BB->getParent()->end();
1196   if (++It == E) It = BB;
1197
1198   // If this is a two way branch, then grab the fallthrough basic block argument
1199   // and build a PowerPC branch pseudo-op, suitable for long branch conversion
1200   // if necessary by the branch selection pass.  Otherwise, emit a standard
1201   // conditional branch.
1202   if (N.getOpcode() == ISD::BRCONDTWOWAY) {
1203     MachineBasicBlock *Fallthrough =
1204       cast<BasicBlockSDNode>(N.getOperand(3))->getBasicBlock();
1205     if (Dest != It) {
1206       BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
1207         .addMBB(Dest).addMBB(Fallthrough);
1208       if (Fallthrough != It)
1209         BuildMI(BB, PPC::B, 1).addMBB(Fallthrough);
1210     } else {
1211       if (Fallthrough != It) {
1212         Opc = PPC32InstrInfo::invertPPCBranchOpcode(Opc);
1213         BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
1214           .addMBB(Fallthrough).addMBB(Dest);
1215       }
1216     }
1217   } else {
1218     BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
1219       .addMBB(Dest).addMBB(It);
1220   }
1221   return;
1222 }
1223
1224 unsigned ISel::SelectExprFP(SDOperand N, unsigned Result)
1225 {
1226   unsigned Tmp1, Tmp2, Tmp3;
1227   unsigned Opc = 0;
1228   SDNode *Node = N.Val;
1229   MVT::ValueType DestType = N.getValueType();
1230   unsigned opcode = N.getOpcode();
1231
1232   switch (opcode) {
1233   default:
1234     Node->dump();
1235     assert(0 && "Node not handled!\n");
1236
1237   case ISD::SELECT: {
1238     // Attempt to generate FSEL.  We can do this whenever we have an FP result,
1239     // and an FP comparison in the SetCC node.
1240     SetCCSDNode* SetCC = dyn_cast<SetCCSDNode>(N.getOperand(0).Val);
1241     if (SetCC && N.getOperand(0).getOpcode() == ISD::SETCC &&
1242         !MVT::isInteger(SetCC->getOperand(0).getValueType()) &&
1243         SetCC->getCondition() != ISD::SETEQ &&
1244         SetCC->getCondition() != ISD::SETNE) {
1245       MVT::ValueType VT = SetCC->getOperand(0).getValueType();
1246       unsigned TV = SelectExpr(N.getOperand(1)); // Use if TRUE
1247       unsigned FV = SelectExpr(N.getOperand(2)); // Use if FALSE
1248
1249       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1));
1250       if (CN && (CN->isExactlyValue(-0.0) || CN->isExactlyValue(0.0))) {
1251         switch(SetCC->getCondition()) {
1252         default: assert(0 && "Invalid FSEL condition"); abort();
1253         case ISD::SETULT:
1254         case ISD::SETLT:
1255           std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
1256         case ISD::SETUGE:
1257         case ISD::SETGE:
1258           Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
1259           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp1).addReg(TV).addReg(FV);
1260           return Result;
1261         case ISD::SETUGT:
1262         case ISD::SETGT:
1263           std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
1264         case ISD::SETULE:
1265         case ISD::SETLE: {
1266           if (SetCC->getOperand(0).getOpcode() == ISD::FNEG) {
1267             Tmp2 = SelectExpr(SetCC->getOperand(0).getOperand(0));
1268           } else {
1269             Tmp2 = MakeReg(VT);
1270             Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
1271             BuildMI(BB, PPC::FNEG, 1, Tmp2).addReg(Tmp1);
1272           }
1273           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp2).addReg(TV).addReg(FV);
1274           return Result;
1275         }
1276         }
1277       } else {
1278         Opc = (MVT::f64 == VT) ? PPC::FSUB : PPC::FSUBS;
1279         Tmp1 = SelectExpr(SetCC->getOperand(0));   // Val to compare against
1280         Tmp2 = SelectExpr(SetCC->getOperand(1));
1281         Tmp3 =  MakeReg(VT);
1282         switch(SetCC->getCondition()) {
1283         default: assert(0 && "Invalid FSEL condition"); abort();
1284         case ISD::SETULT:
1285         case ISD::SETLT:
1286           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1287           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(FV).addReg(TV);
1288           return Result;
1289         case ISD::SETUGE:
1290         case ISD::SETGE:
1291           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1292           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(TV).addReg(FV);
1293           return Result;
1294         case ISD::SETUGT:
1295         case ISD::SETGT:
1296           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
1297           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(FV).addReg(TV);
1298           return Result;
1299         case ISD::SETULE:
1300         case ISD::SETLE:
1301           BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
1302           BuildMI(BB, PPC::FSEL, 3, Result).addReg(Tmp3).addReg(TV).addReg(FV);
1303           return Result;
1304         }
1305       }
1306       assert(0 && "Should never get here");
1307       return 0;
1308     }
1309
1310     bool Inv;
1311     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
1312     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
1313     unsigned CCReg = SelectCC(N.getOperand(0), Opc, Inv, Tmp3);
1314
1315     // Create an iterator with which to insert the MBB for copying the false
1316     // value and the MBB to hold the PHI instruction for this SetCC.
1317     MachineBasicBlock *thisMBB = BB;
1318     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1319     ilist<MachineBasicBlock>::iterator It = BB;
1320     ++It;
1321
1322     //  thisMBB:
1323     //  ...
1324     //   TrueVal = ...
1325     //   cmpTY ccX, r1, r2
1326     //   bCC copy1MBB
1327     //   fallthrough --> copy0MBB
1328     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1329     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1330     BuildMI(BB, Opc, 2).addReg(CCReg).addMBB(sinkMBB);
1331     MachineFunction *F = BB->getParent();
1332     F->getBasicBlockList().insert(It, copy0MBB);
1333     F->getBasicBlockList().insert(It, sinkMBB);
1334     // Update machine-CFG edges
1335     BB->addSuccessor(copy0MBB);
1336     BB->addSuccessor(sinkMBB);
1337
1338     //  copy0MBB:
1339     //   %FalseValue = ...
1340     //   # fallthrough to sinkMBB
1341     BB = copy0MBB;
1342     // Update machine-CFG edges
1343     BB->addSuccessor(sinkMBB);
1344
1345     //  sinkMBB:
1346     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1347     //  ...
1348     BB = sinkMBB;
1349     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
1350       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1351     return Result;
1352   }
1353
1354   case ISD::FNEG:
1355     if (!NoExcessFPPrecision &&
1356         ISD::ADD == N.getOperand(0).getOpcode() &&
1357         N.getOperand(0).Val->hasOneUse() &&
1358         ISD::MUL == N.getOperand(0).getOperand(0).getOpcode() &&
1359         N.getOperand(0).getOperand(0).Val->hasOneUse()) {
1360       ++FusedFP; // Statistic
1361       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0).getOperand(0));
1362       Tmp2 = SelectExpr(N.getOperand(0).getOperand(0).getOperand(1));
1363       Tmp3 = SelectExpr(N.getOperand(0).getOperand(1));
1364       Opc = DestType == MVT::f64 ? PPC::FNMADD : PPC::FNMADDS;
1365       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1366     } else if (!NoExcessFPPrecision &&
1367         ISD::ADD == N.getOperand(0).getOpcode() &&
1368         N.getOperand(0).Val->hasOneUse() &&
1369         ISD::MUL == N.getOperand(0).getOperand(1).getOpcode() &&
1370         N.getOperand(0).getOperand(1).Val->hasOneUse()) {
1371       ++FusedFP; // Statistic
1372       Tmp1 = SelectExpr(N.getOperand(0).getOperand(1).getOperand(0));
1373       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1).getOperand(1));
1374       Tmp3 = SelectExpr(N.getOperand(0).getOperand(0));
1375       Opc = DestType == MVT::f64 ? PPC::FNMADD : PPC::FNMADDS;
1376       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1377     } else if (ISD::FABS == N.getOperand(0).getOpcode()) {
1378       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1379       BuildMI(BB, PPC::FNABS, 1, Result).addReg(Tmp1);
1380     } else {
1381       Tmp1 = SelectExpr(N.getOperand(0));
1382       BuildMI(BB, PPC::FNEG, 1, Result).addReg(Tmp1);
1383     }
1384     return Result;
1385
1386   case ISD::FABS:
1387     Tmp1 = SelectExpr(N.getOperand(0));
1388     BuildMI(BB, PPC::FABS, 1, Result).addReg(Tmp1);
1389     return Result;
1390
1391   case ISD::FP_ROUND:
1392     assert (DestType == MVT::f32 &&
1393             N.getOperand(0).getValueType() == MVT::f64 &&
1394             "only f64 to f32 conversion supported here");
1395     Tmp1 = SelectExpr(N.getOperand(0));
1396     BuildMI(BB, PPC::FRSP, 1, Result).addReg(Tmp1);
1397     return Result;
1398
1399   case ISD::FP_EXTEND:
1400     assert (DestType == MVT::f64 &&
1401             N.getOperand(0).getValueType() == MVT::f32 &&
1402             "only f32 to f64 conversion supported here");
1403     Tmp1 = SelectExpr(N.getOperand(0));
1404     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
1405     return Result;
1406
1407   case ISD::CopyFromReg:
1408     if (Result == 1)
1409       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1410     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
1411     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
1412     return Result;
1413
1414   case ISD::ConstantFP: {
1415     ConstantFPSDNode *CN = cast<ConstantFPSDNode>(N);
1416     Result = getConstDouble(CN->getValue(), Result);
1417     return Result;
1418   }
1419
1420   case ISD::ADD:
1421     if (!NoExcessFPPrecision && N.getOperand(0).getOpcode() == ISD::MUL &&
1422         N.getOperand(0).Val->hasOneUse()) {
1423       ++FusedFP; // Statistic
1424       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1425       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1426       Tmp3 = SelectExpr(N.getOperand(1));
1427       Opc = DestType == MVT::f64 ? PPC::FMADD : PPC::FMADDS;
1428       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1429       return Result;
1430     }
1431     if (!NoExcessFPPrecision && N.getOperand(1).getOpcode() == ISD::MUL &&
1432         N.getOperand(1).Val->hasOneUse()) {
1433       ++FusedFP; // Statistic
1434       Tmp1 = SelectExpr(N.getOperand(1).getOperand(0));
1435       Tmp2 = SelectExpr(N.getOperand(1).getOperand(1));
1436       Tmp3 = SelectExpr(N.getOperand(0));
1437       Opc = DestType == MVT::f64 ? PPC::FMADD : PPC::FMADDS;
1438       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1439       return Result;
1440     }
1441     Opc = DestType == MVT::f64 ? PPC::FADD : PPC::FADDS;
1442     Tmp1 = SelectExpr(N.getOperand(0));
1443     Tmp2 = SelectExpr(N.getOperand(1));
1444     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1445     return Result;
1446
1447   case ISD::SUB:
1448     if (!NoExcessFPPrecision && N.getOperand(0).getOpcode() == ISD::MUL &&
1449         N.getOperand(0).Val->hasOneUse()) {
1450       ++FusedFP; // Statistic
1451       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1452       Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1453       Tmp3 = SelectExpr(N.getOperand(1));
1454       Opc = DestType == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS;
1455       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1456       return Result;
1457     }
1458     if (!NoExcessFPPrecision && N.getOperand(1).getOpcode() == ISD::MUL &&
1459         N.getOperand(1).Val->hasOneUse()) {
1460       ++FusedFP; // Statistic
1461       Tmp1 = SelectExpr(N.getOperand(1).getOperand(0));
1462       Tmp2 = SelectExpr(N.getOperand(1).getOperand(1));
1463       Tmp3 = SelectExpr(N.getOperand(0));
1464       Opc = DestType == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS;
1465       BuildMI(BB, Opc, 3, Result).addReg(Tmp1).addReg(Tmp2).addReg(Tmp3);
1466       return Result;
1467     }
1468     Opc = DestType == MVT::f64 ? PPC::FSUB : PPC::FSUBS;
1469     Tmp1 = SelectExpr(N.getOperand(0));
1470     Tmp2 = SelectExpr(N.getOperand(1));
1471     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1472     return Result;
1473
1474   case ISD::MUL:
1475   case ISD::SDIV:
1476     switch( opcode ) {
1477     case ISD::MUL:  Opc = DestType == MVT::f64 ? PPC::FMUL : PPC::FMULS; break;
1478     case ISD::SDIV: Opc = DestType == MVT::f64 ? PPC::FDIV : PPC::FDIVS; break;
1479     };
1480     Tmp1 = SelectExpr(N.getOperand(0));
1481     Tmp2 = SelectExpr(N.getOperand(1));
1482     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1483     return Result;
1484
1485   case ISD::UINT_TO_FP:
1486   case ISD::SINT_TO_FP: {
1487     assert (N.getOperand(0).getValueType() == MVT::i32
1488             && "int to float must operate on i32");
1489     bool IsUnsigned = (ISD::UINT_TO_FP == opcode);
1490     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
1491     Tmp2 = MakeReg(MVT::f64); // temp reg to load the integer value into
1492     Tmp3 = MakeReg(MVT::i32); // temp reg to hold the conversion constant
1493
1494     int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
1495     MachineConstantPool *CP = BB->getParent()->getConstantPool();
1496
1497     if (IsUnsigned) {
1498       unsigned ConstF = getConstDouble(0x1.000000p52);
1499       // Store the hi & low halves of the fp value, currently in int regs
1500       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
1501       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
1502       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp1), FrameIdx, 4);
1503       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
1504       // Generate the return value with a subtract
1505       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
1506     } else {
1507       unsigned ConstF = getConstDouble(0x1.000008p52);
1508       unsigned TmpL = MakeReg(MVT::i32);
1509       // Store the hi & low halves of the fp value, currently in int regs
1510       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
1511       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
1512       BuildMI(BB, PPC::XORIS, 2, TmpL).addReg(Tmp1).addImm(0x8000);
1513       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(TmpL), FrameIdx, 4);
1514       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
1515       // Generate the return value with a subtract
1516       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
1517     }
1518     return Result;
1519   }
1520   }
1521   assert(0 && "Should never get here");
1522   return 0;
1523 }
1524
1525 unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
1526   unsigned Result;
1527   unsigned Tmp1, Tmp2, Tmp3;
1528   unsigned Opc = 0;
1529   unsigned opcode = N.getOpcode();
1530
1531   SDNode *Node = N.Val;
1532   MVT::ValueType DestType = N.getValueType();
1533
1534   unsigned &Reg = ExprMap[N];
1535   if (Reg) return Reg;
1536
1537   switch (N.getOpcode()) {
1538   default:
1539     Reg = Result = (N.getValueType() != MVT::Other) ?
1540                             MakeReg(N.getValueType()) : 1;
1541     break;
1542   case ISD::CALL:
1543     // If this is a call instruction, make sure to prepare ALL of the result
1544     // values as well as the chain.
1545     if (Node->getNumValues() == 1)
1546       Reg = Result = 1;  // Void call, just a chain.
1547     else {
1548       Result = MakeReg(Node->getValueType(0));
1549       ExprMap[N.getValue(0)] = Result;
1550       for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
1551         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
1552       ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
1553     }
1554     break;
1555   case ISD::ADD_PARTS:
1556   case ISD::SUB_PARTS:
1557   case ISD::SHL_PARTS:
1558   case ISD::SRL_PARTS:
1559   case ISD::SRA_PARTS:
1560     Result = MakeReg(Node->getValueType(0));
1561     ExprMap[N.getValue(0)] = Result;
1562     for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
1563       ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
1564     break;
1565   }
1566
1567   if (ISD::CopyFromReg == opcode)
1568     DestType = N.getValue(0).getValueType();
1569
1570   if (DestType == MVT::f64 || DestType == MVT::f32)
1571     if (ISD::LOAD != opcode && ISD::EXTLOAD != opcode &&
1572         ISD::UNDEF != opcode && ISD::CALL != opcode)
1573       return SelectExprFP(N, Result);
1574
1575   switch (opcode) {
1576   default:
1577     Node->dump();
1578     assert(0 && "Node not handled!\n");
1579   case ISD::UNDEF:
1580     BuildMI(BB, PPC::IMPLICIT_DEF, 0, Result);
1581     return Result;
1582   case ISD::DYNAMIC_STACKALLOC:
1583     // Generate both result values.  FIXME: Need a better commment here?
1584     if (Result != 1)
1585       ExprMap[N.getValue(1)] = 1;
1586     else
1587       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1588
1589     // FIXME: We are currently ignoring the requested alignment for handling
1590     // greater than the stack alignment.  This will need to be revisited at some
1591     // point.  Align = N.getOperand(2);
1592     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
1593         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
1594       std::cerr << "Cannot allocate stack object with greater alignment than"
1595                 << " the stack alignment yet!";
1596       abort();
1597     }
1598     Select(N.getOperand(0));
1599     Tmp1 = SelectExpr(N.getOperand(1));
1600     // Subtract size from stack pointer, thereby allocating some space.
1601     BuildMI(BB, PPC::SUBF, 2, PPC::R1).addReg(Tmp1).addReg(PPC::R1);
1602     // Put a pointer to the space into the result register by copying the SP
1603     BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R1).addReg(PPC::R1);
1604     return Result;
1605
1606   case ISD::ConstantPool:
1607     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
1608     Tmp2 = MakeReg(MVT::i32);
1609     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp2).addReg(getGlobalBaseReg())
1610       .addConstantPoolIndex(Tmp1);
1611     BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp2).addConstantPoolIndex(Tmp1);
1612     return Result;
1613
1614   case ISD::FrameIndex:
1615     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
1616     addFrameReference(BuildMI(BB, PPC::ADDI, 2, Result), (int)Tmp1, 0, false);
1617     return Result;
1618
1619   case ISD::GlobalAddress: {
1620     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1621     Tmp1 = MakeReg(MVT::i32);
1622     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
1623       .addGlobalAddress(GV);
1624     if (GV->hasWeakLinkage() || GV->isExternal()) {
1625       BuildMI(BB, PPC::LWZ, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
1626     } else {
1627       BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp1).addGlobalAddress(GV);
1628     }
1629     return Result;
1630   }
1631
1632   case ISD::LOAD:
1633   case ISD::EXTLOAD:
1634   case ISD::ZEXTLOAD:
1635   case ISD::SEXTLOAD: {
1636     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
1637       Node->getValueType(0) : cast<MVTSDNode>(Node)->getExtraValueType();
1638     bool sext = (ISD::SEXTLOAD == opcode);
1639
1640     // Make sure we generate both values.
1641     if (Result != 1)
1642       ExprMap[N.getValue(1)] = 1;   // Generate the token
1643     else
1644       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1645
1646     SDOperand Chain   = N.getOperand(0);
1647     SDOperand Address = N.getOperand(1);
1648     Select(Chain);
1649
1650     switch (TypeBeingLoaded) {
1651     default: Node->dump(); assert(0 && "Cannot load this type!");
1652     case MVT::i1:  Opc = PPC::LBZ; break;
1653     case MVT::i8:  Opc = PPC::LBZ; break;
1654     case MVT::i16: Opc = sext ? PPC::LHA : PPC::LHZ; break;
1655     case MVT::i32: Opc = PPC::LWZ; break;
1656     case MVT::f32: Opc = PPC::LFS; break;
1657     case MVT::f64: Opc = PPC::LFD; break;
1658     }
1659
1660     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Address)) {
1661       Tmp1 = MakeReg(MVT::i32);
1662       int CPI = CP->getIndex();
1663       BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
1664         .addConstantPoolIndex(CPI);
1665       BuildMI(BB, Opc, 2, Result).addConstantPoolIndex(CPI).addReg(Tmp1);
1666     }
1667     else if(Address.getOpcode() == ISD::FrameIndex) {
1668       Tmp1 = cast<FrameIndexSDNode>(Address)->getIndex();
1669       addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1);
1670     } else {
1671       int offset;
1672       bool idx = SelectAddr(Address, Tmp1, offset);
1673       if (idx) {
1674         Opc = IndexedOpForOp(Opc);
1675         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(offset);
1676       } else {
1677         BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
1678       }
1679     }
1680     return Result;
1681   }
1682
1683   case ISD::CALL: {
1684     unsigned GPR_idx = 0, FPR_idx = 0;
1685     static const unsigned GPR[] = {
1686       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1687       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1688     };
1689     static const unsigned FPR[] = {
1690       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1691       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1692     };
1693
1694     // Lower the chain for this call.
1695     Select(N.getOperand(0));
1696     ExprMap[N.getValue(Node->getNumValues()-1)] = 1;
1697
1698     MachineInstr *CallMI;
1699     // Emit the correct call instruction based on the type of symbol called.
1700     if (GlobalAddressSDNode *GASD =
1701         dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
1702       CallMI = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(GASD->getGlobal(),
1703                                                            true);
1704     } else if (ExternalSymbolSDNode *ESSDN =
1705                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
1706       CallMI = BuildMI(PPC::CALLpcrel, 1).addExternalSymbol(ESSDN->getSymbol(),
1707                                                             true);
1708     } else {
1709       Tmp1 = SelectExpr(N.getOperand(1));
1710       BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Tmp1).addReg(Tmp1);
1711       BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
1712       CallMI = BuildMI(PPC::CALLindirect, 3).addImm(20).addImm(0)
1713         .addReg(PPC::R12);
1714     }
1715
1716     // Load the register args to virtual regs
1717     std::vector<unsigned> ArgVR;
1718     for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
1719       ArgVR.push_back(SelectExpr(N.getOperand(i)));
1720
1721     // Copy the virtual registers into the appropriate argument register
1722     for(int i = 0, e = ArgVR.size(); i < e; ++i) {
1723       switch(N.getOperand(i+2).getValueType()) {
1724       default: Node->dump(); assert(0 && "Unknown value type for call");
1725       case MVT::i1:
1726       case MVT::i8:
1727       case MVT::i16:
1728       case MVT::i32:
1729         assert(GPR_idx < 8 && "Too many int args");
1730         if (N.getOperand(i+2).getOpcode() != ISD::UNDEF) {
1731           BuildMI(BB, PPC::OR,2,GPR[GPR_idx]).addReg(ArgVR[i]).addReg(ArgVR[i]);
1732           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1733         }
1734         ++GPR_idx;
1735         break;
1736       case MVT::f64:
1737       case MVT::f32:
1738         assert(FPR_idx < 13 && "Too many fp args");
1739         BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgVR[i]);
1740         CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1741         ++FPR_idx;
1742         break;
1743       }
1744     }
1745
1746     // Put the call instruction in the correct place in the MachineBasicBlock
1747     BB->push_back(CallMI);
1748
1749     switch (Node->getValueType(0)) {
1750     default: assert(0 && "Unknown value type for call result!");
1751     case MVT::Other: return 1;
1752     case MVT::i1:
1753     case MVT::i8:
1754     case MVT::i16:
1755     case MVT::i32:
1756       if (Node->getValueType(1) == MVT::i32) {
1757         BuildMI(BB, PPC::OR, 2, Result+1).addReg(PPC::R3).addReg(PPC::R3);
1758         BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R4).addReg(PPC::R4);
1759       } else {
1760         BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R3).addReg(PPC::R3);
1761       }
1762       break;
1763     case MVT::f32:
1764     case MVT::f64:
1765       BuildMI(BB, PPC::FMR, 1, Result).addReg(PPC::F1);
1766       break;
1767     }
1768     return Result+N.ResNo;
1769   }
1770
1771   case ISD::SIGN_EXTEND:
1772   case ISD::SIGN_EXTEND_INREG:
1773     Tmp1 = SelectExpr(N.getOperand(0));
1774     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1775     default: Node->dump(); assert(0 && "Unhandled SIGN_EXTEND type"); break;
1776     case MVT::i16:
1777       BuildMI(BB, PPC::EXTSH, 1, Result).addReg(Tmp1);
1778       break;
1779     case MVT::i8:
1780       BuildMI(BB, PPC::EXTSB, 1, Result).addReg(Tmp1);
1781       break;
1782     case MVT::i1:
1783       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp1).addSImm(0);
1784       break;
1785     }
1786     return Result;
1787
1788   case ISD::CopyFromReg:
1789     if (Result == 1)
1790       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
1791     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
1792     BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp1).addReg(Tmp1);
1793     return Result;
1794
1795   case ISD::SHL:
1796     Tmp1 = SelectExpr(N.getOperand(0));
1797     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1798       Tmp2 = CN->getValue() & 0x1F;
1799       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Tmp2).addImm(0)
1800         .addImm(31-Tmp2);
1801     } else {
1802       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
1803       BuildMI(BB, PPC::SLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1804     }
1805     return Result;
1806
1807   case ISD::SRL:
1808     Tmp1 = SelectExpr(N.getOperand(0));
1809     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1810       Tmp2 = CN->getValue() & 0x1F;
1811       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(32-Tmp2)
1812         .addImm(Tmp2).addImm(31);
1813     } else {
1814       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
1815       BuildMI(BB, PPC::SRW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1816     }
1817     return Result;
1818
1819   case ISD::SRA:
1820     Tmp1 = SelectExpr(N.getOperand(0));
1821     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1822       Tmp2 = CN->getValue() & 0x1F;
1823       BuildMI(BB, PPC::SRAWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1824     } else {
1825       Tmp2 = FoldIfWideZeroExtend(N.getOperand(1));
1826       BuildMI(BB, PPC::SRAW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1827     }
1828     return Result;
1829
1830   case ISD::CTLZ:
1831     Tmp1 = SelectExpr(N.getOperand(0));
1832     BuildMI(BB, PPC::CNTLZW, 1, Result).addReg(Tmp1);
1833     return Result;
1834
1835   case ISD::ADD:
1836     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1837     Tmp1 = SelectExpr(N.getOperand(0));
1838     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1839       default: assert(0 && "unhandled result code");
1840       case 0: // No immediate
1841         Tmp2 = SelectExpr(N.getOperand(1));
1842         BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
1843         break;
1844       case 1: // Low immediate
1845         BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1846         break;
1847       case 2: // Shifted immediate
1848         BuildMI(BB, PPC::ADDIS, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1849         break;
1850     }
1851     return Result;
1852
1853   case ISD::AND:
1854     if (PPCCRopts) {
1855       if (N.getOperand(0).getOpcode() == ISD::SETCC ||
1856           N.getOperand(1).getOpcode() == ISD::SETCC) {
1857         bool Inv;
1858         Tmp1 = SelectCCExpr(N, Opc, Inv, Tmp2);
1859         MoveCRtoGPR(Tmp1, Inv, Tmp2, Result);
1860         return Result;
1861       }
1862     }
1863     // FIXME: should add check in getImmediateForOpcode to return a value
1864     // indicating the immediate is a run of set bits so we can emit a bitfield
1865     // clear with RLWINM instead.
1866     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1867       default: assert(0 && "unhandled result code");
1868       case 0: // No immediate
1869         // Check for andc: and, (xor a, -1), b
1870         if (N.getOperand(0).getOpcode() == ISD::XOR &&
1871           N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
1872         cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
1873           Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1874           Tmp2 = SelectExpr(N.getOperand(1));
1875           BuildMI(BB, PPC::ANDC, 2, Result).addReg(Tmp2).addReg(Tmp1);
1876           return Result;
1877         }
1878         // It wasn't and-with-complement, emit a regular and
1879         Tmp1 = SelectExpr(N.getOperand(0));
1880         Tmp2 = SelectExpr(N.getOperand(1));
1881         Opc = Recording ? PPC::ANDo : PPC::AND;
1882         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1883         break;
1884       case 1: // Low immediate
1885         Tmp1 = SelectExpr(N.getOperand(0));
1886         BuildMI(BB, PPC::ANDIo, 2, Result).addReg(Tmp1).addImm(Tmp2);
1887         break;
1888       case 2: // Shifted immediate
1889         Tmp1 = SelectExpr(N.getOperand(0));
1890         BuildMI(BB, PPC::ANDISo, 2, Result).addReg(Tmp1).addImm(Tmp2);
1891         break;
1892       case 5: // Bitfield mask
1893         Opc = Recording ? PPC::RLWINMo : PPC::RLWINM;
1894         Tmp3 = Tmp2 >> 16;  // MB
1895         Tmp2 &= 0xFFFF;     // ME
1896
1897         if (N.getOperand(0).getOpcode() == ISD::SRL)
1898           if (ConstantSDNode *SA =
1899               dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
1900
1901             // We can fold the RLWINM and the SRL together if the mask is
1902             // clearing the top bits which are rotated around.
1903             unsigned RotAmt = 32-(SA->getValue() & 31);
1904             if (Tmp2 <= RotAmt) {
1905               Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1906               BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(RotAmt)
1907                 .addImm(Tmp3).addImm(Tmp2);
1908               break;
1909             }
1910           }
1911
1912         Tmp1 = SelectExpr(N.getOperand(0));
1913         BuildMI(BB, Opc, 4, Result).addReg(Tmp1).addImm(0)
1914           .addImm(Tmp3).addImm(Tmp2);
1915         break;
1916     }
1917     RecordSuccess = true;
1918     return Result;
1919
1920   case ISD::OR:
1921     if (SelectBitfieldInsert(N, Result))
1922       return Result;
1923     if (PPCCRopts) {
1924       if (N.getOperand(0).getOpcode() == ISD::SETCC ||
1925           N.getOperand(1).getOpcode() == ISD::SETCC) {
1926         bool Inv;
1927         Tmp1 = SelectCCExpr(N, Opc, Inv, Tmp2);
1928         MoveCRtoGPR(Tmp1, Inv, Tmp2, Result);
1929         return Result;
1930       }
1931     }
1932     Tmp1 = SelectExpr(N.getOperand(0));
1933     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1934       default: assert(0 && "unhandled result code");
1935       case 0: // No immediate
1936         Tmp2 = SelectExpr(N.getOperand(1));
1937         Opc = Recording ? PPC::ORo : PPC::OR;
1938         RecordSuccess = true;
1939         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1940         break;
1941       case 1: // Low immediate
1942         BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1943         break;
1944       case 2: // Shifted immediate
1945         BuildMI(BB, PPC::ORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
1946         break;
1947     }
1948     return Result;
1949
1950   case ISD::XOR: {
1951     // Check for EQV: xor, (xor a, -1), b
1952     if (N.getOperand(0).getOpcode() == ISD::XOR &&
1953         N.getOperand(0).getOperand(1).getOpcode() == ISD::Constant &&
1954         cast<ConstantSDNode>(N.getOperand(0).getOperand(1))->isAllOnesValue()) {
1955       Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1956       Tmp2 = SelectExpr(N.getOperand(1));
1957       BuildMI(BB, PPC::EQV, 2, Result).addReg(Tmp1).addReg(Tmp2);
1958       return Result;
1959     }
1960     // Check for NOT, NOR, EQV, and NAND: xor (copy, or, xor, and), -1
1961     if (N.getOperand(1).getOpcode() == ISD::Constant &&
1962         cast<ConstantSDNode>(N.getOperand(1))->isAllOnesValue()) {
1963       switch(N.getOperand(0).getOpcode()) {
1964       case ISD::OR:
1965         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1966         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1967         BuildMI(BB, PPC::NOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1968         break;
1969       case ISD::AND:
1970         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1971         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1972         BuildMI(BB, PPC::NAND, 2, Result).addReg(Tmp1).addReg(Tmp2);
1973         break;
1974       case ISD::XOR:
1975         Tmp1 = SelectExpr(N.getOperand(0).getOperand(0));
1976         Tmp2 = SelectExpr(N.getOperand(0).getOperand(1));
1977         BuildMI(BB, PPC::EQV, 2, Result).addReg(Tmp1).addReg(Tmp2);
1978         break;
1979       default:
1980         Tmp1 = SelectExpr(N.getOperand(0));
1981         BuildMI(BB, PPC::NOR, 2, Result).addReg(Tmp1).addReg(Tmp1);
1982         break;
1983       }
1984       return Result;
1985     }
1986     Tmp1 = SelectExpr(N.getOperand(0));
1987     switch(getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1988       default: assert(0 && "unhandled result code");
1989       case 0: // No immediate
1990         Tmp2 = SelectExpr(N.getOperand(1));
1991         BuildMI(BB, PPC::XOR, 2, Result).addReg(Tmp1).addReg(Tmp2);
1992         break;
1993       case 1: // Low immediate
1994         BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1995         break;
1996       case 2: // Shifted immediate
1997         BuildMI(BB, PPC::XORIS, 2, Result).addReg(Tmp1).addImm(Tmp2);
1998         break;
1999     }
2000     return Result;
2001   }
2002
2003   case ISD::SUB:
2004     if (1 == getImmediateForOpcode(N.getOperand(0), opcode, Tmp1, true)) {
2005       Tmp2 = SelectExpr(N.getOperand(1));
2006       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp2).addSImm(Tmp1);
2007     } else if (1 == getImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
2008       Tmp1 = SelectExpr(N.getOperand(0));
2009       BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
2010     } else {
2011       Tmp1 = SelectExpr(N.getOperand(0));
2012       Tmp2 = SelectExpr(N.getOperand(1));
2013       BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
2014     }
2015     return Result;
2016
2017   case ISD::MUL:
2018     Tmp1 = SelectExpr(N.getOperand(0));
2019     if (1 == getImmediateForOpcode(N.getOperand(1), opcode, Tmp2))
2020       BuildMI(BB, PPC::MULLI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
2021     else {
2022       Tmp2 = SelectExpr(N.getOperand(1));
2023       BuildMI(BB, PPC::MULLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
2024     }
2025     return Result;
2026
2027   case ISD::MULHS:
2028   case ISD::MULHU:
2029     Tmp1 = SelectExpr(N.getOperand(0));
2030     Tmp2 = SelectExpr(N.getOperand(1));
2031     Opc = (ISD::MULHU == opcode) ? PPC::MULHWU : PPC::MULHW;
2032     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2033     return Result;
2034
2035   case ISD::SDIV:
2036   case ISD::UDIV:
2037     switch (getImmediateForOpcode(N.getOperand(1), opcode, Tmp3)) {
2038     default: break;
2039     // If this is an sdiv by a power of two, we can use an srawi/addze pair.
2040     case 3:
2041       Tmp1 = MakeReg(MVT::i32);
2042       Tmp2 = SelectExpr(N.getOperand(0));
2043       if ((int)Tmp3 < 0) {
2044         unsigned Tmp4 = MakeReg(MVT::i32);
2045         BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(-Tmp3);
2046         BuildMI(BB, PPC::ADDZE, 1, Tmp4).addReg(Tmp1);
2047         BuildMI(BB, PPC::NEG, 1, Result).addReg(Tmp4);
2048       } else {
2049         BuildMI(BB, PPC::SRAWI, 2, Tmp1).addReg(Tmp2).addImm(Tmp3);
2050         BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp1);
2051       }
2052       return Result;
2053     // If this is a divide by constant, we can emit code using some magic
2054     // constants to implement it as a multiply instead.
2055     case 4:
2056       ExprMap.erase(N);
2057       if (opcode == ISD::SDIV)
2058         return SelectExpr(BuildSDIVSequence(N));
2059       else
2060         return SelectExpr(BuildUDIVSequence(N));
2061     }
2062     Tmp1 = SelectExpr(N.getOperand(0));
2063     Tmp2 = SelectExpr(N.getOperand(1));
2064     Opc = (ISD::UDIV == opcode) ? PPC::DIVWU : PPC::DIVW;
2065     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2066     return Result;
2067
2068   case ISD::ADD_PARTS:
2069   case ISD::SUB_PARTS: {
2070     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
2071            "Not an i64 add/sub!");
2072     // Emit all of the operands.
2073     std::vector<unsigned> InVals;
2074     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
2075       InVals.push_back(SelectExpr(N.getOperand(i)));
2076     if (N.getOpcode() == ISD::ADD_PARTS) {
2077       BuildMI(BB, PPC::ADDC, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2078       BuildMI(BB, PPC::ADDE, 2, Result+1).addReg(InVals[1]).addReg(InVals[3]);
2079     } else {
2080       BuildMI(BB, PPC::SUBFC, 2, Result).addReg(InVals[2]).addReg(InVals[0]);
2081       BuildMI(BB, PPC::SUBFE, 2, Result+1).addReg(InVals[3]).addReg(InVals[1]);
2082     }
2083     return Result+N.ResNo;
2084   }
2085
2086   case ISD::SHL_PARTS:
2087   case ISD::SRA_PARTS:
2088   case ISD::SRL_PARTS: {
2089     assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
2090            "Not an i64 shift!");
2091     unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
2092     unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
2093     unsigned SHReg = FoldIfWideZeroExtend(N.getOperand(2));
2094     Tmp1 = MakeReg(MVT::i32);
2095     Tmp2 = MakeReg(MVT::i32);
2096     Tmp3 = MakeReg(MVT::i32);
2097     unsigned Tmp4 = MakeReg(MVT::i32);
2098     unsigned Tmp5 = MakeReg(MVT::i32);
2099     unsigned Tmp6 = MakeReg(MVT::i32);
2100     BuildMI(BB, PPC::SUBFIC, 2, Tmp1).addReg(SHReg).addSImm(32);
2101     if (ISD::SHL_PARTS == opcode) {
2102       BuildMI(BB, PPC::SLW, 2, Tmp2).addReg(ShiftOpHi).addReg(SHReg);
2103       BuildMI(BB, PPC::SRW, 2, Tmp3).addReg(ShiftOpLo).addReg(Tmp1);
2104       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
2105       BuildMI(BB, PPC::ADDI, 2, Tmp5).addReg(SHReg).addSImm(-32);
2106       BuildMI(BB, PPC::SLW, 2, Tmp6).addReg(ShiftOpLo).addReg(Tmp5);
2107       BuildMI(BB, PPC::OR, 2, Result+1).addReg(Tmp4).addReg(Tmp6);
2108       BuildMI(BB, PPC::SLW, 2, Result).addReg(ShiftOpLo).addReg(SHReg);
2109     } else if (ISD::SRL_PARTS == opcode) {
2110       BuildMI(BB, PPC::SRW, 2, Tmp2).addReg(ShiftOpLo).addReg(SHReg);
2111       BuildMI(BB, PPC::SLW, 2, Tmp3).addReg(ShiftOpHi).addReg(Tmp1);
2112       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
2113       BuildMI(BB, PPC::ADDI, 2, Tmp5).addReg(SHReg).addSImm(-32);
2114       BuildMI(BB, PPC::SRW, 2, Tmp6).addReg(ShiftOpHi).addReg(Tmp5);
2115       BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp4).addReg(Tmp6);
2116       BuildMI(BB, PPC::SRW, 2, Result+1).addReg(ShiftOpHi).addReg(SHReg);
2117     } else {
2118       MachineBasicBlock *TmpMBB = new MachineBasicBlock(BB->getBasicBlock());
2119       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2120       MachineBasicBlock *OldMBB = BB;
2121       MachineFunction *F = BB->getParent();
2122       ilist<MachineBasicBlock>::iterator It = BB; ++It;
2123       F->getBasicBlockList().insert(It, TmpMBB);
2124       F->getBasicBlockList().insert(It, PhiMBB);
2125       BB->addSuccessor(TmpMBB);
2126       BB->addSuccessor(PhiMBB);
2127       BuildMI(BB, PPC::SRW, 2, Tmp2).addReg(ShiftOpLo).addReg(SHReg);
2128       BuildMI(BB, PPC::SLW, 2, Tmp3).addReg(ShiftOpHi).addReg(Tmp1);
2129       BuildMI(BB, PPC::OR, 2, Tmp4).addReg(Tmp2).addReg(Tmp3);
2130       BuildMI(BB, PPC::ADDICo, 2, Tmp5).addReg(SHReg).addSImm(-32);
2131       BuildMI(BB, PPC::SRAW, 2, Tmp6).addReg(ShiftOpHi).addReg(Tmp5);
2132       BuildMI(BB, PPC::SRAW, 2, Result+1).addReg(ShiftOpHi).addReg(SHReg);
2133       BuildMI(BB, PPC::BLE, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2134       // Select correct least significant half if the shift amount > 32
2135       BB = TmpMBB;
2136       unsigned Tmp7 = MakeReg(MVT::i32);
2137       BuildMI(BB, PPC::OR, 2, Tmp7).addReg(Tmp6).addReg(Tmp6);
2138       TmpMBB->addSuccessor(PhiMBB);
2139       BB = PhiMBB;
2140       BuildMI(BB, PPC::PHI, 4, Result).addReg(Tmp4).addMBB(OldMBB)
2141         .addReg(Tmp7).addMBB(TmpMBB);
2142     }
2143     return Result+N.ResNo;
2144   }
2145
2146   case ISD::FP_TO_UINT:
2147   case ISD::FP_TO_SINT: {
2148     bool U = (ISD::FP_TO_UINT == opcode);
2149     Tmp1 = SelectExpr(N.getOperand(0));
2150     if (!U) {
2151       Tmp2 = MakeReg(MVT::f64);
2152       BuildMI(BB, PPC::FCTIWZ, 1, Tmp2).addReg(Tmp1);
2153       int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
2154       addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(Tmp2), FrameIdx);
2155       addFrameReference(BuildMI(BB, PPC::LWZ, 2, Result), FrameIdx, 4);
2156       return Result;
2157     } else {
2158       unsigned Zero = getConstDouble(0.0);
2159       unsigned MaxInt = getConstDouble((1LL << 32) - 1);
2160       unsigned Border = getConstDouble(1LL << 31);
2161       unsigned UseZero = MakeReg(MVT::f64);
2162       unsigned UseMaxInt = MakeReg(MVT::f64);
2163       unsigned UseChoice = MakeReg(MVT::f64);
2164       unsigned TmpReg = MakeReg(MVT::f64);
2165       unsigned TmpReg2 = MakeReg(MVT::f64);
2166       unsigned ConvReg = MakeReg(MVT::f64);
2167       unsigned IntTmp = MakeReg(MVT::i32);
2168       unsigned XorReg = MakeReg(MVT::i32);
2169       MachineFunction *F = BB->getParent();
2170       int FrameIdx = F->getFrameInfo()->CreateStackObject(8, 8);
2171       // Update machine-CFG edges
2172       MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2173       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2174       MachineBasicBlock *OldMBB = BB;
2175       ilist<MachineBasicBlock>::iterator It = BB; ++It;
2176       F->getBasicBlockList().insert(It, XorMBB);
2177       F->getBasicBlockList().insert(It, PhiMBB);
2178       BB->addSuccessor(XorMBB);
2179       BB->addSuccessor(PhiMBB);
2180       // Convert from floating point to unsigned 32-bit value
2181       // Use 0 if incoming value is < 0.0
2182       BuildMI(BB, PPC::FSEL, 3, UseZero).addReg(Tmp1).addReg(Tmp1).addReg(Zero);
2183       // Use 2**32 - 1 if incoming value is >= 2**32
2184       BuildMI(BB, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(Tmp1);
2185       BuildMI(BB, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt).addReg(UseZero)
2186         .addReg(MaxInt);
2187       // Subtract 2**31
2188       BuildMI(BB, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2189       // Use difference if >= 2**31
2190       BuildMI(BB, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice).addReg(Border);
2191       BuildMI(BB, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2192         .addReg(UseChoice);
2193       // Convert to integer
2194       BuildMI(BB, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2195       addFrameReference(BuildMI(BB, PPC::STFD, 3).addReg(ConvReg), FrameIdx);
2196       addFrameReference(BuildMI(BB, PPC::LWZ, 2, IntTmp), FrameIdx, 4);
2197       BuildMI(BB, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2198       BuildMI(BB, PPC::B, 1).addMBB(XorMBB);
2199
2200       // XorMBB:
2201       //   add 2**31 if input was >= 2**31
2202       BB = XorMBB;
2203       BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2204       XorMBB->addSuccessor(PhiMBB);
2205
2206       // PhiMBB:
2207       //   DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2208       BB = PhiMBB;
2209       BuildMI(BB, PPC::PHI, 4, Result).addReg(IntTmp).addMBB(OldMBB)
2210         .addReg(XorReg).addMBB(XorMBB);
2211       return Result;
2212     }
2213     assert(0 && "Should never get here");
2214     return 0;
2215   }
2216
2217   case ISD::SETCC:
2218     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
2219       if (ConstantSDNode *CN =
2220           dyn_cast<ConstantSDNode>(SetCC->getOperand(1).Val)) {
2221         // We can codegen setcc op, imm very efficiently compared to a brcond.
2222         // Check for those cases here.
2223         // setcc op, 0
2224         if (CN->getValue() == 0) {
2225           Tmp1 = SelectExpr(SetCC->getOperand(0));
2226           switch (SetCC->getCondition()) {
2227           default: SetCC->dump(); assert(0 && "Unhandled SetCC condition"); abort();
2228           case ISD::SETEQ:
2229             Tmp2 = MakeReg(MVT::i32);
2230             BuildMI(BB, PPC::CNTLZW, 1, Tmp2).addReg(Tmp1);
2231             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp2).addImm(27)
2232               .addImm(5).addImm(31);
2233             break;
2234           case ISD::SETNE:
2235             Tmp2 = MakeReg(MVT::i32);
2236             BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(-1);
2237             BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp2).addReg(Tmp1);
2238             break;
2239           case ISD::SETLT:
2240             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(1)
2241               .addImm(31).addImm(31);
2242             break;
2243           case ISD::SETGT:
2244             Tmp2 = MakeReg(MVT::i32);
2245             Tmp3 = MakeReg(MVT::i32);
2246             BuildMI(BB, PPC::NEG, 2, Tmp2).addReg(Tmp1);
2247             BuildMI(BB, PPC::ANDC, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
2248             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
2249               .addImm(31).addImm(31);
2250             break;
2251           }
2252           return Result;
2253         }
2254         // setcc op, -1
2255         if (CN->isAllOnesValue()) {
2256           Tmp1 = SelectExpr(SetCC->getOperand(0));
2257           switch (SetCC->getCondition()) {
2258           default: assert(0 && "Unhandled SetCC condition"); abort();
2259           case ISD::SETEQ:
2260             Tmp2 = MakeReg(MVT::i32);
2261             Tmp3 = MakeReg(MVT::i32);
2262             BuildMI(BB, PPC::ADDIC, 2, Tmp2).addReg(Tmp1).addSImm(1);
2263             BuildMI(BB, PPC::LI, 1, Tmp3).addSImm(0);
2264             BuildMI(BB, PPC::ADDZE, 1, Result).addReg(Tmp3);
2265             break;
2266           case ISD::SETNE:
2267             Tmp2 = MakeReg(MVT::i32);
2268             Tmp3 = MakeReg(MVT::i32);
2269             BuildMI(BB, PPC::NOR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
2270             BuildMI(BB, PPC::ADDIC, 2, Tmp3).addReg(Tmp2).addSImm(-1);
2271             BuildMI(BB, PPC::SUBFE, 2, Result).addReg(Tmp3).addReg(Tmp2);
2272             break;
2273           case ISD::SETLT:
2274             Tmp2 = MakeReg(MVT::i32);
2275             Tmp3 = MakeReg(MVT::i32);
2276             BuildMI(BB, PPC::ADDI, 2, Tmp2).addReg(Tmp1).addSImm(1);
2277             BuildMI(BB, PPC::AND, 2, Tmp3).addReg(Tmp2).addReg(Tmp1);
2278             BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp3).addImm(1)
2279               .addImm(31).addImm(31);
2280             break;
2281           case ISD::SETGT:
2282             Tmp2 = MakeReg(MVT::i32);
2283             BuildMI(BB, PPC::RLWINM, 4, Tmp2).addReg(Tmp1).addImm(1)
2284               .addImm(31).addImm(31);
2285             BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp2).addImm(1);
2286             break;
2287           }
2288           return Result;
2289         }
2290       }
2291
2292       bool Inv;
2293       unsigned CCReg = SelectCC(N, Opc, Inv, Tmp2);
2294       MoveCRtoGPR(CCReg, Inv, Tmp2, Result);
2295       return Result;
2296     }
2297     assert(0 && "Is this legal?");
2298     return 0;
2299
2300   case ISD::SELECT: {
2301     bool Inv;
2302     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
2303     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
2304     unsigned CCReg = SelectCC(N.getOperand(0), Opc, Inv, Tmp3);
2305
2306     // Create an iterator with which to insert the MBB for copying the false
2307     // value and the MBB to hold the PHI instruction for this SetCC.
2308     MachineBasicBlock *thisMBB = BB;
2309     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2310     ilist<MachineBasicBlock>::iterator It = BB;
2311     ++It;
2312
2313     //  thisMBB:
2314     //  ...
2315     //   TrueVal = ...
2316     //   cmpTY ccX, r1, r2
2317     //   bCC copy1MBB
2318     //   fallthrough --> copy0MBB
2319     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
2320     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
2321     BuildMI(BB, Opc, 2).addReg(CCReg).addMBB(sinkMBB);
2322     MachineFunction *F = BB->getParent();
2323     F->getBasicBlockList().insert(It, copy0MBB);
2324     F->getBasicBlockList().insert(It, sinkMBB);
2325     // Update machine-CFG edges
2326     BB->addSuccessor(copy0MBB);
2327     BB->addSuccessor(sinkMBB);
2328
2329     //  copy0MBB:
2330     //   %FalseValue = ...
2331     //   # fallthrough to sinkMBB
2332     BB = copy0MBB;
2333     // Update machine-CFG edges
2334     BB->addSuccessor(sinkMBB);
2335
2336     //  sinkMBB:
2337     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2338     //  ...
2339     BB = sinkMBB;
2340     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
2341       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
2342     return Result;
2343   }
2344
2345   case ISD::Constant:
2346     switch (N.getValueType()) {
2347     default: assert(0 && "Cannot use constants of this type!");
2348     case MVT::i1:
2349       BuildMI(BB, PPC::LI, 1, Result)
2350         .addSImm(!cast<ConstantSDNode>(N)->isNullValue());
2351       break;
2352     case MVT::i32:
2353       {
2354         int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
2355         if (v < 32768 && v >= -32768) {
2356           BuildMI(BB, PPC::LI, 1, Result).addSImm(v);
2357         } else {
2358           Tmp1 = MakeReg(MVT::i32);
2359           BuildMI(BB, PPC::LIS, 1, Tmp1).addSImm(v >> 16);
2360           BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(v & 0xFFFF);
2361         }
2362       }
2363     }
2364     return Result;
2365   }
2366
2367   return 0;
2368 }
2369
2370 void ISel::Select(SDOperand N) {
2371   unsigned Tmp1, Tmp2, Opc;
2372   unsigned opcode = N.getOpcode();
2373
2374   if (!ExprMap.insert(std::make_pair(N, 1)).second)
2375     return;  // Already selected.
2376
2377   SDNode *Node = N.Val;
2378
2379   switch (Node->getOpcode()) {
2380   default:
2381     Node->dump(); std::cerr << "\n";
2382     assert(0 && "Node not handled yet!");
2383   case ISD::EntryToken: return;  // Noop
2384   case ISD::TokenFactor:
2385     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
2386       Select(Node->getOperand(i));
2387     return;
2388   case ISD::CALLSEQ_START:
2389   case ISD::CALLSEQ_END:
2390     Select(N.getOperand(0));
2391     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
2392     Opc = N.getOpcode() == ISD::CALLSEQ_START ? PPC::ADJCALLSTACKDOWN :
2393       PPC::ADJCALLSTACKUP;
2394     BuildMI(BB, Opc, 1).addImm(Tmp1);
2395     return;
2396   case ISD::BR: {
2397     MachineBasicBlock *Dest =
2398       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
2399     Select(N.getOperand(0));
2400     BuildMI(BB, PPC::B, 1).addMBB(Dest);
2401     return;
2402   }
2403   case ISD::BRCOND:
2404   case ISD::BRCONDTWOWAY:
2405     SelectBranchCC(N);
2406     return;
2407   case ISD::CopyToReg:
2408     Select(N.getOperand(0));
2409     Tmp1 = SelectExpr(N.getOperand(1));
2410     Tmp2 = cast<RegSDNode>(N)->getReg();
2411
2412     if (Tmp1 != Tmp2) {
2413       if (N.getOperand(1).getValueType() == MVT::f64 ||
2414           N.getOperand(1).getValueType() == MVT::f32)
2415         BuildMI(BB, PPC::FMR, 1, Tmp2).addReg(Tmp1);
2416       else
2417         BuildMI(BB, PPC::OR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
2418     }
2419     return;
2420   case ISD::ImplicitDef:
2421     Select(N.getOperand(0));
2422     BuildMI(BB, PPC::IMPLICIT_DEF, 0, cast<RegSDNode>(N)->getReg());
2423     return;
2424   case ISD::RET:
2425     switch (N.getNumOperands()) {
2426     default:
2427       assert(0 && "Unknown return instruction!");
2428     case 3:
2429       assert(N.getOperand(1).getValueType() == MVT::i32 &&
2430              N.getOperand(2).getValueType() == MVT::i32 &&
2431              "Unknown two-register value!");
2432       Select(N.getOperand(0));
2433       Tmp1 = SelectExpr(N.getOperand(1));
2434       Tmp2 = SelectExpr(N.getOperand(2));
2435       BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp2).addReg(Tmp2);
2436       BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(Tmp1).addReg(Tmp1);
2437       break;
2438     case 2:
2439       Select(N.getOperand(0));
2440       Tmp1 = SelectExpr(N.getOperand(1));
2441       switch (N.getOperand(1).getValueType()) {
2442         default:
2443           assert(0 && "Unknown return type!");
2444         case MVT::f64:
2445         case MVT::f32:
2446           BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(Tmp1);
2447           break;
2448         case MVT::i32:
2449           BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
2450           break;
2451       }
2452     case 1:
2453       Select(N.getOperand(0));
2454       break;
2455     }
2456     BuildMI(BB, PPC::BLR, 0); // Just emit a 'ret' instruction
2457     return;
2458   case ISD::TRUNCSTORE:
2459   case ISD::STORE:
2460     {
2461       SDOperand Chain   = N.getOperand(0);
2462       SDOperand Value   = N.getOperand(1);
2463       SDOperand Address = N.getOperand(2);
2464       Select(Chain);
2465
2466       Tmp1 = SelectExpr(Value); //value
2467
2468       if (opcode == ISD::STORE) {
2469         switch(Value.getValueType()) {
2470         default: assert(0 && "unknown Type in store");
2471         case MVT::i32: Opc = PPC::STW; break;
2472         case MVT::f64: Opc = PPC::STFD; break;
2473         case MVT::f32: Opc = PPC::STFS; break;
2474         }
2475       } else { //ISD::TRUNCSTORE
2476         switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
2477         default: assert(0 && "unknown Type in store");
2478         case MVT::i1:
2479         case MVT::i8: Opc  = PPC::STB; break;
2480         case MVT::i16: Opc = PPC::STH; break;
2481         }
2482       }
2483
2484       if(Address.getOpcode() == ISD::FrameIndex)
2485       {
2486         Tmp2 = cast<FrameIndexSDNode>(Address)->getIndex();
2487         addFrameReference(BuildMI(BB, Opc, 3).addReg(Tmp1), (int)Tmp2);
2488       }
2489       else
2490       {
2491         int offset;
2492         bool idx = SelectAddr(Address, Tmp2, offset);
2493         if (idx) {
2494           Opc = IndexedOpForOp(Opc);
2495           BuildMI(BB, Opc, 3).addReg(Tmp1).addReg(Tmp2).addReg(offset);
2496         } else {
2497           BuildMI(BB, Opc, 3).addReg(Tmp1).addImm(offset).addReg(Tmp2);
2498         }
2499       }
2500       return;
2501     }
2502   case ISD::EXTLOAD:
2503   case ISD::SEXTLOAD:
2504   case ISD::ZEXTLOAD:
2505   case ISD::LOAD:
2506   case ISD::CopyFromReg:
2507   case ISD::CALL:
2508   case ISD::DYNAMIC_STACKALLOC:
2509     ExprMap.erase(N);
2510     SelectExpr(N);
2511     return;
2512   }
2513   assert(0 && "Should not be reached!");
2514 }
2515
2516
2517 /// createPPC32PatternInstructionSelector - This pass converts an LLVM function
2518 /// into a machine code representation using pattern matching and a machine
2519 /// description file.
2520 ///
2521 FunctionPass *llvm::createPPC32ISelPattern(TargetMachine &TM) {
2522   return new ISel(TM);
2523 }
2524