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