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