Rewrite emitCastOperation, refactoring parts of it into emitIntegerCast, and
[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/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.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
38     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
39
40     // MBBMap - Mapping between LLVM BB -> Machine BB
41     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
42
43     V8ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
44
45     /// runOnFunction - Top level implementation of instruction selection for
46     /// the entire function.
47     ///
48     bool runOnFunction(Function &Fn);
49
50     virtual const char *getPassName() const {
51       return "SparcV8 Simple Instruction Selection";
52     }
53
54     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
55     /// constant expression GEP support.
56     ///
57     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
58                           Value *Src, User::op_iterator IdxBegin,
59                           User::op_iterator IdxEnd, unsigned TargetReg);
60
61     /// emitCastOperation - Common code shared between visitCastInst and
62     /// constant expression cast support.
63     ///
64     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
65                            Value *Src, const Type *DestTy, unsigned TargetReg);
66
67     /// emitIntegerCast, emitFPToIntegerCast - Helper methods for
68     /// emitCastOperation.
69     ///
70     void emitIntegerCast (MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
71                           const Type *oldTy, unsigned SrcReg, const Type *newTy,
72                           unsigned DestReg);
73     void emitFPToIntegerCast (MachineBasicBlock *BB,
74                               MachineBasicBlock::iterator IP, const Type *oldTy,
75                               unsigned SrcReg, const Type *newTy,
76                               unsigned DestReg);
77
78     /// visitBasicBlock - This method is called when we are visiting a new basic
79     /// block.  This simply creates a new MachineBasicBlock to emit code into
80     /// and adds it to the current MachineFunction.  Subsequent visit* for
81     /// instructions will be invoked for all instructions in the basic block.
82     ///
83     void visitBasicBlock(BasicBlock &LLVM_BB) {
84       BB = MBBMap[&LLVM_BB];
85     }
86
87     void visitBinaryOperator(Instruction &I);
88     void visitShiftInst (ShiftInst &SI) { visitBinaryOperator (SI); }
89     void visitSetCondInst(SetCondInst &I);
90     void visitCallInst(CallInst &I);
91     void visitReturnInst(ReturnInst &I);
92     void visitBranchInst(BranchInst &I);
93     void visitCastInst(CastInst &I);
94     void visitLoadInst(LoadInst &I);
95     void visitStoreInst(StoreInst &I);
96     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
97     void visitGetElementPtrInst(GetElementPtrInst &I);
98     void visitAllocaInst(AllocaInst &I);
99
100     void visitInstruction(Instruction &I) {
101       std::cerr << "Unhandled instruction: " << I;
102       abort();
103     }
104
105     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
106     /// function, lowering any calls to unknown intrinsic functions into the
107     /// equivalent LLVM code.
108     void LowerUnknownIntrinsicFunctionCalls(Function &F);
109     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
110
111     void LoadArgumentsToVirtualRegs(Function *F);
112
113     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
114     /// because we have to generate our sources into the source basic blocks,
115     /// not the current one.
116     ///
117     void SelectPHINodes();
118
119     /// copyConstantToRegister - Output the instructions required to put the
120     /// specified constant into the specified register.
121     ///
122     void copyConstantToRegister(MachineBasicBlock *MBB,
123                                 MachineBasicBlock::iterator IP,
124                                 Constant *C, unsigned R);
125
126     /// makeAnotherReg - This method returns the next register number we haven't
127     /// yet used.
128     ///
129     /// Long values are handled somewhat specially.  They are always allocated
130     /// as pairs of 32 bit integer values.  The register number returned is the
131     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
132     /// of the long value.
133     ///
134     unsigned makeAnotherReg(const Type *Ty) {
135       assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
136              "Current target doesn't have SparcV8 reg info??");
137       const SparcV8RegisterInfo *MRI =
138         static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
139       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
140         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
141         // Create the lower part
142         F->getSSARegMap()->createVirtualRegister(RC);
143         // Create the upper part.
144         return F->getSSARegMap()->createVirtualRegister(RC)-1;
145       }
146
147       // Add the mapping of regnumber => reg class to MachineFunction
148       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
149       return F->getSSARegMap()->createVirtualRegister(RC);
150     }
151
152     unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
153     unsigned getReg(Value *V) {
154       // Just append to the end of the current bb.
155       MachineBasicBlock::iterator It = BB->end();
156       return getReg(V, BB, It);
157     }
158     unsigned getReg(Value *V, MachineBasicBlock *MBB,
159                     MachineBasicBlock::iterator IPt) {
160       unsigned &Reg = RegMap[V];
161       if (Reg == 0) {
162         Reg = makeAnotherReg(V->getType());
163         RegMap[V] = Reg;
164       }
165       // If this operand is a constant, emit the code to copy the constant into
166       // the register here...
167       //
168       if (Constant *C = dyn_cast<Constant>(V)) {
169         copyConstantToRegister(MBB, IPt, C, Reg);
170         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
171       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
172         // Move the address of the global into the register
173         unsigned TmpReg = makeAnotherReg(V->getType());
174         BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
175         BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
176           .addGlobalAddress (GV);
177         RegMap.erase(V);  // Assign a new name to this address if ref'd again
178       }
179
180       return Reg;
181     }
182
183   };
184 }
185
186 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
187   return new V8ISel(TM);
188 }
189
190 enum TypeClass {
191   cByte, cShort, cInt, cLong, cFloat, cDouble
192 };
193
194 static TypeClass getClass (const Type *T) {
195   switch (T->getTypeID()) {
196     case Type::UByteTyID:  case Type::SByteTyID:  return cByte;
197     case Type::UShortTyID: case Type::ShortTyID:  return cShort;
198     case Type::PointerTyID:
199     case Type::UIntTyID:   case Type::IntTyID:    return cInt;
200     case Type::ULongTyID:  case Type::LongTyID:   return cLong;
201     case Type::FloatTyID:                         return cFloat;
202     case Type::DoubleTyID:                        return cDouble;
203     default:
204       assert (0 && "Type of unknown class passed to getClass?");
205       return cByte;
206   }
207 }
208
209 static TypeClass getClassB(const Type *T) {
210   if (T == Type::BoolTy) return cByte;
211   return getClass(T);
212 }
213
214 /// copyConstantToRegister - Output the instructions required to put the
215 /// specified constant into the specified register.
216 ///
217 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
218                                     MachineBasicBlock::iterator IP,
219                                     Constant *C, unsigned R) {
220   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
221     switch (CE->getOpcode()) {
222     case Instruction::GetElementPtr:
223       emitGEPOperation(MBB, IP, CE->getOperand(0),
224                        CE->op_begin()+1, CE->op_end(), R);
225       return;
226     case Instruction::Cast:
227       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
228       return;
229     default:
230       std::cerr << "Copying this constant expr not yet handled: " << *CE;
231       abort();
232     }
233   }
234
235   if (C->getType()->isIntegral ()) {
236     uint64_t Val;
237     unsigned Class = getClassB (C->getType ());
238     if (Class == cLong) {
239       unsigned TmpReg = makeAnotherReg (Type::IntTy);
240       unsigned TmpReg2 = makeAnotherReg (Type::IntTy);
241       // Copy the value into the register pair.
242       // R = top(more-significant) half, R+1 = bottom(less-significant) half
243       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
244       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
245                              Val >> 32), R);
246       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
247                              Val & 0xffffffffU), R+1);
248       return;
249     }
250
251     assert(Class <= cInt && "Type not handled yet!");
252
253     if (C->getType() == Type::BoolTy) {
254       Val = (C == ConstantBool::True);
255     } else {
256       ConstantInt *CI = cast<ConstantInt> (C);
257       Val = CI->getRawValue ();
258     }
259     switch (Class) {
260       case cByte:  Val =  (int8_t) Val; break;
261       case cShort: Val = (int16_t) Val; break;
262       case cInt:   Val = (int32_t) Val; break;
263       default:
264         std::cerr << "Offending constant: " << *C << "\n";
265         assert (0 && "Can't copy this kind of constant into register yet");
266         return;
267     }
268     if (Val == 0) {
269       BuildMI (*MBB, IP, V8::ORrr, 2, R).addReg (V8::G0).addReg(V8::G0);
270     } else if (((int64_t)Val >= -4096) && ((int64_t)Val <= 4095)) {
271       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm(Val);
272     } else {
273       unsigned TmpReg = makeAnotherReg (C->getType ());
274       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
275         .addSImm (((uint32_t) Val) >> 10);
276       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
277         .addSImm (((uint32_t) Val) & 0x03ff);
278       return;
279     }
280   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
281     // We need to spill the constant to memory...
282     MachineConstantPool *CP = F->getConstantPool();
283     unsigned CPI = CP->getConstantPoolIndex(CFP);
284     const Type *Ty = CFP->getType();
285     unsigned TmpReg = makeAnotherReg (Type::UIntTy);
286     unsigned AddrReg = makeAnotherReg (Type::UIntTy);
287
288     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
289     unsigned LoadOpcode = Ty == Type::FloatTy ? V8::LDFri : V8::LDDFri;
290     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addConstantPoolIndex (CPI);
291     BuildMI (*MBB, IP, V8::ORri, 2, AddrReg).addReg (TmpReg)
292       .addConstantPoolIndex (CPI);
293     BuildMI (*MBB, IP, LoadOpcode, 2, R).addReg (AddrReg).addSImm (0);
294   } else if (isa<ConstantPointerNull>(C)) {
295     // Copy zero (null pointer) to the register.
296     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm (0);
297   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
298     // Copy it with a SETHI/OR pair; the JIT + asmwriter should recognize
299     // that SETHI %reg,global == SETHI %reg,%hi(global) and 
300     // OR %reg,global,%reg == OR %reg,%lo(global),%reg.
301     unsigned TmpReg = makeAnotherReg (C->getType ());
302     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addGlobalAddress(GV);
303     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg(TmpReg).addGlobalAddress(GV);
304   } else {
305     std::cerr << "Offending constant: " << *C << "\n";
306     assert (0 && "Can't copy this kind of constant into register yet");
307   }
308 }
309
310 void V8ISel::LoadArgumentsToVirtualRegs (Function *LF) {
311   unsigned ArgOffset;
312   static const unsigned IncomingArgRegs[] = { V8::I0, V8::I1, V8::I2,
313     V8::I3, V8::I4, V8::I5 };
314   // Add IMPLICIT_DEFs of input regs.
315   ArgOffset = 0;
316   for (Function::aiterator I = LF->abegin(), E = LF->aend();
317        I != E && ArgOffset < 6; ++I, ++ArgOffset) {
318     unsigned Reg = getReg(*I);
319     switch (getClassB(I->getType())) {
320     case cByte:
321     case cShort:
322     case cInt:
323     case cFloat:
324       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgOffset]);
325       break;
326     case cDouble:
327     case cLong:
328       // Double and Long use register pairs.
329       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgOffset]);
330       ++ArgOffset;
331       if (ArgOffset < 6)
332         BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgOffset]);
333       break;
334     default:
335       assert (0 && "type not handled");
336       return;
337     }
338   }
339
340   ArgOffset = 0;
341   for (Function::aiterator I = LF->abegin(), E = LF->aend(); I != E;
342        ++I, ++ArgOffset) {
343     unsigned Reg = getReg(*I);
344     if (ArgOffset < 6) {
345
346       switch (getClassB(I->getType())) {
347       case cByte:
348       case cShort:
349       case cInt:
350         BuildMI(BB, V8::ORrr, 2, Reg).addReg (V8::G0)
351           .addReg (IncomingArgRegs[ArgOffset]);
352         break;
353       case cFloat: {
354         // Single-fp args are passed in integer registers; go through
355         // memory to get them into FP registers. (Bleh!)
356         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
357         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
358         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0)
359           .addReg (IncomingArgRegs[ArgOffset]);
360         BuildMI (BB, V8::LDFri, 2, Reg).addFrameIndex (FI).addSImm (0);
361         break;
362       }
363       case cDouble: {
364         // Double-fp args are passed in pairs of integer registers; go through
365         // memory to get them into FP registers. (Double bleh!)
366         unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
367         int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
368         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0)
369           .addReg (IncomingArgRegs[ArgOffset]);
370         ++ArgOffset;
371         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (4)
372           .addReg (IncomingArgRegs[ArgOffset]);
373         BuildMI (BB, V8::LDDFri, 2, Reg).addFrameIndex (FI).addSImm (0);
374         break;
375       }
376       default:
377         // FIXME: handle cLong
378         assert (0 && "64-bit int (long/ulong) function args not handled");
379         return;
380       }
381
382     } else {
383
384       switch (getClassB(I->getType())) {
385       case cByte:
386       case cShort:
387       case cInt: {
388         int FI = F->getFrameInfo()->CreateFixedObject(4, 68 + (4 * ArgOffset));
389         BuildMI (BB, V8::LD, 2, Reg).addFrameIndex (FI).addSImm(0);
390         break;
391       }
392       case cFloat: {
393         int FI = F->getFrameInfo()->CreateFixedObject(4, 68 + (4 * ArgOffset));
394         BuildMI (BB, V8::LDFri, 2, Reg).addFrameIndex (FI).addSImm(0);
395         break;
396       }
397       case cDouble: {
398         int FI = F->getFrameInfo()->CreateFixedObject(8, 68 + (4 * ArgOffset));
399         BuildMI (BB, V8::LDDFri, 2, Reg).addFrameIndex (FI).addSImm(0);
400         break;
401       }
402       default:
403         // FIXME: handle cLong
404         assert (0 && "64-bit integer (long/ulong) function args not handled");
405         return;
406       }
407     }
408   }
409
410 }
411
412 void V8ISel::SelectPHINodes() {
413   const TargetInstrInfo &TII = *TM.getInstrInfo();
414   const Function &LF = *F->getFunction();  // The LLVM function...
415   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
416     const BasicBlock *BB = I;
417     MachineBasicBlock &MBB = *MBBMap[I];
418
419     // Loop over all of the PHI nodes in the LLVM basic block...
420     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
421     for (BasicBlock::const_iterator I = BB->begin();
422          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
423
424       // Create a new machine instr PHI node, and insert it.
425       unsigned PHIReg = getReg(*PN);
426       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
427                                     V8::PHI, PN->getNumOperands(), PHIReg);
428
429       MachineInstr *LongPhiMI = 0;
430       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
431         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
432                             V8::PHI, PN->getNumOperands(), PHIReg+1);
433
434       // PHIValues - Map of blocks to incoming virtual registers.  We use this
435       // so that we only initialize one incoming value for a particular block,
436       // even if the block has multiple entries in the PHI node.
437       //
438       std::map<MachineBasicBlock*, unsigned> PHIValues;
439
440       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
441         MachineBasicBlock *PredMBB = 0;
442         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
443              PE = MBB.pred_end (); PI != PE; ++PI)
444           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
445             PredMBB = *PI;
446             break;
447           }
448         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
449         
450         unsigned ValReg;
451         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
452           PHIValues.lower_bound(PredMBB);
453
454         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
455           // We already inserted an initialization of the register for this
456           // predecessor.  Recycle it.
457           ValReg = EntryIt->second;
458
459         } else {        
460           // Get the incoming value into a virtual register.
461           //
462           Value *Val = PN->getIncomingValue(i);
463
464           // If this is a constant or GlobalValue, we may have to insert code
465           // into the basic block to compute it into a virtual register.
466           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
467               isa<GlobalValue>(Val)) {
468             // Simple constants get emitted at the end of the basic block,
469             // before any terminator instructions.  We "know" that the code to
470             // move a constant into a register will never clobber any flags.
471             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
472           } else {
473             // Because we don't want to clobber any values which might be in
474             // physical registers with the computation of this constant (which
475             // might be arbitrarily complex if it is a constant expression),
476             // just insert the computation at the top of the basic block.
477             MachineBasicBlock::iterator PI = PredMBB->begin();
478             
479             // Skip over any PHI nodes though!
480             while (PI != PredMBB->end() && PI->getOpcode() == V8::PHI)
481               ++PI;
482             
483             ValReg = getReg(Val, PredMBB, PI);
484           }
485
486           // Remember that we inserted a value for this PHI for this predecessor
487           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
488         }
489
490         PhiMI->addRegOperand(ValReg);
491         PhiMI->addMachineBasicBlockOperand(PredMBB);
492         if (LongPhiMI) {
493           LongPhiMI->addRegOperand(ValReg+1);
494           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
495         }
496       }
497
498       // Now that we emitted all of the incoming values for the PHI node, make
499       // sure to reposition the InsertPoint after the PHI that we just added.
500       // This is needed because we might have inserted a constant into this
501       // block, right after the PHI's which is before the old insert point!
502       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
503       ++PHIInsertPoint;
504     }
505   }
506 }
507
508 bool V8ISel::runOnFunction(Function &Fn) {
509   // First pass over the function, lower any unknown intrinsic functions
510   // with the IntrinsicLowering class.
511   LowerUnknownIntrinsicFunctionCalls(Fn);
512   
513   F = &MachineFunction::construct(&Fn, TM);
514   
515   // Create all of the machine basic blocks for the function...
516   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
517     F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
518   
519   BB = &F->front();
520   
521   // Set up a frame object for the return address.  This is used by the
522   // llvm.returnaddress & llvm.frameaddress intrinisics.
523   //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
524   
525   // Copy incoming arguments off of the stack and out of fixed registers.
526   LoadArgumentsToVirtualRegs(&Fn);
527   
528   // Instruction select everything except PHI nodes
529   visit(Fn);
530   
531   // Select the PHI nodes
532   SelectPHINodes();
533   
534   RegMap.clear();
535   MBBMap.clear();
536   F = 0;
537   // We always build a machine code representation for the function
538   return true;
539 }
540
541 void V8ISel::visitCastInst(CastInst &I) {
542   Value *Op = I.getOperand(0);
543   unsigned DestReg = getReg(I);
544   MachineBasicBlock::iterator MI = BB->end();
545   emitCastOperation(BB, MI, Op, I.getType(), DestReg);
546 }
547
548
549 void V8ISel::emitIntegerCast (MachineBasicBlock *BB,
550                               MachineBasicBlock::iterator IP, const Type *oldTy,
551                               unsigned SrcReg, const Type *newTy,
552                               unsigned DestReg) {
553   if (oldTy == newTy) {
554     // No-op cast - just emit a copy; assume the reg. allocator will zap it.
555     BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg(SrcReg);
556     return;
557   }
558   // Emit left-shift, then right-shift to sign- or zero-extend.
559   unsigned TmpReg = makeAnotherReg (newTy);
560   unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
561   BuildMI (*BB, IP, V8::SLLri, 2, TmpReg).addZImm (shiftWidth).addReg(SrcReg);
562   if (newTy->isSigned ()) { // sign-extend with SRA
563     BuildMI(*BB, IP, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
564   } else { // zero-extend with SRL
565     BuildMI(*BB, IP, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
566   }
567 }
568
569 void V8ISel::emitFPToIntegerCast (MachineBasicBlock *BB,
570                                   MachineBasicBlock::iterator IP,
571                                   const Type *oldTy, unsigned SrcReg,
572                                   const Type *newTy, unsigned DestReg) {
573   unsigned FPCastOpcode, FPStoreOpcode, FPSize, FPAlign;
574   unsigned oldTyClass = getClassB(oldTy);
575   if (oldTyClass == cFloat) { 
576     FPCastOpcode = V8::FSTOI; FPStoreOpcode = V8::STFri; FPSize = 4; 
577     FPAlign = TM.getTargetData().getFloatAlignment();
578   } else { // it's a double
579     FPCastOpcode = V8::FDTOI; FPStoreOpcode = V8::STDFri; FPSize = 8; 
580     FPAlign = TM.getTargetData().getDoubleAlignment();
581   }
582   unsigned TempReg = makeAnotherReg (oldTy);
583   BuildMI (*BB, IP, FPCastOpcode, 1, TempReg).addReg (SrcReg);
584   int FI = F->getFrameInfo()->CreateStackObject(FPSize, FPAlign);
585   BuildMI (*BB, IP, FPStoreOpcode, 3).addFrameIndex (FI).addSImm (0)
586     .addReg (TempReg);
587   unsigned TempReg2 = makeAnotherReg (newTy);
588   BuildMI (*BB, IP, V8::LD, 3, TempReg2).addFrameIndex (FI).addSImm (0);
589   emitIntegerCast (BB, IP, Type::IntTy, TempReg2, newTy, DestReg);
590 }
591
592 /// emitCastOperation - Common code shared between visitCastInst and constant
593 /// expression cast support.
594 ///
595 void V8ISel::emitCastOperation(MachineBasicBlock *BB,
596                                MachineBasicBlock::iterator IP, Value *Src,
597                                const Type *DestTy, unsigned DestReg) {
598   const Type *SrcTy = Src->getType();
599   unsigned SrcClass = getClassB(SrcTy);
600   unsigned DestClass = getClassB(DestTy);
601   unsigned SrcReg = getReg(Src, BB, IP);
602
603   const Type *oldTy = SrcTy;
604   const Type *newTy = DestTy;
605   unsigned oldTyClass = SrcClass;
606   unsigned newTyClass = DestClass;
607
608   if (oldTyClass < cLong && newTyClass < cLong) {
609     emitIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
610   } else switch (newTyClass) {
611     case cByte:
612     case cShort:
613     case cInt:
614       switch (oldTyClass) {
615       case cFloat: 
616       case cDouble:
617         emitFPToIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
618         break;
619       default: goto not_yet;
620       }
621       return;
622
623     case cFloat:
624       switch (oldTyClass) {
625       case cLong: goto not_yet;
626       case cFloat:
627         BuildMI (*BB, IP, V8::FMOVS, 1, DestReg).addReg (SrcReg);
628         break;
629       case cDouble:
630         BuildMI (*BB, IP, V8::FDTOS, 1, DestReg).addReg (SrcReg);
631         break;
632       default: {
633         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
634         // cast integer type to float.  Store it to a stack slot and then load
635         // it using ldf into a floating point register. then do fitos.
636         unsigned TmpReg = makeAnotherReg (newTy);
637         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
638         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
639           .addReg (SrcReg);
640         BuildMI (*BB, IP, V8::LDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
641         BuildMI (*BB, IP, V8::FITOS, 1, DestReg).addReg(TmpReg);
642         break;
643       }
644       }
645       return;
646
647     case cDouble:
648       switch (oldTyClass) {
649       case cLong: goto not_yet;
650       case cFloat:
651         BuildMI (*BB, IP, V8::FSTOD, 1, DestReg).addReg (SrcReg);
652         break;
653       case cDouble: // use double move pseudo-instr
654         BuildMI (*BB, IP, V8::FpMOVD, 1, DestReg).addReg (SrcReg);
655         break;
656       default: {
657         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
658         unsigned TmpReg = makeAnotherReg (newTy);
659         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
660         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
661           .addReg (SrcReg);
662         BuildMI (*BB, IP, V8::LDDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
663         BuildMI (*BB, IP, V8::FITOD, 1, DestReg).addReg(TmpReg);
664         break;
665       }
666       }
667       return;
668
669     case cLong:
670       switch (oldTyClass) {
671       case cLong:
672         // Just copy it
673         BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (SrcReg);
674         BuildMI (*BB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0)
675           .addReg (SrcReg+1);
676         break;
677       default: goto not_yet;
678       }
679       return;
680
681     default: goto not_yet;
682   }
683   return;
684 not_yet:
685   std::cerr << "Sorry, cast still unsupported: SrcTy = " << *SrcTy
686             << ", DestTy = " << *DestTy << "\n";
687   abort ();
688 }
689
690 void V8ISel::visitLoadInst(LoadInst &I) {
691   unsigned DestReg = getReg (I);
692   unsigned PtrReg = getReg (I.getOperand (0));
693   switch (getClassB (I.getType ())) {
694    case cByte:
695     if (I.getType ()->isSigned ())
696       BuildMI (BB, V8::LDSB, 2, DestReg).addReg (PtrReg).addSImm(0);
697     else
698       BuildMI (BB, V8::LDUB, 2, DestReg).addReg (PtrReg).addSImm(0);
699     return;
700    case cShort:
701     if (I.getType ()->isSigned ())
702       BuildMI (BB, V8::LDSH, 2, DestReg).addReg (PtrReg).addSImm(0);
703     else
704       BuildMI (BB, V8::LDUH, 2, DestReg).addReg (PtrReg).addSImm(0);
705     return;
706    case cInt:
707     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
708     return;
709    case cLong:
710     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
711     BuildMI (BB, V8::LD, 2, DestReg+1).addReg (PtrReg).addSImm(4);
712     return;
713    case cFloat:
714     BuildMI (BB, V8::LDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
715     return;
716    case cDouble:
717     BuildMI (BB, V8::LDDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
718     return;
719    default:
720     std::cerr << "Load instruction not handled: " << I;
721     abort ();
722     return;
723   }
724 }
725
726 void V8ISel::visitStoreInst(StoreInst &I) {
727   Value *SrcVal = I.getOperand (0);
728   unsigned SrcReg = getReg (SrcVal);
729   unsigned PtrReg = getReg (I.getOperand (1));
730   switch (getClassB (SrcVal->getType ())) {
731    case cByte:
732     BuildMI (BB, V8::STB, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
733     return;
734    case cShort:
735     BuildMI (BB, V8::STH, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
736     return;
737    case cInt:
738     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
739     return;
740    case cLong:
741     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
742     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (4).addReg (SrcReg+1);
743     return;
744    case cFloat:
745     BuildMI (BB, V8::STFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
746     return;
747    case cDouble:
748     BuildMI (BB, V8::STDFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
749     return;
750    default:
751     std::cerr << "Store instruction not handled: " << I;
752     abort ();
753     return;
754   }
755 }
756
757 void V8ISel::visitCallInst(CallInst &I) {
758   MachineInstr *TheCall;
759   // Is it an intrinsic function call?
760   if (Function *F = I.getCalledFunction()) {
761     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
762       visitIntrinsicCall(ID, I);   // Special intrinsics are not handled here
763       return;
764     }
765   }
766
767   unsigned extraStack = 0;
768   // How much extra call stack will we need?
769   for (unsigned i = 7; i < I.getNumOperands (); ++i) {
770     switch (getClassB (I.getOperand (i)->getType ())) {
771       case cLong: extraStack += 8; break;
772       case cFloat: extraStack += 4; break;
773       case cDouble: extraStack += 8; break;
774       default: extraStack += 4; break;
775     }
776   }
777
778   // Deal with args
779   static const unsigned OutgoingArgRegs[] = { V8::O0, V8::O1, V8::O2, V8::O3,
780     V8::O4, V8::O5 };
781   for (unsigned i = 1; i < I.getNumOperands (); ++i) {
782     unsigned ArgReg = getReg (I.getOperand (i));
783     if (i < 7) {
784       if (getClassB (I.getOperand (i)->getType ()) < cLong) {
785         // Schlep it over into the incoming arg register
786         BuildMI (BB, V8::ORrr, 2, OutgoingArgRegs[i - 1]).addReg (V8::G0)
787           .addReg (ArgReg);
788       } else if (getClassB (I.getOperand (i)->getType ()) == cFloat) {
789         // Single-fp args are passed in integer registers; go through
790         // memory to get them out of FP registers. (Bleh!)
791         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
792         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
793         BuildMI (BB, V8::STFri, 3).addFrameIndex (FI).addSImm (0)
794           .addReg (ArgReg);
795         BuildMI (BB, V8::LD, 2, OutgoingArgRegs[i - 1]).addFrameIndex (FI)
796           .addSImm (0);
797       } else if (getClassB (I.getOperand (i)->getType ()) == cDouble) {
798         // Double-fp args are passed in pairs of integer registers; go through
799         // memory to get them out of FP registers. (Bleh!)
800         assert (i <= 5 && "Can't deal with double-fp args past #5 yet");
801         unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
802         int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
803         BuildMI (BB, V8::STDFri, 3).addFrameIndex (FI).addSImm (0)
804           .addReg (ArgReg);
805         BuildMI (BB, V8::LD, 2, OutgoingArgRegs[i - 1]).addFrameIndex (FI)
806           .addSImm (0);
807         BuildMI (BB, V8::LD, 2, OutgoingArgRegs[i]).addFrameIndex (FI)
808           .addSImm (4);
809       } else {
810         assert (0 && "64-bit (double, long, etc.) 'call' opnds not handled");
811       }
812     } else {
813       if (i == 7 && extraStack)
814         BuildMI (BB, V8::ADJCALLSTACKDOWN, 1).addImm (extraStack);
815       // Store arg into designated outgoing-arg stack slot
816       if (getClassB (I.getOperand (i)->getType ()) < cLong) {
817         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (64+4*i)
818           .addReg (ArgReg);
819       } else {
820         assert (0 && "can't push this kind of excess arg on stack yet");
821       }
822     }
823   }
824
825   // Emit call instruction
826   if (Function *F = I.getCalledFunction ()) {
827     BuildMI (BB, V8::CALL, 1).addGlobalAddress (F, true);
828   } else {  // Emit an indirect call...
829     unsigned Reg = getReg (I.getCalledValue ());
830     BuildMI (BB, V8::JMPLrr, 3, V8::O7).addReg (Reg).addReg (V8::G0);
831   }
832
833   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKUP, 1).addImm (extraStack);
834
835   // Deal w/ return value: schlep it over into the destination register
836   if (I.getType () == Type::VoidTy)
837     return;
838   unsigned DestReg = getReg (I);
839   switch (getClassB (I.getType ())) {
840     case cByte:
841     case cShort:
842     case cInt:
843       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
844       break;
845     case cFloat:
846       BuildMI (BB, V8::FMOVS, 2, DestReg).addReg(V8::F0);
847       break;
848     case cDouble:
849       BuildMI (BB, V8::FpMOVD, 2, DestReg).addReg(V8::D0);
850       break;
851     case cLong:
852       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
853       BuildMI (BB, V8::ORrr, 2, DestReg+1).addReg(V8::G0).addReg(V8::O1);
854       break;
855     default:
856       std::cerr << "Return type of call instruction not handled: " << I;
857       abort ();
858   }
859 }
860
861 void V8ISel::visitReturnInst(ReturnInst &I) {
862   if (I.getNumOperands () == 1) {
863     unsigned RetValReg = getReg (I.getOperand (0));
864     switch (getClassB (I.getOperand (0)->getType ())) {
865       case cByte:
866       case cShort:
867       case cInt:
868         // Schlep it over into i0 (where it will become o0 after restore).
869         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
870         break;
871       case cFloat:
872         BuildMI (BB, V8::FMOVS, 1, V8::F0).addReg(RetValReg);
873         break;
874       case cDouble:
875         BuildMI (BB, V8::FpMOVD, 1, V8::D0).addReg(RetValReg);
876         break;
877       case cLong:
878         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
879         BuildMI (BB, V8::ORrr, 2, V8::I1).addReg(V8::G0).addReg(RetValReg+1);
880         break;
881       default:
882         std::cerr << "Return instruction of this type not handled: " << I;
883         abort ();
884     }
885   }
886
887   // Just emit a 'retl' instruction to return.
888   BuildMI(BB, V8::RETL, 0);
889   return;
890 }
891
892 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
893   Function::iterator I = BB; ++I;  // Get iterator to next block
894   return I != BB->getParent()->end() ? &*I : 0;
895 }
896
897 /// visitBranchInst - Handles conditional and unconditional branches.
898 ///
899 void V8ISel::visitBranchInst(BranchInst &I) {
900   BasicBlock *takenSucc = I.getSuccessor (0);
901   MachineBasicBlock *takenSuccMBB = MBBMap[takenSucc];
902   BB->addSuccessor (takenSuccMBB);
903   if (I.isConditional()) {  // conditional branch
904     BasicBlock *notTakenSucc = I.getSuccessor (1);
905     MachineBasicBlock *notTakenSuccMBB = MBBMap[notTakenSucc];
906     BB->addSuccessor (notTakenSuccMBB);
907
908     // CondReg=(<condition>);
909     // If (CondReg==0) goto notTakenSuccMBB;
910     unsigned CondReg = getReg (I.getCondition ());
911     BuildMI (BB, V8::CMPri, 2).addSImm (0).addReg (CondReg);
912     BuildMI (BB, V8::BE, 1).addMBB (notTakenSuccMBB);
913   }
914   // goto takenSuccMBB;
915   BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
916 }
917
918 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
919 /// constant expression GEP support.
920 ///
921 void V8ISel::emitGEPOperation (MachineBasicBlock *MBB,
922                                MachineBasicBlock::iterator IP,
923                                Value *Src, User::op_iterator IdxBegin,
924                                User::op_iterator IdxEnd, unsigned TargetReg) {
925   const TargetData &TD = TM.getTargetData ();
926   const Type *Ty = Src->getType ();
927   unsigned basePtrReg = getReg (Src, MBB, IP);
928
929   // GEPs have zero or more indices; we must perform a struct access
930   // or array access for each one.
931   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
932        ++oi) {
933     Value *idx = *oi;
934     unsigned nextBasePtrReg = makeAnotherReg (Type::UIntTy);
935     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
936       // It's a struct access.  idx is the index into the structure,
937       // which names the field. Use the TargetData structure to
938       // pick out what the layout of the structure is in memory.
939       // Use the (constant) structure index's value to find the
940       // right byte offset from the StructLayout class's list of
941       // structure member offsets.
942       unsigned fieldIndex = cast<ConstantUInt> (idx)->getValue ();
943       unsigned memberOffset =
944         TD.getStructLayout (StTy)->MemberOffsets[fieldIndex];
945       // Emit an ADD to add memberOffset to the basePtr.
946       BuildMI (*MBB, IP, V8::ADDri, 2,
947                nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
948       // The next type is the member of the structure selected by the
949       // index.
950       Ty = StTy->getElementType (fieldIndex);
951     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
952       // It's an array or pointer access: [ArraySize x ElementType].
953       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
954       // must find the size of the pointed-to type (Not coincidentally, the next
955       // type is the type of the elements in the array).
956       Ty = SqTy->getElementType ();
957       unsigned elementSize = TD.getTypeSize (Ty);
958       unsigned idxReg = getReg (idx, MBB, IP);
959       unsigned OffsetReg = makeAnotherReg (Type::IntTy);
960       unsigned elementSizeReg = makeAnotherReg (Type::UIntTy);
961       copyConstantToRegister (MBB, IP,
962         ConstantUInt::get(Type::UIntTy, elementSize), elementSizeReg);
963       // Emit a SMUL to multiply the register holding the index by
964       // elementSize, putting the result in OffsetReg.
965       BuildMI (*MBB, IP, V8::SMULrr, 2,
966                OffsetReg).addReg (elementSizeReg).addReg (idxReg);
967       // Emit an ADD to add OffsetReg to the basePtr.
968       BuildMI (*MBB, IP, V8::ADDrr, 2,
969                nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
970     }
971     basePtrReg = nextBasePtrReg;
972   }
973   // After we have processed all the indices, the result is left in
974   // basePtrReg.  Move it to the register where we were expected to
975   // put the answer.
976   BuildMI (BB, V8::ORrr, 1, TargetReg).addReg (V8::G0).addReg (basePtrReg);
977 }
978
979 void V8ISel::visitGetElementPtrInst (GetElementPtrInst &I) {
980   unsigned outputReg = getReg (I);
981   emitGEPOperation (BB, BB->end (), I.getOperand (0),
982                     I.op_begin ()+1, I.op_end (), outputReg);
983 }
984
985
986 void V8ISel::visitBinaryOperator (Instruction &I) {
987   unsigned DestReg = getReg (I);
988   unsigned Op0Reg = getReg (I.getOperand (0));
989   unsigned Op1Reg = getReg (I.getOperand (1));
990
991   unsigned Class = getClassB (I.getType());
992   unsigned OpCase = ~0;
993
994   if (Class > cLong) {
995     switch (I.getOpcode ()) {
996     case Instruction::Add: OpCase = 0; break;
997     case Instruction::Sub: OpCase = 1; break;
998     case Instruction::Mul: OpCase = 2; break;
999     case Instruction::Div: OpCase = 3; break;
1000     default: visitInstruction (I); return;
1001     }
1002     static unsigned Opcodes[] = { V8::FADDS, V8::FADDD,
1003                                   V8::FSUBS, V8::FSUBD,
1004                                   V8::FMULS, V8::FMULD,
1005                                   V8::FDIVS, V8::FDIVD };
1006     BuildMI (BB, Opcodes[2*OpCase + (Class - cFloat)], 2, DestReg)
1007       .addReg (Op0Reg).addReg (Op1Reg);
1008     return;
1009   }
1010
1011   unsigned ResultReg = DestReg;
1012   if (Class != cInt && Class != cLong)
1013     ResultReg = makeAnotherReg (I.getType ());
1014
1015   if (Class == cLong) {
1016     DEBUG (std::cerr << "Class = cLong\n");
1017     DEBUG (std::cerr << "Op0Reg = " << Op0Reg << ", " << Op0Reg+1 << "\n");
1018     DEBUG (std::cerr << "Op1Reg = " << Op1Reg << ", " << Op1Reg+1 << "\n");
1019     DEBUG (std::cerr << "ResultReg = " << ResultReg << ", " << ResultReg+1 << "\n");
1020     DEBUG (std::cerr << "DestReg = " << DestReg << ", " << DestReg+1 <<  "\n");
1021   }
1022
1023   // FIXME: support long, ulong.
1024   switch (I.getOpcode ()) {
1025   case Instruction::Add: OpCase = 0; break;
1026   case Instruction::Sub: OpCase = 1; break;
1027   case Instruction::Mul: OpCase = 2; break;
1028   case Instruction::And: OpCase = 3; break;
1029   case Instruction::Or:  OpCase = 4; break;
1030   case Instruction::Xor: OpCase = 5; break;
1031   case Instruction::Shl: OpCase = 6; break;
1032   case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
1033
1034   case Instruction::Div:
1035   case Instruction::Rem: {
1036     unsigned Dest = ResultReg;
1037     if (I.getOpcode() == Instruction::Rem)
1038       Dest = makeAnotherReg(I.getType());
1039
1040     // FIXME: this is probably only right for 32 bit operands.
1041     if (I.getType ()->isSigned()) {
1042       unsigned Tmp = makeAnotherReg (I.getType ());
1043       // Sign extend into the Y register
1044       BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
1045       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (Tmp).addReg (V8::G0);
1046       BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1047     } else {
1048       // Zero extend into the Y register, ie, just set it to zero
1049       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (V8::G0).addReg (V8::G0);
1050       BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1051     }
1052
1053     if (I.getOpcode() == Instruction::Rem) {
1054       unsigned Tmp = makeAnotherReg (I.getType ());
1055       BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
1056       BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
1057     }
1058     break;
1059   }
1060   default:
1061     visitInstruction (I);
1062     return;
1063   }
1064
1065   static const unsigned Opcodes[] = {
1066     V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
1067     V8::SLLrr, V8::SRLrr, V8::SRArr
1068   };
1069   if (OpCase != ~0U) {
1070     BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1071   }
1072
1073   switch (getClassB (I.getType ())) {
1074     case cByte: 
1075       if (I.getType ()->isSigned ()) { // add byte
1076         BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
1077       } else { // add ubyte
1078         unsigned TmpReg = makeAnotherReg (I.getType ());
1079         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
1080         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
1081       }
1082       break;
1083     case cShort:
1084       if (I.getType ()->isSigned ()) { // add short
1085         unsigned TmpReg = makeAnotherReg (I.getType ());
1086         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1087         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
1088       } else { // add ushort
1089         unsigned TmpReg = makeAnotherReg (I.getType ());
1090         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1091         BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
1092       }
1093       break;
1094     case cInt:
1095       // Nothing to do here.
1096       break;
1097     case cLong:
1098       // Only support and, or, xor.
1099       if (OpCase < 3 || OpCase > 5) {
1100         visitInstruction (I);
1101         return;
1102       }
1103       // Do the other half of the value:
1104       BuildMI (BB, Opcodes[OpCase], 2, ResultReg+1).addReg (Op0Reg+1)
1105         .addReg (Op1Reg+1);
1106       break;
1107     default:
1108       visitInstruction (I);
1109   }
1110 }
1111
1112 void V8ISel::visitSetCondInst(SetCondInst &I) {
1113   unsigned Op0Reg = getReg (I.getOperand (0));
1114   unsigned Op1Reg = getReg (I.getOperand (1));
1115   unsigned DestReg = getReg (I);
1116   const Type *Ty = I.getOperand (0)->getType ();
1117   
1118   // Compare the two values.
1119   assert (getClass (Ty) != cLong && "can't setcc on longs yet");
1120   if (getClass (Ty) < cLong) {
1121     BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1122   } else if (getClass (Ty) == cFloat) {
1123     BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1124   } else if (getClass (Ty) == cDouble) {
1125     BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1126   }
1127
1128   unsigned BranchIdx;
1129   switch (I.getOpcode()) {
1130   default: assert(0 && "Unknown setcc instruction!");
1131   case Instruction::SetEQ: BranchIdx = 0; break;
1132   case Instruction::SetNE: BranchIdx = 1; break;
1133   case Instruction::SetLT: BranchIdx = 2; break;
1134   case Instruction::SetGT: BranchIdx = 3; break;
1135   case Instruction::SetLE: BranchIdx = 4; break;
1136   case Instruction::SetGE: BranchIdx = 5; break;
1137   }
1138   unsigned Column = 0;
1139   if (Ty->isSigned()) ++Column;
1140   if (Ty->isFloatingPoint()) ++Column;
1141   static unsigned OpcodeTab[3*6] = {
1142                                  // LLVM            SparcV8
1143                                  //        unsigned signed  fp
1144     V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1145     V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1146     V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1147     V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1148     V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1149     V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1150   };
1151   unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1152
1153   MachineBasicBlock *thisMBB = BB;
1154   const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1155   //  thisMBB:
1156   //  ...
1157   //   subcc %reg0, %reg1, %g0
1158   //   bCC copy1MBB
1159   //   ba copy0MBB
1160
1161   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1162   // if we could insert other, non-terminator instructions after the
1163   // bCC. But MBB->getFirstTerminator() can't understand this.
1164   MachineBasicBlock *copy1MBB = new MachineBasicBlock (LLVM_BB);
1165   F->getBasicBlockList ().push_back (copy1MBB);
1166   BuildMI (BB, Opcode, 1).addMBB (copy1MBB);
1167   MachineBasicBlock *copy0MBB = new MachineBasicBlock (LLVM_BB);
1168   F->getBasicBlockList ().push_back (copy0MBB);
1169   BuildMI (BB, V8::BA, 1).addMBB (copy0MBB);
1170   // Update machine-CFG edges
1171   BB->addSuccessor (copy1MBB);
1172   BB->addSuccessor (copy0MBB);
1173
1174   //  copy0MBB:
1175   //   %FalseValue = or %G0, 0
1176   //   ba sinkMBB
1177   BB = copy0MBB;
1178   unsigned FalseValue = makeAnotherReg (I.getType ());
1179   BuildMI (BB, V8::ORri, 2, FalseValue).addReg (V8::G0).addZImm (0);
1180   MachineBasicBlock *sinkMBB = new MachineBasicBlock (LLVM_BB);
1181   F->getBasicBlockList ().push_back (sinkMBB);
1182   BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
1183   // Update machine-CFG edges
1184   BB->addSuccessor (sinkMBB);
1185
1186   DEBUG (std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1187   DEBUG (std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
1188   DEBUG (std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1189   DEBUG (std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1190
1191   //  copy1MBB:
1192   //   %TrueValue = or %G0, 1
1193   //   ba sinkMBB
1194   BB = copy1MBB;
1195   unsigned TrueValue = makeAnotherReg (I.getType ());
1196   BuildMI (BB, V8::ORri, 2, TrueValue).addReg (V8::G0).addZImm (1);
1197   BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
1198   // Update machine-CFG edges
1199   BB->addSuccessor (sinkMBB);
1200
1201   //  sinkMBB:
1202   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1203   //  ...
1204   BB = sinkMBB;
1205   BuildMI (BB, V8::PHI, 4, DestReg).addReg (FalseValue)
1206     .addMBB (copy0MBB).addReg (TrueValue).addMBB (copy1MBB);
1207 }
1208
1209 void V8ISel::visitAllocaInst(AllocaInst &I) {
1210   // Find the data size of the alloca inst's getAllocatedType.
1211   const Type *Ty = I.getAllocatedType();
1212   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1213
1214   unsigned ArraySizeReg = getReg (I.getArraySize ());
1215   unsigned TySizeReg = getReg (ConstantUInt::get (Type::UIntTy, TySize));
1216   unsigned TmpReg1 = makeAnotherReg (Type::UIntTy);
1217   unsigned TmpReg2 = makeAnotherReg (Type::UIntTy);
1218   unsigned StackAdjReg = makeAnotherReg (Type::UIntTy);
1219
1220   // StackAdjReg = (ArraySize * TySize) rounded up to nearest doubleword boundary
1221   BuildMI (BB, V8::UMULrr, 2, TmpReg1).addReg (ArraySizeReg).addReg (TySizeReg);
1222
1223   // Round up TmpReg1 to nearest doubleword boundary:
1224   BuildMI (BB, V8::ADDri, 2, TmpReg2).addReg (TmpReg1).addSImm (7);
1225   BuildMI (BB, V8::ANDri, 2, StackAdjReg).addReg (TmpReg2).addSImm (-8);
1226
1227   // Subtract size from stack pointer, thereby allocating some space.
1228   BuildMI (BB, V8::SUBrr, 2, V8::SP).addReg (V8::SP).addReg (StackAdjReg);
1229
1230   // Put a pointer to the space into the result register, by copying
1231   // the stack pointer.
1232   BuildMI (BB, V8::ADDri, 2, getReg(I)).addReg (V8::SP).addSImm (96);
1233
1234   // Inform the Frame Information that we have just allocated a variable-sized
1235   // object.
1236   F->getFrameInfo()->CreateVariableSizedObject();
1237 }
1238
1239 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1240 /// function, lowering any calls to unknown intrinsic functions into the
1241 /// equivalent LLVM code.
1242 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1243   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1244     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1245       if (CallInst *CI = dyn_cast<CallInst>(I++))
1246         if (Function *F = CI->getCalledFunction())
1247           switch (F->getIntrinsicID()) {
1248           case Intrinsic::not_intrinsic: break;
1249           default:
1250             // All other intrinsic calls we must lower.
1251             Instruction *Before = CI->getPrev();
1252             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1253             if (Before) {        // Move iterator to instruction after call
1254               I = Before;  ++I;
1255             } else {
1256               I = BB->begin();
1257             }
1258           }
1259 }
1260
1261
1262 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1263   unsigned TmpReg1, TmpReg2;
1264   switch (ID) {
1265   default: assert(0 && "Intrinsic not supported!");
1266   }
1267 }