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