Convert tabs to spaces
[oota-llvm.git] / lib / Target / SparcV8 / SparcV8ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for SparcV8 --===//
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 // This file defines a simple peephole instruction selector for the V8 target
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SparcV8.h"
15 #include "SparcV8InstrInfo.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/IntrinsicLowering.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "llvm/Support/CFG.h"
30 using namespace llvm;
31
32 namespace {
33   struct V8ISel : public FunctionPass, public InstVisitor<V8ISel> {
34     TargetMachine &TM;
35     MachineFunction *F;                 // The function we are compiling into
36     MachineBasicBlock *BB;              // The current MBB we are compiling
37     int VarArgsOffset;                  // Offset from fp for start of varargs area
38
39     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
40
41     // MBBMap - Mapping between LLVM BB -> Machine BB
42     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
43
44     V8ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
45
46     /// runOnFunction - Top level implementation of instruction selection for
47     /// the entire function.
48     ///
49     bool runOnFunction(Function &Fn);
50
51     virtual const char *getPassName() const {
52       return "SparcV8 Simple Instruction Selection";
53     }
54
55     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
56     /// constant expression GEP support.
57     ///
58     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
59                           Value *Src, User::op_iterator IdxBegin,
60                           User::op_iterator IdxEnd, unsigned TargetReg);
61
62     /// emitCastOperation - Common code shared between visitCastInst and
63     /// constant expression cast support.
64     ///
65     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
66                            Value *Src, const Type *DestTy, unsigned TargetReg);
67
68     /// emitIntegerCast, emitFPToIntegerCast - Helper methods for
69     /// emitCastOperation.
70     ///
71     unsigned emitIntegerCast (MachineBasicBlock *BB,
72                               MachineBasicBlock::iterator IP,
73                               const Type *oldTy, unsigned SrcReg,
74                               const Type *newTy, unsigned DestReg,
75                               bool castToLong = false);
76     void emitFPToIntegerCast (MachineBasicBlock *BB,
77                               MachineBasicBlock::iterator IP, const Type *oldTy,
78                               unsigned SrcReg, const Type *newTy,
79                               unsigned DestReg);
80
81     /// visitBasicBlock - This method is called when we are visiting a new basic
82     /// block.  This simply creates a new MachineBasicBlock to emit code into
83     /// and adds it to the current MachineFunction.  Subsequent visit* for
84     /// instructions will be invoked for all instructions in the basic block.
85     ///
86     void visitBasicBlock(BasicBlock &LLVM_BB) {
87       BB = MBBMap[&LLVM_BB];
88     }
89
90     void emitOp64LibraryCall (MachineBasicBlock *MBB,
91                               MachineBasicBlock::iterator IP,
92                               unsigned DestReg, const char *FuncName,
93                               unsigned Op0Reg, unsigned Op1Reg);
94     void emitShift64 (MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
95                       Instruction &I, unsigned DestReg, unsigned Op0Reg,
96                       unsigned Op1Reg);
97     void visitBinaryOperator(Instruction &I);
98     void visitShiftInst (ShiftInst &SI) { visitBinaryOperator (SI); }
99     void visitSetCondInst(SetCondInst &I);
100     void visitCallInst(CallInst &I);
101     void visitReturnInst(ReturnInst &I);
102     void visitBranchInst(BranchInst &I);
103     void visitUnreachableInst(UnreachableInst &I) {}
104     void visitCastInst(CastInst &I);
105     void visitVANextInst(VANextInst &I);
106     void visitVAArgInst(VAArgInst &I);
107     void visitLoadInst(LoadInst &I);
108     void visitStoreInst(StoreInst &I);
109     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
110     void visitGetElementPtrInst(GetElementPtrInst &I);
111     void visitAllocaInst(AllocaInst &I);
112
113     void visitInstruction(Instruction &I) {
114       std::cerr << "Unhandled instruction: " << I;
115       abort();
116     }
117
118     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
119     /// function, lowering any calls to unknown intrinsic functions into the
120     /// equivalent LLVM code.
121     void LowerUnknownIntrinsicFunctionCalls(Function &F);
122     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
123
124     void LoadArgumentsToVirtualRegs(Function *F);
125
126     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
127     /// because we have to generate our sources into the source basic blocks,
128     /// not the current one.
129     ///
130     void SelectPHINodes();
131
132     /// copyConstantToRegister - Output the instructions required to put the
133     /// specified constant into the specified register.
134     ///
135     void copyConstantToRegister(MachineBasicBlock *MBB,
136                                 MachineBasicBlock::iterator IP,
137                                 Constant *C, unsigned R);
138
139     /// makeAnotherReg - This method returns the next register number we haven't
140     /// yet used.
141     ///
142     /// Long values are handled somewhat specially.  They are always allocated
143     /// as pairs of 32 bit integer values.  The register number returned is the
144     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
145     /// of the long value.
146     ///
147     unsigned makeAnotherReg(const Type *Ty) {
148       assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
149              "Current target doesn't have SparcV8 reg info??");
150       const SparcV8RegisterInfo *MRI =
151         static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
152       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
153         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
154         // Create the lower part
155         F->getSSARegMap()->createVirtualRegister(RC);
156         // Create the upper part.
157         return F->getSSARegMap()->createVirtualRegister(RC)-1;
158       }
159
160       // Add the mapping of regnumber => reg class to MachineFunction
161       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
162       return F->getSSARegMap()->createVirtualRegister(RC);
163     }
164
165     unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
166     unsigned getReg(Value *V) {
167       // Just append to the end of the current bb.
168       MachineBasicBlock::iterator It = BB->end();
169       return getReg(V, BB, It);
170     }
171     unsigned getReg(Value *V, MachineBasicBlock *MBB,
172                     MachineBasicBlock::iterator IPt) {
173       unsigned &Reg = RegMap[V];
174       if (Reg == 0) {
175         Reg = makeAnotherReg(V->getType());
176         RegMap[V] = Reg;
177       }
178       // If this operand is a constant, emit the code to copy the constant into
179       // the register here...
180       //
181       if (Constant *C = dyn_cast<Constant>(V)) {
182         copyConstantToRegister(MBB, IPt, C, Reg);
183         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
184       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
185         // Move the address of the global into the register
186         unsigned TmpReg = makeAnotherReg(V->getType());
187         BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
188         BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
189           .addGlobalAddress (GV);
190         RegMap.erase(V);  // Assign a new name to this address if ref'd again
191       }
192
193       return Reg;
194     }
195
196   };
197 }
198
199 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
200   return new V8ISel(TM);
201 }
202
203 enum TypeClass {
204   cByte, cShort, cInt, cLong, cFloat, cDouble
205 };
206
207 static TypeClass getClass (const Type *T) {
208   switch (T->getTypeID()) {
209     case Type::UByteTyID:  case Type::SByteTyID:  return cByte;
210     case Type::UShortTyID: case Type::ShortTyID:  return cShort;
211     case Type::PointerTyID:
212     case Type::UIntTyID:   case Type::IntTyID:    return cInt;
213     case Type::ULongTyID:  case Type::LongTyID:   return cLong;
214     case Type::FloatTyID:                         return cFloat;
215     case Type::DoubleTyID:                        return cDouble;
216     default:
217       assert (0 && "Type of unknown class passed to getClass?");
218       return cByte;
219   }
220 }
221
222 static TypeClass getClassB(const Type *T) {
223   if (T == Type::BoolTy) return cByte;
224   return getClass(T);
225 }
226
227 /// copyConstantToRegister - Output the instructions required to put the
228 /// specified constant into the specified register.
229 ///
230 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
231                                     MachineBasicBlock::iterator IP,
232                                     Constant *C, unsigned R) {
233   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
234     switch (CE->getOpcode()) {
235     case Instruction::GetElementPtr:
236       emitGEPOperation(MBB, IP, CE->getOperand(0),
237                        CE->op_begin()+1, CE->op_end(), R);
238       return;
239     case Instruction::Cast:
240       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
241       return;
242     default:
243       std::cerr << "Copying this constant expr not yet handled: " << *CE;
244       abort();
245     }
246   } else if (isa<UndefValue>(C)) {
247     BuildMI(*MBB, IP, V8::IMPLICIT_DEF, 0, R);
248     if (getClassB (C->getType ()) == cLong)
249       BuildMI(*MBB, IP, V8::IMPLICIT_DEF, 0, R+1);
250     return;
251   }
252
253   if (C->getType()->isIntegral ()) {
254     unsigned Class = getClassB (C->getType ());
255     if (Class == cLong) {
256       unsigned TmpReg = makeAnotherReg (Type::IntTy);
257       unsigned TmpReg2 = makeAnotherReg (Type::IntTy);
258       // Copy the value into the register pair.
259       // R = top(more-significant) half, R+1 = bottom(less-significant) half
260       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
261       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
262                              Val >> 32), R);
263       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
264                              Val & 0xffffffffU), R+1);
265       return;
266     }
267
268     assert(Class <= cInt && "Type not handled yet!");
269     unsigned Val;
270
271     if (C->getType() == Type::BoolTy) {
272       Val = (C == ConstantBool::True);
273     } else {
274       ConstantIntegral *CI = cast<ConstantIntegral> (C);
275       Val = CI->getRawValue();
276     }
277     if (C->getType()->isSigned()) {
278       switch (Class) {
279         case cByte:  Val =  (int8_t) Val; break;
280         case cShort: Val = (int16_t) Val; break;
281         case cInt:   Val = (int32_t) Val; break;
282       }
283     } else {
284       switch (Class) {
285         case cByte:  Val =  (uint8_t) Val; break;
286         case cShort: Val = (uint16_t) Val; break;
287         case cInt:   Val = (uint32_t) Val; break;
288       }
289     }
290     if (Val == 0) {
291       BuildMI (*MBB, IP, V8::ORrr, 2, R).addReg (V8::G0).addReg(V8::G0);
292     } else if ((int)Val >= -4096 && (int)Val <= 4095) {
293       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm(Val);
294     } else {
295       unsigned TmpReg = makeAnotherReg (C->getType ());
296       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
297         .addSImm (((uint32_t) Val) >> 10);
298       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
299         .addSImm (((uint32_t) Val) & 0x03ff);
300       return;
301     }
302   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
303     // We need to spill the constant to memory...
304     MachineConstantPool *CP = F->getConstantPool();
305     unsigned CPI = CP->getConstantPoolIndex(CFP);
306     const Type *Ty = CFP->getType();
307     unsigned TmpReg = makeAnotherReg (Type::UIntTy);
308     unsigned AddrReg = makeAnotherReg (Type::UIntTy);
309
310     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
311     unsigned LoadOpcode = Ty == Type::FloatTy ? V8::LDFri : V8::LDDFri;
312     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addConstantPoolIndex (CPI);
313     BuildMI (*MBB, IP, V8::ORri, 2, AddrReg).addReg (TmpReg)
314       .addConstantPoolIndex (CPI);
315     BuildMI (*MBB, IP, LoadOpcode, 2, R).addReg (AddrReg).addSImm (0);
316   } else if (isa<ConstantPointerNull>(C)) {
317     // Copy zero (null pointer) to the register.
318     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm (0);
319   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
320     // Copy it with a SETHI/OR pair; the JIT + asmwriter should recognize
321     // that SETHI %reg,global == SETHI %reg,%hi(global) and
322     // OR %reg,global,%reg == OR %reg,%lo(global),%reg.
323     unsigned TmpReg = makeAnotherReg (C->getType ());
324     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addGlobalAddress(GV);
325     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg(TmpReg).addGlobalAddress(GV);
326   } else {
327     std::cerr << "Offending constant: " << *C << "\n";
328     assert (0 && "Can't copy this kind of constant into register yet");
329   }
330 }
331
332 void V8ISel::LoadArgumentsToVirtualRegs (Function *LF) {
333   static const unsigned IncomingArgRegs[] = { V8::I0, V8::I1, V8::I2,
334     V8::I3, V8::I4, V8::I5 };
335
336   // Add IMPLICIT_DEFs of input regs.
337   unsigned ArgNo = 0;
338   for (Function::arg_iterator I = LF->arg_begin(), E = LF->arg_end();
339        I != E && ArgNo < 6; ++I, ++ArgNo) {
340     switch (getClassB(I->getType())) {
341     case cByte:
342     case cShort:
343     case cInt:
344     case cFloat:
345       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgNo]);
346       break;
347     case cDouble:
348     case cLong:
349       // Double and Long use register pairs.
350       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgNo]);
351       ++ArgNo;
352       if (ArgNo < 6)
353         BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgNo]);
354       break;
355     default:
356       assert (0 && "type not handled");
357       return;
358     }
359   }
360
361   const unsigned *IAREnd = &IncomingArgRegs[6];
362   const unsigned *IAR = &IncomingArgRegs[0];
363   unsigned ArgOffset = 68;
364
365   // Store registers onto stack if this is a varargs function.
366   // FIXME: This doesn't really pertain to "loading arguments into
367   // virtual registers", so it's not clear that it really belongs here.
368   // FIXME: We could avoid storing any args onto the stack that don't
369   // need to be in memory, because they come before the ellipsis in the
370   // parameter list (and thus could never be accessed through va_arg).
371   if (LF->getFunctionType ()->isVarArg ()) {
372     for (unsigned i = 0; i < 6; ++i) {
373       int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
374       assert (IAR != IAREnd
375               && "About to dereference past end of IncomingArgRegs");
376       BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
377       ArgOffset += 4;
378     }
379     // Reset the pointers now that we're done.
380     ArgOffset = 68;
381     IAR = &IncomingArgRegs[0];
382   }
383
384   // Copy args out of their incoming hard regs or stack slots into virtual regs.
385   for (Function::arg_iterator I = LF->arg_begin(), E = LF->arg_end(); I != E; ++I) {
386     Argument &A = *I;
387     unsigned ArgReg = getReg (A);
388     if (getClassB (A.getType ()) < cLong) {
389       // Get it out of the incoming arg register
390       if (ArgOffset < 92) {
391         assert (IAR != IAREnd
392                 && "About to dereference past end of IncomingArgRegs");
393         BuildMI (BB, V8::ORrr, 2, ArgReg).addReg (V8::G0).addReg (*IAR++);
394       } else {
395         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
396         BuildMI (BB, V8::LD, 3, ArgReg).addFrameIndex (FI).addSImm (0);
397       }
398       ArgOffset += 4;
399     } else if (getClassB (A.getType ()) == cFloat) {
400       if (ArgOffset < 92) {
401         // Single-fp args are passed in integer registers; go through
402         // memory to get them out of integer registers and back into fp. (Bleh!)
403         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
404         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
405         assert (IAR != IAREnd
406                 && "About to dereference past end of IncomingArgRegs");
407         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
408         BuildMI (BB, V8::LDFri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
409       } else {
410         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
411         BuildMI (BB, V8::LDFri, 3, ArgReg).addFrameIndex (FI).addSImm (0);
412       }
413       ArgOffset += 4;
414     } else if (getClassB (A.getType ()) == cDouble) {
415       // Double-fp args are passed in pairs of integer registers; go through
416       // memory to get them out of integer registers and back into fp. (Bleh!)
417       // We'd like to 'ldd' these right out of the incoming-args area,
418       // but it might not be 8-byte aligned (e.g., call x(int x, double d)).
419       unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
420       int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
421       if (ArgOffset < 92 && IAR != IAREnd) {
422         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
423       } else {
424         unsigned TempReg = makeAnotherReg (Type::IntTy);
425         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (0);
426         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (TempReg);
427       }
428       ArgOffset += 4;
429       if (ArgOffset < 92 && IAR != IAREnd) {
430         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (4).addReg (*IAR++);
431       } else {
432         unsigned TempReg = makeAnotherReg (Type::IntTy);
433         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (4);
434         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (4).addReg (TempReg);
435       }
436       ArgOffset += 4;
437       BuildMI (BB, V8::LDDFri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
438     } else if (getClassB (A.getType ()) == cLong) {
439       // do the first half...
440       if (ArgOffset < 92) {
441         assert (IAR != IAREnd
442                 && "About to dereference past end of IncomingArgRegs");
443         BuildMI (BB, V8::ORrr, 2, ArgReg).addReg (V8::G0).addReg (*IAR++);
444       } else {
445         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
446         BuildMI (BB, V8::LD, 2, ArgReg).addFrameIndex (FI).addSImm (0);
447       }
448       ArgOffset += 4;
449       // ...then do the second half
450       if (ArgOffset < 92) {
451         assert (IAR != IAREnd
452                 && "About to dereference past end of IncomingArgRegs");
453         BuildMI (BB, V8::ORrr, 2, ArgReg+1).addReg (V8::G0).addReg (*IAR++);
454       } else {
455         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
456         BuildMI (BB, V8::LD, 2, ArgReg+1).addFrameIndex (FI).addSImm (0);
457       }
458       ArgOffset += 4;
459     } else {
460       assert (0 && "Unknown class?!");
461     }
462   }
463
464   // If the function takes variable number of arguments, remember the fp
465   // offset for the start of the first vararg value... this is used to expand
466   // llvm.va_start.
467   if (LF->getFunctionType ()->isVarArg ())
468     VarArgsOffset = ArgOffset;
469 }
470
471 void V8ISel::SelectPHINodes() {
472   const TargetInstrInfo &TII = *TM.getInstrInfo();
473   const Function &LF = *F->getFunction();  // The LLVM function...
474   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
475     const BasicBlock *BB = I;
476     MachineBasicBlock &MBB = *MBBMap[I];
477
478     // Loop over all of the PHI nodes in the LLVM basic block...
479     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
480     for (BasicBlock::const_iterator I = BB->begin();
481          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
482
483       // Create a new machine instr PHI node, and insert it.
484       unsigned PHIReg = getReg(*PN);
485       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
486                                     V8::PHI, PN->getNumOperands(), PHIReg);
487
488       MachineInstr *LongPhiMI = 0;
489       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
490         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
491                             V8::PHI, PN->getNumOperands(), PHIReg+1);
492
493       // PHIValues - Map of blocks to incoming virtual registers.  We use this
494       // so that we only initialize one incoming value for a particular block,
495       // even if the block has multiple entries in the PHI node.
496       //
497       std::map<MachineBasicBlock*, unsigned> PHIValues;
498
499       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
500         MachineBasicBlock *PredMBB = 0;
501         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
502              PE = MBB.pred_end (); PI != PE; ++PI)
503           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
504             PredMBB = *PI;
505             break;
506           }
507         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
508
509         unsigned ValReg;
510         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
511           PHIValues.lower_bound(PredMBB);
512
513         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
514           // We already inserted an initialization of the register for this
515           // predecessor.  Recycle it.
516           ValReg = EntryIt->second;
517
518         } else {
519           // Get the incoming value into a virtual register.
520           //
521           Value *Val = PN->getIncomingValue(i);
522
523           // If this is a constant or GlobalValue, we may have to insert code
524           // into the basic block to compute it into a virtual register.
525           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
526               isa<GlobalValue>(Val)) {
527             // Simple constants get emitted at the end of the basic block,
528             // before any terminator instructions.  We "know" that the code to
529             // move a constant into a register will never clobber any flags.
530             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
531           } else {
532             // Because we don't want to clobber any values which might be in
533             // physical registers with the computation of this constant (which
534             // might be arbitrarily complex if it is a constant expression),
535             // just insert the computation at the top of the basic block.
536             MachineBasicBlock::iterator PI = PredMBB->begin();
537
538             // Skip over any PHI nodes though!
539             while (PI != PredMBB->end() && PI->getOpcode() == V8::PHI)
540               ++PI;
541
542             ValReg = getReg(Val, PredMBB, PI);
543           }
544
545           // Remember that we inserted a value for this PHI for this predecessor
546           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
547         }
548
549         PhiMI->addRegOperand(ValReg);
550         PhiMI->addMachineBasicBlockOperand(PredMBB);
551         if (LongPhiMI) {
552           LongPhiMI->addRegOperand(ValReg+1);
553           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
554         }
555       }
556
557       // Now that we emitted all of the incoming values for the PHI node, make
558       // sure to reposition the InsertPoint after the PHI that we just added.
559       // This is needed because we might have inserted a constant into this
560       // block, right after the PHI's which is before the old insert point!
561       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
562       ++PHIInsertPoint;
563     }
564   }
565 }
566
567 bool V8ISel::runOnFunction(Function &Fn) {
568   // First pass over the function, lower any unknown intrinsic functions
569   // with the IntrinsicLowering class.
570   LowerUnknownIntrinsicFunctionCalls(Fn);
571
572   F = &MachineFunction::construct(&Fn, TM);
573
574   // Create all of the machine basic blocks for the function...
575   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
576     F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
577
578   BB = &F->front();
579
580   // Set up a frame object for the return address.  This is used by the
581   // llvm.returnaddress & llvm.frameaddress intrinisics.
582   //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
583
584   // Copy incoming arguments off of the stack and out of fixed registers.
585   LoadArgumentsToVirtualRegs(&Fn);
586
587   // Instruction select everything except PHI nodes
588   visit(Fn);
589
590   // Select the PHI nodes
591   SelectPHINodes();
592
593   RegMap.clear();
594   MBBMap.clear();
595   F = 0;
596   // We always build a machine code representation for the function
597   return true;
598 }
599
600 void V8ISel::visitCastInst(CastInst &I) {
601   Value *Op = I.getOperand(0);
602   unsigned DestReg = getReg(I);
603   MachineBasicBlock::iterator MI = BB->end();
604   emitCastOperation(BB, MI, Op, I.getType(), DestReg);
605 }
606
607 unsigned V8ISel::emitIntegerCast (MachineBasicBlock *BB,
608                               MachineBasicBlock::iterator IP, const Type *oldTy,
609                               unsigned SrcReg, const Type *newTy,
610                               unsigned DestReg, bool castToLong) {
611   unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
612   if (oldTy == newTy || (!castToLong && shiftWidth == 0)) {
613     // No-op cast - just emit a copy; assume the reg. allocator will zap it.
614     BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg(SrcReg);
615     return SrcReg;
616   }
617   // Emit left-shift, then right-shift to sign- or zero-extend.
618   unsigned TmpReg = makeAnotherReg (newTy);
619   BuildMI (*BB, IP, V8::SLLri, 2, TmpReg).addZImm (shiftWidth).addReg(SrcReg);
620   if (newTy->isSigned ()) { // sign-extend with SRA
621     BuildMI(*BB, IP, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
622   } else { // zero-extend with SRL
623     BuildMI(*BB, IP, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
624   }
625   // Return the temp reg. in case this is one half of a cast to long.
626   return TmpReg;
627 }
628
629 void V8ISel::emitFPToIntegerCast (MachineBasicBlock *BB,
630                                   MachineBasicBlock::iterator IP,
631                                   const Type *oldTy, unsigned SrcReg,
632                                   const Type *newTy, unsigned DestReg) {
633   unsigned FPCastOpcode, FPStoreOpcode, FPSize, FPAlign;
634   unsigned oldTyClass = getClassB(oldTy);
635   if (oldTyClass == cFloat) {
636     FPCastOpcode = V8::FSTOI; FPStoreOpcode = V8::STFri; FPSize = 4;
637     FPAlign = TM.getTargetData().getFloatAlignment();
638   } else { // it's a double
639     FPCastOpcode = V8::FDTOI; FPStoreOpcode = V8::STDFri; FPSize = 8;
640     FPAlign = TM.getTargetData().getDoubleAlignment();
641   }
642   unsigned TempReg = makeAnotherReg (oldTy);
643   BuildMI (*BB, IP, FPCastOpcode, 1, TempReg).addReg (SrcReg);
644   int FI = F->getFrameInfo()->CreateStackObject(FPSize, FPAlign);
645   BuildMI (*BB, IP, FPStoreOpcode, 3).addFrameIndex (FI).addSImm (0)
646     .addReg (TempReg);
647   unsigned TempReg2 = makeAnotherReg (newTy);
648   BuildMI (*BB, IP, V8::LD, 3, TempReg2).addFrameIndex (FI).addSImm (0);
649   emitIntegerCast (BB, IP, Type::IntTy, TempReg2, newTy, DestReg);
650 }
651
652 /// emitCastOperation - Common code shared between visitCastInst and constant
653 /// expression cast support.
654 ///
655 void V8ISel::emitCastOperation(MachineBasicBlock *BB,
656                                MachineBasicBlock::iterator IP, Value *Src,
657                                const Type *DestTy, unsigned DestReg) {
658   const Type *SrcTy = Src->getType();
659   unsigned SrcClass = getClassB(SrcTy);
660   unsigned DestClass = getClassB(DestTy);
661   unsigned SrcReg = getReg(Src, BB, IP);
662
663   const Type *oldTy = SrcTy;
664   const Type *newTy = DestTy;
665   unsigned oldTyClass = SrcClass;
666   unsigned newTyClass = DestClass;
667
668   if (oldTyClass < cLong && newTyClass < cLong) {
669     emitIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
670   } else switch (newTyClass) {
671     case cByte:
672     case cShort:
673     case cInt:
674       switch (oldTyClass) {
675       case cLong:
676         // Treat it like a cast from the lower half of the value.
677         emitIntegerCast (BB, IP, Type::IntTy, SrcReg+1, newTy, DestReg);
678         break;
679       case cFloat:
680       case cDouble:
681         emitFPToIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
682         break;
683       default: goto not_yet;
684       }
685       return;
686
687     case cFloat:
688       switch (oldTyClass) {
689       case cLong: goto not_yet;
690       case cFloat:
691         BuildMI (*BB, IP, V8::FMOVS, 1, DestReg).addReg (SrcReg);
692         break;
693       case cDouble:
694         BuildMI (*BB, IP, V8::FDTOS, 1, DestReg).addReg (SrcReg);
695         break;
696       default: {
697         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
698         // cast integer type to float.  Store it to a stack slot and then load
699         // it using ldf into a floating point register. then do fitos.
700         unsigned TmpReg = makeAnotherReg (newTy);
701         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
702         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
703           .addReg (SrcReg);
704         BuildMI (*BB, IP, V8::LDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
705         BuildMI (*BB, IP, V8::FITOS, 1, DestReg).addReg(TmpReg);
706         break;
707       }
708       }
709       return;
710
711     case cDouble:
712       switch (oldTyClass) {
713       case cLong: goto not_yet;
714       case cFloat:
715         BuildMI (*BB, IP, V8::FSTOD, 1, DestReg).addReg (SrcReg);
716         break;
717       case cDouble: // use double move pseudo-instr
718         BuildMI (*BB, IP, V8::FpMOVD, 1, DestReg).addReg (SrcReg);
719         break;
720       default: {
721         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
722         unsigned TmpReg = makeAnotherReg (newTy);
723         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
724         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
725           .addReg (SrcReg);
726         BuildMI (*BB, IP, V8::LDDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
727         BuildMI (*BB, IP, V8::FITOD, 1, DestReg).addReg(TmpReg);
728         break;
729       }
730       }
731       return;
732
733     case cLong:
734       switch (oldTyClass) {
735       case cByte:
736       case cShort:
737       case cInt: {
738         // Cast to (u)int in the bottom half, and sign(zero) extend in the top
739         // half.
740         const Type *OldHalfTy = oldTy->isSigned() ? Type::IntTy : Type::UIntTy;
741         const Type *NewHalfTy = newTy->isSigned() ? Type::IntTy : Type::UIntTy;
742         unsigned TempReg = emitIntegerCast (BB, IP, OldHalfTy, SrcReg,
743                                             NewHalfTy, DestReg+1, true);
744         if (newTy->isSigned ()) {
745           BuildMI (*BB, IP, V8::SRAri, 2, DestReg).addReg (TempReg)
746             .addZImm (31);
747         } else {
748           BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0)
749             .addReg (V8::G0);
750         }
751         break;
752       }
753       case cLong:
754         // Just copy both halves.
755         BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (SrcReg);
756         BuildMI (*BB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0)
757           .addReg (SrcReg+1);
758         break;
759       default: goto not_yet;
760       }
761       return;
762
763     default: goto not_yet;
764   }
765   return;
766 not_yet:
767   std::cerr << "Sorry, cast still unsupported: SrcTy = " << *SrcTy
768             << ", DestTy = " << *DestTy << "\n";
769   abort ();
770 }
771
772 void V8ISel::visitLoadInst(LoadInst &I) {
773   unsigned DestReg = getReg (I);
774   unsigned PtrReg = getReg (I.getOperand (0));
775   switch (getClassB (I.getType ())) {
776    case cByte:
777     if (I.getType ()->isSigned ())
778       BuildMI (BB, V8::LDSB, 2, DestReg).addReg (PtrReg).addSImm(0);
779     else
780       BuildMI (BB, V8::LDUB, 2, DestReg).addReg (PtrReg).addSImm(0);
781     return;
782    case cShort:
783     if (I.getType ()->isSigned ())
784       BuildMI (BB, V8::LDSH, 2, DestReg).addReg (PtrReg).addSImm(0);
785     else
786       BuildMI (BB, V8::LDUH, 2, DestReg).addReg (PtrReg).addSImm(0);
787     return;
788    case cInt:
789     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
790     return;
791    case cLong:
792     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
793     BuildMI (BB, V8::LD, 2, DestReg+1).addReg (PtrReg).addSImm(4);
794     return;
795    case cFloat:
796     BuildMI (BB, V8::LDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
797     return;
798    case cDouble:
799     BuildMI (BB, V8::LDDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
800     return;
801    default:
802     std::cerr << "Load instruction not handled: " << I;
803     abort ();
804     return;
805   }
806 }
807
808 void V8ISel::visitStoreInst(StoreInst &I) {
809   Value *SrcVal = I.getOperand (0);
810   unsigned SrcReg = getReg (SrcVal);
811   unsigned PtrReg = getReg (I.getOperand (1));
812   switch (getClassB (SrcVal->getType ())) {
813    case cByte:
814     BuildMI (BB, V8::STB, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
815     return;
816    case cShort:
817     BuildMI (BB, V8::STH, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
818     return;
819    case cInt:
820     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
821     return;
822    case cLong:
823     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
824     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (4).addReg (SrcReg+1);
825     return;
826    case cFloat:
827     BuildMI (BB, V8::STFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
828     return;
829    case cDouble:
830     BuildMI (BB, V8::STDFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
831     return;
832    default:
833     std::cerr << "Store instruction not handled: " << I;
834     abort ();
835     return;
836   }
837 }
838
839 void V8ISel::visitCallInst(CallInst &I) {
840   MachineInstr *TheCall;
841   // Is it an intrinsic function call?
842   if (Function *F = I.getCalledFunction()) {
843     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
844       visitIntrinsicCall(ID, I);   // Special intrinsics are not handled here
845       return;
846     }
847   }
848
849   // How much extra call stack will we need?
850   int extraStack = 0;
851   for (unsigned i = 0; i < I.getNumOperands (); ++i) {
852     switch (getClassB (I.getOperand (i)->getType ())) {
853       case cLong: extraStack += 8; break;
854       case cFloat: extraStack += 4; break;
855       case cDouble: extraStack += 8; break;
856       default: extraStack += 4; break;
857     }
858   }
859   extraStack -= 24;
860   if (extraStack < 0) {
861     extraStack = 0;
862   } else {
863     // Round up extra stack size to the nearest doubleword.
864     extraStack = (extraStack + 7) & ~7;
865   }
866
867   // Deal with args
868   static const unsigned OutgoingArgRegs[] = { V8::O0, V8::O1, V8::O2, V8::O3,
869     V8::O4, V8::O5 };
870   const unsigned *OAREnd = &OutgoingArgRegs[6];
871   const unsigned *OAR = &OutgoingArgRegs[0];
872   unsigned ArgOffset = 68;
873   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKDOWN, 1).addImm (extraStack);
874   for (unsigned i = 1; i < I.getNumOperands (); ++i) {
875     unsigned ArgReg = getReg (I.getOperand (i));
876     if (getClassB (I.getOperand (i)->getType ()) < cLong) {
877       // Schlep it over into the incoming arg register
878       if (ArgOffset < 92) {
879         assert (OAR != OAREnd &&
880                 "About to dereference past end of OutgoingArgRegs");
881         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg);
882       } else {
883         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset)
884           .addReg (ArgReg);
885       }
886       ArgOffset += 4;
887     } else if (getClassB (I.getOperand (i)->getType ()) == cFloat) {
888       if (ArgOffset < 92) {
889         // Single-fp args are passed in integer registers; go through
890         // memory to get them out of FP registers. (Bleh!)
891         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
892         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
893         BuildMI (BB, V8::STFri, 3).addFrameIndex(FI).addSImm(0).addReg(ArgReg);
894         assert (OAR != OAREnd &&
895                 "About to dereference past end of OutgoingArgRegs");
896         BuildMI (BB, V8::LD, 2, *OAR++).addFrameIndex (FI).addSImm (0);
897       } else {
898         BuildMI (BB, V8::STFri, 3).addReg (V8::SP).addSImm (ArgOffset)
899           .addReg (ArgReg);
900       }
901       ArgOffset += 4;
902     } else if (getClassB (I.getOperand (i)->getType ()) == cDouble) {
903       // Double-fp args are passed in pairs of integer registers; go through
904       // memory to get them out of FP registers. (Bleh!)
905       // We'd like to 'std' these right onto the outgoing-args area, but it might
906       // not be 8-byte aligned (e.g., call x(int x, double d)). sigh.
907       unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
908       int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
909       BuildMI (BB, V8::STDFri, 3).addFrameIndex (FI).addSImm (0).addReg (ArgReg);
910       if (ArgOffset < 92 && OAR != OAREnd) {
911         assert (OAR != OAREnd &&
912                 "About to dereference past end of OutgoingArgRegs");
913         BuildMI (BB, V8::LD, 2, *OAR++).addFrameIndex (FI).addSImm (0);
914       } else {
915         unsigned TempReg = makeAnotherReg (Type::IntTy);
916         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (0);
917         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset)
918           .addReg (TempReg);
919       }
920       ArgOffset += 4;
921       if (ArgOffset < 92 && OAR != OAREnd) {
922         assert (OAR != OAREnd &&
923                 "About to dereference past end of OutgoingArgRegs");
924         BuildMI (BB, V8::LD, 2, *OAR++).addFrameIndex (FI).addSImm (4);
925       } else {
926         unsigned TempReg = makeAnotherReg (Type::IntTy);
927         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (4);
928         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset)
929           .addReg (TempReg);
930       }
931       ArgOffset += 4;
932     } else if (getClassB (I.getOperand (i)->getType ()) == cLong) {
933       // do the first half...
934       if (ArgOffset < 92) {
935         assert (OAR != OAREnd &&
936                 "About to dereference past end of OutgoingArgRegs");
937         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg);
938       } else {
939         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset)
940           .addReg (ArgReg);
941       }
942       ArgOffset += 4;
943       // ...then do the second half
944       if (ArgOffset < 92) {
945         assert (OAR != OAREnd &&
946                 "About to dereference past end of OutgoingArgRegs");
947         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg+1);
948       } else {
949         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset)
950           .addReg (ArgReg+1);
951       }
952       ArgOffset += 4;
953     } else {
954       assert (0 && "Unknown class?!");
955     }
956   }
957
958   // Emit call instruction
959   if (Function *F = I.getCalledFunction ()) {
960     BuildMI (BB, V8::CALL, 1).addGlobalAddress (F, true);
961   } else {  // Emit an indirect call...
962     unsigned Reg = getReg (I.getCalledValue ());
963     BuildMI (BB, V8::JMPLrr, 3, V8::O7).addReg (Reg).addReg (V8::G0);
964   }
965
966   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKUP, 1).addImm (extraStack);
967
968   // Deal w/ return value: schlep it over into the destination register
969   if (I.getType () == Type::VoidTy)
970     return;
971   unsigned DestReg = getReg (I);
972   switch (getClassB (I.getType ())) {
973     case cByte:
974     case cShort:
975     case cInt:
976       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
977       break;
978     case cFloat:
979       BuildMI (BB, V8::FMOVS, 2, DestReg).addReg(V8::F0);
980       break;
981     case cDouble:
982       BuildMI (BB, V8::FpMOVD, 2, DestReg).addReg(V8::D0);
983       break;
984     case cLong:
985       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
986       BuildMI (BB, V8::ORrr, 2, DestReg+1).addReg(V8::G0).addReg(V8::O1);
987       break;
988     default:
989       std::cerr << "Return type of call instruction not handled: " << I;
990       abort ();
991   }
992 }
993
994 void V8ISel::visitReturnInst(ReturnInst &I) {
995   if (I.getNumOperands () == 1) {
996     unsigned RetValReg = getReg (I.getOperand (0));
997     switch (getClassB (I.getOperand (0)->getType ())) {
998       case cByte:
999       case cShort:
1000       case cInt:
1001         // Schlep it over into i0 (where it will become o0 after restore).
1002         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
1003         break;
1004       case cFloat:
1005         BuildMI (BB, V8::FMOVS, 1, V8::F0).addReg(RetValReg);
1006         break;
1007       case cDouble:
1008         BuildMI (BB, V8::FpMOVD, 1, V8::D0).addReg(RetValReg);
1009         break;
1010       case cLong:
1011         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
1012         BuildMI (BB, V8::ORrr, 2, V8::I1).addReg(V8::G0).addReg(RetValReg+1);
1013         break;
1014       default:
1015         std::cerr << "Return instruction of this type not handled: " << I;
1016         abort ();
1017     }
1018   }
1019
1020   // Just emit a 'retl' instruction to return.
1021   BuildMI(BB, V8::RETL, 0);
1022   return;
1023 }
1024
1025 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1026   Function::iterator I = BB; ++I;  // Get iterator to next block
1027   return I != BB->getParent()->end() ? &*I : 0;
1028 }
1029
1030 /// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it
1031 /// into the conditional branch which is the only user of the cc instruction.
1032 /// This is the case if the conditional branch is the only user of the setcc.
1033 ///
1034 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
1035   //return 0; // disable.
1036   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1037     if (SCI->hasOneUse()) {
1038       BranchInst *User = dyn_cast<BranchInst>(SCI->use_back());
1039       if (User
1040           && (SCI->getNext() == User)
1041           && (getClassB(SCI->getOperand(0)->getType()) != cLong)
1042           && User->isConditional() && (User->getCondition() == V))
1043         return SCI;
1044     }
1045   return 0;
1046 }
1047
1048 /// visitBranchInst - Handles conditional and unconditional branches.
1049 ///
1050 void V8ISel::visitBranchInst(BranchInst &I) {
1051   BasicBlock *takenSucc = I.getSuccessor (0);
1052   MachineBasicBlock *takenSuccMBB = MBBMap[takenSucc];
1053   BB->addSuccessor (takenSuccMBB);
1054   if (I.isConditional()) {  // conditional branch
1055     BasicBlock *notTakenSucc = I.getSuccessor (1);
1056     MachineBasicBlock *notTakenSuccMBB = MBBMap[notTakenSucc];
1057     BB->addSuccessor (notTakenSuccMBB);
1058
1059     // See if we can fold a previous setcc instr into this branch.
1060     SetCondInst *SCI = canFoldSetCCIntoBranch(I.getCondition());
1061     if (SCI == 0) {
1062       // The condition did not come from a setcc which we could fold.
1063       // CondReg=(<condition>);
1064       // If (CondReg==0) goto notTakenSuccMBB;
1065       unsigned CondReg = getReg (I.getCondition ());
1066       BuildMI (BB, V8::CMPri, 2).addSImm (0).addReg (CondReg);
1067       BuildMI (BB, V8::BE, 1).addMBB (notTakenSuccMBB);
1068       BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
1069       return;
1070     }
1071
1072     // Fold the setCC instr into the branch.
1073     unsigned Op0Reg = getReg (SCI->getOperand (0));
1074     unsigned Op1Reg = getReg (SCI->getOperand (1));
1075     const Type *Ty = SCI->getOperand (0)->getType ();
1076
1077     // Compare the two values.
1078     if (getClass (Ty) < cLong) {
1079       BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1080     } else if (getClass (Ty) == cLong) {
1081       assert (0 && "Can't fold setcc long/ulong into branch");
1082     } else if (getClass (Ty) == cFloat) {
1083       BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1084     } else if (getClass (Ty) == cDouble) {
1085       BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1086     }
1087
1088     unsigned BranchIdx;
1089     switch (SCI->getOpcode()) {
1090     default: assert(0 && "Unknown setcc instruction!");
1091     case Instruction::SetEQ: BranchIdx = 0; break;
1092     case Instruction::SetNE: BranchIdx = 1; break;
1093     case Instruction::SetLT: BranchIdx = 2; break;
1094     case Instruction::SetGT: BranchIdx = 3; break;
1095     case Instruction::SetLE: BranchIdx = 4; break;
1096     case Instruction::SetGE: BranchIdx = 5; break;
1097     }
1098
1099     unsigned Column = 0;
1100     if (Ty->isSigned() && !Ty->isFloatingPoint()) Column = 1;
1101     if (Ty->isFloatingPoint()) Column = 2;
1102     static unsigned OpcodeTab[3*6] = {
1103                                    // LLVM            SparcV8
1104                                    //        unsigned signed  fp
1105       V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1106       V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1107       V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1108       V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1109       V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1110       V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1111     };
1112     unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1113     BuildMI (BB, Opcode, 1).addMBB (takenSuccMBB);
1114     BuildMI (BB, V8::BA, 1).addMBB (notTakenSuccMBB);
1115   } else {
1116     // goto takenSuccMBB;
1117     BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
1118   }
1119 }
1120
1121 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
1122 /// constant expression GEP support.
1123 ///
1124 void V8ISel::emitGEPOperation (MachineBasicBlock *MBB,
1125                                MachineBasicBlock::iterator IP,
1126                                Value *Src, User::op_iterator IdxBegin,
1127                                User::op_iterator IdxEnd, unsigned TargetReg) {
1128   const TargetData &TD = TM.getTargetData ();
1129   const Type *Ty = Src->getType ();
1130   unsigned basePtrReg = getReg (Src, MBB, IP);
1131
1132   // GEPs have zero or more indices; we must perform a struct access
1133   // or array access for each one.
1134   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
1135        ++oi) {
1136     Value *idx = *oi;
1137     unsigned nextBasePtrReg = makeAnotherReg (Type::UIntTy);
1138     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
1139       // It's a struct access.  idx is the index into the structure,
1140       // which names the field. Use the TargetData structure to
1141       // pick out what the layout of the structure is in memory.
1142       // Use the (constant) structure index's value to find the
1143       // right byte offset from the StructLayout class's list of
1144       // structure member offsets.
1145       unsigned fieldIndex = cast<ConstantUInt> (idx)->getValue ();
1146       unsigned memberOffset =
1147         TD.getStructLayout (StTy)->MemberOffsets[fieldIndex];
1148       // Emit an ADD to add memberOffset to the basePtr.
1149       // We might have to copy memberOffset into a register first, if
1150       // it's big.
1151       if (memberOffset + 4096 < 8191) {
1152         BuildMI (*MBB, IP, V8::ADDri, 2,
1153                  nextBasePtrReg).addReg (basePtrReg).addSImm (memberOffset);
1154       } else {
1155         unsigned offsetReg = makeAnotherReg (Type::IntTy);
1156         copyConstantToRegister (MBB, IP,
1157           ConstantSInt::get(Type::IntTy, memberOffset), offsetReg);
1158         BuildMI (*MBB, IP, V8::ADDrr, 2,
1159                  nextBasePtrReg).addReg (basePtrReg).addReg (offsetReg);
1160       }
1161       // The next type is the member of the structure selected by the
1162       // index.
1163       Ty = StTy->getElementType (fieldIndex);
1164     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
1165       // It's an array or pointer access: [ArraySize x ElementType].
1166       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
1167       // must find the size of the pointed-to type (Not coincidentally, the next
1168       // type is the type of the elements in the array).
1169       Ty = SqTy->getElementType ();
1170       unsigned elementSize = TD.getTypeSize (Ty);
1171       unsigned OffsetReg = ~0U;
1172       int64_t Offset = -1;
1173       bool addImmed = false;
1174       if (isa<ConstantIntegral> (idx)) {
1175         // If idx is a constant, we don't have to emit the multiply.
1176         int64_t Val = cast<ConstantIntegral> (idx)->getRawValue ();
1177         if ((Val * elementSize) + 4096 < 8191) {
1178           // (Val * elementSize) is constant and fits in an immediate field.
1179           // emit: nextBasePtrReg = ADDri basePtrReg, (Val * elementSize)
1180           addImmed = true;
1181           Offset = Val * elementSize;
1182         } else {
1183           // (Val * elementSize) is constant, but doesn't fit in an immediate
1184           // field.  emit: OffsetReg = (Val * elementSize)
1185           //               nextBasePtrReg = ADDrr OffsetReg, basePtrReg
1186           OffsetReg = makeAnotherReg (Type::IntTy);
1187           copyConstantToRegister (MBB, IP,
1188             ConstantSInt::get(Type::IntTy, Val * elementSize), OffsetReg);
1189         }
1190       } else {
1191         // idx is not constant, we have to shift or multiply.
1192         OffsetReg = makeAnotherReg (Type::IntTy);
1193         unsigned idxReg = getReg (idx, MBB, IP);
1194         switch (elementSize) {
1195           case 1:
1196             BuildMI (*MBB, IP, V8::ORrr, 2, OffsetReg).addReg (V8::G0).addReg (idxReg);
1197             break;
1198           case 2:
1199             BuildMI (*MBB, IP, V8::SLLri, 2, OffsetReg).addReg (idxReg).addZImm (1);
1200             break;
1201           case 4:
1202             BuildMI (*MBB, IP, V8::SLLri, 2, OffsetReg).addReg (idxReg).addZImm (2);
1203             break;
1204           case 8:
1205             BuildMI (*MBB, IP, V8::SLLri, 2, OffsetReg).addReg (idxReg).addZImm (3);
1206             break;
1207           default: {
1208             if (elementSize + 4096 < 8191) {
1209               // Emit a SMUL to multiply the register holding the index by
1210               // elementSize, putting the result in OffsetReg.
1211               BuildMI (*MBB, IP, V8::SMULri, 2,
1212                        OffsetReg).addReg (idxReg).addSImm (elementSize);
1213             } else {
1214               unsigned elementSizeReg = makeAnotherReg (Type::UIntTy);
1215               copyConstantToRegister (MBB, IP,
1216                 ConstantUInt::get(Type::UIntTy, elementSize), elementSizeReg);
1217               // Emit a SMUL to multiply the register holding the index by
1218               // the register w/ elementSize, putting the result in OffsetReg.
1219               BuildMI (*MBB, IP, V8::SMULrr, 2,
1220                        OffsetReg).addReg (idxReg).addReg (elementSizeReg);
1221             }
1222             break;
1223           }
1224         }
1225       }
1226       if (addImmed) {
1227         // Emit an ADD to add the constant immediate Offset to the basePtr.
1228         BuildMI (*MBB, IP, V8::ADDri, 2,
1229                  nextBasePtrReg).addReg (basePtrReg).addSImm (Offset);
1230       } else {
1231         // Emit an ADD to add OffsetReg to the basePtr.
1232         BuildMI (*MBB, IP, V8::ADDrr, 2,
1233                  nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
1234       }
1235     }
1236     basePtrReg = nextBasePtrReg;
1237   }
1238   // After we have processed all the indices, the result is left in
1239   // basePtrReg.  Move it to the register where we were expected to
1240   // put the answer.
1241   BuildMI (BB, V8::ORrr, 1, TargetReg).addReg (V8::G0).addReg (basePtrReg);
1242 }
1243
1244 void V8ISel::visitGetElementPtrInst (GetElementPtrInst &I) {
1245   unsigned outputReg = getReg (I);
1246   emitGEPOperation (BB, BB->end (), I.getOperand (0),
1247                     I.op_begin ()+1, I.op_end (), outputReg);
1248 }
1249
1250 void V8ISel::emitOp64LibraryCall (MachineBasicBlock *MBB,
1251                                   MachineBasicBlock::iterator IP,
1252                                   unsigned DestReg,
1253                                   const char *FuncName,
1254                                   unsigned Op0Reg, unsigned Op1Reg) {
1255   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O0).addReg (V8::G0).addReg (Op0Reg);
1256   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O1).addReg (V8::G0).addReg (Op0Reg+1);
1257   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O2).addReg (V8::G0).addReg (Op1Reg);
1258   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O3).addReg (V8::G0).addReg (Op1Reg+1);
1259   BuildMI (*MBB, IP, V8::CALL, 1).addExternalSymbol (FuncName, true);
1260   BuildMI (*MBB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (V8::O0);
1261   BuildMI (*MBB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0).addReg (V8::O1);
1262 }
1263
1264 void V8ISel::emitShift64 (MachineBasicBlock *MBB,
1265                           MachineBasicBlock::iterator IP, Instruction &I,
1266                           unsigned DestReg, unsigned SrcReg,
1267                           unsigned ShiftAmtReg) {
1268   bool isSigned = I.getType()->isSigned();
1269
1270   switch (I.getOpcode ()) {
1271   case Instruction::Shr: {
1272     unsigned CarryReg = makeAnotherReg (Type::IntTy),
1273              ThirtyTwo = makeAnotherReg (Type::IntTy),
1274              HalfShiftReg = makeAnotherReg (Type::IntTy),
1275              NegHalfShiftReg = makeAnotherReg (Type::IntTy),
1276              TempReg = makeAnotherReg (Type::IntTy);
1277     unsigned OneShiftOutReg = makeAnotherReg (Type::ULongTy),
1278              TwoShiftsOutReg = makeAnotherReg (Type::ULongTy);
1279
1280     MachineBasicBlock *thisMBB = BB;
1281     const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1282     MachineBasicBlock *shiftMBB = new MachineBasicBlock (LLVM_BB);
1283     F->getBasicBlockList ().push_back (shiftMBB);
1284     MachineBasicBlock *oneShiftMBB = new MachineBasicBlock (LLVM_BB);
1285     F->getBasicBlockList ().push_back (oneShiftMBB);
1286     MachineBasicBlock *twoShiftsMBB = new MachineBasicBlock (LLVM_BB);
1287     F->getBasicBlockList ().push_back (twoShiftsMBB);
1288     MachineBasicBlock *continueMBB = new MachineBasicBlock (LLVM_BB);
1289     F->getBasicBlockList ().push_back (continueMBB);
1290
1291     // .lshr_begin:
1292     //   ...
1293     //   subcc %g0, ShiftAmtReg, %g0                   ! Is ShAmt == 0?
1294     //   be .lshr_continue                             ! Then don't shift.
1295     //   ba .lshr_shift                                ! else shift.
1296
1297     BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (V8::G0)
1298       .addReg (ShiftAmtReg);
1299     BuildMI (BB, V8::BE, 1).addMBB (continueMBB);
1300     BuildMI (BB, V8::BA, 1).addMBB (shiftMBB);
1301
1302     // Update machine-CFG edges
1303     BB->addSuccessor (continueMBB);
1304     BB->addSuccessor (shiftMBB);
1305
1306     // .lshr_shift: ! [preds: begin]
1307     //   or %g0, 32, ThirtyTwo
1308     //   subcc ThirtyTwo, ShiftAmtReg, HalfShiftReg    ! Calculate 32 - shamt
1309     //   bg .lshr_two_shifts                           ! If >0, b two_shifts
1310     //   ba .lshr_one_shift                            ! else one_shift.
1311
1312     BB = shiftMBB;
1313
1314     BuildMI (BB, V8::ORri, 2, ThirtyTwo).addReg (V8::G0).addSImm (32);
1315     BuildMI (BB, V8::SUBCCrr, 2, HalfShiftReg).addReg (ThirtyTwo)
1316       .addReg (ShiftAmtReg);
1317     BuildMI (BB, V8::BG, 1).addMBB (twoShiftsMBB);
1318     BuildMI (BB, V8::BA, 1).addMBB (oneShiftMBB);
1319
1320     // Update machine-CFG edges
1321     BB->addSuccessor (twoShiftsMBB);
1322     BB->addSuccessor (oneShiftMBB);
1323
1324     // .lshr_two_shifts: ! [preds: shift]
1325     //   sll SrcReg, HalfShiftReg, CarryReg            ! Save the borrows
1326     //  ! <SHIFT> in following is sra if signed, srl if unsigned
1327     //   <SHIFT> SrcReg, ShiftAmtReg, TwoShiftsOutReg  ! Shift top half
1328     //   srl SrcReg+1, ShiftAmtReg, TempReg            ! Shift bottom half
1329     //   or TempReg, CarryReg, TwoShiftsOutReg+1       ! Restore the borrows
1330     //   ba .lshr_continue
1331     unsigned ShiftOpcode = (isSigned ? V8::SRArr : V8::SRLrr);
1332
1333     BB = twoShiftsMBB;
1334
1335     BuildMI (BB, V8::SLLrr, 2, CarryReg).addReg (SrcReg)
1336       .addReg (HalfShiftReg);
1337     BuildMI (BB, ShiftOpcode, 2, TwoShiftsOutReg).addReg (SrcReg)
1338       .addReg (ShiftAmtReg);
1339     BuildMI (BB, V8::SRLrr, 2, TempReg).addReg (SrcReg+1)
1340       .addReg (ShiftAmtReg);
1341     BuildMI (BB, V8::ORrr, 2, TwoShiftsOutReg+1).addReg (TempReg)
1342       .addReg (CarryReg);
1343     BuildMI (BB, V8::BA, 1).addMBB (continueMBB);
1344
1345     // Update machine-CFG edges
1346     BB->addSuccessor (continueMBB);
1347
1348     // .lshr_one_shift: ! [preds: shift]
1349     //  ! if unsigned:
1350     //   or %g0, %g0, OneShiftOutReg                       ! Zero top half
1351     //  ! or, if signed:
1352     //   sra SrcReg, 31, OneShiftOutReg                    ! Sign-ext top half
1353     //   sub %g0, HalfShiftReg, NegHalfShiftReg            ! Make ShiftAmt >0
1354     //   <SHIFT> SrcReg, NegHalfShiftReg, OneShiftOutReg+1 ! Shift bottom half
1355     //   ba .lshr_continue
1356
1357     BB = oneShiftMBB;
1358
1359     if (isSigned)
1360       BuildMI (BB, V8::SRAri, 2, OneShiftOutReg).addReg (SrcReg).addZImm (31);
1361     else
1362       BuildMI (BB, V8::ORrr, 2, OneShiftOutReg).addReg (V8::G0)
1363         .addReg (V8::G0);
1364     BuildMI (BB, V8::SUBrr, 2, NegHalfShiftReg).addReg (V8::G0)
1365       .addReg (HalfShiftReg);
1366     BuildMI (BB, ShiftOpcode, 2, OneShiftOutReg+1).addReg (SrcReg)
1367       .addReg (NegHalfShiftReg);
1368     BuildMI (BB, V8::BA, 1).addMBB (continueMBB);
1369
1370     // Update machine-CFG edges
1371     BB->addSuccessor (continueMBB);
1372
1373     // .lshr_continue: ! [preds: begin, do_one_shift, do_two_shifts]
1374     //   phi (SrcReg, begin), (TwoShiftsOutReg, two_shifts),
1375     //       (OneShiftOutReg, one_shift), DestReg      ! Phi top half...
1376     //   phi (SrcReg+1, begin), (TwoShiftsOutReg+1, two_shifts),
1377     //       (OneShiftOutReg+1, one_shift), DestReg+1  ! And phi bottom half.
1378
1379     BB = continueMBB;
1380     BuildMI (BB, V8::PHI, 6, DestReg).addReg (SrcReg).addMBB (thisMBB)
1381       .addReg (TwoShiftsOutReg).addMBB (twoShiftsMBB)
1382       .addReg (OneShiftOutReg).addMBB (oneShiftMBB);
1383     BuildMI (BB, V8::PHI, 6, DestReg+1).addReg (SrcReg+1).addMBB (thisMBB)
1384       .addReg (TwoShiftsOutReg+1).addMBB (twoShiftsMBB)
1385       .addReg (OneShiftOutReg+1).addMBB (oneShiftMBB);
1386     return;
1387   }
1388   case Instruction::Shl:
1389   default:
1390     std::cerr << "Sorry, 64-bit shifts are not yet supported:\n" << I;
1391     abort ();
1392   }
1393 }
1394
1395 void V8ISel::visitBinaryOperator (Instruction &I) {
1396   unsigned DestReg = getReg (I);
1397   unsigned Op0Reg = getReg (I.getOperand (0));
1398
1399   unsigned Class = getClassB (I.getType());
1400   unsigned OpCase = ~0;
1401
1402   if (Class > cLong) {
1403     unsigned Op1Reg = getReg (I.getOperand (1));
1404     switch (I.getOpcode ()) {
1405     case Instruction::Add: OpCase = 0; break;
1406     case Instruction::Sub: OpCase = 1; break;
1407     case Instruction::Mul: OpCase = 2; break;
1408     case Instruction::Div: OpCase = 3; break;
1409     default: visitInstruction (I); return;
1410     }
1411     static unsigned Opcodes[] = { V8::FADDS, V8::FADDD,
1412                                   V8::FSUBS, V8::FSUBD,
1413                                   V8::FMULS, V8::FMULD,
1414                                   V8::FDIVS, V8::FDIVD };
1415     BuildMI (BB, Opcodes[2*OpCase + (Class - cFloat)], 2, DestReg)
1416       .addReg (Op0Reg).addReg (Op1Reg);
1417     return;
1418   }
1419
1420   unsigned ResultReg = DestReg;
1421   if (Class != cInt && Class != cLong)
1422     ResultReg = makeAnotherReg (I.getType ());
1423
1424   if (Class == cLong) {
1425     const char *FuncName;
1426     unsigned Op1Reg = getReg (I.getOperand (1));
1427     DEBUG (std::cerr << "Class = cLong\n");
1428     DEBUG (std::cerr << "Op0Reg = " << Op0Reg << ", " << Op0Reg+1 << "\n");
1429     DEBUG (std::cerr << "Op1Reg = " << Op1Reg << ", " << Op1Reg+1 << "\n");
1430     DEBUG (std::cerr << "ResultReg = " << ResultReg << ", " << ResultReg+1 << "\n");
1431     DEBUG (std::cerr << "DestReg = " << DestReg << ", " << DestReg+1 <<  "\n");
1432     switch (I.getOpcode ()) {
1433     case Instruction::Add:
1434       BuildMI (BB, V8::ADDCCrr, 2, ResultReg+1).addReg (Op0Reg+1)
1435         .addReg (Op1Reg+1);
1436       BuildMI (BB, V8::ADDXrr, 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1437       return;
1438     case Instruction::Sub:
1439       BuildMI (BB, V8::SUBCCrr, 2, ResultReg+1).addReg (Op0Reg+1)
1440         .addReg (Op1Reg+1);
1441       BuildMI (BB, V8::SUBXrr, 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1442       return;
1443     case Instruction::Mul:
1444       FuncName = I.getType ()->isSigned () ? "__mul64" : "__umul64";
1445       emitOp64LibraryCall (BB, BB->end (), DestReg, FuncName, Op0Reg, Op1Reg);
1446       return;
1447     case Instruction::Div:
1448       FuncName = I.getType ()->isSigned () ? "__div64" : "__udiv64";
1449       emitOp64LibraryCall (BB, BB->end (), DestReg, FuncName, Op0Reg, Op1Reg);
1450       return;
1451     case Instruction::Rem:
1452       FuncName = I.getType ()->isSigned () ? "__rem64" : "__urem64";
1453       emitOp64LibraryCall (BB, BB->end (), DestReg, FuncName, Op0Reg, Op1Reg);
1454       return;
1455     case Instruction::Shl:
1456     case Instruction::Shr:
1457       emitShift64 (BB, BB->end (), I, DestReg, Op0Reg, Op1Reg);
1458       return;
1459     }
1460   }
1461
1462   switch (I.getOpcode ()) {
1463   case Instruction::Add: OpCase = 0; break;
1464   case Instruction::Sub: OpCase = 1; break;
1465   case Instruction::Mul: OpCase = 2; break;
1466   case Instruction::And: OpCase = 3; break;
1467   case Instruction::Or:  OpCase = 4; break;
1468   case Instruction::Xor: OpCase = 5; break;
1469   case Instruction::Shl: OpCase = 6; break;
1470   case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
1471
1472   case Instruction::Div:
1473   case Instruction::Rem: {
1474     unsigned Dest = ResultReg;
1475     unsigned Op1Reg = getReg (I.getOperand (1));
1476     if (I.getOpcode() == Instruction::Rem)
1477       Dest = makeAnotherReg(I.getType());
1478
1479     // FIXME: this is probably only right for 32 bit operands.
1480     if (I.getType ()->isSigned()) {
1481       unsigned Tmp = makeAnotherReg (I.getType ());
1482       // Sign extend into the Y register
1483       BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
1484       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (Tmp).addReg (V8::G0);
1485       BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1486     } else {
1487       // Zero extend into the Y register, ie, just set it to zero
1488       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (V8::G0).addReg (V8::G0);
1489       BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1490     }
1491
1492     if (I.getOpcode() == Instruction::Rem) {
1493       unsigned Tmp = makeAnotherReg (I.getType ());
1494       BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
1495       BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
1496     }
1497     break;
1498   }
1499   default:
1500     visitInstruction (I);
1501     return;
1502   }
1503
1504   static const unsigned Opcodes[] = {
1505     V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
1506     V8::SLLrr, V8::SRLrr, V8::SRArr
1507   };
1508   static const unsigned OpcodesRI[] = {
1509     V8::ADDri, V8::SUBri, V8::SMULri, V8::ANDri, V8::ORri, V8::XORri,
1510     V8::SLLri, V8::SRLri, V8::SRAri
1511   };
1512   unsigned Op1Reg = ~0U;
1513   if (OpCase != ~0U) {
1514     Value *Arg1 = I.getOperand (1);
1515     bool useImmed = false;
1516     int64_t Val = 0;
1517     if ((getClassB (I.getType ()) <= cInt) && (isa<ConstantIntegral> (Arg1))) {
1518       Val = cast<ConstantIntegral> (Arg1)->getRawValue ();
1519       useImmed = (Val > -4096 && Val < 4095);
1520     }
1521     if (useImmed) {
1522       BuildMI (BB, OpcodesRI[OpCase], 2, ResultReg).addReg (Op0Reg).addSImm (Val);
1523     } else {
1524       Op1Reg = getReg (I.getOperand (1));
1525       BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1526     }
1527   }
1528
1529   switch (getClassB (I.getType ())) {
1530     case cByte:
1531       if (I.getType ()->isSigned ()) { // add byte
1532         BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
1533       } else { // add ubyte
1534         unsigned TmpReg = makeAnotherReg (I.getType ());
1535         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
1536         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
1537       }
1538       break;
1539     case cShort:
1540       if (I.getType ()->isSigned ()) { // add short
1541         unsigned TmpReg = makeAnotherReg (I.getType ());
1542         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1543         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
1544       } else { // add ushort
1545         unsigned TmpReg = makeAnotherReg (I.getType ());
1546         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1547         BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
1548       }
1549       break;
1550     case cInt:
1551       // Nothing to do here.
1552       break;
1553     case cLong: {
1554       // Only support and, or, xor here - others taken care of above.
1555       if (OpCase < 3 || OpCase > 5) {
1556         visitInstruction (I);
1557         return;
1558       }
1559       // Do the other half of the value:
1560       BuildMI (BB, Opcodes[OpCase], 2, ResultReg+1).addReg (Op0Reg+1)
1561         .addReg (Op1Reg+1);
1562       break;
1563     }
1564     default:
1565       visitInstruction (I);
1566   }
1567 }
1568
1569 void V8ISel::visitSetCondInst(SetCondInst &I) {
1570   if (canFoldSetCCIntoBranch(&I))
1571     return;  // Fold this into a branch.
1572
1573   unsigned Op0Reg = getReg (I.getOperand (0));
1574   unsigned Op1Reg = getReg (I.getOperand (1));
1575   unsigned DestReg = getReg (I);
1576   const Type *Ty = I.getOperand (0)->getType ();
1577
1578   // Compare the two values.
1579   if (getClass (Ty) < cLong) {
1580     BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1581   } else if (getClass (Ty) == cLong) {
1582     switch (I.getOpcode()) {
1583     default: assert(0 && "Unknown setcc instruction!");
1584     case Instruction::SetEQ:
1585     case Instruction::SetNE: {
1586       unsigned TempReg0 = makeAnotherReg (Type::IntTy),
1587                TempReg1 = makeAnotherReg (Type::IntTy),
1588                TempReg2 = makeAnotherReg (Type::IntTy),
1589                TempReg3 = makeAnotherReg (Type::IntTy);
1590       MachineOpCode Opcode;
1591       int Immed;
1592       // These guys are special - no branches needed!
1593       BuildMI (BB, V8::XORrr, 2, TempReg0).addReg (Op0Reg+1).addReg (Op1Reg+1);
1594       BuildMI (BB, V8::XORrr, 2, TempReg1).addReg (Op0Reg).addReg (Op1Reg);
1595       BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (V8::G0).addReg (TempReg1);
1596       Opcode = I.getOpcode() == Instruction::SetEQ ? V8::SUBXri : V8::ADDXri;
1597       Immed  = I.getOpcode() == Instruction::SetEQ ? -1         : 0;
1598       BuildMI (BB, Opcode, 2, TempReg2).addReg (V8::G0).addSImm (Immed);
1599       BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (V8::G0).addReg (TempReg0);
1600       BuildMI (BB, Opcode, 2, TempReg3).addReg (V8::G0).addSImm (Immed);
1601       Opcode = I.getOpcode() == Instruction::SetEQ ? V8::ANDrr  : V8::ORrr;
1602       BuildMI (BB, Opcode, 2, DestReg).addReg (TempReg2).addReg (TempReg3);
1603       return;
1604     }
1605     case Instruction::SetLT:
1606     case Instruction::SetGE:
1607       BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (Op0Reg+1).addReg (Op1Reg+1);
1608       BuildMI (BB, V8::SUBXCCrr, 2, V8::G0).addReg (Op0Reg).addReg (Op1Reg);
1609       break;
1610     case Instruction::SetGT:
1611     case Instruction::SetLE:
1612       BuildMI (BB, V8::SUBCCri, 2, V8::G0).addReg (V8::G0).addSImm (1);
1613       BuildMI (BB, V8::SUBXCCrr, 2, V8::G0).addReg (Op0Reg+1).addReg (Op1Reg+1);
1614       BuildMI (BB, V8::SUBXCCrr, 2, V8::G0).addReg (Op0Reg).addReg (Op1Reg);
1615       break;
1616     }
1617   } else if (getClass (Ty) == cFloat) {
1618     BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1619   } else if (getClass (Ty) == cDouble) {
1620     BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1621   }
1622
1623   unsigned BranchIdx;
1624   switch (I.getOpcode()) {
1625   default: assert(0 && "Unknown setcc instruction!");
1626   case Instruction::SetEQ: BranchIdx = 0; break;
1627   case Instruction::SetNE: BranchIdx = 1; break;
1628   case Instruction::SetLT: BranchIdx = 2; break;
1629   case Instruction::SetGT: BranchIdx = 3; break;
1630   case Instruction::SetLE: BranchIdx = 4; break;
1631   case Instruction::SetGE: BranchIdx = 5; break;
1632   }
1633
1634   unsigned Column = 0;
1635   if (Ty->isSigned() && !Ty->isFloatingPoint()) Column = 1;
1636   if (Ty->isFloatingPoint()) Column = 2;
1637   static unsigned OpcodeTab[3*6] = {
1638                                  // LLVM            SparcV8
1639                                  //        unsigned signed  fp
1640     V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1641     V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1642     V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1643     V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1644     V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1645     V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1646   };
1647   unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1648
1649   MachineBasicBlock *thisMBB = BB;
1650   const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1651   //  thisMBB:
1652   //  ...
1653   //   subcc %reg0, %reg1, %g0
1654   //   TrueVal = or G0, 1
1655   //   bCC sinkMBB
1656
1657   unsigned TrueValue = makeAnotherReg (I.getType ());
1658   BuildMI (BB, V8::ORri, 2, TrueValue).addReg (V8::G0).addZImm (1);
1659
1660   MachineBasicBlock *copy0MBB = new MachineBasicBlock (LLVM_BB);
1661   MachineBasicBlock *sinkMBB = new MachineBasicBlock (LLVM_BB);
1662   BuildMI (BB, Opcode, 1).addMBB (sinkMBB);
1663
1664   // Update machine-CFG edges
1665   BB->addSuccessor (sinkMBB);
1666   BB->addSuccessor (copy0MBB);
1667
1668   //  copy0MBB:
1669   //   %FalseValue = or %G0, 0
1670   //   # fall through
1671   BB = copy0MBB;
1672   F->getBasicBlockList ().push_back (BB);
1673   unsigned FalseValue = makeAnotherReg (I.getType ());
1674   BuildMI (BB, V8::ORrr, 2, FalseValue).addReg (V8::G0).addReg (V8::G0);
1675
1676   // Update machine-CFG edges
1677   BB->addSuccessor (sinkMBB);
1678
1679   DEBUG (std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1680   DEBUG (std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1681   DEBUG (std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1682
1683   //  sinkMBB:
1684   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1685   //  ...
1686   BB = sinkMBB;
1687   F->getBasicBlockList ().push_back (BB);
1688   BuildMI (BB, V8::PHI, 4, DestReg).addReg (FalseValue)
1689     .addMBB (copy0MBB).addReg (TrueValue).addMBB (thisMBB);
1690 }
1691
1692 void V8ISel::visitAllocaInst(AllocaInst &I) {
1693   // Find the data size of the alloca inst's getAllocatedType.
1694   const Type *Ty = I.getAllocatedType();
1695   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1696
1697   unsigned ArraySizeReg = getReg (I.getArraySize ());
1698   unsigned TySizeReg = getReg (ConstantUInt::get (Type::UIntTy, TySize));
1699   unsigned TmpReg1 = makeAnotherReg (Type::UIntTy);
1700   unsigned TmpReg2 = makeAnotherReg (Type::UIntTy);
1701   unsigned StackAdjReg = makeAnotherReg (Type::UIntTy);
1702
1703   // StackAdjReg = (ArraySize * TySize) rounded up to nearest
1704   // doubleword boundary.
1705   BuildMI (BB, V8::UMULrr, 2, TmpReg1).addReg (ArraySizeReg).addReg (TySizeReg);
1706
1707   // Round up TmpReg1 to nearest doubleword boundary:
1708   BuildMI (BB, V8::ADDri, 2, TmpReg2).addReg (TmpReg1).addSImm (7);
1709   BuildMI (BB, V8::ANDri, 2, StackAdjReg).addReg (TmpReg2).addSImm (-8);
1710
1711   // Subtract size from stack pointer, thereby allocating some space.
1712   BuildMI (BB, V8::SUBrr, 2, V8::SP).addReg (V8::SP).addReg (StackAdjReg);
1713
1714   // Put a pointer to the space into the result register, by copying
1715   // the stack pointer.
1716   BuildMI (BB, V8::ADDri, 2, getReg(I)).addReg (V8::SP).addSImm (96);
1717
1718   // Inform the Frame Information that we have just allocated a variable-sized
1719   // object.
1720   F->getFrameInfo()->CreateVariableSizedObject();
1721 }
1722
1723 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1724 /// function, lowering any calls to unknown intrinsic functions into the
1725 /// equivalent LLVM code.
1726 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1727   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1728     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1729       if (CallInst *CI = dyn_cast<CallInst>(I++))
1730         if (Function *F = CI->getCalledFunction())
1731           switch (F->getIntrinsicID()) {
1732           case Intrinsic::vastart:
1733           case Intrinsic::vacopy:
1734           case Intrinsic::vaend:
1735             // We directly implement these intrinsics
1736           case Intrinsic::not_intrinsic: break;
1737           default:
1738             // All other intrinsic calls we must lower.
1739             Instruction *Before = CI->getPrev();
1740             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1741             if (Before) {        // Move iterator to instruction after call
1742               I = Before;  ++I;
1743             } else {
1744               I = BB->begin();
1745             }
1746           }
1747 }
1748
1749
1750 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1751   switch (ID) {
1752   default:
1753     std::cerr << "Sorry, unknown intrinsic function call:\n" << CI; abort ();
1754
1755   case Intrinsic::vastart: {
1756     // Add the VarArgsOffset to the frame pointer, and copy it to the result.
1757     unsigned DestReg = getReg (CI);
1758     BuildMI (BB, V8::ADDri, 2, DestReg).addReg (V8::FP).addSImm (VarArgsOffset);
1759     return;
1760   }
1761
1762   case Intrinsic::vaend:
1763     // va_end is a no-op on SparcV8.
1764     return;
1765
1766   case Intrinsic::vacopy: {
1767     // Copy the va_list ptr (arg1) to the result.
1768     unsigned DestReg = getReg (CI), SrcReg = getReg (CI.getOperand (1));
1769     BuildMI (BB, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (SrcReg);
1770     return;
1771   }
1772   }
1773 }
1774
1775 void V8ISel::visitVANextInst (VANextInst &I) {
1776   // Add the type size to the vararg pointer (arg0).
1777   unsigned DestReg = getReg (I);
1778   unsigned SrcReg = getReg (I.getOperand (0));
1779   unsigned TySize = TM.getTargetData ().getTypeSize (I.getArgType ());
1780   BuildMI (BB, V8::ADDri, 2, DestReg).addReg (SrcReg).addSImm (TySize);
1781 }
1782
1783 void V8ISel::visitVAArgInst (VAArgInst &I) {
1784   unsigned VAList = getReg (I.getOperand (0));
1785   unsigned DestReg = getReg (I);
1786
1787   switch (I.getType ()->getTypeID ()) {
1788   case Type::PointerTyID:
1789   case Type::UIntTyID:
1790   case Type::IntTyID:
1791     BuildMI (BB, V8::LD, 2, DestReg).addReg (VAList).addSImm (0);
1792     return;
1793
1794   case Type::ULongTyID:
1795   case Type::LongTyID:
1796     BuildMI (BB, V8::LD, 2, DestReg).addReg (VAList).addSImm (0);
1797     BuildMI (BB, V8::LD, 2, DestReg+1).addReg (VAList).addSImm (4);
1798     return;
1799
1800   case Type::DoubleTyID: {
1801     unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
1802     unsigned TempReg = makeAnotherReg (Type::IntTy);
1803     unsigned TempReg2 = makeAnotherReg (Type::IntTy);
1804     int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
1805     BuildMI (BB, V8::LD, 2, TempReg).addReg (VAList).addSImm (0);
1806     BuildMI (BB, V8::LD, 2, TempReg2).addReg (VAList).addSImm (4);
1807     BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (TempReg);
1808     BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (4).addReg (TempReg2);
1809     BuildMI (BB, V8::LDDFri, 2, DestReg).addFrameIndex (FI).addSImm (0);
1810     return;
1811   }
1812
1813   default:
1814     std::cerr << "Sorry, vaarg instruction of this type still unsupported:\n"
1815               << I;
1816     abort ();
1817     return;
1818   }
1819 }