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