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