Make error messages more useful than jsut an abort
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 target
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "X86.h"
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/Type.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include <map>
30
31 /// BMI - A special BuildMI variant that takes an iterator to insert the
32 /// instruction at as well as a basic block.  This is the version for when you
33 /// have a destination register in mind.
34 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
35                                       MachineBasicBlock::iterator &I,
36                                       MachineOpCode Opcode,
37                                       unsigned NumOperands,
38                                       unsigned DestReg) {
39   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
40   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
41   I = MBB->insert(I, MI)+1;
42   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
43 }
44
45 /// BMI - A special BuildMI variant that takes an iterator to insert the
46 /// instruction at as well as a basic block.
47 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
48                                       MachineBasicBlock::iterator &I,
49                                       MachineOpCode Opcode,
50                                       unsigned NumOperands) {
51   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
52   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
53   I = MBB->insert(I, MI)+1;
54   return MachineInstrBuilder(MI);
55 }
56
57
58 namespace {
59   struct ISel : public FunctionPass, InstVisitor<ISel> {
60     TargetMachine &TM;
61     MachineFunction *F;                 // The function we are compiling into
62     MachineBasicBlock *BB;              // The current MBB we are compiling
63     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
64
65     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
66
67     // MBBMap - Mapping between LLVM BB -> Machine BB
68     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
69
70     ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
71
72     /// runOnFunction - Top level implementation of instruction selection for
73     /// the entire function.
74     ///
75     bool runOnFunction(Function &Fn) {
76       F = &MachineFunction::construct(&Fn, TM);
77
78       // Create all of the machine basic blocks for the function...
79       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
80         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
81
82       BB = &F->front();
83
84       // Copy incoming arguments off of the stack...
85       LoadArgumentsToVirtualRegs(Fn);
86
87       // Instruction select everything except PHI nodes
88       visit(Fn);
89
90       // Select the PHI nodes
91       SelectPHINodes();
92
93       RegMap.clear();
94       MBBMap.clear();
95       F = 0;
96       return false;  // We never modify the LLVM itself.
97     }
98
99     virtual const char *getPassName() const {
100       return "X86 Simple Instruction Selection";
101     }
102
103     /// visitBasicBlock - This method is called when we are visiting a new basic
104     /// block.  This simply creates a new MachineBasicBlock to emit code into
105     /// and adds it to the current MachineFunction.  Subsequent visit* for
106     /// instructions will be invoked for all instructions in the basic block.
107     ///
108     void visitBasicBlock(BasicBlock &LLVM_BB) {
109       BB = MBBMap[&LLVM_BB];
110     }
111
112     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113     /// from the stack into virtual registers.
114     ///
115     void LoadArgumentsToVirtualRegs(Function &F);
116
117     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
118     /// because we have to generate our sources into the source basic blocks,
119     /// not the current one.
120     ///
121     void SelectPHINodes();
122
123     // Visitation methods for various instructions.  These methods simply emit
124     // fixed X86 code for each instruction.
125     //
126
127     // Control flow operators
128     void visitReturnInst(ReturnInst &RI);
129     void visitBranchInst(BranchInst &BI);
130
131     struct ValueRecord {
132       unsigned Reg;
133       const Type *Ty;
134       ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
135     };
136     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
137                 const std::vector<ValueRecord> &Args);
138     void visitCallInst(CallInst &I);
139     void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
140
141     // Arithmetic operators
142     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
143     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
144     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
145     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
146                     unsigned DestReg, const Type *DestTy,
147                     unsigned Op0Reg, unsigned Op1Reg);
148     void visitMul(BinaryOperator &B);
149
150     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
151     void visitRem(BinaryOperator &B) { visitDivRem(B); }
152     void visitDivRem(BinaryOperator &B);
153
154     // Bitwise operators
155     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
156     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
157     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
158
159     // Comparison operators...
160     void visitSetCondInst(SetCondInst &I);
161     bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
162
163     // Memory Instructions
164     MachineInstr *doFPLoad(MachineBasicBlock *MBB,
165                            MachineBasicBlock::iterator &MBBI,
166                            const Type *Ty, unsigned DestReg);
167     void visitLoadInst(LoadInst &I);
168     void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
169     void visitStoreInst(StoreInst &I);
170     void visitGetElementPtrInst(GetElementPtrInst &I);
171     void visitAllocaInst(AllocaInst &I);
172     void visitMallocInst(MallocInst &I);
173     void visitFreeInst(FreeInst &I);
174     
175     // Other operators
176     void visitShiftInst(ShiftInst &I);
177     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
178     void visitCastInst(CastInst &I);
179     void visitVarArgInst(VarArgInst &I);
180
181     void visitInstruction(Instruction &I) {
182       std::cerr << "Cannot instruction select: " << I;
183       abort();
184     }
185
186     /// promote32 - Make a value 32-bits wide, and put it somewhere.
187     ///
188     void promote32(unsigned targetReg, const ValueRecord &VR);
189
190     /// EmitByteSwap - Byteswap SrcReg into DestReg.
191     ///
192     void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
193     
194     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
195     /// constant expression GEP support.
196     ///
197     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
198                           Value *Src, User::op_iterator IdxBegin,
199                           User::op_iterator IdxEnd, unsigned TargetReg);
200
201     /// emitCastOperation - Common code shared between visitCastInst and
202     /// constant expression cast support.
203     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
204                            Value *Src, const Type *DestTy, unsigned TargetReg);
205
206     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
207     /// and constant expression support.
208     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
209                                    MachineBasicBlock::iterator &IP,
210                                    Value *Op0, Value *Op1,
211                                    unsigned OperatorClass, unsigned TargetReg);
212
213     /// copyConstantToRegister - Output the instructions required to put the
214     /// specified constant into the specified register.
215     ///
216     void copyConstantToRegister(MachineBasicBlock *MBB,
217                                 MachineBasicBlock::iterator &MBBI,
218                                 Constant *C, unsigned Reg);
219
220     /// makeAnotherReg - This method returns the next register number we haven't
221     /// yet used.
222     ///
223     /// Long values are handled somewhat specially.  They are always allocated
224     /// as pairs of 32 bit integer values.  The register number returned is the
225     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
226     /// of the long value.
227     ///
228     unsigned makeAnotherReg(const Type *Ty) {
229       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
230         const TargetRegisterClass *RC =
231           TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
232         // Create the lower part
233         F->getSSARegMap()->createVirtualRegister(RC);
234         // Create the upper part.
235         return F->getSSARegMap()->createVirtualRegister(RC)-1;
236       }
237
238       // Add the mapping of regnumber => reg class to MachineFunction
239       const TargetRegisterClass *RC =
240         TM.getRegisterInfo()->getRegClassForType(Ty);
241       return F->getSSARegMap()->createVirtualRegister(RC);
242     }
243
244     /// getReg - This method turns an LLVM value into a register number.  This
245     /// is guaranteed to produce the same register number for a particular value
246     /// every time it is queried.
247     ///
248     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
249     unsigned getReg(Value *V) {
250       // Just append to the end of the current bb.
251       MachineBasicBlock::iterator It = BB->end();
252       return getReg(V, BB, It);
253     }
254     unsigned getReg(Value *V, MachineBasicBlock *MBB,
255                     MachineBasicBlock::iterator &IPt) {
256       unsigned &Reg = RegMap[V];
257       if (Reg == 0) {
258         Reg = makeAnotherReg(V->getType());
259         RegMap[V] = Reg;
260       }
261
262       // If this operand is a constant, emit the code to copy the constant into
263       // the register here...
264       //
265       if (Constant *C = dyn_cast<Constant>(V)) {
266         copyConstantToRegister(MBB, IPt, C, Reg);
267         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
268       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
269         // Move the address of the global into the register
270         BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
271         RegMap.erase(V);  // Assign a new name to this address if ref'd again
272       }
273
274       return Reg;
275     }
276   };
277 }
278
279 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
280 /// Representation.
281 ///
282 enum TypeClass {
283   cByte, cShort, cInt, cFP, cLong
284 };
285
286 /// getClass - Turn a primitive type into a "class" number which is based on the
287 /// size of the type, and whether or not it is floating point.
288 ///
289 static inline TypeClass getClass(const Type *Ty) {
290   switch (Ty->getPrimitiveID()) {
291   case Type::SByteTyID:
292   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
293   case Type::ShortTyID:
294   case Type::UShortTyID:  return cShort;     // Short operands are class #1
295   case Type::IntTyID:
296   case Type::UIntTyID:
297   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
298
299   case Type::FloatTyID:
300   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
301
302   case Type::LongTyID:
303   case Type::ULongTyID:   return cLong;      // Longs are class #4
304   default:
305     assert(0 && "Invalid type to getClass!");
306     return cByte;  // not reached
307   }
308 }
309
310 // getClassB - Just like getClass, but treat boolean values as bytes.
311 static inline TypeClass getClassB(const Type *Ty) {
312   if (Ty == Type::BoolTy) return cByte;
313   return getClass(Ty);
314 }
315
316
317 /// copyConstantToRegister - Output the instructions required to put the
318 /// specified constant into the specified register.
319 ///
320 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
321                                   MachineBasicBlock::iterator &IP,
322                                   Constant *C, unsigned R) {
323   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
324     unsigned Class = 0;
325     switch (CE->getOpcode()) {
326     case Instruction::GetElementPtr:
327       emitGEPOperation(MBB, IP, CE->getOperand(0),
328                        CE->op_begin()+1, CE->op_end(), R);
329       return;
330     case Instruction::Cast:
331       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
332       return;
333
334     case Instruction::Xor: ++Class; // FALL THROUGH
335     case Instruction::Or:  ++Class; // FALL THROUGH
336     case Instruction::And: ++Class; // FALL THROUGH
337     case Instruction::Sub: ++Class; // FALL THROUGH
338     case Instruction::Add:
339       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
340                                 Class, R);
341       return;
342
343     default:
344       std::cerr << "Offending expr: " << C << "\n";
345       assert(0 && "Constant expressions not yet handled!\n");
346     }
347   }
348
349   if (C->getType()->isIntegral()) {
350     unsigned Class = getClassB(C->getType());
351
352     if (Class == cLong) {
353       // Copy the value into the register pair.
354       uint64_t Val;
355       if (C->getType()->isSigned())
356         Val = cast<ConstantSInt>(C)->getValue();
357       else
358         Val = cast<ConstantUInt>(C)->getValue();
359
360       BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
361       BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
362       return;
363     }
364
365     assert(Class <= cInt && "Type not handled yet!");
366
367     static const unsigned IntegralOpcodeTab[] = {
368       X86::MOVir8, X86::MOVir16, X86::MOVir32
369     };
370
371     if (C->getType() == Type::BoolTy) {
372       BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
373     } else if (C->getType()->isSigned()) {
374       ConstantSInt *CSI = cast<ConstantSInt>(C);
375       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
376     } else {
377       ConstantUInt *CUI = cast<ConstantUInt>(C);
378       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
379     }
380   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
381     double Value = CFP->getValue();
382     if (Value == +0.0)
383       BMI(MBB, IP, X86::FLD0, 0, R);
384     else if (Value == +1.0)
385       BMI(MBB, IP, X86::FLD1, 0, R);
386     else {
387       // Otherwise we need to spill the constant to memory...
388       MachineConstantPool *CP = F->getConstantPool();
389       unsigned CPI = CP->getConstantPoolIndex(CFP);
390       addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
391     }
392
393   } else if (isa<ConstantPointerNull>(C)) {
394     // Copy zero (null pointer) to the register.
395     BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
396   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
397     unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
398     BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
399   } else {
400     std::cerr << "Offending constant: " << C << "\n";
401     assert(0 && "Type not handled yet!");
402   }
403 }
404
405 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
406 /// the stack into virtual registers.
407 ///
408 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
409   // Emit instructions to load the arguments...  On entry to a function on the
410   // X86, the stack frame looks like this:
411   //
412   // [ESP] -- return address
413   // [ESP + 4] -- first argument (leftmost lexically)
414   // [ESP + 8] -- second argument, if first argument is four bytes in size
415   //    ... 
416   //
417   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
418   MachineFrameInfo *MFI = F->getFrameInfo();
419
420   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
421     unsigned Reg = getReg(*I);
422     
423     int FI;          // Frame object index
424     switch (getClassB(I->getType())) {
425     case cByte:
426       FI = MFI->CreateFixedObject(1, ArgOffset);
427       addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
428       break;
429     case cShort:
430       FI = MFI->CreateFixedObject(2, ArgOffset);
431       addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
432       break;
433     case cInt:
434       FI = MFI->CreateFixedObject(4, ArgOffset);
435       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
436       break;
437     case cLong:
438       FI = MFI->CreateFixedObject(8, ArgOffset);
439       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
440       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
441       ArgOffset += 4;   // longs require 4 additional bytes
442       break;
443     case cFP:
444       unsigned Opcode;
445       if (I->getType() == Type::FloatTy) {
446         Opcode = X86::FLDr32;
447         FI = MFI->CreateFixedObject(4, ArgOffset);
448       } else {
449         Opcode = X86::FLDr64;
450         FI = MFI->CreateFixedObject(8, ArgOffset);
451         ArgOffset += 4;   // doubles require 4 additional bytes
452       }
453       addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
454       break;
455     default:
456       assert(0 && "Unhandled argument type!");
457     }
458     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
459   }
460
461   // If the function takes variable number of arguments, add a frame offset for
462   // the start of the first vararg value... this is used to expand
463   // llvm.va_start.
464   if (Fn.getFunctionType()->isVarArg())
465     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
466 }
467
468
469 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
470 /// because we have to generate our sources into the source basic blocks, not
471 /// the current one.
472 ///
473 void ISel::SelectPHINodes() {
474   const TargetInstrInfo &TII = TM.getInstrInfo();
475   const Function &LF = *F->getFunction();  // The LLVM function...
476   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
477     const BasicBlock *BB = I;
478     MachineBasicBlock *MBB = MBBMap[I];
479
480     // Loop over all of the PHI nodes in the LLVM basic block...
481     unsigned NumPHIs = 0;
482     for (BasicBlock::const_iterator I = BB->begin();
483          PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
484
485       // Create a new machine instr PHI node, and insert it.
486       unsigned PHIReg = getReg(*PN);
487       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
488       MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
489
490       MachineInstr *LongPhiMI = 0;
491       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
492         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
493         MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
494       }
495
496       // PHIValues - Map of blocks to incoming virtual registers.  We use this
497       // so that we only initialize one incoming value for a particular block,
498       // even if the block has multiple entries in the PHI node.
499       //
500       std::map<MachineBasicBlock*, unsigned> PHIValues;
501
502       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
503         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
504         unsigned ValReg;
505         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
506           PHIValues.lower_bound(PredMBB);
507
508         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
509           // We already inserted an initialization of the register for this
510           // predecessor.  Recycle it.
511           ValReg = EntryIt->second;
512
513         } else {        
514           // Get the incoming value into a virtual register.  If it is not
515           // already available in a virtual register, insert the computation
516           // code into PredMBB
517           //
518           MachineBasicBlock::iterator PI = PredMBB->end();
519           while (PI != PredMBB->begin() &&
520                  TII.isTerminatorInstr((*(PI-1))->getOpcode()))
521             --PI;
522           ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
523
524           // Remember that we inserted a value for this PHI for this predecessor
525           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
526         }
527
528         PhiMI->addRegOperand(ValReg);
529         PhiMI->addMachineBasicBlockOperand(PredMBB);
530         if (LongPhiMI) {
531           LongPhiMI->addRegOperand(ValReg+1);
532           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
533         }
534       }
535     }
536   }
537 }
538
539 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
540 // the conditional branch instruction which is the only user of the cc
541 // instruction.  This is the case if the conditional branch is the only user of
542 // the setcc, and if the setcc is in the same basic block as the conditional
543 // branch.  We also don't handle long arguments below, so we reject them here as
544 // well.
545 //
546 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
547   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
548     if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
549         SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
550       const Type *Ty = SCI->getOperand(0)->getType();
551       if (Ty != Type::LongTy && Ty != Type::ULongTy)
552         return SCI;
553     }
554   return 0;
555 }
556
557 // Return a fixed numbering for setcc instructions which does not depend on the
558 // order of the opcodes.
559 //
560 static unsigned getSetCCNumber(unsigned Opcode) {
561   switch(Opcode) {
562   default: assert(0 && "Unknown setcc instruction!");
563   case Instruction::SetEQ: return 0;
564   case Instruction::SetNE: return 1;
565   case Instruction::SetLT: return 2;
566   case Instruction::SetGE: return 3;
567   case Instruction::SetGT: return 4;
568   case Instruction::SetLE: return 5;
569   }
570 }
571
572 // LLVM  -> X86 signed  X86 unsigned
573 // -----    ----------  ------------
574 // seteq -> sete        sete
575 // setne -> setne       setne
576 // setlt -> setl        setb
577 // setge -> setge       setae
578 // setgt -> setg        seta
579 // setle -> setle       setbe
580 static const unsigned SetCCOpcodeTab[2][6] = {
581   {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
582   {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
583 };
584
585 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
586
587   // The arguments are already supposed to be of the same type.
588   const Type *CompTy = Op0->getType();
589   bool isSigned = CompTy->isSigned();
590   unsigned reg1 = getReg(Op0);
591   unsigned reg2 = getReg(Op1);
592
593   unsigned Class = getClassB(CompTy);
594   switch (Class) {
595   default: assert(0 && "Unknown type class!");
596     // Emit: cmp <var1>, <var2> (do the comparison).  We can
597     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
598     // 32-bit.
599   case cByte:
600     BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
601     break;
602   case cShort:
603     BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
604     break;
605   case cInt:
606     BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
607     break;
608   case cFP:
609     BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
610     BuildMI(BB, X86::FNSTSWr8, 0);
611     BuildMI(BB, X86::SAHF, 1);
612     isSigned = false;   // Compare with unsigned operators
613     break;
614
615   case cLong:
616     if (OpNum < 2) {    // seteq, setne
617       unsigned LoTmp = makeAnotherReg(Type::IntTy);
618       unsigned HiTmp = makeAnotherReg(Type::IntTy);
619       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
620       BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
621       BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
622       BuildMI(BB, X86::ORrr32,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
623       break;  // Allow the sete or setne to be generated from flags set by OR
624     } else {
625       // Emit a sequence of code which compares the high and low parts once
626       // each, then uses a conditional move to handle the overflow case.  For
627       // example, a setlt for long would generate code like this:
628       //
629       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
630       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
631       // dest = hi(op1) == hi(op2) ? AL : BL;
632       //
633
634       // FIXME: This would be much better if we had hierarchical register
635       // classes!  Until then, hardcode registers so that we can deal with their
636       // aliases (because we don't have conditional byte moves).
637       //
638       BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
639       BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
640       BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
641       BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
642       BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
643       // NOTE: visitSetCondInst knows that the value is dumped into the BL
644       // register at this point for long values...
645       return isSigned;
646     }
647   }
648   return isSigned;
649 }
650
651
652 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
653 /// register, then move it to wherever the result should be. 
654 ///
655 void ISel::visitSetCondInst(SetCondInst &I) {
656   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
657
658   unsigned OpNum = getSetCCNumber(I.getOpcode());
659   unsigned DestReg = getReg(I);
660   bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
661                                               I.getOperand(1));
662
663   if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
664     // Handle normal comparisons with a setcc instruction...
665     BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
666   } else {
667     // Handle long comparisons by copying the value which is already in BL into
668     // the register we want...
669     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
670   }
671 }
672
673 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
674 /// operand, in the specified target register.
675 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
676   bool isUnsigned = VR.Ty->isUnsigned();
677   switch (getClassB(VR.Ty)) {
678   case cByte:
679     // Extend value into target register (8->32)
680     if (isUnsigned)
681       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
682     else
683       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
684     break;
685   case cShort:
686     // Extend value into target register (16->32)
687     if (isUnsigned)
688       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
689     else
690       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
691     break;
692   case cInt:
693     // Move value into target register (32->32)
694     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
695     break;
696   default:
697     assert(0 && "Unpromotable operand class in promote32");
698   }
699 }
700
701 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
702 /// we have the following possibilities:
703 ///
704 ///   ret void: No return value, simply emit a 'ret' instruction
705 ///   ret sbyte, ubyte : Extend value into EAX and return
706 ///   ret short, ushort: Extend value into EAX and return
707 ///   ret int, uint    : Move value into EAX and return
708 ///   ret pointer      : Move value into EAX and return
709 ///   ret long, ulong  : Move value into EAX/EDX and return
710 ///   ret float/double : Top of FP stack
711 ///
712 void ISel::visitReturnInst(ReturnInst &I) {
713   if (I.getNumOperands() == 0) {
714     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
715     return;
716   }
717
718   Value *RetVal = I.getOperand(0);
719   unsigned RetReg = getReg(RetVal);
720   switch (getClassB(RetVal->getType())) {
721   case cByte:   // integral return values: extend or move into EAX and return
722   case cShort:
723   case cInt:
724     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
725     // Declare that EAX is live on exit
726     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
727     break;
728   case cFP:                   // Floats & Doubles: Return in ST(0)
729     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
730     // Declare that top-of-stack is live on exit
731     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
732     break;
733   case cLong:
734     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
735     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
736     // Declare that EAX & EDX are live on exit
737     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
738     break;
739   default:
740     visitInstruction(I);
741   }
742   // Emit a 'ret' instruction
743   BuildMI(BB, X86::RET, 0);
744 }
745
746 // getBlockAfter - Return the basic block which occurs lexically after the
747 // specified one.
748 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
749   Function::iterator I = BB; ++I;  // Get iterator to next block
750   return I != BB->getParent()->end() ? &*I : 0;
751 }
752
753 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
754 /// that since code layout is frozen at this point, that if we are trying to
755 /// jump to a block that is the immediate successor of the current block, we can
756 /// just make a fall-through (but we don't currently).
757 ///
758 void ISel::visitBranchInst(BranchInst &BI) {
759   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
760
761   if (!BI.isConditional()) {  // Unconditional branch?
762     if (BI.getSuccessor(0) != NextBB)
763       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
764     return;
765   }
766
767   // See if we can fold the setcc into the branch itself...
768   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
769   if (SCI == 0) {
770     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
771     // computed some other way...
772     unsigned condReg = getReg(BI.getCondition());
773     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
774     if (BI.getSuccessor(1) == NextBB) {
775       if (BI.getSuccessor(0) != NextBB)
776         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
777     } else {
778       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
779       
780       if (BI.getSuccessor(0) != NextBB)
781         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
782     }
783     return;
784   }
785
786   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
787   bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
788                                               SCI->getOperand(1));
789   
790   // LLVM  -> X86 signed  X86 unsigned
791   // -----    ----------  ------------
792   // seteq -> je          je
793   // setne -> jne         jne
794   // setlt -> jl          jb
795   // setge -> jge         jae
796   // setgt -> jg          ja
797   // setle -> jle         jbe
798   static const unsigned OpcodeTab[2][6] = {
799     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
800     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
801   };
802   
803   if (BI.getSuccessor(0) != NextBB) {
804     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
805     if (BI.getSuccessor(1) != NextBB)
806       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
807   } else {
808     // Change to the inverse condition...
809     if (BI.getSuccessor(1) != NextBB) {
810       OpNum ^= 1;
811       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
812     }
813   }
814 }
815
816
817 /// doCall - This emits an abstract call instruction, setting up the arguments
818 /// and the return value as appropriate.  For the actual function call itself,
819 /// it inserts the specified CallMI instruction into the stream.
820 ///
821 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
822                   const std::vector<ValueRecord> &Args) {
823
824   // Count how many bytes are to be pushed on the stack...
825   unsigned NumBytes = 0;
826
827   if (!Args.empty()) {
828     for (unsigned i = 0, e = Args.size(); i != e; ++i)
829       switch (getClassB(Args[i].Ty)) {
830       case cByte: case cShort: case cInt:
831         NumBytes += 4; break;
832       case cLong:
833         NumBytes += 8; break;
834       case cFP:
835         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
836         break;
837       default: assert(0 && "Unknown class!");
838       }
839
840     // Adjust the stack pointer for the new arguments...
841     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
842
843     // Arguments go on the stack in reverse order, as specified by the ABI.
844     unsigned ArgOffset = 0;
845     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
846       unsigned ArgReg = Args[i].Reg;
847       switch (getClassB(Args[i].Ty)) {
848       case cByte:
849       case cShort: {
850         // Promote arg to 32 bits wide into a temporary register...
851         unsigned R = makeAnotherReg(Type::UIntTy);
852         promote32(R, Args[i]);
853         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
854                      X86::ESP, ArgOffset).addReg(R);
855         break;
856       }
857       case cInt:
858         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
859                      X86::ESP, ArgOffset).addReg(ArgReg);
860         break;
861       case cLong:
862         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
863                      X86::ESP, ArgOffset).addReg(ArgReg);
864         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
865                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
866         ArgOffset += 4;        // 8 byte entry, not 4.
867         break;
868         
869       case cFP:
870         if (Args[i].Ty == Type::FloatTy) {
871           addRegOffset(BuildMI(BB, X86::FSTr32, 5),
872                        X86::ESP, ArgOffset).addReg(ArgReg);
873         } else {
874           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
875           addRegOffset(BuildMI(BB, X86::FSTr64, 5),
876                        X86::ESP, ArgOffset).addReg(ArgReg);
877           ArgOffset += 4;       // 8 byte entry, not 4.
878         }
879         break;
880
881       default: assert(0 && "Unknown class!");
882       }
883       ArgOffset += 4;
884     }
885   } else {
886     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
887   }
888
889   BB->push_back(CallMI);
890
891   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
892
893   // If there is a return value, scavenge the result from the location the call
894   // leaves it in...
895   //
896   if (Ret.Ty != Type::VoidTy) {
897     unsigned DestClass = getClassB(Ret.Ty);
898     switch (DestClass) {
899     case cByte:
900     case cShort:
901     case cInt: {
902       // Integral results are in %eax, or the appropriate portion
903       // thereof.
904       static const unsigned regRegMove[] = {
905         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
906       };
907       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
908       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
909       break;
910     }
911     case cFP:     // Floating-point return values live in %ST(0)
912       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
913       break;
914     case cLong:   // Long values are left in EDX:EAX
915       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
916       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
917       break;
918     default: assert(0 && "Unknown class!");
919     }
920   }
921 }
922
923
924 /// visitCallInst - Push args on stack and do a procedure call instruction.
925 void ISel::visitCallInst(CallInst &CI) {
926   MachineInstr *TheCall;
927   if (Function *F = CI.getCalledFunction()) {
928     // Is it an intrinsic function call?
929     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
930       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
931       return;
932     }
933
934     // Emit a CALL instruction with PC-relative displacement.
935     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
936   } else {  // Emit an indirect call...
937     unsigned Reg = getReg(CI.getCalledValue());
938     TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
939   }
940
941   std::vector<ValueRecord> Args;
942   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
943     Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
944                                CI.getOperand(i)->getType()));
945
946   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
947   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
948 }        
949
950 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
951   unsigned TmpReg1, TmpReg2;
952   switch (ID) {
953   case LLVMIntrinsic::va_start:
954     // Get the address of the first vararg value...
955     TmpReg1 = makeAnotherReg(Type::UIntTy);
956     addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
957     TmpReg2 = getReg(CI.getOperand(1));
958     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
959     return;
960
961   case LLVMIntrinsic::va_end: return;   // Noop on X86
962   case LLVMIntrinsic::va_copy:
963     TmpReg1 = getReg(CI.getOperand(2));  // Get existing va_list
964     TmpReg2 = getReg(CI.getOperand(1));  // Get va_list* to store into
965     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
966     return;
967
968   default: assert(0 && "Unknown intrinsic for X86!");
969   }
970 }
971
972
973 /// visitSimpleBinary - Implement simple binary operators for integral types...
974 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
975 /// Xor.
976 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
977   unsigned DestReg = getReg(B);
978   MachineBasicBlock::iterator MI = BB->end();
979   emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
980                             OperatorClass, DestReg);
981 }
982
983 /// visitSimpleBinary - Implement simple binary operators for integral types...
984 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
985 /// 4 for Xor.
986 ///
987 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
988 /// and constant expression support.
989 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
990                                      MachineBasicBlock::iterator &IP,
991                                      Value *Op0, Value *Op1,
992                                      unsigned OperatorClass,unsigned TargetReg){
993   unsigned Class = getClassB(Op0->getType());
994
995   static const unsigned OpcodeTab[][4] = {
996     // Arithmetic operators
997     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
998     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
999
1000     // Bitwise operators
1001     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
1002     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
1003     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
1004   };
1005
1006   bool isLong = false;
1007   if (Class == cLong) {
1008     isLong = true;
1009     Class = cInt;          // Bottom 32 bits are handled just like ints
1010   }
1011   
1012   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1013   assert(Opcode && "Floating point arguments to logical inst?");
1014   unsigned Op0r = getReg(Op0, BB, IP);
1015   unsigned Op1r = getReg(Op1, BB, IP);
1016   BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
1017
1018   if (isLong) {        // Handle the upper 32 bits of long values...
1019     static const unsigned TopTab[] = {
1020       X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1021     };
1022     BMI(BB, IP, TopTab[OperatorClass], 2,
1023         TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
1024   }
1025 }
1026
1027 /// doMultiply - Emit appropriate instructions to multiply together the
1028 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1029 /// result should be given as DestTy.
1030 ///
1031 /// FIXME: doMultiply should use one of the two address IMUL instructions!
1032 ///
1033 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
1034                       unsigned DestReg, const Type *DestTy,
1035                       unsigned op0Reg, unsigned op1Reg) {
1036   unsigned Class = getClass(DestTy);
1037   switch (Class) {
1038   case cFP:              // Floating point multiply
1039     BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1040     return;
1041   default:
1042   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1043   case cByte:
1044   case cShort:
1045   case cInt:          // Small integerals, handled below...
1046     break;
1047   }
1048  
1049   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1050   static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32  };
1051   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1052   unsigned Reg     = Regs[Class];
1053
1054   // Emit a MOV to put the first operand into the appropriately-sized
1055   // subreg of EAX.
1056   BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
1057   
1058   // Emit the appropriate multiply instruction.
1059   BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
1060
1061   // Emit another MOV to put the result into the destination register.
1062   BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
1063 }
1064
1065 /// visitMul - Multiplies are not simple binary operators because they must deal
1066 /// with the EAX register explicitly.
1067 ///
1068 void ISel::visitMul(BinaryOperator &I) {
1069   unsigned Op0Reg  = getReg(I.getOperand(0));
1070   unsigned Op1Reg  = getReg(I.getOperand(1));
1071   unsigned DestReg = getReg(I);
1072
1073   // Simple scalar multiply?
1074   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1075     MachineBasicBlock::iterator MBBI = BB->end();
1076     doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1077   } else {
1078     // Long value.  We have to do things the hard way...
1079     // Multiply the two low parts... capturing carry into EDX
1080     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1081     BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg);  // AL*BL
1082
1083     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1084     BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX);     // AL*BL
1085     BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1086
1087     MachineBasicBlock::iterator MBBI = BB->end();
1088     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1089     doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1090
1091     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1092     BuildMI(BB, X86::ADDrr32, 2,                         // AH*BL+(AL*BL >> 32)
1093             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1094     
1095     MBBI = BB->end();
1096     unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1097     doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1098     
1099     BuildMI(BB, X86::ADDrr32, 2,               // AL*BH + AH*BL + (AL*BL >> 32)
1100             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1101   }
1102 }
1103
1104
1105 /// visitDivRem - Handle division and remainder instructions... these
1106 /// instruction both require the same instructions to be generated, they just
1107 /// select the result from a different register.  Note that both of these
1108 /// instructions work differently for signed and unsigned operands.
1109 ///
1110 void ISel::visitDivRem(BinaryOperator &I) {
1111   unsigned Class     = getClass(I.getType());
1112   unsigned Op0Reg    = getReg(I.getOperand(0));
1113   unsigned Op1Reg    = getReg(I.getOperand(1));
1114   unsigned ResultReg = getReg(I);
1115
1116   switch (Class) {
1117   case cFP:              // Floating point divide
1118     if (I.getOpcode() == Instruction::Div)
1119       BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1120     else {               // Floating point remainder...
1121       MachineInstr *TheCall =
1122         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1123       std::vector<ValueRecord> Args;
1124       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1125       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1126       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1127     }
1128     return;
1129   case cLong: {
1130     static const char *FnName[] =
1131       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1132
1133     unsigned NameIdx = I.getType()->isUnsigned()*2;
1134     NameIdx += I.getOpcode() == Instruction::Div;
1135     MachineInstr *TheCall =
1136       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1137
1138     std::vector<ValueRecord> Args;
1139     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1140     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1141     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1142     return;
1143   }
1144   case cByte: case cShort: case cInt:
1145     break;          // Small integerals, handled below...
1146   default: assert(0 && "Unknown class!");
1147   }
1148
1149   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1150   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1151   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
1152   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1153   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1154
1155   static const unsigned DivOpcode[][4] = {
1156     { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 },  // Unsigned division
1157     { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 },  // Signed division
1158   };
1159
1160   bool isSigned   = I.getType()->isSigned();
1161   unsigned Reg    = Regs[Class];
1162   unsigned ExtReg = ExtRegs[Class];
1163
1164   // Put the first operand into one of the A registers...
1165   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1166
1167   if (isSigned) {
1168     // Emit a sign extension instruction...
1169     BuildMI(BB, ExtOpcode[Class], 0);
1170   } else {
1171     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1172     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1173   }
1174
1175   // Emit the appropriate divide or remainder instruction...
1176   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1177
1178   // Figure out which register we want to pick the result out of...
1179   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1180   
1181   // Put the result into the destination register...
1182   BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1183 }
1184
1185
1186 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1187 /// for constant immediate shift values, and for constant immediate
1188 /// shift values equal to 1. Even the general case is sort of special,
1189 /// because the shift amount has to be in CL, not just any old register.
1190 ///
1191 void ISel::visitShiftInst(ShiftInst &I) {
1192   unsigned SrcReg = getReg(I.getOperand(0));
1193   unsigned DestReg = getReg(I);
1194   bool isLeftShift = I.getOpcode() == Instruction::Shl;
1195   bool isSigned = I.getType()->isSigned();
1196   unsigned Class = getClass(I.getType());
1197   
1198   static const unsigned ConstantOperand[][4] = {
1199     { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 },  // SHR
1200     { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 },  // SAR
1201     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SHL
1202     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SAL = SHL
1203   };
1204
1205   static const unsigned NonConstantOperand[][4] = {
1206     { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 },  // SHR
1207     { X86::SARrr8, X86::SARrr16, X86::SARrr32 },  // SAR
1208     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SHL
1209     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SAL = SHL
1210   };
1211
1212   // Longs, as usual, are handled specially...
1213   if (Class == cLong) {
1214     // If we have a constant shift, we can generate much more efficient code
1215     // than otherwise...
1216     //
1217     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1218       unsigned Amount = CUI->getValue();
1219       if (Amount < 32) {
1220         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1221         if (isLeftShift) {
1222           BuildMI(BB, Opc[3], 3, 
1223                   DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1224           BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1225         } else {
1226           BuildMI(BB, Opc[3], 3,
1227                   DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addZImm(Amount);
1228           BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1229         }
1230       } else {                 // Shifting more than 32 bits
1231         Amount -= 32;
1232         if (isLeftShift) {
1233           BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1234           BuildMI(BB, X86::MOVir32, 1,DestReg  ).addZImm(0);
1235         } else {
1236           unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1237           BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1238           BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1239         }
1240       }
1241     } else {
1242       visitInstruction(I);  // FIXME: Implement long shift by non-constant
1243     }
1244     return;
1245   }
1246
1247   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1248     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1249     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1250
1251     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1252     BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1253   } else {                  // The shift amount is non-constant.
1254     BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1255
1256     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1257     BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1258   }
1259 }
1260
1261
1262 /// doFPLoad - This method is used to load an FP value from memory using the
1263 /// current endianness.  NOTE: This method returns a partially constructed load
1264 /// instruction which needs to have the memory source filled in still.
1265 ///
1266 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1267                              MachineBasicBlock::iterator &MBBI,
1268                              const Type *Ty, unsigned DestReg) {
1269   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1270   unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1271
1272   if (TM.getTargetData().isLittleEndian()) // fast path...
1273     return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1274
1275   // If we are big-endian, start by creating an LEA instruction to represent the
1276   // address of the memory location to load from...
1277   //
1278   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1279   MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1280
1281   // Allocate a temporary stack slot to transform the value into...
1282   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1283
1284   // Perform the bswaps 32 bits at a time...
1285   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1286   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1287   addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1288   BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1289   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1290   addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1291                     FrameIdx, Offset).addReg(TmpReg2);
1292   
1293   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1294     TmpReg1 = makeAnotherReg(Type::UIntTy);
1295     TmpReg2 = makeAnotherReg(Type::UIntTy);
1296
1297     addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1298     BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1299     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1300     addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1301   }
1302
1303   // Now we can reload the final byteswapped result into the final destination.
1304   addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1305   return Result;
1306 }
1307
1308 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1309 ///
1310 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1311   // Emit the byte swap instruction...
1312   switch (Class) {
1313   case cByte:
1314     // No byteswap necessary for 8 bit value...
1315     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1316     break;
1317   case cInt:
1318     // Use the 32 bit bswap instruction to do a 32 bit swap...
1319     BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1320     break;
1321     
1322   case cShort:
1323     // For 16 bit we have to use an xchg instruction, because there is no
1324     // 16-bit bswap.  XCHG is necessarily not in SSA form, so we force things
1325     // into AX to do the xchg.
1326     //
1327     BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1328     BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1329       .addReg(X86::AH, MOTy::UseAndDef);
1330     BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1331     break;
1332   default: assert(0 && "Cannot byteswap this class!");
1333   }
1334 }
1335
1336
1337 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1338 /// instruction.  The load and store instructions are the only place where we
1339 /// need to worry about the memory layout of the target machine.
1340 ///
1341 void ISel::visitLoadInst(LoadInst &I) {
1342   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1343   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1344   unsigned SrcAddrReg = getReg(I.getOperand(0));
1345   unsigned DestReg = getReg(I);
1346
1347   unsigned Class = getClass(I.getType());
1348   switch (Class) {
1349   case cFP: {
1350     MachineBasicBlock::iterator MBBI = BB->end();
1351     addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1352     return;
1353   }
1354   case cLong: case cInt: case cShort: case cByte:
1355     break;      // Integers of various sizes handled below
1356   default: assert(0 && "Unknown memory class!");
1357   }
1358
1359   // We need to adjust the input pointer if we are emulating a big-endian
1360   // long-pointer target.  On these systems, the pointer that we are interested
1361   // in is in the upper part of the eight byte memory image of the pointer.  It
1362   // also happens to be byte-swapped, but this will be handled later.
1363   //
1364   if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1365     unsigned R = makeAnotherReg(Type::UIntTy);
1366     BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1367     SrcAddrReg = R;
1368   }
1369
1370   unsigned IReg = DestReg;
1371   if (!isLittleEndian)  // If big endian we need an intermediate stage
1372     DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1373
1374   static const unsigned Opcode[] = {
1375     X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1376   };
1377   addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1378
1379   // Handle long values now...
1380   if (Class == cLong) {
1381     if (isLittleEndian) {
1382       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1383     } else {
1384       EmitByteSwap(IReg+1, DestReg, cInt);
1385       unsigned TempReg = makeAnotherReg(Type::IntTy);
1386       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1387       EmitByteSwap(IReg, TempReg, cInt);
1388     }
1389     return;
1390   }
1391
1392   if (!isLittleEndian)
1393     EmitByteSwap(IReg, DestReg, Class);
1394 }
1395
1396
1397 /// doFPStore - This method is used to store an FP value to memory using the
1398 /// current endianness.
1399 ///
1400 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1401   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1402   unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1403
1404   if (TM.getTargetData().isLittleEndian()) {  // fast path...
1405     addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1406     return;
1407   }
1408
1409   // Allocate a temporary stack slot to transform the value into...
1410   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1411   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1412   addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1413
1414   // Store the value into a temporary stack slot...
1415   addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1416
1417   // Perform the bswaps 32 bits at a time...
1418   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1419   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1420   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1421   BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1422   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1423   addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1424                DestAddrReg, Offset).addReg(TmpReg2);
1425   
1426   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1427     TmpReg1 = makeAnotherReg(Type::UIntTy);
1428     TmpReg2 = makeAnotherReg(Type::UIntTy);
1429
1430     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1431     BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1432     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1433     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1434   }
1435 }
1436
1437
1438 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1439 /// instruction.
1440 ///
1441 void ISel::visitStoreInst(StoreInst &I) {
1442   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1443   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1444   unsigned ValReg      = getReg(I.getOperand(0));
1445   unsigned AddressReg  = getReg(I.getOperand(1));
1446
1447   unsigned Class = getClass(I.getOperand(0)->getType());
1448   switch (Class) {
1449   case cLong:
1450     if (isLittleEndian) {
1451       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1452       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1453                    AddressReg, 4).addReg(ValReg+1);
1454     } else {
1455       unsigned T1 = makeAnotherReg(Type::IntTy);
1456       unsigned T2 = makeAnotherReg(Type::IntTy);
1457       EmitByteSwap(T1, ValReg  , cInt);
1458       EmitByteSwap(T2, ValReg+1, cInt);
1459       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1460       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1461     }
1462     return;
1463   case cFP:
1464     doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1465     return;
1466   case cInt: case cShort: case cByte:
1467     break;      // Integers of various sizes handled below
1468   default: assert(0 && "Unknown memory class!");
1469   }
1470
1471   if (!isLittleEndian && hasLongPointers &&
1472       isa<PointerType>(I.getOperand(0)->getType())) {
1473     unsigned R = makeAnotherReg(Type::UIntTy);
1474     BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1475     AddressReg = R;
1476   }
1477
1478   if (!isLittleEndian && Class != cByte) {
1479     unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1480     EmitByteSwap(R, ValReg, Class);
1481     ValReg = R;
1482   }
1483
1484   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1485   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1486 }
1487
1488
1489 /// visitCastInst - Here we have various kinds of copying with or without
1490 /// sign extension going on.
1491 void ISel::visitCastInst(CastInst &CI) {
1492   unsigned DestReg = getReg(CI);
1493   MachineBasicBlock::iterator MI = BB->end();
1494   emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1495 }
1496
1497 /// emitCastOperation - Common code shared between visitCastInst and
1498 /// constant expression cast support.
1499 void ISel::emitCastOperation(MachineBasicBlock *BB,
1500                              MachineBasicBlock::iterator &IP,
1501                              Value *Src, const Type *DestTy,
1502                              unsigned DestReg) {
1503   unsigned SrcReg = getReg(Src, BB, IP);
1504   const Type *SrcTy = Src->getType();
1505   unsigned SrcClass = getClassB(SrcTy);
1506   unsigned DestClass = getClassB(DestTy);
1507
1508   // Implement casts to bool by using compare on the operand followed by set if
1509   // not zero on the result.
1510   if (DestTy == Type::BoolTy) {
1511     if (SrcClass == cFP || SrcClass == cLong)
1512       abort();  // FIXME: implement cast (long & FP) to bool
1513     
1514     BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1515     BMI(BB, IP, X86::SETNEr, 1, DestReg);
1516     return;
1517   }
1518
1519   static const unsigned RegRegMove[] = {
1520     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1521   };
1522
1523   // Implement casts between values of the same type class (as determined by
1524   // getClass) by using a register-to-register move.
1525   if (SrcClass == DestClass) {
1526     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1527       BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1528     } else if (SrcClass == cFP) {
1529       if (SrcTy == Type::FloatTy) {  // double -> float
1530         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1531         BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1532       } else {                       // float -> double
1533         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1534                "Unknown cFP member!");
1535         // Truncate from double to float by storing to memory as short, then
1536         // reading it back.
1537         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1538         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1539         addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1540         addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1541       }
1542     } else if (SrcClass == cLong) {
1543       BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1544       BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1545     } else {
1546       assert(0 && "Cannot handle this type of cast instruction!");
1547       abort();
1548     }
1549     return;
1550   }
1551
1552   // Handle cast of SMALLER int to LARGER int using a move with sign extension
1553   // or zero extension, depending on whether the source type was signed.
1554   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1555       SrcClass < DestClass) {
1556     bool isLong = DestClass == cLong;
1557     if (isLong) DestClass = cInt;
1558
1559     static const unsigned Opc[][4] = {
1560       { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1561       { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 }  // u
1562     };
1563     
1564     bool isUnsigned = SrcTy->isUnsigned();
1565     BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1566         DestReg).addReg(SrcReg);
1567
1568     if (isLong) {  // Handle upper 32 bits as appropriate...
1569       if (isUnsigned)     // Zero out top bits...
1570         BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1571       else                // Sign extend bottom half...
1572         BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1573     }
1574     return;
1575   }
1576
1577   // Special case long -> int ...
1578   if (SrcClass == cLong && DestClass == cInt) {
1579     BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1580     return;
1581   }
1582   
1583   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1584   // move out of AX or AL.
1585   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1586       && SrcClass > DestClass) {
1587     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1588     BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1589     BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1590     return;
1591   }
1592
1593   // Handle casts from integer to floating point now...
1594   if (DestClass == cFP) {
1595     // unsigned int -> load as 64 bit int.
1596     // unsigned long long -> more complex
1597     if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy) {
1598       assert(0 && "Cannot handle this type of cast!");
1599       abort();  // don't handle unsigned src yet!
1600     }
1601
1602     // We don't have the facilities for directly loading byte sized data from
1603     // memory.  Promote it to 16 bits.
1604     if (SrcClass == cByte) {
1605       unsigned TmpReg = makeAnotherReg(Type::ShortTy);
1606       BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1607           1, TmpReg).addReg(SrcReg);
1608       SrcTy = Type::ShortTy;     // Pretend the short is our input now!
1609       SrcClass = cShort;
1610       SrcReg = TmpReg;
1611     }
1612
1613     // Spill the integer to memory and reload it from there...
1614     int FrameIdx =
1615       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1616
1617     if (SrcClass == cLong) {
1618       if (SrcTy == Type::ULongTy) {
1619         assert(0 && "FIXME: Handle cast ulong to FP");
1620         abort();
1621       }
1622       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1623       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1624                         FrameIdx, 4).addReg(SrcReg+1);
1625     } else {
1626       static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1627       addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1628     }
1629
1630     static const unsigned Op2[] =
1631       { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
1632     addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1633     return;
1634   }
1635
1636   // Handle casts from floating point to integer now...
1637   if (SrcClass == cFP) {
1638     // Change the floating point control register to use "round towards zero"
1639     // mode when truncating to an integer value.
1640     //
1641     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1642     addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1643
1644     // Load the old value of the high byte of the control word...
1645     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1646     addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1647
1648     // Set the high part to be round to zero...
1649     addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1650
1651     // Reload the modified control word now...
1652     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1653     
1654     // Restore the memory image of control word to original value
1655     addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1656                       CWFrameIdx, 1).addReg(HighPartOfCW);
1657
1658     // We don't have the facilities for directly storing byte sized data to
1659     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
1660     // larger classes because we only have signed FP stores.
1661     unsigned StoreClass  = DestClass;
1662     const Type *StoreTy  = DestTy;
1663     if (StoreClass == cByte || DestTy->isUnsigned())
1664       switch (StoreClass) {
1665       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
1666       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
1667       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
1668       case cLong:  abort(); // FIXME: unsigned long long -> more complex
1669       default: assert(0 && "Unknown store class!");
1670       }
1671
1672     // Spill the integer to memory and reload it from there...
1673     int FrameIdx =
1674       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1675
1676     static const unsigned Op1[] =
1677       { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1678     addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1679
1680     if (DestClass == cLong) {
1681       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1682       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1683     } else {
1684       static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1685       addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1686     }
1687
1688     // Reload the original control word now...
1689     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1690     return;
1691   }
1692
1693   // Anything we haven't handled already, we can't (yet) handle at all.
1694   assert(0 && "Unhandled cast instruction!");
1695   abort();
1696 }
1697
1698 /// visitVarArgInst - Implement the va_arg instruction...
1699 ///
1700 void ISel::visitVarArgInst(VarArgInst &I) {
1701   unsigned SrcReg = getReg(I.getOperand(0));
1702   unsigned DestReg = getReg(I);
1703
1704   // Load the va_list into a register...
1705   unsigned VAList = makeAnotherReg(Type::UIntTy);
1706   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1707
1708   unsigned Size;
1709   switch (I.getType()->getPrimitiveID()) {
1710   default:
1711     std::cerr << I;
1712     assert(0 && "Error: bad type for va_arg instruction!");
1713     return;
1714   case Type::PointerTyID:
1715   case Type::UIntTyID:
1716   case Type::IntTyID:
1717     Size = 4;
1718     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1719     break;
1720   case Type::ULongTyID:
1721   case Type::LongTyID:
1722     Size = 8;
1723     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1724     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1725     break;
1726   case Type::DoubleTyID:
1727     Size = 8;
1728     addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1729     break;
1730   }
1731
1732   // Increment the VAList pointer...
1733   unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1734   BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1735
1736   // Update the VAList in memory...
1737   addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1738 }
1739
1740
1741 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1742 // returns zero when the input is not exactly a power of two.
1743 static unsigned ExactLog2(unsigned Val) {
1744   if (Val == 0) return 0;
1745   unsigned Count = 0;
1746   while (Val != 1) {
1747     if (Val & 1) return 0;
1748     Val >>= 1;
1749     ++Count;
1750   }
1751   return Count+1;
1752 }
1753
1754 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1755   unsigned outputReg = getReg(I);
1756   MachineBasicBlock::iterator MI = BB->end();
1757   emitGEPOperation(BB, MI, I.getOperand(0),
1758                    I.op_begin()+1, I.op_end(), outputReg);
1759 }
1760
1761 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1762                             MachineBasicBlock::iterator &IP,
1763                             Value *Src, User::op_iterator IdxBegin,
1764                             User::op_iterator IdxEnd, unsigned TargetReg) {
1765   const TargetData &TD = TM.getTargetData();
1766   const Type *Ty = Src->getType();
1767   unsigned BaseReg = getReg(Src, MBB, IP);
1768
1769   // GEPs have zero or more indices; we must perform a struct access
1770   // or array access for each one.
1771   for (GetElementPtrInst::op_iterator oi = IdxBegin,
1772          oe = IdxEnd; oi != oe; ++oi) {
1773     Value *idx = *oi;
1774     unsigned NextReg = BaseReg;
1775     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1776       // It's a struct access.  idx is the index into the structure,
1777       // which names the field. This index must have ubyte type.
1778       const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1779       assert(CUI->getType() == Type::UByteTy
1780               && "Funny-looking structure index in GEP");
1781       // Use the TargetData structure to pick out what the layout of
1782       // the structure is in memory.  Since the structure index must
1783       // be constant, we can get its value and use it to find the
1784       // right byte offset from the StructLayout class's list of
1785       // structure member offsets.
1786       unsigned idxValue = CUI->getValue();
1787       unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1788       if (FieldOff) {
1789         NextReg = makeAnotherReg(Type::UIntTy);
1790         // Emit an ADD to add FieldOff to the basePtr.
1791         BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1792       }
1793       // The next type is the member of the structure selected by the
1794       // index.
1795       Ty = StTy->getElementTypes()[idxValue];
1796     } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1797       // It's an array or pointer access: [ArraySize x ElementType].
1798
1799       // idx is the index into the array.  Unlike with structure
1800       // indices, we may not know its actual value at code-generation
1801       // time.
1802       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1803
1804       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1805       // must find the size of the pointed-to type (Not coincidentally, the next
1806       // type is the type of the elements in the array).
1807       Ty = SqTy->getElementType();
1808       unsigned elementSize = TD.getTypeSize(Ty);
1809
1810       // If idxReg is a constant, we don't need to perform the multiply!
1811       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1812         if (!CSI->isNullValue()) {
1813           unsigned Offset = elementSize*CSI->getValue();
1814           NextReg = makeAnotherReg(Type::UIntTy);
1815           BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1816         }
1817       } else if (elementSize == 1) {
1818         // If the element size is 1, we don't have to multiply, just add
1819         unsigned idxReg = getReg(idx, MBB, IP);
1820         NextReg = makeAnotherReg(Type::UIntTy);
1821         BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1822       } else {
1823         unsigned idxReg = getReg(idx, MBB, IP);
1824         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1825         if (unsigned Shift = ExactLog2(elementSize)) {
1826           // If the element size is exactly a power of 2, use a shift to get it.
1827           BMI(MBB, IP, X86::SHLir32, 2,
1828               OffsetReg).addReg(idxReg).addZImm(Shift-1);
1829         } else {
1830           // Most general case, emit a multiply...
1831           unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1832           BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1833         
1834           // Emit a MUL to multiply the register holding the index by
1835           // elementSize, putting the result in OffsetReg.
1836           doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1837         }
1838         // Emit an ADD to add OffsetReg to the basePtr.
1839         NextReg = makeAnotherReg(Type::UIntTy);
1840         BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1841       }
1842     }
1843     // Now that we are here, further indices refer to subtypes of this
1844     // one, so we don't need to worry about BaseReg itself, anymore.
1845     BaseReg = NextReg;
1846   }
1847   // After we have processed all the indices, the result is left in
1848   // BaseReg.  Move it to the register where we were expected to
1849   // put the answer.  A 32-bit move should do it, because we are in
1850   // ILP32 land.
1851   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
1852 }
1853
1854
1855 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1856 /// frame manager, otherwise do it the hard way.
1857 ///
1858 void ISel::visitAllocaInst(AllocaInst &I) {
1859   // Find the data size of the alloca inst's getAllocatedType.
1860   const Type *Ty = I.getAllocatedType();
1861   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1862
1863   // If this is a fixed size alloca in the entry block for the function,
1864   // statically stack allocate the space.
1865   //
1866   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1867     if (I.getParent() == I.getParent()->getParent()->begin()) {
1868       TySize *= CUI->getValue();   // Get total allocated size...
1869       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1870       
1871       // Create a new stack object using the frame manager...
1872       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1873       addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1874       return;
1875     }
1876   }
1877   
1878   // Create a register to hold the temporary result of multiplying the type size
1879   // constant by the variable amount.
1880   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1881   unsigned SrcReg1 = getReg(I.getArraySize());
1882   unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1883   BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1884   
1885   // TotalSizeReg = mul <numelements>, <TypeSize>
1886   MachineBasicBlock::iterator MBBI = BB->end();
1887   doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1888
1889   // AddedSize = add <TotalSizeReg>, 15
1890   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1891   BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1892
1893   // AlignedSize = and <AddedSize>, ~15
1894   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1895   BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1896   
1897   // Subtract size from stack pointer, thereby allocating some space.
1898   BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
1899
1900   // Put a pointer to the space into the result register, by copying
1901   // the stack pointer.
1902   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1903
1904   // Inform the Frame Information that we have just allocated a variable-sized
1905   // object.
1906   F->getFrameInfo()->CreateVariableSizedObject();
1907 }
1908
1909 /// visitMallocInst - Malloc instructions are code generated into direct calls
1910 /// to the library malloc.
1911 ///
1912 void ISel::visitMallocInst(MallocInst &I) {
1913   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1914   unsigned Arg;
1915
1916   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1917     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1918   } else {
1919     Arg = makeAnotherReg(Type::UIntTy);
1920     unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1921     unsigned Op1Reg = getReg(I.getOperand(0));
1922     MachineBasicBlock::iterator MBBI = BB->end();
1923     doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1924                
1925                
1926   }
1927
1928   std::vector<ValueRecord> Args;
1929   Args.push_back(ValueRecord(Arg, Type::UIntTy));
1930   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1931                                   1).addExternalSymbol("malloc", true);
1932   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1933 }
1934
1935
1936 /// visitFreeInst - Free instructions are code gen'd to call the free libc
1937 /// function.
1938 ///
1939 void ISel::visitFreeInst(FreeInst &I) {
1940   std::vector<ValueRecord> Args;
1941   Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1942                              I.getOperand(0)->getType()));
1943   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1944                                   1).addExternalSymbol("free", true);
1945   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1946 }
1947    
1948
1949 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1950 /// into a machine code representation is a very simple peep-hole fashion.  The
1951 /// generated code sucks but the implementation is nice and simple.
1952 ///
1953 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1954   return new ISel(TM);
1955 }