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