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