5c47f06d5b3dbcbe9615b4c26398a144b5a0432b
[oota-llvm.git] / lib / Target / PowerPC / PPC64ISelSimple.cpp
1 //===-- PPC64ISelSimple.cpp - A simple instruction selector for PowerPC ---===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "isel"
11 #include "PowerPC.h"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "PPC64TargetMachine.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/Debug.h"
30 #include "Support/Statistic.h"
31 #include <vector>
32 using namespace llvm;
33
34 namespace {
35   Statistic<> GEPFolds("ppc64-codegen", "Number of GEPs folded");
36
37   /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
38   /// PPC Representation.
39   ///
40   enum TypeClass {
41     cByte, cShort, cInt, cFP32, cFP64, cLong
42   };
43 }
44
45 /// getClass - Turn a primitive type into a "class" number which is based on the
46 /// size of the type, and whether or not it is floating point.
47 ///
48 static inline TypeClass getClass(const Type *Ty) {
49   switch (Ty->getTypeID()) {
50   case Type::SByteTyID:
51   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
52   case Type::ShortTyID:
53   case Type::UShortTyID:  return cShort;     // Short operands are class #1
54   case Type::IntTyID:
55   case Type::UIntTyID:    return cInt;       // Ints are class #2
56
57   case Type::FloatTyID:   return cFP32;      // Single float is #3
58   case Type::DoubleTyID:  return cFP64;      // Double Point is #4
59
60   case Type::PointerTyID:
61   case Type::LongTyID:
62   case Type::ULongTyID:   return cLong;      // Longs and pointers are class #5
63   default:
64     assert(0 && "Invalid type to getClass!");
65     return cByte;  // not reached
66   }
67 }
68
69 // getClassB - Just like getClass, but treat boolean values as ints.
70 static inline TypeClass getClassB(const Type *Ty) {
71   if (Ty == Type::BoolTy) return cInt;
72   return getClass(Ty);
73 }
74
75 namespace {
76   struct ISel : public FunctionPass, InstVisitor<ISel> {
77     PPC64TargetMachine &TM;
78     MachineFunction *F;                 // The function we are compiling into
79     MachineBasicBlock *BB;              // The current MBB we are compiling
80     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
81     
82     std::map<Value*, unsigned> RegMap;  // Mapping between Values and SSA Regs
83
84     // External functions used in the Module
85     Function *fmodfFn, *fmodFn, *__cmpdi2Fn, *__moddi3Fn, *__divdi3Fn, 
86       *__umoddi3Fn,  *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__fixunssfdiFn,
87       *__fixunsdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
88
89     // MBBMap - Mapping between LLVM BB -> Machine BB
90     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
91
92     // AllocaMap - Mapping from fixed sized alloca instructions to the
93     // FrameIndex for the alloca.
94     std::map<AllocaInst*, unsigned> AllocaMap;
95
96     // A Reg to hold the base address used for global loads and stores, and a
97     // flag to set whether or not we need to emit it for this function.
98     unsigned GlobalBaseReg;
99     bool GlobalBaseInitialized;
100     
101     ISel(TargetMachine &tm) : TM(reinterpret_cast<PPC64TargetMachine&>(tm)), 
102       F(0), BB(0) {}
103
104     bool doInitialization(Module &M) {
105       // Add external functions that we may call
106       Type *i = Type::IntTy;
107       Type *d = Type::DoubleTy;
108       Type *f = Type::FloatTy;
109       Type *l = Type::LongTy;
110       Type *ul = Type::ULongTy;
111       Type *voidPtr = PointerType::get(Type::SByteTy);
112       // float fmodf(float, float);
113       fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
114       // double fmod(double, double);
115       fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
116       // int __cmpdi2(long, long);
117       __cmpdi2Fn = M.getOrInsertFunction("__cmpdi2", i, l, l, 0);
118       // long __moddi3(long, long);
119       __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
120       // long __divdi3(long, long);
121       __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
122       // unsigned long __umoddi3(unsigned long, unsigned long);
123       __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
124       // unsigned long __udivdi3(unsigned long, unsigned long);
125       __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
126       // long __fixsfdi(float)
127       __fixsfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
128       // long __fixdfdi(double)
129       __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
130       // unsigned long __fixunssfdi(float)
131       __fixunssfdiFn = M.getOrInsertFunction("__fixunssfdi", ul, f, 0);
132       // unsigned long __fixunsdfdi(double)
133       __fixunsdfdiFn = M.getOrInsertFunction("__fixunsdfdi", ul, d, 0);
134       // float __floatdisf(long)
135       __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
136       // double __floatdidf(long)
137       __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
138       // void* malloc(size_t)
139       mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
140       // void free(void*)
141       freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
142       return false;
143     }
144
145     /// runOnFunction - Top level implementation of instruction selection for
146     /// the entire function.
147     ///
148     bool runOnFunction(Function &Fn) {
149       // First pass over the function, lower any unknown intrinsic functions
150       // with the IntrinsicLowering class.
151       LowerUnknownIntrinsicFunctionCalls(Fn);
152
153       F = &MachineFunction::construct(&Fn, TM);
154
155       // Create all of the machine basic blocks for the function...
156       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
157         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
158
159       BB = &F->front();
160
161       // Make sure we re-emit a set of the global base reg if necessary
162       GlobalBaseInitialized = false;
163
164       // Copy incoming arguments off of the stack...
165       LoadArgumentsToVirtualRegs(Fn);
166
167       // Instruction select everything except PHI nodes
168       visit(Fn);
169
170       // Select the PHI nodes
171       SelectPHINodes();
172
173       RegMap.clear();
174       MBBMap.clear();
175       AllocaMap.clear();
176       F = 0;
177       // We always build a machine code representation for the function
178       return true;
179     }
180
181     virtual const char *getPassName() const {
182       return "PowerPC Simple Instruction Selection";
183     }
184
185     /// visitBasicBlock - This method is called when we are visiting a new basic
186     /// block.  This simply creates a new MachineBasicBlock to emit code into
187     /// and adds it to the current MachineFunction.  Subsequent visit* for
188     /// instructions will be invoked for all instructions in the basic block.
189     ///
190     void visitBasicBlock(BasicBlock &LLVM_BB) {
191       BB = MBBMap[&LLVM_BB];
192     }
193
194     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
195     /// function, lowering any calls to unknown intrinsic functions into the
196     /// equivalent LLVM code.
197     ///
198     void LowerUnknownIntrinsicFunctionCalls(Function &F);
199
200     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
201     /// from the stack into virtual registers.
202     ///
203     void LoadArgumentsToVirtualRegs(Function &F);
204
205     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
206     /// because we have to generate our sources into the source basic blocks,
207     /// not the current one.
208     ///
209     void SelectPHINodes();
210
211     // Visitation methods for various instructions.  These methods simply emit
212     // fixed PowerPC code for each instruction.
213
214     // Control flow operators
215     void visitReturnInst(ReturnInst &RI);
216     void visitBranchInst(BranchInst &BI);
217
218     struct ValueRecord {
219       Value *Val;
220       unsigned Reg;
221       const Type *Ty;
222       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
223       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
224     };
225     
226     // This struct is for recording the necessary operations to emit the GEP
227     struct CollapsedGepOp {
228       bool isMul;
229       Value *index;
230       ConstantSInt *size;
231       CollapsedGepOp(bool mul, Value *i, ConstantSInt *s) :
232         isMul(mul), index(i), size(s) {}
233     };
234
235     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
236                 const std::vector<ValueRecord> &Args, bool isVarArg);
237     void visitCallInst(CallInst &I);
238     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
239
240     // Arithmetic operators
241     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
242     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
243     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
244     void visitMul(BinaryOperator &B);
245
246     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
247     void visitRem(BinaryOperator &B) { visitDivRem(B); }
248     void visitDivRem(BinaryOperator &B);
249
250     // Bitwise operators
251     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
252     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
253     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
254
255     // Comparison operators...
256     void visitSetCondInst(SetCondInst &I);
257     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
258                             MachineBasicBlock *MBB,
259                             MachineBasicBlock::iterator MBBI);
260     void visitSelectInst(SelectInst &SI);
261     
262     
263     // Memory Instructions
264     void visitLoadInst(LoadInst &I);
265     void visitStoreInst(StoreInst &I);
266     void visitGetElementPtrInst(GetElementPtrInst &I);
267     void visitAllocaInst(AllocaInst &I);
268     void visitMallocInst(MallocInst &I);
269     void visitFreeInst(FreeInst &I);
270     
271     // Other operators
272     void visitShiftInst(ShiftInst &I);
273     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
274     void visitCastInst(CastInst &I);
275     void visitVANextInst(VANextInst &I);
276     void visitVAArgInst(VAArgInst &I);
277
278     void visitInstruction(Instruction &I) {
279       std::cerr << "Cannot instruction select: " << I;
280       abort();
281     }
282
283     /// promote32 - Make a value 32-bits wide, and put it somewhere.
284     ///
285     void promote32(unsigned targetReg, const ValueRecord &VR);
286
287     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
288     /// constant expression GEP support.
289     ///
290     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
291                           Value *Src, User::op_iterator IdxBegin,
292                           User::op_iterator IdxEnd, unsigned TargetReg,
293                           bool CollapseRemainder, ConstantSInt **Remainder,
294                           unsigned *PendingAddReg);
295
296     /// emitCastOperation - Common code shared between visitCastInst and
297     /// constant expression cast support.
298     ///
299     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
300                            Value *Src, const Type *DestTy, unsigned TargetReg);
301
302     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
303     /// and constant expression support.
304     ///
305     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
306                                    MachineBasicBlock::iterator IP,
307                                    Value *Op0, Value *Op1,
308                                    unsigned OperatorClass, unsigned TargetReg);
309
310     /// emitBinaryFPOperation - This method handles emission of floating point
311     /// Add (0), Sub (1), Mul (2), and Div (3) operations.
312     void emitBinaryFPOperation(MachineBasicBlock *BB,
313                                MachineBasicBlock::iterator IP,
314                                Value *Op0, Value *Op1,
315                                unsigned OperatorClass, unsigned TargetReg);
316
317     void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
318                       Value *Op0, Value *Op1, unsigned TargetReg);
319
320     void doMultiply(MachineBasicBlock *MBB,
321                     MachineBasicBlock::iterator IP,
322                     unsigned DestReg, Value *Op0, Value *Op1);
323   
324     /// doMultiplyConst - This method will multiply the value in Op0Reg by the
325     /// value of the ContantInt *CI
326     void doMultiplyConst(MachineBasicBlock *MBB, 
327                          MachineBasicBlock::iterator IP,
328                          unsigned DestReg, Value *Op0, ConstantInt *CI);
329
330     void emitDivRemOperation(MachineBasicBlock *BB,
331                              MachineBasicBlock::iterator IP,
332                              Value *Op0, Value *Op1, bool isDiv,
333                              unsigned TargetReg);
334
335     /// emitSetCCOperation - Common code shared between visitSetCondInst and
336     /// constant expression support.
337     ///
338     void emitSetCCOperation(MachineBasicBlock *BB,
339                             MachineBasicBlock::iterator IP,
340                             Value *Op0, Value *Op1, unsigned Opcode,
341                             unsigned TargetReg);
342
343     /// emitShiftOperation - Common code shared between visitShiftInst and
344     /// constant expression support.
345     ///
346     void emitShiftOperation(MachineBasicBlock *MBB,
347                             MachineBasicBlock::iterator IP,
348                             Value *Op, Value *ShiftAmount, bool isLeftShift,
349                             const Type *ResultTy, unsigned DestReg);
350       
351     /// emitSelectOperation - Common code shared between visitSelectInst and the
352     /// constant expression support.
353     ///
354     void emitSelectOperation(MachineBasicBlock *MBB,
355                              MachineBasicBlock::iterator IP,
356                              Value *Cond, Value *TrueVal, Value *FalseVal,
357                              unsigned DestReg);
358
359     /// copyGlobalBaseToRegister - Output the instructions required to put the
360     /// base address to use for accessing globals into a register.
361     ///
362     void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
363                                         MachineBasicBlock::iterator IP,
364                                         unsigned R);
365
366     /// copyConstantToRegister - Output the instructions required to put the
367     /// specified constant into the specified register.
368     ///
369     void copyConstantToRegister(MachineBasicBlock *MBB,
370                                 MachineBasicBlock::iterator MBBI,
371                                 Constant *C, unsigned Reg);
372
373     void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
374                    unsigned LHS, unsigned RHS);
375
376     /// makeAnotherReg - This method returns the next register number we haven't
377     /// yet used.
378     ///
379     unsigned makeAnotherReg(const Type *Ty) {
380       assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
381              "Current target doesn't have PPC reg info??");
382       const PowerPCRegisterInfo *PPCRI =
383         static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
384       // Add the mapping of regnumber => reg class to MachineFunction
385       const TargetRegisterClass *RC = PPCRI->getRegClassForType(Ty);
386       return F->getSSARegMap()->createVirtualRegister(RC);
387     }
388
389     /// getReg - This method turns an LLVM value into a register number.
390     ///
391     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
392     unsigned getReg(Value *V) {
393       // Just append to the end of the current bb.
394       MachineBasicBlock::iterator It = BB->end();
395       return getReg(V, BB, It);
396     }
397     unsigned getReg(Value *V, MachineBasicBlock *MBB,
398                     MachineBasicBlock::iterator IPt);
399     
400     /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
401     /// is okay to use as an immediate argument to a certain binary operation
402     bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode);
403
404     /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
405     /// that is to be statically allocated with the initial stack frame
406     /// adjustment.
407     unsigned getFixedSizedAllocaFI(AllocaInst *AI);
408   };
409 }
410
411 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
412 /// instruction in the entry block, return it.  Otherwise, return a null
413 /// pointer.
414 static AllocaInst *dyn_castFixedAlloca(Value *V) {
415   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
416     BasicBlock *BB = AI->getParent();
417     if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
418       return AI;
419   }
420   return 0;
421 }
422
423 /// getReg - This method turns an LLVM value into a register number.
424 ///
425 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
426                       MachineBasicBlock::iterator IPt) {
427   if (Constant *C = dyn_cast<Constant>(V)) {
428     unsigned Reg = makeAnotherReg(V->getType());
429     copyConstantToRegister(MBB, IPt, C, Reg);
430     return Reg;
431   } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
432     unsigned Reg = makeAnotherReg(V->getType());
433     unsigned FI = getFixedSizedAllocaFI(AI);
434     addFrameReference(BuildMI(*MBB, IPt, PPC::ADDI, 2, Reg), FI, 0, false);
435     return Reg;
436   }
437
438   unsigned &Reg = RegMap[V];
439   if (Reg == 0) {
440     Reg = makeAnotherReg(V->getType());
441     RegMap[V] = Reg;
442   }
443
444   return Reg;
445 }
446
447 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
448 /// is okay to use as an immediate argument to a certain binary operator.
449 ///
450 /// Operator is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for Xor.
451 bool ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Operator) {
452   ConstantSInt *Op1Cs;
453   ConstantUInt *Op1Cu;
454       
455   // ADDI, Compare, and non-indexed Load take SIMM
456   bool cond1 = (Operator == 0) 
457     && (Op1Cs = dyn_cast<ConstantSInt>(CI))
458     && (Op1Cs->getValue() <= 32767)
459     && (Op1Cs->getValue() >= -32768);
460
461   // SUBI takes -SIMM since it is a mnemonic for ADDI
462   bool cond2 = (Operator == 1)
463     && (Op1Cs = dyn_cast<ConstantSInt>(CI)) 
464     && (Op1Cs->getValue() <= 32768)
465     && (Op1Cs->getValue() >= -32767);
466       
467   // ANDIo, ORI, and XORI take unsigned values
468   bool cond3 = (Operator >= 2)
469     && (Op1Cs = dyn_cast<ConstantSInt>(CI))
470     && (Op1Cs->getValue() >= 0)
471     && (Op1Cs->getValue() <= 32767);
472
473   // ADDI and SUBI take SIMMs, so we have to make sure the UInt would fit
474   bool cond4 = (Operator < 2)
475     && (Op1Cu = dyn_cast<ConstantUInt>(CI)) 
476     && (Op1Cu->getValue() <= 32767);
477
478   // ANDIo, ORI, and XORI take UIMMs, so they can be larger
479   bool cond5 = (Operator >= 2)
480     && (Op1Cu = dyn_cast<ConstantUInt>(CI))
481     && (Op1Cu->getValue() <= 65535);
482
483   if (cond1 || cond2 || cond3 || cond4 || cond5)
484     return true;
485
486   return false;
487 }
488
489 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
490 /// that is to be statically allocated with the initial stack frame
491 /// adjustment.
492 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
493   // Already computed this?
494   std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
495   if (I != AllocaMap.end() && I->first == AI) return I->second;
496
497   const Type *Ty = AI->getAllocatedType();
498   ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
499   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
500   TySize *= CUI->getValue();   // Get total allocated size...
501   unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
502       
503   // Create a new stack object using the frame manager...
504   int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
505   AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
506   return FrameIdx;
507 }
508
509
510 /// copyGlobalBaseToRegister - Output the instructions required to put the
511 /// base address to use for accessing globals into a register.
512 ///
513 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
514                                     MachineBasicBlock::iterator IP,
515                                     unsigned R) {
516   if (!GlobalBaseInitialized) {
517     // Insert the set of GlobalBaseReg into the first MBB of the function
518     MachineBasicBlock &FirstMBB = F->front();
519     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
520     GlobalBaseReg = makeAnotherReg(Type::IntTy);
521     BuildMI(FirstMBB, MBBI, PPC::IMPLICIT_DEF, 0, PPC::LR);
522     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, GlobalBaseReg);
523     GlobalBaseInitialized = true;
524   }
525   // Emit our copy of GlobalBaseReg to the destination register in the
526   // current MBB
527   BuildMI(*MBB, IP, PPC::OR, 2, R).addReg(GlobalBaseReg)
528     .addReg(GlobalBaseReg);
529 }
530
531 /// copyConstantToRegister - Output the instructions required to put the
532 /// specified constant into the specified register.
533 ///
534 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
535                                   MachineBasicBlock::iterator IP,
536                                   Constant *C, unsigned R) {
537   if (C->getType()->isIntegral()) {
538     unsigned Class = getClassB(C->getType());
539
540     if (Class == cLong) {
541       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
542         uint64_t uval = CUI->getValue();
543         if (uval < (1LL << 32)) {
544           ConstantUInt *CU = ConstantUInt::get(Type::UIntTy, uval);
545           copyConstantToRegister(MBB, IP, CU, R);
546           return;
547         }
548       } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
549         int64_t val = CUI->getValue();
550         if (val < (1LL << 31)) {
551           ConstantUInt *CU = ConstantUInt::get(Type::UIntTy, val);
552           copyConstantToRegister(MBB, IP, CU, R);
553           return;
554         }
555       } else {
556         std::cerr << "Unhandled long constant type!\n";
557         abort();
558       }
559       // Spill long to the constant pool and load it
560       MachineConstantPool *CP = F->getConstantPool();
561       unsigned CPI = CP->getConstantPoolIndex(C);
562       BuildMI(*MBB, IP, PPC::LD, 1, R)
563         .addReg(PPC::R2).addConstantPoolIndex(CPI);
564     }
565     
566     assert(Class <= cInt && "Type not handled yet!");
567
568     // Handle bool
569     if (C->getType() == Type::BoolTy) {
570       BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(C == ConstantBool::True);
571       return;
572     }
573     
574     // Handle int
575     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
576       unsigned uval = CUI->getValue();
577       if (uval < 32768) {
578         BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(uval);
579       } else {
580         unsigned Temp = makeAnotherReg(Type::IntTy);
581         BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(uval >> 16);
582         BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(uval);
583       }
584       return;
585     } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
586       int sval = CSI->getValue();
587       if (sval < 32768 && sval >= -32768) {
588         BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(sval);
589       } else {
590         unsigned Temp = makeAnotherReg(Type::IntTy);
591         BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(sval >> 16);
592         BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(sval);
593       }
594       return;
595     }
596     std::cerr << "Unhandled integer constant!\n";
597     abort();
598   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
599     // We need to spill the constant to memory...
600     MachineConstantPool *CP = F->getConstantPool();
601     unsigned CPI = CP->getConstantPoolIndex(CFP);
602     const Type *Ty = CFP->getType();
603     unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC::LFS : PPC::LFD;
604     BuildMI(*MBB,IP,LoadOpcode,2,R).addConstantPoolIndex(CPI).addReg(PPC::R2);
605   } else if (isa<ConstantPointerNull>(C)) {
606     // Copy zero (null pointer) to the register.
607     BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(0);
608   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
609     static unsigned OpcodeTable[] = {
610       PPC::LBZ, PPC::LHZ, PPC::LWZ, PPC::LFS, PPC::LFD, PPC::LD
611     };
612     unsigned Opcode = OpcodeTable[getClassB(GV->getType())];
613     BuildMI(*MBB, IP, Opcode, 2, R).addGlobalAddress(GV).addReg(PPC::R2);
614   } else {
615     std::cerr << "Offending constant: " << *C << "\n";
616     assert(0 && "Type not handled yet!");
617   }
618 }
619
620 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
621 /// the stack into virtual registers.
622 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
623   unsigned ArgOffset = 24;
624   unsigned GPR_remaining = 8;
625   unsigned FPR_remaining = 13;
626   unsigned GPR_idx = 0, FPR_idx = 0;
627   static const unsigned GPR[] = { 
628     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
629     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
630   };
631   static const unsigned FPR[] = {
632     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
633     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
634   };
635     
636   MachineFrameInfo *MFI = F->getFrameInfo();
637  
638   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
639     bool ArgLive = !I->use_empty();
640     unsigned Reg = ArgLive ? getReg(*I) : 0;
641     int FI;          // Frame object index
642
643     switch (getClassB(I->getType())) {
644     case cByte:
645       if (ArgLive) {
646         FI = MFI->CreateFixedObject(4, ArgOffset);
647         if (GPR_remaining > 0) {
648           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
649           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
650             .addReg(GPR[GPR_idx]);
651         } else {
652           addFrameReference(BuildMI(BB, PPC::LBZ, 2, Reg), FI);
653         }
654       }
655       break;
656     case cShort:
657       if (ArgLive) {
658         FI = MFI->CreateFixedObject(4, ArgOffset);
659         if (GPR_remaining > 0) {
660           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
661           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
662             .addReg(GPR[GPR_idx]);
663         } else {
664           addFrameReference(BuildMI(BB, PPC::LHZ, 2, Reg), FI);
665         }
666       }
667       break;
668     case cInt:
669       if (ArgLive) {
670         FI = MFI->CreateFixedObject(4, ArgOffset);
671         if (GPR_remaining > 0) {
672           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
673           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
674             .addReg(GPR[GPR_idx]);
675         } else {
676           addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
677         }
678       }
679       break;
680     case cLong:
681       if (ArgLive) {
682         FI = MFI->CreateFixedObject(8, ArgOffset);
683         if (GPR_remaining > 1) {
684           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
685           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
686             .addReg(GPR[GPR_idx]);
687         } else {
688           addFrameReference(BuildMI(BB, PPC::LD, 2, Reg), FI);
689         }
690       }
691       // longs require 4 additional bytes
692       ArgOffset += 4;
693       break;
694     case cFP32:
695      if (ArgLive) {
696         FI = MFI->CreateFixedObject(4, ArgOffset);
697
698         if (FPR_remaining > 0) {
699           BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
700           BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
701           FPR_remaining--;
702           FPR_idx++;
703         } else {
704           addFrameReference(BuildMI(BB, PPC::LFS, 2, Reg), FI);
705         }
706       }
707       break;
708     case cFP64:
709       if (ArgLive) {
710         FI = MFI->CreateFixedObject(8, ArgOffset);
711
712         if (FPR_remaining > 0) {
713           BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
714           BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
715           FPR_remaining--;
716           FPR_idx++;
717         } else {
718           addFrameReference(BuildMI(BB, PPC::LFD, 2, Reg), FI);
719         }
720       }
721
722       // doubles require 4 additional bytes and use 2 GPRs of param space
723       ArgOffset += 4;   
724       if (GPR_remaining > 0) {
725         GPR_remaining--;
726         GPR_idx++;
727       }
728       break;
729     default:
730       assert(0 && "Unhandled argument type!");
731     }
732     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
733     if (GPR_remaining > 0) {
734       GPR_remaining--;    // uses up 2 GPRs
735       GPR_idx++;
736     }
737   }
738
739   // If the function takes variable number of arguments, add a frame offset for
740   // the start of the first vararg value... this is used to expand
741   // llvm.va_start.
742   if (Fn.getFunctionType()->isVarArg())
743     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
744 }
745
746
747 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
748 /// because we have to generate our sources into the source basic blocks, not
749 /// the current one.
750 ///
751 void ISel::SelectPHINodes() {
752   const TargetInstrInfo &TII = *TM.getInstrInfo();
753   const Function &LF = *F->getFunction();  // The LLVM function...
754   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
755     const BasicBlock *BB = I;
756     MachineBasicBlock &MBB = *MBBMap[I];
757
758     // Loop over all of the PHI nodes in the LLVM basic block...
759     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
760     for (BasicBlock::const_iterator I = BB->begin();
761          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
762
763       // Create a new machine instr PHI node, and insert it.
764       unsigned PHIReg = getReg(*PN);
765       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
766                                     PPC::PHI, PN->getNumOperands(), PHIReg);
767
768       // PHIValues - Map of blocks to incoming virtual registers.  We use this
769       // so that we only initialize one incoming value for a particular block,
770       // even if the block has multiple entries in the PHI node.
771       //
772       std::map<MachineBasicBlock*, unsigned> PHIValues;
773
774       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
775         MachineBasicBlock *PredMBB = 0;
776         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
777              PE = MBB.pred_end (); PI != PE; ++PI)
778           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
779             PredMBB = *PI;
780             break;
781           }
782         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
783
784         unsigned ValReg;
785         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
786           PHIValues.lower_bound(PredMBB);
787
788         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
789           // We already inserted an initialization of the register for this
790           // predecessor.  Recycle it.
791           ValReg = EntryIt->second;
792         } else {
793           // Get the incoming value into a virtual register.
794           //
795           Value *Val = PN->getIncomingValue(i);
796
797           // If this is a constant or GlobalValue, we may have to insert code
798           // into the basic block to compute it into a virtual register.
799           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
800               isa<GlobalValue>(Val)) {
801             // Simple constants get emitted at the end of the basic block,
802             // before any terminator instructions.  We "know" that the code to
803             // move a constant into a register will never clobber any flags.
804             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
805           } else {
806             // Because we don't want to clobber any values which might be in
807             // physical registers with the computation of this constant (which
808             // might be arbitrarily complex if it is a constant expression),
809             // just insert the computation at the top of the basic block.
810             MachineBasicBlock::iterator PI = PredMBB->begin();
811
812             // Skip over any PHI nodes though!
813             while (PI != PredMBB->end() && PI->getOpcode() == PPC::PHI)
814               ++PI;
815
816             ValReg = getReg(Val, PredMBB, PI);
817           }
818
819           // Remember that we inserted a value for this PHI for this predecessor
820           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
821         }
822
823         PhiMI->addRegOperand(ValReg);
824         PhiMI->addMachineBasicBlockOperand(PredMBB);
825       }
826
827       // Now that we emitted all of the incoming values for the PHI node, make
828       // sure to reposition the InsertPoint after the PHI that we just added.
829       // This is needed because we might have inserted a constant into this
830       // block, right after the PHI's which is before the old insert point!
831       PHIInsertPoint = PhiMI;
832       ++PHIInsertPoint;
833     }
834   }
835 }
836
837
838 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
839 // it into the conditional branch or select instruction which is the only user
840 // of the cc instruction.  This is the case if the conditional branch is the
841 // only user of the setcc, and if the setcc is in the same basic block as the
842 // conditional branch.
843 //
844 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
845   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
846     if (SCI->hasOneUse()) {
847       Instruction *User = cast<Instruction>(SCI->use_back());
848       if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
849           SCI->getParent() == User->getParent())
850         return SCI;
851     }
852   return 0;
853 }
854
855
856 // canFoldGEPIntoLoadOrStore - Return the GEP instruction if we can fold it into
857 // the load or store instruction that is the only user of the GEP.
858 //
859 static GetElementPtrInst *canFoldGEPIntoLoadOrStore(Value *V) {
860   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V))
861     if (GEPI->hasOneUse()) {
862       Instruction *User = cast<Instruction>(GEPI->use_back());
863       if (isa<StoreInst>(User) &&
864           GEPI->getParent() == User->getParent() &&
865           User->getOperand(0) != GEPI &&
866           User->getOperand(1) == GEPI) {
867         ++GEPFolds;
868         return GEPI;
869       }
870       if (isa<LoadInst>(User) &&
871           GEPI->getParent() == User->getParent() &&
872           User->getOperand(0) == GEPI) {
873         ++GEPFolds;
874         return GEPI;
875       }
876     }
877   return 0;
878 }
879
880
881 // Return a fixed numbering for setcc instructions which does not depend on the
882 // order of the opcodes.
883 //
884 static unsigned getSetCCNumber(unsigned Opcode) {
885   switch (Opcode) {
886   default: assert(0 && "Unknown setcc instruction!");
887   case Instruction::SetEQ: return 0;
888   case Instruction::SetNE: return 1;
889   case Instruction::SetLT: return 2;
890   case Instruction::SetGE: return 3;
891   case Instruction::SetGT: return 4;
892   case Instruction::SetLE: return 5;
893   }
894 }
895
896 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
897   switch (Opcode) {
898   default: assert(0 && "Unknown setcc instruction!");
899   case Instruction::SetEQ: return PPC::BEQ;
900   case Instruction::SetNE: return PPC::BNE;
901   case Instruction::SetLT: return PPC::BLT;
902   case Instruction::SetGE: return PPC::BGE;
903   case Instruction::SetGT: return PPC::BGT;
904   case Instruction::SetLE: return PPC::BLE;
905   }
906 }
907
908 /// emitUCOM - emits an unordered FP compare.
909 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
910                      unsigned LHS, unsigned RHS) {
911     BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(LHS).addReg(RHS);
912 }
913
914 /// EmitComparison - emits a comparison of the two operands, returning the
915 /// extended setcc code to use.  The result is in CR0.
916 ///
917 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
918                               MachineBasicBlock *MBB,
919                               MachineBasicBlock::iterator IP) {
920   // The arguments are already supposed to be of the same type.
921   const Type *CompTy = Op0->getType();
922   unsigned Class = getClassB(CompTy);
923   unsigned Op0r = getReg(Op0, MBB, IP);
924
925   // Before we do a comparison, we have to make sure that we're truncating our
926   // registers appropriately.
927   if (Class == cByte) {
928     unsigned TmpReg = makeAnotherReg(CompTy);
929     if (CompTy->isSigned())
930       BuildMI(*MBB, IP, PPC::EXTSB, 1, TmpReg).addReg(Op0r);
931     else
932       BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
933         .addImm(24).addImm(31);
934     Op0r = TmpReg;
935   } else if (Class == cShort) {
936     unsigned TmpReg = makeAnotherReg(CompTy);
937     if (CompTy->isSigned())
938       BuildMI(*MBB, IP, PPC::EXTSH, 1, TmpReg).addReg(Op0r);
939     else
940       BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
941         .addImm(16).addImm(31);
942     Op0r = TmpReg;
943   }
944   
945   // Use crand for lt, gt and crandc for le, ge
946   unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC::CRAND : PPC::CRANDC;
947   unsigned Opcode = CompTy->isSigned() ? PPC::CMPW : PPC::CMPLW;
948   unsigned OpcodeImm = CompTy->isSigned() ? PPC::CMPWI : PPC::CMPLWI;
949   if (Class == cLong) {
950     Opcode = CompTy->isSigned() ? PPC::CMPD : PPC::CMPLD;
951     OpcodeImm = CompTy->isSigned() ? PPC::CMPDI : PPC::CMPLDI;
952   }
953
954   // Special case handling of: cmp R, i
955   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
956     unsigned Op1v = CI->getRawValue() & 0xFFFF;
957
958     // Treat compare like ADDI for the purposes of immediate suitability
959     if (canUseAsImmediateForOpcode(CI, 0)) {
960       BuildMI(*MBB, IP, OpcodeImm, 2, PPC::CR0).addReg(Op0r).addSImm(Op1v);
961     } else {
962       unsigned Op1r = getReg(Op1, MBB, IP);
963       BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
964     }
965     return OpNum;
966   }
967
968   unsigned Op1r = getReg(Op1, MBB, IP);
969
970   switch (Class) {
971   default: assert(0 && "Unknown type class!");
972   case cByte:
973   case cShort:
974   case cInt:
975   case cLong:
976     BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
977     break;
978
979   case cFP32:
980   case cFP64:
981     emitUCOM(MBB, IP, Op0r, Op1r);
982     break;
983   }
984
985   return OpNum;
986 }
987
988 /// visitSetCondInst - emit code to calculate the condition via
989 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
990 ///
991 void ISel::visitSetCondInst(SetCondInst &I) {
992   if (canFoldSetCCIntoBranchOrSelect(&I))
993     return;
994
995   unsigned DestReg = getReg(I);
996   unsigned OpNum = I.getOpcode();
997   const Type *Ty = I.getOperand (0)->getType();
998
999   EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
1000   
1001   unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
1002   MachineBasicBlock *thisMBB = BB;
1003   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1004   ilist<MachineBasicBlock>::iterator It = BB;
1005   ++It;
1006   
1007   //  thisMBB:
1008   //  ...
1009   //   cmpTY cr0, r1, r2
1010   //   bCC copy1MBB
1011   //   b copy0MBB
1012
1013   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1014   // if we could insert other, non-terminator instructions after the
1015   // bCC. But MBB->getFirstTerminator() can't understand this.
1016   MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1017   F->getBasicBlockList().insert(It, copy1MBB);
1018   BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1019   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1020   F->getBasicBlockList().insert(It, copy0MBB);
1021   BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1022   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1023   F->getBasicBlockList().insert(It, sinkMBB);
1024   // Update machine-CFG edges
1025   BB->addSuccessor(copy1MBB);
1026   BB->addSuccessor(copy0MBB);
1027
1028   //  copy1MBB:
1029   //   %TrueValue = li 1
1030   //   b sinkMBB
1031   BB = copy1MBB;
1032   unsigned TrueValue = makeAnotherReg(I.getType());
1033   BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1034   BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1035   // Update machine-CFG edges
1036   BB->addSuccessor(sinkMBB);
1037
1038   //  copy0MBB:
1039   //   %FalseValue = li 0
1040   //   fallthrough
1041   BB = copy0MBB;
1042   unsigned FalseValue = makeAnotherReg(I.getType());
1043   BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1044   // Update machine-CFG edges
1045   BB->addSuccessor(sinkMBB);
1046
1047   //  sinkMBB:
1048   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1049   //  ...
1050   BB = sinkMBB;
1051   BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1052     .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1053 }
1054
1055 void ISel::visitSelectInst(SelectInst &SI) {
1056   unsigned DestReg = getReg(SI);
1057   MachineBasicBlock::iterator MII = BB->end();
1058   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1059                       SI.getFalseValue(), DestReg);
1060 }
1061  
1062 /// emitSelect - Common code shared between visitSelectInst and the constant
1063 /// expression support.
1064 /// FIXME: this is most likely broken in one or more ways.  Namely, PowerPC has
1065 /// no select instruction.  FSEL only works for comparisons against zero.
1066 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1067                                MachineBasicBlock::iterator IP,
1068                                Value *Cond, Value *TrueVal, Value *FalseVal,
1069                                unsigned DestReg) {
1070   unsigned SelectClass = getClassB(TrueVal->getType());
1071   unsigned Opcode;
1072
1073   // See if we can fold the setcc into the select instruction, or if we have
1074   // to get the register of the Cond value
1075   if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1076     // We successfully folded the setcc into the select instruction.
1077     unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1078     OpNum = EmitComparison(OpNum, SCI->getOperand(0),SCI->getOperand(1),MBB,IP);
1079     Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1080   } else {
1081     unsigned CondReg = getReg(Cond, MBB, IP);
1082     BuildMI(*MBB, IP, PPC::CMPI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
1083     Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1084   }
1085
1086   //  thisMBB:
1087   //  ...
1088   //   cmpTY cr0, r1, r2
1089   //   bCC copy1MBB
1090   //   b copy0MBB
1091
1092   MachineBasicBlock *thisMBB = BB;
1093   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1094   ilist<MachineBasicBlock>::iterator It = BB;
1095   ++It;
1096
1097   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1098   // if we could insert other, non-terminator instructions after the
1099   // bCC. But MBB->getFirstTerminator() can't understand this.
1100   MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1101   F->getBasicBlockList().insert(It, copy1MBB);
1102   BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1103   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1104   F->getBasicBlockList().insert(It, copy0MBB);
1105   BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1106   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1107   F->getBasicBlockList().insert(It, sinkMBB);
1108   // Update machine-CFG edges
1109   BB->addSuccessor(copy1MBB);
1110   BB->addSuccessor(copy0MBB);
1111
1112   //  copy1MBB:
1113   //   %TrueValue = ...
1114   //   b sinkMBB
1115   BB = copy1MBB;
1116   unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1117   BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1118   // Update machine-CFG edges
1119   BB->addSuccessor(sinkMBB);
1120
1121   //  copy0MBB:
1122   //   %FalseValue = ...
1123   //   fallthrough
1124   BB = copy0MBB;
1125   unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1126   // Update machine-CFG edges
1127   BB->addSuccessor(sinkMBB);
1128
1129   //  sinkMBB:
1130   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1131   //  ...
1132   BB = sinkMBB;
1133   BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1134     .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1135   return;
1136 }
1137
1138
1139
1140 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1141 /// operand, in the specified target register.
1142 ///
1143 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1144   bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1145
1146   Value *Val = VR.Val;
1147   const Type *Ty = VR.Ty;
1148   if (Val) {
1149     if (Constant *C = dyn_cast<Constant>(Val)) {
1150       Val = ConstantExpr::getCast(C, Type::IntTy);
1151       if (isa<ConstantExpr>(Val))   // Could not fold
1152         Val = C;
1153       else
1154         Ty = Type::IntTy;           // Folded!
1155     }
1156
1157     // If this is a simple constant, just emit a load directly to avoid the copy
1158     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1159       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1160
1161       if (TheVal < 32768 && TheVal >= -32768) {
1162         BuildMI(BB, PPC::LI, 1, targetReg).addSImm(TheVal);
1163       } else {
1164         unsigned TmpReg = makeAnotherReg(Type::IntTy);
1165         BuildMI(BB, PPC::LIS, 1, TmpReg).addSImm(TheVal >> 16);
1166         BuildMI(BB, PPC::ORI, 2, targetReg).addReg(TmpReg)
1167           .addImm(TheVal & 0xFFFF);
1168       }
1169       return;
1170     }
1171   }
1172
1173   // Make sure we have the register number for this value...
1174   unsigned Reg = Val ? getReg(Val) : VR.Reg;
1175   switch (getClassB(Ty)) {
1176   case cByte:
1177     // Extend value into target register (8->32)
1178     if (isUnsigned)
1179       BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1180         .addZImm(24).addZImm(31);
1181     else
1182       BuildMI(BB, PPC::EXTSB, 1, targetReg).addReg(Reg);
1183     break;
1184   case cShort:
1185     // Extend value into target register (16->32)
1186     if (isUnsigned)
1187       BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1188         .addZImm(16).addZImm(31);
1189     else
1190       BuildMI(BB, PPC::EXTSH, 1, targetReg).addReg(Reg);
1191     break;
1192   case cInt:
1193   case cLong:
1194     // Move value into target register (32->32)
1195     BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1196     break;
1197   default:
1198     assert(0 && "Unpromotable operand class in promote32");
1199   }
1200 }
1201
1202 /// visitReturnInst - implemented with BLR
1203 ///
1204 void ISel::visitReturnInst(ReturnInst &I) {
1205   // Only do the processing if this is a non-void return
1206   if (I.getNumOperands() > 0) {
1207     Value *RetVal = I.getOperand(0);
1208     switch (getClassB(RetVal->getType())) {
1209     case cByte:   // integral return values: extend or move into r3 and return
1210     case cShort:
1211     case cInt:
1212     case cLong:
1213       promote32(PPC::R3, ValueRecord(RetVal));
1214       break;
1215     case cFP32:
1216     case cFP64: {   // Floats & Doubles: Return in f1
1217       unsigned RetReg = getReg(RetVal);
1218       BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(RetReg);
1219       break;
1220     }
1221     default:
1222       visitInstruction(I);
1223     }
1224   }
1225   BuildMI(BB, PPC::BLR, 1).addImm(1);
1226 }
1227
1228 // getBlockAfter - Return the basic block which occurs lexically after the
1229 // specified one.
1230 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1231   Function::iterator I = BB; ++I;  // Get iterator to next block
1232   return I != BB->getParent()->end() ? &*I : 0;
1233 }
1234
1235 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1236 /// that since code layout is frozen at this point, that if we are trying to
1237 /// jump to a block that is the immediate successor of the current block, we can
1238 /// just make a fall-through (but we don't currently).
1239 ///
1240 void ISel::visitBranchInst(BranchInst &BI) {
1241   // Update machine-CFG edges
1242   BB->addSuccessor(MBBMap[BI.getSuccessor(0)]);
1243   if (BI.isConditional())
1244     BB->addSuccessor(MBBMap[BI.getSuccessor(1)]);
1245   
1246   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1247
1248   if (!BI.isConditional()) {  // Unconditional branch?
1249     if (BI.getSuccessor(0) != NextBB) 
1250       BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1251     return;
1252   }
1253   
1254   // See if we can fold the setcc into the branch itself...
1255   SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1256   if (SCI == 0) {
1257     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1258     // computed some other way...
1259     unsigned condReg = getReg(BI.getCondition());
1260     BuildMI(BB, PPC::CMPLI, 3, PPC::CR0).addImm(0).addReg(condReg)
1261       .addImm(0);
1262     if (BI.getSuccessor(1) == NextBB) {
1263       if (BI.getSuccessor(0) != NextBB)
1264         BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BNE)
1265           .addMBB(MBBMap[BI.getSuccessor(0)])
1266           .addMBB(MBBMap[BI.getSuccessor(1)]);
1267     } else {
1268       BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BEQ)
1269         .addMBB(MBBMap[BI.getSuccessor(1)])
1270         .addMBB(MBBMap[BI.getSuccessor(0)]);
1271       if (BI.getSuccessor(0) != NextBB)
1272         BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1273     }
1274     return;
1275   }
1276
1277   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1278   unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1279   MachineBasicBlock::iterator MII = BB->end();
1280   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1281   
1282   if (BI.getSuccessor(0) != NextBB) {
1283     BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1284       .addMBB(MBBMap[BI.getSuccessor(0)])
1285       .addMBB(MBBMap[BI.getSuccessor(1)]);
1286     if (BI.getSuccessor(1) != NextBB)
1287       BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1288   } else {
1289     // Change to the inverse condition...
1290     if (BI.getSuccessor(1) != NextBB) {
1291       Opcode = PowerPCInstrInfo::invertPPCBranchOpcode(Opcode);
1292       BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1293         .addMBB(MBBMap[BI.getSuccessor(1)])
1294         .addMBB(MBBMap[BI.getSuccessor(0)]);
1295     }
1296   }
1297 }
1298
1299 /// doCall - This emits an abstract call instruction, setting up the arguments
1300 /// and the return value as appropriate.  For the actual function call itself,
1301 /// it inserts the specified CallMI instruction into the stream.
1302 ///
1303 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1304                   const std::vector<ValueRecord> &Args, bool isVarArg) {
1305   // Count how many bytes are to be pushed on the stack, including the linkage
1306   // area, and parameter passing area.
1307   unsigned NumBytes = 24;
1308   unsigned ArgOffset = 24;
1309
1310   if (!Args.empty()) {
1311     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1312       switch (getClassB(Args[i].Ty)) {
1313       case cByte: case cShort: case cInt:
1314         NumBytes += 4; break;
1315       case cLong:
1316         NumBytes += 8; break;
1317       case cFP32:
1318         NumBytes += 4; break;
1319       case cFP64:
1320         NumBytes += 8; break;
1321         break;
1322       default: assert(0 && "Unknown class!");
1323       }
1324
1325     // Just to be safe, we'll always reserve the full 32 bytes worth of
1326     // argument passing space in case any called code gets funky on us.
1327     if (NumBytes < 24 + 32) NumBytes = 24 + 32;
1328
1329     // Adjust the stack pointer for the new arguments...
1330     // These functions are automatically eliminated by the prolog/epilog pass
1331     BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1332
1333     // Arguments go on the stack in reverse order, as specified by the ABI.
1334     // Offset to the paramater area on the stack is 24.
1335     int GPR_remaining = 8, FPR_remaining = 13;
1336     unsigned GPR_idx = 0, FPR_idx = 0;
1337     static const unsigned GPR[] = { 
1338       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1339       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1340     };
1341     static const unsigned FPR[] = {
1342       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, 
1343       PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, 
1344       PPC::F13
1345     };
1346     
1347     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1348       unsigned ArgReg;
1349       switch (getClassB(Args[i].Ty)) {
1350       case cByte:
1351       case cShort:
1352         // Promote arg to 32 bits wide into a temporary register...
1353         ArgReg = makeAnotherReg(Type::UIntTy);
1354         promote32(ArgReg, Args[i]);
1355           
1356         // Reg or stack?
1357         if (GPR_remaining > 0) {
1358           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1359             .addReg(ArgReg);
1360           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1361         }
1362         if (GPR_remaining <= 0 || isVarArg) {
1363           BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1364             .addReg(PPC::R1);
1365         }
1366         break;
1367       case cInt:
1368         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1369
1370         // Reg or stack?
1371         if (GPR_remaining > 0) {
1372           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1373             .addReg(ArgReg);
1374           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1375         }
1376         if (GPR_remaining <= 0 || isVarArg) {
1377           BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1378             .addReg(PPC::R1);
1379         }
1380         break;
1381       case cLong:
1382         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1383
1384         // Reg or stack?
1385         if (GPR_remaining > 0) {
1386           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1387             .addReg(ArgReg);
1388           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1389         }
1390         if (GPR_remaining <= 0 || isVarArg) {
1391           BuildMI(BB, PPC::STD, 3).addReg(ArgReg).addSImm(ArgOffset)
1392             .addReg(PPC::R1);
1393         }
1394         ArgOffset += 4;        // 8 byte entry, not 4.
1395         break;
1396       case cFP32:
1397         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1398         // Reg or stack?
1399         if (FPR_remaining > 0) {
1400           BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1401           CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1402           FPR_remaining--;
1403           FPR_idx++;
1404           
1405           // If this is a vararg function, and there are GPRs left, also
1406           // pass the float in an int.  Otherwise, put it on the stack.
1407           if (isVarArg) {
1408             BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1409             .addReg(PPC::R1);
1410             if (GPR_remaining > 0) {
1411               BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx])
1412               .addSImm(ArgOffset).addReg(ArgReg);
1413               CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1414             }
1415           }
1416         } else {
1417           BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1418           .addReg(PPC::R1);
1419         }
1420         break;
1421       case cFP64:
1422         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1423         // Reg or stack?
1424         if (FPR_remaining > 0) {
1425           BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1426           CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1427           FPR_remaining--;
1428           FPR_idx++;
1429           // For vararg functions, must pass doubles via int regs as well
1430           if (isVarArg) {
1431             BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1432             .addReg(PPC::R1);
1433             
1434             if (GPR_remaining > 0) {
1435               BuildMI(BB, PPC::LD, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1436               .addReg(PPC::R1);
1437               CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1438             }
1439           }
1440         } else {
1441           BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1442           .addReg(PPC::R1);
1443         }
1444         // Doubles use 8 bytes
1445         ArgOffset += 4;
1446         break;
1447         
1448       default: assert(0 && "Unknown class!");
1449       }
1450       ArgOffset += 4;
1451       GPR_remaining--;
1452       GPR_idx++;
1453     }
1454   } else {
1455     BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(0);
1456   }
1457
1458   BuildMI(BB, PPC::IMPLICIT_DEF, 0, PPC::LR);
1459   BB->push_back(CallMI);
1460   BuildMI(BB, PPC::NOP, 0);
1461   
1462   // These functions are automatically eliminated by the prolog/epilog pass
1463   BuildMI(BB, PPC::ADJCALLSTACKUP, 1).addImm(NumBytes);
1464
1465   // If there is a return value, scavenge the result from the location the call
1466   // leaves it in...
1467   //
1468   if (Ret.Ty != Type::VoidTy) {
1469     unsigned DestClass = getClassB(Ret.Ty);
1470     switch (DestClass) {
1471     case cByte:
1472     case cShort:
1473     case cInt:
1474     case cLong:
1475       // Integral results are in r3
1476       BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1477       break;
1478     case cFP32:   // Floating-point return values live in f1
1479     case cFP64:
1480       BuildMI(BB, PPC::FMR, 1, Ret.Reg).addReg(PPC::F1);
1481       break;
1482     default: assert(0 && "Unknown class!");
1483     }
1484   }
1485 }
1486
1487
1488 /// visitCallInst - Push args on stack and do a procedure call instruction.
1489 void ISel::visitCallInst(CallInst &CI) {
1490   MachineInstr *TheCall;
1491   Function *F = CI.getCalledFunction();
1492   if (F) {
1493     // Is it an intrinsic function call?
1494     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1495       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1496       return;
1497     }
1498     // Emit a CALL instruction with PC-relative displacement.
1499     TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(F, true);
1500     // Add it to the set of functions called to be used by the Printer
1501     TM.CalledFunctions.insert(F);
1502   } else {  // Emit an indirect call through the CTR
1503     unsigned Reg = getReg(CI.getCalledValue());
1504     BuildMI(BB, PPC::MTCTR, 1).addReg(Reg);
1505     TheCall = BuildMI(PPC::CALLindirect, 2).addZImm(20).addZImm(0);
1506   }
1507
1508   std::vector<ValueRecord> Args;
1509   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1510     Args.push_back(ValueRecord(CI.getOperand(i)));
1511
1512   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1513   bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1514   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1515 }         
1516
1517
1518 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1519 ///
1520 static Value *dyncastIsNan(Value *V) {
1521   if (CallInst *CI = dyn_cast<CallInst>(V))
1522     if (Function *F = CI->getCalledFunction())
1523       if (F->getIntrinsicID() == Intrinsic::isunordered)
1524         return CI->getOperand(1);
1525   return 0;
1526 }
1527
1528 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1529 /// or's whos operands are all calls to the isnan predicate.
1530 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1531   assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1532
1533   // Check all uses, which will be or's of isnans if this predicate is true.
1534   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1535     Instruction *I = cast<Instruction>(*UI);
1536     if (I->getOpcode() != Instruction::Or) return false;
1537     if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1538     if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1539   }
1540
1541   return true;
1542 }
1543
1544 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1545 /// function, lowering any calls to unknown intrinsic functions into the
1546 /// equivalent LLVM code.
1547 ///
1548 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1549   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1550     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1551       if (CallInst *CI = dyn_cast<CallInst>(I++))
1552         if (Function *F = CI->getCalledFunction())
1553           switch (F->getIntrinsicID()) {
1554           case Intrinsic::not_intrinsic:
1555           case Intrinsic::vastart:
1556           case Intrinsic::vacopy:
1557           case Intrinsic::vaend:
1558           case Intrinsic::returnaddress:
1559           case Intrinsic::frameaddress:
1560             // FIXME: should lower these ourselves
1561             // case Intrinsic::isunordered:
1562             // case Intrinsic::memcpy: -> doCall().  system memcpy almost
1563             // guaranteed to be faster than anything we generate ourselves
1564             // We directly implement these intrinsics
1565             break;
1566           case Intrinsic::readio: {
1567             // On PPC, memory operations are in-order.  Lower this intrinsic
1568             // into a volatile load.
1569             Instruction *Before = CI->getPrev();
1570             LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1571             CI->replaceAllUsesWith(LI);
1572             BB->getInstList().erase(CI);
1573             break;
1574           }
1575           case Intrinsic::writeio: {
1576             // On PPC, memory operations are in-order.  Lower this intrinsic
1577             // into a volatile store.
1578             Instruction *Before = CI->getPrev();
1579             StoreInst *SI = new StoreInst(CI->getOperand(1),
1580                                           CI->getOperand(2), true, CI);
1581             CI->replaceAllUsesWith(SI);
1582             BB->getInstList().erase(CI);
1583             break;
1584           }
1585           default:
1586             // All other intrinsic calls we must lower.
1587             Instruction *Before = CI->getPrev();
1588             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1589             if (Before) {        // Move iterator to instruction after call
1590               I = Before; ++I;
1591             } else {
1592               I = BB->begin();
1593             }
1594           }
1595 }
1596
1597 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1598   unsigned TmpReg1, TmpReg2, TmpReg3;
1599   switch (ID) {
1600   case Intrinsic::vastart:
1601     // Get the address of the first vararg value...
1602     TmpReg1 = getReg(CI);
1603     addFrameReference(BuildMI(BB, PPC::ADDI, 2, TmpReg1), VarArgsFrameIndex, 
1604                       0, false);
1605     return;
1606
1607   case Intrinsic::vacopy:
1608     TmpReg1 = getReg(CI);
1609     TmpReg2 = getReg(CI.getOperand(1));
1610     BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1611     return;
1612   case Intrinsic::vaend: return;
1613
1614   case Intrinsic::returnaddress:
1615     TmpReg1 = getReg(CI);
1616     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1617       MachineFrameInfo *MFI = F->getFrameInfo();
1618       unsigned NumBytes = MFI->getStackSize();
1619       
1620       BuildMI(BB, PPC::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1621         .addReg(PPC::R1);
1622     } else {
1623       // Values other than zero are not implemented yet.
1624       BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1625     }
1626     return;
1627
1628   case Intrinsic::frameaddress:
1629     TmpReg1 = getReg(CI);
1630     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1631       BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(PPC::R1).addReg(PPC::R1);
1632     } else {
1633       // Values other than zero are not implemented yet.
1634       BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1635     }
1636     return;
1637     
1638 #if 0
1639     // This may be useful for supporting isunordered
1640   case Intrinsic::isnan:
1641     // If this is only used by 'isunordered' style comparisons, don't emit it.
1642     if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1643     TmpReg1 = getReg(CI.getOperand(1));
1644     emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1645     TmpReg2 = makeAnotherReg(Type::IntTy);
1646     BuildMI(BB, PPC::MFCR, TmpReg2);
1647     TmpReg3 = getReg(CI);
1648     BuildMI(BB, PPC::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1649     return;
1650 #endif
1651     
1652   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1653   }
1654 }
1655
1656 /// visitSimpleBinary - Implement simple binary operators for integral types...
1657 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1658 /// Xor.
1659 ///
1660 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1661   unsigned DestReg = getReg(B);
1662   MachineBasicBlock::iterator MI = BB->end();
1663   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1664   unsigned Class = getClassB(B.getType());
1665
1666   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1667 }
1668
1669 /// emitBinaryFPOperation - This method handles emission of floating point
1670 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1671 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1672                                  MachineBasicBlock::iterator IP,
1673                                  Value *Op0, Value *Op1,
1674                                  unsigned OperatorClass, unsigned DestReg) {
1675
1676   // Special case: op Reg, <const fp>
1677   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1678     // Create a constant pool entry for this constant.
1679     MachineConstantPool *CP = F->getConstantPool();
1680     unsigned CPI = CP->getConstantPoolIndex(Op1C);
1681     const Type *Ty = Op1->getType();
1682     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1683
1684     static const unsigned OpcodeTab[][4] = {
1685       { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS },  // Float
1686       { PPC::FADD,  PPC::FSUB,  PPC::FMUL,  PPC::FDIV },   // Double
1687     };
1688
1689     unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1690     unsigned Op1Reg = getReg(Op1C, BB, IP);
1691     unsigned Op0r = getReg(Op0, BB, IP);
1692     BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1693     return;
1694   }
1695   
1696   // Special case: R1 = op <const fp>, R2
1697   if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1698     if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1699       // -0.0 - X === -X
1700       unsigned op1Reg = getReg(Op1, BB, IP);
1701       BuildMI(*BB, IP, PPC::FNEG, 1, DestReg).addReg(op1Reg);
1702       return;
1703     } else {
1704       // R1 = op CST, R2  -->  R1 = opr R2, CST
1705
1706       // Create a constant pool entry for this constant.
1707       MachineConstantPool *CP = F->getConstantPool();
1708       unsigned CPI = CP->getConstantPoolIndex(Op0C);
1709       const Type *Ty = Op0C->getType();
1710       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1711
1712       static const unsigned OpcodeTab[][4] = {
1713         { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS },  // Float
1714         { PPC::FADD,  PPC::FSUB,  PPC::FMUL,  PPC::FDIV },   // Double
1715       };
1716
1717       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1718       unsigned Op0Reg = getReg(Op0C, BB, IP);
1719       unsigned Op1Reg = getReg(Op1, BB, IP);
1720       BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1721       return;
1722     }
1723
1724   // General case.
1725   static const unsigned OpcodeTab[] = {
1726     PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV
1727   };
1728
1729   unsigned Opcode = OpcodeTab[OperatorClass];
1730   unsigned Op0r = getReg(Op0, BB, IP);
1731   unsigned Op1r = getReg(Op1, BB, IP);
1732   BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1733 }
1734
1735 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1736 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1737 /// Or, 4 for Xor.
1738 ///
1739 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1740 /// and constant expression support.
1741 ///
1742 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1743                                      MachineBasicBlock::iterator IP,
1744                                      Value *Op0, Value *Op1,
1745                                      unsigned OperatorClass, unsigned DestReg) {
1746   unsigned Class = getClassB(Op0->getType());
1747
1748   // Arithmetic and Bitwise operators
1749   static const unsigned OpcodeTab[] = {
1750     PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR
1751   };
1752   static const unsigned ImmOpcodeTab[] = {
1753     PPC::ADDI, PPC::SUBI, PPC::ANDIo, PPC::ORI, PPC::XORI
1754   };
1755   static const unsigned RImmOpcodeTab[] = {
1756     PPC::ADDI, PPC::SUBFIC, PPC::ANDIo, PPC::ORI, PPC::XORI
1757   };
1758
1759   if (Class == cFP32 || Class == cFP64) {
1760     assert(OperatorClass < 2 && "No logical ops for FP!");
1761     emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1762     return;
1763   }
1764
1765   if (Op0->getType() == Type::BoolTy) {
1766     if (OperatorClass == 3)
1767       // If this is an or of two isnan's, emit an FP comparison directly instead
1768       // of or'ing two isnan's together.
1769       if (Value *LHS = dyncastIsNan(Op0))
1770         if (Value *RHS = dyncastIsNan(Op1)) {
1771           unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1772           unsigned TmpReg = makeAnotherReg(Type::IntTy);
1773           emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1774           BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
1775           BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1776             .addImm(31).addImm(31);
1777           return;
1778         }
1779   }
1780
1781   // Special case: op <const int>, Reg
1782   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1783     // sub 0, X -> subfic
1784     if (OperatorClass == 1 && canUseAsImmediateForOpcode(CI, 0)) {
1785       unsigned Op1r = getReg(Op1, MBB, IP);
1786       int imm = CI->getRawValue() & 0xFFFF;
1787       BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg).addReg(Op1r).addSImm(imm);
1788       return;
1789     }
1790     
1791     // If it is easy to do, swap the operands and emit an immediate op
1792     if (Class != cLong && OperatorClass != 1 && 
1793         canUseAsImmediateForOpcode(CI, OperatorClass)) {
1794       unsigned Op1r = getReg(Op1, MBB, IP);
1795       int imm = CI->getRawValue() & 0xFFFF;
1796     
1797       if (OperatorClass < 2)
1798         BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1799           .addSImm(imm);
1800       else
1801         BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1802           .addZImm(imm);
1803       return;
1804     }
1805   }
1806
1807   // Special case: op Reg, <const int>
1808   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1809     unsigned Op0r = getReg(Op0, MBB, IP);
1810
1811     // xor X, -1 -> not X
1812     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1813       BuildMI(*MBB, IP, PPC::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1814       return;
1815     }
1816     
1817     if (canUseAsImmediateForOpcode(Op1C, OperatorClass)) {
1818       int immediate = Op1C->getRawValue() & 0xFFFF;
1819       
1820       if (OperatorClass < 2)
1821         BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1822           .addSImm(immediate);
1823       else
1824         BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1825           .addZImm(immediate);
1826     } else {
1827       unsigned Op1r = getReg(Op1, MBB, IP);
1828       BuildMI(*MBB, IP, OpcodeTab[OperatorClass], 2, DestReg).addReg(Op0r)
1829         .addReg(Op1r);
1830     }
1831     return;
1832   }
1833   
1834   // We couldn't generate an immediate variant of the op, load both halves into
1835   // registers and emit the appropriate opcode.
1836   unsigned Op0r = getReg(Op0, MBB, IP);
1837   unsigned Op1r = getReg(Op1, MBB, IP);
1838
1839   unsigned Opcode = OpcodeTab[OperatorClass];
1840   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1841   return;
1842 }
1843
1844 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1845 // returns zero when the input is not exactly a power of two.
1846 static unsigned ExactLog2(unsigned Val) {
1847   if (Val == 0 || (Val & (Val-1))) return 0;
1848   unsigned Count = 0;
1849   while (Val != 1) {
1850     Val >>= 1;
1851     ++Count;
1852   }
1853   return Count;
1854 }
1855
1856 /// doMultiply - Emit appropriate instructions to multiply together the
1857 /// Values Op0 and Op1, and put the result in DestReg.
1858 ///
1859 void ISel::doMultiply(MachineBasicBlock *MBB,
1860                       MachineBasicBlock::iterator IP,
1861                       unsigned DestReg, Value *Op0, Value *Op1) {
1862   unsigned Class0 = getClass(Op0->getType());
1863   unsigned Class1 = getClass(Op1->getType());
1864   
1865   unsigned Op0r = getReg(Op0, MBB, IP);
1866   unsigned Op1r = getReg(Op1, MBB, IP);
1867   
1868   // 64 x 64 -> 64
1869   if (Class0 == cLong && Class1 == cLong) {
1870     BuildMI(*MBB, IP, PPC::MULLD, 2, DestReg).addReg(Op0r).addReg(Op1r);
1871     return;
1872   }
1873   
1874   // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
1875   if (Class0 == cLong && Class1 <= cInt) {
1876     // FIXME: CLEAR or SIGN EXTEND Op1
1877     BuildMI(*MBB, IP, PPC::MULLD, 2, DestReg).addReg(Op0r).addReg(Op1r);
1878     return;
1879   }
1880   
1881   // 32 x 32 -> 32
1882   if (Class0 <= cInt && Class1 <= cInt) {
1883     BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
1884     return;
1885   }
1886   
1887   assert(0 && "doMultiply cannot operate on unknown type!");
1888 }
1889
1890 /// doMultiplyConst - This method will multiply the value in Op0 by the
1891 /// value of the ContantInt *CI
1892 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1893                            MachineBasicBlock::iterator IP,
1894                            unsigned DestReg, Value *Op0, ConstantInt *CI) {
1895   unsigned Class = getClass(Op0->getType());
1896
1897   // Mul op0, 0 ==> 0
1898   if (CI->isNullValue()) {
1899     BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
1900     return;
1901   }
1902   
1903   // Mul op0, 1 ==> op0
1904   if (CI->equalsInt(1)) {
1905     unsigned Op0r = getReg(Op0, MBB, IP);
1906     BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1907     return;
1908   }
1909
1910   // If the element size is exactly a power of 2, use a shift to get it.
1911   if (unsigned Shift = ExactLog2(CI->getRawValue())) {
1912     ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
1913     emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), DestReg);
1914     return;
1915   }
1916   
1917   // If 32 bits or less and immediate is in right range, emit mul by immediate
1918   if (Class == cByte || Class == cShort || Class == cInt) {
1919     if (canUseAsImmediateForOpcode(CI, 0)) {
1920       unsigned Op0r = getReg(Op0, MBB, IP);
1921       unsigned imm = CI->getRawValue() & 0xFFFF;
1922       BuildMI(*MBB, IP, PPC::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
1923       return;
1924     }
1925   }
1926   
1927   doMultiply(MBB, IP, DestReg, Op0, CI);
1928 }
1929
1930 void ISel::visitMul(BinaryOperator &I) {
1931   unsigned ResultReg = getReg(I);
1932
1933   Value *Op0 = I.getOperand(0);
1934   Value *Op1 = I.getOperand(1);
1935
1936   MachineBasicBlock::iterator IP = BB->end();
1937   emitMultiply(BB, IP, Op0, Op1, ResultReg);
1938 }
1939
1940 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1941                         Value *Op0, Value *Op1, unsigned DestReg) {
1942   TypeClass Class = getClass(Op0->getType());
1943
1944   switch (Class) {
1945   case cByte:
1946   case cShort:
1947   case cInt:
1948   case cLong:
1949     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1950       doMultiplyConst(MBB, IP, DestReg, Op0, CI);
1951     } else {
1952       doMultiply(MBB, IP, DestReg, Op0, Op1);
1953     }
1954     return;
1955   case cFP32:
1956   case cFP64:
1957     emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1958     return;
1959     break;
1960   }
1961 }
1962
1963
1964 /// visitDivRem - Handle division and remainder instructions... these
1965 /// instruction both require the same instructions to be generated, they just
1966 /// select the result from a different register.  Note that both of these
1967 /// instructions work differently for signed and unsigned operands.
1968 ///
1969 void ISel::visitDivRem(BinaryOperator &I) {
1970   unsigned ResultReg = getReg(I);
1971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1972
1973   MachineBasicBlock::iterator IP = BB->end();
1974   emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
1975                       ResultReg);
1976 }
1977
1978 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1979                                MachineBasicBlock::iterator IP,
1980                                Value *Op0, Value *Op1, bool isDiv,
1981                                unsigned ResultReg) {
1982   const Type *Ty = Op0->getType();
1983   unsigned Class = getClass(Ty);
1984   switch (Class) {
1985   case cFP32:
1986     if (isDiv) {
1987       // Floating point divide...
1988       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
1989       return;
1990     } else {
1991       // Floating point remainder via fmodf(float x, float y);
1992       unsigned Op0Reg = getReg(Op0, BB, IP);
1993       unsigned Op1Reg = getReg(Op1, BB, IP);
1994       MachineInstr *TheCall =
1995         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
1996       std::vector<ValueRecord> Args;
1997       Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
1998       Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
1999       doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2000       TM.CalledFunctions.insert(fmodfFn);
2001     }
2002     return;
2003   case cFP64:
2004     if (isDiv) {
2005       // Floating point divide...
2006       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2007       return;
2008     } else {               
2009       // Floating point remainder via fmod(double x, double y);
2010       unsigned Op0Reg = getReg(Op0, BB, IP);
2011       unsigned Op1Reg = getReg(Op1, BB, IP);
2012       MachineInstr *TheCall =
2013         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2014       std::vector<ValueRecord> Args;
2015       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2016       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2017       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2018       TM.CalledFunctions.insert(fmodFn);
2019     }
2020     return;
2021   case cLong: {
2022     static Function* const Funcs[] =
2023       { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2024     unsigned Op0Reg = getReg(Op0, BB, IP);
2025     unsigned Op1Reg = getReg(Op1, BB, IP);
2026     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2027     MachineInstr *TheCall =
2028       BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2029
2030     std::vector<ValueRecord> Args;
2031     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2032     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2033     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2034     TM.CalledFunctions.insert(Funcs[NameIdx]);
2035     return;
2036   }
2037   case cByte: case cShort: case cInt:
2038     break;          // Small integrals, handled below...
2039   default: assert(0 && "Unknown class!");
2040   }
2041
2042   // Special case signed division by power of 2.
2043   if (isDiv)
2044     if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2045       assert(Class != cLong && "This doesn't handle 64-bit divides!");
2046       int V = CI->getValue();
2047
2048       if (V == 1) {       // X /s 1 => X
2049         unsigned Op0Reg = getReg(Op0, BB, IP);
2050         BuildMI(*BB, IP, PPC::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2051         return;
2052       }
2053
2054       if (V == -1) {      // X /s -1 => -X
2055         unsigned Op0Reg = getReg(Op0, BB, IP);
2056         BuildMI(*BB, IP, PPC::NEG, 1, ResultReg).addReg(Op0Reg);
2057         return;
2058       }
2059
2060       unsigned log2V = ExactLog2(V);
2061       if (log2V != 0 && Ty->isSigned()) {
2062         unsigned Op0Reg = getReg(Op0, BB, IP);
2063         unsigned TmpReg = makeAnotherReg(Op0->getType());
2064         
2065         BuildMI(*BB, IP, PPC::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2066         BuildMI(*BB, IP, PPC::ADDZE, 1, ResultReg).addReg(TmpReg);
2067         return;
2068       }
2069     }
2070
2071   unsigned Op0Reg = getReg(Op0, BB, IP);
2072   unsigned Op1Reg = getReg(Op1, BB, IP);
2073   unsigned Opcode = Ty->isSigned() ? PPC::DIVW : PPC::DIVWU;
2074   
2075   if (isDiv) {
2076     BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2077   } else { // Remainder
2078     unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2079     unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2080     
2081     BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2082     BuildMI(*BB, IP, PPC::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2083     BuildMI(*BB, IP, PPC::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2084   }
2085 }
2086
2087
2088 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2089 /// for constant immediate shift values, and for constant immediate
2090 /// shift values equal to 1. Even the general case is sort of special,
2091 /// because the shift amount has to be in CL, not just any old register.
2092 ///
2093 void ISel::visitShiftInst(ShiftInst &I) {
2094   MachineBasicBlock::iterator IP = BB->end();
2095   emitShiftOperation(BB, IP, I.getOperand(0), I.getOperand(1),
2096                      I.getOpcode() == Instruction::Shl, I.getType(),
2097                      getReg(I));
2098 }
2099
2100 /// emitShiftOperation - Common code shared between visitShiftInst and
2101 /// constant expression support.
2102 ///
2103 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2104                               MachineBasicBlock::iterator IP,
2105                               Value *Op, Value *ShiftAmount, bool isLeftShift,
2106                               const Type *ResultTy, unsigned DestReg) {
2107   unsigned SrcReg = getReg (Op, MBB, IP);
2108   bool isSigned = ResultTy->isSigned ();
2109   unsigned Class = getClass (ResultTy);
2110   
2111   // Longs, as usual, are handled specially...
2112   if (Class == cLong) {
2113     // If we have a constant shift, we can generate much more efficient code
2114     // than otherwise...
2115     //
2116     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2117       unsigned Amount = CUI->getValue();
2118       assert(Amount < 64 && "Invalid immediate shift amount!");
2119       if (isLeftShift) {
2120         BuildMI(*MBB, IP, PPC::RLDICR, 3, DestReg).addReg(SrcReg).addImm(Amount)
2121           .addImm(63-Amount);
2122       } else {
2123         if (isSigned) {
2124           BuildMI(*MBB, IP, PPC::SRADI, 2, DestReg).addReg(SrcReg)
2125             .addImm(Amount);
2126         } else {
2127           BuildMI(*MBB, IP, PPC::RLDICL, 3, DestReg).addReg(SrcReg)
2128             .addImm(64-Amount).addImm(Amount);
2129         }
2130       }
2131     } else {
2132       unsigned ShiftReg = getReg (ShiftAmount, MBB, IP);
2133
2134       if (isLeftShift) {
2135         BuildMI(*MBB, IP, PPC::SLD, 2, DestReg).addReg(SrcReg).addReg(ShiftReg);
2136       } else {
2137         unsigned Opcode = (isSigned) ? PPC::SRAD : PPC::SRD;
2138         BuildMI(*MBB, IP, Opcode, DestReg).addReg(SrcReg).addReg(ShiftReg);
2139       }
2140     }
2141     return;
2142   }
2143
2144   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2145     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2146     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2147     unsigned Amount = CUI->getValue();
2148
2149     if (isLeftShift) {
2150       BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2151         .addImm(Amount).addImm(0).addImm(31-Amount);
2152     } else {
2153       if (isSigned) {
2154         BuildMI(*MBB, IP, PPC::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2155       } else {
2156         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2157           .addImm(32-Amount).addImm(Amount).addImm(31);
2158       }
2159     }
2160   } else {                  // The shift amount is non-constant.
2161     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2162
2163     if (isLeftShift) {
2164       BuildMI(*MBB, IP, PPC::SLW, 2, DestReg).addReg(SrcReg)
2165         .addReg(ShiftAmountReg);
2166     } else {
2167       BuildMI(*MBB, IP, isSigned ? PPC::SRAW : PPC::SRW, 2, DestReg)
2168         .addReg(SrcReg).addReg(ShiftAmountReg);
2169     }
2170   }
2171 }
2172
2173
2174 /// visitLoadInst - Implement LLVM load instructions.  Pretty straightforward
2175 /// mapping of LLVM classes to PPC load instructions, with the exception of
2176 /// signed byte loads, which need a sign extension following them.
2177 ///
2178 void ISel::visitLoadInst(LoadInst &I) {
2179   // Immediate opcodes, for reg+imm addressing
2180   static const unsigned ImmOpcodes[] = { 
2181     PPC::LBZ, PPC::LHZ, PPC::LWZ, 
2182     PPC::LFS, PPC::LFD, PPC::LWZ
2183   };
2184   // Indexed opcodes, for reg+reg addressing
2185   static const unsigned IdxOpcodes[] = {
2186     PPC::LBZX, PPC::LHZX, PPC::LWZX,
2187     PPC::LFSX, PPC::LFDX, PPC::LWZX
2188   };
2189
2190   unsigned Class     = getClassB(I.getType());
2191   unsigned ImmOpcode = ImmOpcodes[Class];
2192   unsigned IdxOpcode = IdxOpcodes[Class];
2193   unsigned DestReg   = getReg(I);
2194   Value *SourceAddr  = I.getOperand(0);
2195   
2196   if (Class == cShort && I.getType()->isSigned()) ImmOpcode = PPC::LHA;
2197   if (Class == cShort && I.getType()->isSigned()) IdxOpcode = PPC::LHAX;
2198
2199   if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
2200     unsigned FI = getFixedSizedAllocaFI(AI);
2201     if (Class == cByte && I.getType()->isSigned()) {
2202       unsigned TmpReg = makeAnotherReg(I.getType());
2203       addFrameReference(BuildMI(BB, ImmOpcode, 2, TmpReg), FI);
2204       BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2205     } else {
2206       addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2207     }
2208     return;
2209   }
2210   
2211   // If this load is the only use of the GEP instruction that is its address,
2212   // then we can fold the GEP directly into the load instruction.
2213   // emitGEPOperation with a second to last arg of 'true' will place the
2214   // base register for the GEP into baseReg, and the constant offset from that
2215   // into offset.  If the offset fits in 16 bits, we can emit a reg+imm store
2216   // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2217   if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2218     unsigned baseReg = getReg(GEPI);
2219     unsigned pendingAdd;
2220     ConstantSInt *offset;
2221     
2222     emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1, 
2223                      GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2224
2225     if (pendingAdd == 0 && Class != cLong && 
2226         canUseAsImmediateForOpcode(offset, 0)) {
2227       if (Class == cByte && I.getType()->isSigned()) {
2228         unsigned TmpReg = makeAnotherReg(I.getType());
2229         BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(offset->getValue())
2230           .addReg(baseReg);
2231         BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2232       } else {
2233         BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(offset->getValue())
2234           .addReg(baseReg);
2235       }
2236       return;
2237     }
2238     
2239     unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2240
2241     if (Class == cByte && I.getType()->isSigned()) {
2242       unsigned TmpReg = makeAnotherReg(I.getType());
2243       BuildMI(BB, IdxOpcode, 2, TmpReg).addReg(indexReg).addReg(baseReg);
2244       BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2245     } else {
2246       BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2247     }
2248     return;
2249   }
2250   
2251   // The fallback case, where the load was from a source that could not be
2252   // folded into the load instruction. 
2253   unsigned SrcAddrReg = getReg(SourceAddr);
2254     
2255   if (Class == cByte && I.getType()->isSigned()) {
2256     unsigned TmpReg = makeAnotherReg(I.getType());
2257     BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
2258     BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2259   } else {
2260     BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2261   }
2262 }
2263
2264 /// visitStoreInst - Implement LLVM store instructions
2265 ///
2266 void ISel::visitStoreInst(StoreInst &I) {
2267   // Immediate opcodes, for reg+imm addressing
2268   static const unsigned ImmOpcodes[] = {
2269     PPC::STB, PPC::STH, PPC::STW, 
2270     PPC::STFS, PPC::STFD, PPC::STW
2271   };
2272   // Indexed opcodes, for reg+reg addressing
2273   static const unsigned IdxOpcodes[] = {
2274     PPC::STBX, PPC::STHX, PPC::STWX, 
2275     PPC::STFSX, PPC::STFDX, PPC::STWX
2276   };
2277   
2278   Value *SourceAddr  = I.getOperand(1);
2279   const Type *ValTy  = I.getOperand(0)->getType();
2280   unsigned Class     = getClassB(ValTy);
2281   unsigned ImmOpcode = ImmOpcodes[Class];
2282   unsigned IdxOpcode = IdxOpcodes[Class];
2283   unsigned ValReg    = getReg(I.getOperand(0));
2284
2285   // If this store is the only use of the GEP instruction that is its address,
2286   // then we can fold the GEP directly into the store instruction.
2287   // emitGEPOperation with a second to last arg of 'true' will place the
2288   // base register for the GEP into baseReg, and the constant offset from that
2289   // into offset.  If the offset fits in 16 bits, we can emit a reg+imm store
2290   // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2291   if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2292     unsigned baseReg = getReg(GEPI);
2293     unsigned pendingAdd;
2294     ConstantSInt *offset;
2295     
2296     emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1, 
2297                      GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2298
2299     if (0 == pendingAdd && Class != cLong && 
2300         canUseAsImmediateForOpcode(offset, 0)) {
2301       BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(offset->getValue())
2302         .addReg(baseReg);
2303       return;
2304     }
2305     
2306     unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2307     BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2308     return;
2309   }
2310   
2311   // If the store address wasn't the only use of a GEP, we fall back to the
2312   // standard path: store the ValReg at the value in AddressReg.
2313   unsigned AddressReg  = getReg(I.getOperand(1));
2314   BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2315 }
2316
2317
2318 /// visitCastInst - Here we have various kinds of copying with or without sign
2319 /// extension going on.
2320 ///
2321 void ISel::visitCastInst(CastInst &CI) {
2322   Value *Op = CI.getOperand(0);
2323
2324   unsigned SrcClass = getClassB(Op->getType());
2325   unsigned DestClass = getClassB(CI.getType());
2326
2327   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2328   // of the case are GEP instructions, then the cast does not need to be
2329   // generated explicitly, it will be folded into the GEP.
2330   if (DestClass == cLong && SrcClass == cInt) {
2331     bool AllUsesAreGEPs = true;
2332     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2333       if (!isa<GetElementPtrInst>(*I)) {
2334         AllUsesAreGEPs = false;
2335         break;
2336       }        
2337
2338     // No need to codegen this cast if all users are getelementptr instrs...
2339     if (AllUsesAreGEPs) return;
2340   }
2341
2342   unsigned DestReg = getReg(CI);
2343   MachineBasicBlock::iterator MI = BB->end();
2344   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2345 }
2346
2347 /// emitCastOperation - Common code shared between visitCastInst and constant
2348 /// expression cast support.
2349 ///
2350 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2351                              MachineBasicBlock::iterator IP,
2352                              Value *Src, const Type *DestTy,
2353                              unsigned DestReg) {
2354   const Type *SrcTy = Src->getType();
2355   unsigned SrcClass = getClassB(SrcTy);
2356   unsigned DestClass = getClassB(DestTy);
2357   unsigned SrcReg = getReg(Src, MBB, IP);
2358
2359   // Implement casts to bool by using compare on the operand followed by set if
2360   // not zero on the result.
2361   if (DestTy == Type::BoolTy) {
2362     switch (SrcClass) {
2363     case cByte:
2364     case cShort:
2365     case cInt:
2366     case cLong: {
2367       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2368       BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
2369       BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2370       break;
2371     }
2372     case cFP32:
2373     case cFP64:
2374       // FSEL perhaps?
2375       std::cerr << "ERROR: Cast fp-to-bool not implemented!\n";
2376       abort();
2377     }
2378     return;
2379   }
2380
2381   // Handle cast of Float -> Double
2382   if (SrcClass == cFP32 && DestClass == cFP64) {
2383     BuildMI(*MBB, IP, PPC::FMR, 1, DestReg).addReg(SrcReg);
2384     return;
2385   }
2386   
2387   // Handle cast of Double -> Float
2388   if (SrcClass == cFP64 && DestClass == cFP32) {
2389     BuildMI(*MBB, IP, PPC::FRSP, 1, DestReg).addReg(SrcReg);
2390     return;
2391   }
2392   
2393   // Handle casts from integer to floating point now...
2394   if (DestClass == cFP32 || DestClass == cFP64) {
2395
2396     // Emit a library call for long to float conversion
2397     if (SrcClass == cLong) {
2398       std::vector<ValueRecord> Args;
2399       Args.push_back(ValueRecord(SrcReg, SrcTy));
2400       Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2401       MachineInstr *TheCall =
2402         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2403       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2404       TM.CalledFunctions.insert(floatFn);
2405       return;
2406     }
2407     
2408     // Make sure we're dealing with a full 32 bits
2409     unsigned TmpReg = makeAnotherReg(Type::IntTy);
2410     promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2411
2412     SrcReg = TmpReg;
2413     
2414     // Spill the integer to memory and reload it from there.
2415     // Also spill room for a special conversion constant
2416     int ConstantFrameIndex = 
2417       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2418     int ValueFrameIdx =
2419       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2420
2421     unsigned constantHi = makeAnotherReg(Type::IntTy);
2422     unsigned constantLo = makeAnotherReg(Type::IntTy);
2423     unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2424     unsigned TempF = makeAnotherReg(Type::DoubleTy);
2425     
2426     if (!SrcTy->isSigned()) {
2427       BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2428       BuildMI(*BB, IP, PPC::LI, 1, constantLo).addSImm(0);
2429       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2430                         ConstantFrameIndex);
2431       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo), 
2432                         ConstantFrameIndex, 4);
2433       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2434                         ValueFrameIdx);
2435       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(SrcReg), 
2436                         ValueFrameIdx, 4);
2437       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF), 
2438                         ConstantFrameIndex);
2439       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2440       BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2441     } else {
2442       unsigned TempLo = makeAnotherReg(Type::IntTy);
2443       BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2444       BuildMI(*BB, IP, PPC::LIS, 1, constantLo).addSImm(0x8000);
2445       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2446                         ConstantFrameIndex);
2447       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo), 
2448                         ConstantFrameIndex, 4);
2449       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2450                         ValueFrameIdx);
2451       BuildMI(*BB, IP, PPC::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2452       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(TempLo), 
2453                         ValueFrameIdx, 4);
2454       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF), 
2455                         ConstantFrameIndex);
2456       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2457       BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2458     }
2459     return;
2460   }
2461
2462   // Handle casts from floating point to integer now...
2463   if (SrcClass == cFP32 || SrcClass == cFP64) {
2464     static Function* const Funcs[] =
2465       { __fixsfdiFn, __fixdfdiFn, __fixunssfdiFn, __fixunsdfdiFn };
2466     // emit library call
2467     if (DestClass == cLong) {
2468       bool isDouble = SrcClass == cFP64;
2469       unsigned nameIndex = 2 * DestTy->isSigned() + isDouble;
2470       std::vector<ValueRecord> Args;
2471       Args.push_back(ValueRecord(SrcReg, SrcTy));
2472       Function *floatFn = Funcs[nameIndex];
2473       MachineInstr *TheCall =
2474         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2475       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2476       TM.CalledFunctions.insert(floatFn);
2477       return;
2478     }
2479
2480     int ValueFrameIdx =
2481       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2482
2483     if (DestTy->isSigned()) {
2484       unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2485       
2486       // Convert to integer in the FP reg and store it to a stack slot
2487       BuildMI(*BB, IP, PPC::FCTIWZ, 1, TempReg).addReg(SrcReg);
2488       addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3)
2489                           .addReg(TempReg), ValueFrameIdx);
2490
2491       // There is no load signed byte opcode, so we must emit a sign extend for
2492       // that particular size.  Make sure to source the new integer from the 
2493       // correct offset.
2494       if (DestClass == cByte) {
2495         unsigned TempReg2 = makeAnotherReg(DestTy);
2496         addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, TempReg2), 
2497                           ValueFrameIdx, 7);
2498         BuildMI(*MBB, IP, PPC::EXTSB, DestReg).addReg(TempReg2);
2499       } else {
2500         int offset = (DestClass == cShort) ? 6 : 4;
2501         unsigned LoadOp = (DestClass == cShort) ? PPC::LHA : PPC::LWZ;
2502         addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg), 
2503                           ValueFrameIdx, offset);
2504       }
2505     } else {
2506       unsigned Zero = getReg(ConstantFP::get(Type::DoubleTy, 0.0f));
2507       double maxInt = (1LL << 32) - 1;
2508       unsigned MaxInt = getReg(ConstantFP::get(Type::DoubleTy, maxInt));
2509       double border = 1LL << 31;
2510       unsigned Border = getReg(ConstantFP::get(Type::DoubleTy, border));
2511       unsigned UseZero = makeAnotherReg(Type::DoubleTy);
2512       unsigned UseMaxInt = makeAnotherReg(Type::DoubleTy);
2513       unsigned UseChoice = makeAnotherReg(Type::DoubleTy);
2514       unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
2515       unsigned TmpReg2 = makeAnotherReg(Type::DoubleTy);
2516       unsigned ConvReg = makeAnotherReg(Type::DoubleTy);
2517       unsigned IntTmp = makeAnotherReg(Type::IntTy);
2518       unsigned XorReg = makeAnotherReg(Type::IntTy);
2519       int FrameIdx = 
2520         F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2521       // Update machine-CFG edges
2522       MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2523       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2524       MachineBasicBlock *OldMBB = BB;
2525       ilist<MachineBasicBlock>::iterator It = BB; ++It;
2526       F->getBasicBlockList().insert(It, XorMBB);
2527       F->getBasicBlockList().insert(It, PhiMBB);
2528       BB->addSuccessor(XorMBB);
2529       BB->addSuccessor(PhiMBB);
2530
2531       // Convert from floating point to unsigned 32-bit value
2532       // Use 0 if incoming value is < 0.0
2533       BuildMI(*BB, IP, PPC::FSEL, 3, UseZero).addReg(SrcReg).addReg(SrcReg)
2534         .addReg(Zero);
2535       // Use 2**32 - 1 if incoming value is >= 2**32
2536       BuildMI(*BB, IP, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(SrcReg);
2537       BuildMI(*BB, IP, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt)
2538         .addReg(UseZero).addReg(MaxInt);
2539       // Subtract 2**31
2540       BuildMI(*BB, IP, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2541       // Use difference if >= 2**31
2542       BuildMI(*BB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice)
2543         .addReg(Border);
2544       BuildMI(*BB, IP, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2545         .addReg(UseChoice);
2546       // Convert to integer
2547       BuildMI(*BB, IP, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2548       addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3).addReg(ConvReg),
2549                         FrameIdx);
2550       if (DestClass == cByte) {
2551         addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, DestReg),
2552                           FrameIdx, 7);
2553       } else if (DestClass == cShort) {
2554         addFrameReference(BuildMI(*BB, IP, PPC::LHZ, 2, DestReg),
2555                           FrameIdx, 6);
2556       } if (DestClass == cInt) {
2557         addFrameReference(BuildMI(*BB, IP, PPC::LWZ, 2, IntTmp),
2558                           FrameIdx, 4);
2559         BuildMI(*BB, IP, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2560         BuildMI(*BB, IP, PPC::B, 1).addMBB(XorMBB);
2561
2562         // XorMBB:
2563         //   add 2**31 if input was >= 2**31
2564         BB = XorMBB;
2565         BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2566         XorMBB->addSuccessor(PhiMBB);
2567
2568         // PhiMBB:
2569         //   DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2570         BB = PhiMBB;
2571         BuildMI(BB, PPC::PHI, 2, DestReg).addReg(IntTmp).addMBB(OldMBB)
2572           .addReg(XorReg).addMBB(XorMBB);
2573       }
2574     }
2575     return;
2576   }
2577
2578   // Check our invariants
2579   assert((SrcClass <= cInt || SrcClass == cLong) && 
2580          "Unhandled source class for cast operation!");
2581   assert((DestClass <= cInt || DestClass == cLong) && 
2582          "Unhandled destination class for cast operation!");
2583
2584   bool sourceUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2585   bool destUnsigned = DestTy->isUnsigned();
2586
2587   // Unsigned -> Unsigned, clear if larger
2588   if (sourceUnsigned && destUnsigned) {
2589     // handle long dest class now to keep switch clean
2590     if (DestClass == cLong) {
2591       BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2592       return;
2593     }
2594
2595     // handle u{ byte, short, int } x u{ byte, short, int }
2596     unsigned clearBits = (SrcClass == cByte || DestClass == cByte) ? 24 : 16;
2597     switch (SrcClass) {
2598     case cByte:
2599     case cShort:
2600       if (SrcClass == DestClass)
2601         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2602       else
2603         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2604           .addImm(0).addImm(clearBits).addImm(31);
2605       break;
2606     case cLong:
2607       ++SrcReg;
2608       // Fall through
2609     case cInt:
2610       if (DestClass == cInt)
2611         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2612       else
2613         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2614           .addImm(0).addImm(clearBits).addImm(31);
2615       break;
2616     }
2617     return;
2618   }
2619
2620   // Signed -> Signed
2621   if (!sourceUnsigned && !destUnsigned) {
2622     // handle long dest class now to keep switch clean
2623     if (DestClass == cLong) {
2624       BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2625       return;
2626     }
2627
2628     // handle { byte, short, int } x { byte, short, int }
2629     switch (SrcClass) {
2630     case cByte:
2631       if (DestClass == cByte)
2632         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2633       else
2634         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2635       break;
2636     case cShort:
2637       if (DestClass == cByte)
2638         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2639       else if (DestClass == cShort)
2640         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2641       else
2642         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2643       break;
2644     case cLong:
2645       ++SrcReg;
2646       // Fall through
2647     case cInt:
2648       if (DestClass == cByte)
2649         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2650       else if (DestClass == cShort)
2651         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2652       else
2653         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2654       break;
2655     }
2656     return;
2657   }
2658
2659   // Unsigned -> Signed
2660   if (sourceUnsigned && !destUnsigned) {
2661     // handle long dest class now to keep switch clean
2662     if (DestClass == cLong) {
2663       BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2664       return;
2665     }
2666
2667     // handle u{ byte, short, int } -> { byte, short, int }
2668     switch (SrcClass) {
2669     case cByte:
2670       if (DestClass == cByte)
2671         // uByte 255 -> signed byte == -1
2672         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2673       else
2674         // uByte 255 -> signed short/int == 255
2675         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
2676           .addImm(24).addImm(31);
2677       break;
2678     case cShort:
2679       if (DestClass == cByte)
2680         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2681       else if (DestClass == cShort)
2682         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2683       else
2684         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
2685           .addImm(16).addImm(31);
2686       break;
2687     case cLong:
2688       ++SrcReg;
2689       // Fall through
2690     case cInt:
2691       if (DestClass == cByte)
2692         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2693       else if (DestClass == cShort)
2694         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2695       else
2696         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2697       break;
2698     }
2699     return;
2700   }
2701
2702   // Signed -> Unsigned
2703   if (!sourceUnsigned && destUnsigned) {
2704     // handle long dest class now to keep switch clean
2705     if (DestClass == cLong) {
2706       BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2707       return;
2708     }
2709
2710     // handle { byte, short, int } -> u{ byte, short, int }
2711     unsigned clearBits = (DestClass == cByte) ? 24 : 16;
2712     switch (SrcClass) {
2713     case cByte:
2714     case cShort:
2715       if (DestClass == cByte || DestClass == cShort)
2716         // sbyte -1 -> ubyte 0x000000FF
2717         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2718           .addImm(0).addImm(clearBits).addImm(31);
2719       else
2720         // sbyte -1 -> ubyte 0xFFFFFFFF
2721         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2722       break;
2723     case cLong:
2724       ++SrcReg;
2725       // Fall through
2726     case cInt:
2727       if (DestClass == cInt)
2728         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2729       else
2730         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2731           .addImm(0).addImm(clearBits).addImm(31);
2732       break;
2733     }
2734     return;
2735   }
2736
2737   // Anything we haven't handled already, we can't (yet) handle at all.
2738   std::cerr << "Unhandled cast from " << SrcTy->getDescription()
2739             << "to " << DestTy->getDescription() << '\n';
2740   abort();
2741 }
2742
2743 /// visitVANextInst - Implement the va_next instruction...
2744 ///
2745 void ISel::visitVANextInst(VANextInst &I) {
2746   unsigned VAList = getReg(I.getOperand(0));
2747   unsigned DestReg = getReg(I);
2748
2749   unsigned Size;
2750   switch (I.getArgType()->getTypeID()) {
2751   default:
2752     std::cerr << I;
2753     assert(0 && "Error: bad type for va_next instruction!");
2754     return;
2755   case Type::PointerTyID:
2756   case Type::UIntTyID:
2757   case Type::IntTyID:
2758     Size = 4;
2759     break;
2760   case Type::ULongTyID:
2761   case Type::LongTyID:
2762   case Type::DoubleTyID:
2763     Size = 8;
2764     break;
2765   }
2766
2767   // Increment the VAList pointer...
2768   BuildMI(BB, PPC::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
2769 }
2770
2771 void ISel::visitVAArgInst(VAArgInst &I) {
2772   unsigned VAList = getReg(I.getOperand(0));
2773   unsigned DestReg = getReg(I);
2774
2775   switch (I.getType()->getTypeID()) {
2776   default:
2777     std::cerr << I;
2778     assert(0 && "Error: bad type for va_next instruction!");
2779     return;
2780   case Type::PointerTyID:
2781   case Type::UIntTyID:
2782   case Type::IntTyID:
2783     BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
2784     break;
2785   case Type::ULongTyID:
2786   case Type::LongTyID:
2787     BuildMI(BB, PPC::LD, 2, DestReg).addSImm(0).addReg(VAList);
2788     break;
2789   case Type::FloatTyID:
2790     BuildMI(BB, PPC::LFS, 2, DestReg).addSImm(0).addReg(VAList);
2791     break;
2792   case Type::DoubleTyID:
2793     BuildMI(BB, PPC::LFD, 2, DestReg).addSImm(0).addReg(VAList);
2794     break;
2795   }
2796 }
2797
2798 /// visitGetElementPtrInst - instruction-select GEP instructions
2799 ///
2800 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2801   if (canFoldGEPIntoLoadOrStore(&I))
2802     return;
2803
2804   unsigned outputReg = getReg(I);
2805   emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(), 
2806                    outputReg, false, 0, 0);
2807 }
2808
2809 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
2810 /// constant expression GEP support.
2811 ///
2812 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2813                             MachineBasicBlock::iterator IP,
2814                             Value *Src, User::op_iterator IdxBegin,
2815                             User::op_iterator IdxEnd, unsigned TargetReg,
2816                             bool GEPIsFolded, ConstantSInt **RemainderPtr,
2817                             unsigned *PendingAddReg) {
2818   const TargetData &TD = TM.getTargetData();
2819   const Type *Ty = Src->getType();
2820   unsigned basePtrReg = getReg(Src, MBB, IP);
2821   int64_t constValue = 0;
2822   
2823   // Record the operations to emit the GEP in a vector so that we can emit them
2824   // after having analyzed the entire instruction.
2825   std::vector<CollapsedGepOp> ops;
2826   
2827   // GEPs have zero or more indices; we must perform a struct access
2828   // or array access for each one.
2829   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
2830        ++oi) {
2831     Value *idx = *oi;
2832     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2833       // It's a struct access.  idx is the index into the structure,
2834       // which names the field. Use the TargetData structure to
2835       // pick out what the layout of the structure is in memory.
2836       // Use the (constant) structure index's value to find the
2837       // right byte offset from the StructLayout class's list of
2838       // structure member offsets.
2839       unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
2840       unsigned memberOffset =
2841         TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
2842
2843       // StructType member offsets are always constant values.  Add it to the
2844       // running total.
2845       constValue += memberOffset;
2846
2847       // The next type is the member of the structure selected by the
2848       // index.
2849       Ty = StTy->getElementType (fieldIndex);
2850     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
2851       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2852       // operand.  Handle this case directly now...
2853       if (CastInst *CI = dyn_cast<CastInst>(idx))
2854         if (CI->getOperand(0)->getType() == Type::IntTy ||
2855             CI->getOperand(0)->getType() == Type::UIntTy)
2856           idx = CI->getOperand(0);
2857
2858       // It's an array or pointer access: [ArraySize x ElementType].
2859       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
2860       // must find the size of the pointed-to type (Not coincidentally, the next
2861       // type is the type of the elements in the array).
2862       Ty = SqTy->getElementType();
2863       unsigned elementSize = TD.getTypeSize(Ty);
2864       
2865       if (ConstantInt *C = dyn_cast<ConstantInt>(idx)) {
2866         if (ConstantSInt *CS = dyn_cast<ConstantSInt>(C))
2867           constValue += CS->getValue() * elementSize;
2868         else if (ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2869           constValue += CU->getValue() * elementSize;
2870         else
2871           assert(0 && "Invalid ConstantInt GEP index type!");
2872       } else {
2873         // Push current gep state to this point as an add
2874         ops.push_back(CollapsedGepOp(false, 0, 
2875           ConstantSInt::get(Type::IntTy,constValue)));
2876         
2877         // Push multiply gep op and reset constant value
2878         ops.push_back(CollapsedGepOp(true, idx, 
2879           ConstantSInt::get(Type::IntTy, elementSize)));
2880         
2881         constValue = 0;
2882       }
2883     }
2884   }
2885   // Emit instructions for all the collapsed ops
2886   bool pendingAdd = false;
2887   unsigned pendingAddReg = 0;
2888   
2889   for(std::vector<CollapsedGepOp>::iterator cgo_i = ops.begin(),
2890       cgo_e = ops.end(); cgo_i != cgo_e; ++cgo_i) {
2891     CollapsedGepOp& cgo = *cgo_i;
2892     unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
2893   
2894     // If we didn't emit an add last time through the loop, we need to now so
2895     // that the base reg is updated appropriately.
2896     if (pendingAdd) {
2897       assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
2898       BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2899         .addReg(pendingAddReg);
2900       basePtrReg = nextBasePtrReg;
2901       nextBasePtrReg = makeAnotherReg(Type::IntTy);
2902       pendingAddReg = 0;
2903       pendingAdd = false;
2904     }
2905
2906     if (cgo.isMul) {
2907       // We know the elementSize is a constant, so we can emit a constant mul
2908       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2909       doMultiplyConst(MBB, IP, nextBasePtrReg, cgo.index, cgo.size);
2910       pendingAddReg = basePtrReg;
2911       pendingAdd = true;
2912     } else {
2913       // Try and generate an immediate addition if possible
2914       if (cgo.size->isNullValue()) {
2915         BuildMI(*MBB, IP, PPC::OR, 2, nextBasePtrReg).addReg(basePtrReg)
2916           .addReg(basePtrReg);
2917       } else if (canUseAsImmediateForOpcode(cgo.size, 0)) {
2918         BuildMI(*MBB, IP, PPC::ADDI, 2, nextBasePtrReg).addReg(basePtrReg)
2919           .addSImm(cgo.size->getValue());
2920       } else {
2921         unsigned Op1r = getReg(cgo.size, MBB, IP);
2922         BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2923           .addReg(Op1r);
2924       }
2925     }
2926
2927     basePtrReg = nextBasePtrReg;
2928   }
2929   // Add the current base register plus any accumulated constant value
2930   ConstantSInt *remainder = ConstantSInt::get(Type::IntTy, constValue);
2931   
2932   // If we are emitting this during a fold, copy the current base register to
2933   // the target, and save the current constant offset so the folding load or
2934   // store can try and use it as an immediate.
2935   if (GEPIsFolded) {
2936     // If this is a folded GEP and the last element was an index, then we need
2937     // to do some extra work to turn a shift/add/stw into a shift/stwx
2938     if (pendingAdd && 0 == remainder->getValue()) {
2939       assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
2940       *PendingAddReg = pendingAddReg;
2941     } else {
2942       *PendingAddReg = 0;
2943       if (pendingAdd) {
2944         unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
2945         assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
2946         BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2947           .addReg(pendingAddReg);
2948         basePtrReg = nextBasePtrReg;
2949       }
2950     }
2951     BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
2952       .addReg(basePtrReg);
2953     *RemainderPtr = remainder;
2954     return;
2955   }
2956
2957   // If we still have a pending add at this point, emit it now
2958   if (pendingAdd) {
2959     unsigned TmpReg = makeAnotherReg(Type::IntTy);
2960     BuildMI(*MBB, IP, PPC::ADD, 2, TmpReg).addReg(pendingAddReg)
2961       .addReg(basePtrReg);
2962     basePtrReg = TmpReg;
2963   }
2964   
2965   // After we have processed all the indices, the result is left in
2966   // basePtrReg.  Move it to the register where we were expected to
2967   // put the answer.
2968   if (remainder->isNullValue()) {
2969     BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
2970       .addReg(basePtrReg);
2971   } else if (canUseAsImmediateForOpcode(remainder, 0)) {
2972     BuildMI(*MBB, IP, PPC::ADDI, 2, TargetReg).addReg(basePtrReg)
2973       .addSImm(remainder->getValue());
2974   } else {
2975     unsigned Op1r = getReg(remainder, MBB, IP);
2976     BuildMI(*MBB, IP, PPC::ADD, 2, TargetReg).addReg(basePtrReg).addReg(Op1r);
2977   }
2978 }
2979
2980 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2981 /// frame manager, otherwise do it the hard way.
2982 ///
2983 void ISel::visitAllocaInst(AllocaInst &I) {
2984   // If this is a fixed size alloca in the entry block for the function, we
2985   // statically stack allocate the space, so we don't need to do anything here.
2986   //
2987   if (dyn_castFixedAlloca(&I)) return;
2988   
2989   // Find the data size of the alloca inst's getAllocatedType.
2990   const Type *Ty = I.getAllocatedType();
2991   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2992
2993   // Create a register to hold the temporary result of multiplying the type size
2994   // constant by the variable amount.
2995   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2996   
2997   // TotalSizeReg = mul <numelements>, <TypeSize>
2998   MachineBasicBlock::iterator MBBI = BB->end();
2999   ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
3000   doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
3001
3002   // AddedSize = add <TotalSizeReg>, 15
3003   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3004   BuildMI(BB, PPC::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
3005
3006   // AlignedSize = and <AddedSize>, ~15
3007   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3008   BuildMI(BB, PPC::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
3009     .addImm(0).addImm(27);
3010   
3011   // Subtract size from stack pointer, thereby allocating some space.
3012   BuildMI(BB, PPC::SUB, 2, PPC::R1).addReg(PPC::R1).addReg(AlignedSize);
3013
3014   // Put a pointer to the space into the result register, by copying
3015   // the stack pointer.
3016   BuildMI(BB, PPC::OR, 2, getReg(I)).addReg(PPC::R1).addReg(PPC::R1);
3017
3018   // Inform the Frame Information that we have just allocated a variable-sized
3019   // object.
3020   F->getFrameInfo()->CreateVariableSizedObject();
3021 }
3022
3023 /// visitMallocInst - Malloc instructions are code generated into direct calls
3024 /// to the library malloc.
3025 ///
3026 void ISel::visitMallocInst(MallocInst &I) {
3027   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3028   unsigned Arg;
3029
3030   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3031     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3032   } else {
3033     Arg = makeAnotherReg(Type::UIntTy);
3034     MachineBasicBlock::iterator MBBI = BB->end();
3035     ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
3036     doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
3037   }
3038
3039   std::vector<ValueRecord> Args;
3040   Args.push_back(ValueRecord(Arg, Type::UIntTy));
3041   MachineInstr *TheCall = 
3042     BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
3043   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
3044   TM.CalledFunctions.insert(mallocFn);
3045 }
3046
3047
3048 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3049 /// function.
3050 ///
3051 void ISel::visitFreeInst(FreeInst &I) {
3052   std::vector<ValueRecord> Args;
3053   Args.push_back(ValueRecord(I.getOperand(0)));
3054   MachineInstr *TheCall = 
3055     BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(freeFn, true);
3056   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
3057   TM.CalledFunctions.insert(freeFn);
3058 }
3059    
3060 /// createPPC64ISelSimple - This pass converts an LLVM function into a machine
3061 /// code representation is a very simple peep-hole fashion.
3062 ///
3063 FunctionPass *llvm::createPPC64ISelSimple(TargetMachine &TM) {
3064   return new ISel(TM);
3065 }