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