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