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