78d5a1cad6cd0fe724caaa538e70702a116a0979
[oota-llvm.git] / lib / Target / X86 / InstSelectSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
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 x86 target
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicLowering.h"
22 #include "llvm/Pass.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/Statistic.h"
34 using namespace llvm;
35
36 namespace {
37   Statistic<>
38   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
39 }
40
41 /// BMI - A special BuildMI variant that takes an iterator to insert the
42 /// instruction at as well as a basic block.  This is the version for when you
43 /// have a destination register in mind.
44 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
45                                       MachineBasicBlock::iterator I,
46                                       int Opcode, unsigned NumOperands,
47                                       unsigned DestReg) {
48   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
49   MBB->insert(I, MI);
50   return MachineInstrBuilder(MI).addReg(DestReg, MachineOperand::Def);
51 }
52
53 /// BMI - A special BuildMI variant that takes an iterator to insert the
54 /// instruction at as well as a basic block.
55 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
56                                       MachineBasicBlock::iterator I,
57                                       int Opcode, unsigned NumOperands) {
58   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
59   MBB->insert(I, MI);
60   return MachineInstrBuilder(MI);
61 }
62
63
64 namespace {
65   struct ISel : public FunctionPass, InstVisitor<ISel> {
66     TargetMachine &TM;
67     MachineFunction *F;                 // The function we are compiling into
68     MachineBasicBlock *BB;              // The current MBB we are compiling
69     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
70     int ReturnAddressIndex;             // FrameIndex for the return address
71
72     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
73
74     // MBBMap - Mapping between LLVM BB -> Machine BB
75     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
76
77     ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
78
79     /// runOnFunction - Top level implementation of instruction selection for
80     /// the entire function.
81     ///
82     bool runOnFunction(Function &Fn) {
83       // First pass over the function, lower any unknown intrinsic functions
84       // with the IntrinsicLowering class.
85       LowerUnknownIntrinsicFunctionCalls(Fn);
86
87       F = &MachineFunction::construct(&Fn, TM);
88
89       // Create all of the machine basic blocks for the function...
90       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
91         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
92
93       BB = &F->front();
94
95       // Set up a frame object for the return address.  This is used by the
96       // llvm.returnaddress & llvm.frameaddress intrinisics.
97       ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
98
99       // Copy incoming arguments off of the stack...
100       LoadArgumentsToVirtualRegs(Fn);
101
102       // Instruction select everything except PHI nodes
103       visit(Fn);
104
105       // Select the PHI nodes
106       SelectPHINodes();
107
108       // Insert the FP_REG_KILL instructions into blocks that need them.
109       InsertFPRegKills();
110
111       RegMap.clear();
112       MBBMap.clear();
113       F = 0;
114       // We always build a machine code representation for the function
115       return true;
116     }
117
118     virtual const char *getPassName() const {
119       return "X86 Simple Instruction Selection";
120     }
121
122     /// visitBasicBlock - This method is called when we are visiting a new basic
123     /// block.  This simply creates a new MachineBasicBlock to emit code into
124     /// and adds it to the current MachineFunction.  Subsequent visit* for
125     /// instructions will be invoked for all instructions in the basic block.
126     ///
127     void visitBasicBlock(BasicBlock &LLVM_BB) {
128       BB = MBBMap[&LLVM_BB];
129     }
130
131     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
132     /// function, lowering any calls to unknown intrinsic functions into the
133     /// equivalent LLVM code.
134     void LowerUnknownIntrinsicFunctionCalls(Function &F);
135
136     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
137     /// from the stack into virtual registers.
138     ///
139     void LoadArgumentsToVirtualRegs(Function &F);
140
141     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
142     /// because we have to generate our sources into the source basic blocks,
143     /// not the current one.
144     ///
145     void SelectPHINodes();
146
147     /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
148     /// that need them.  This only occurs due to the floating point stackifier
149     /// not being aggressive enough to handle arbitrary global stackification.
150     ///
151     void InsertFPRegKills();
152
153     // Visitation methods for various instructions.  These methods simply emit
154     // fixed X86 code for each instruction.
155     //
156
157     // Control flow operators
158     void visitReturnInst(ReturnInst &RI);
159     void visitBranchInst(BranchInst &BI);
160
161     struct ValueRecord {
162       Value *Val;
163       unsigned Reg;
164       const Type *Ty;
165       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
166       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
167     };
168     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
169                 const std::vector<ValueRecord> &Args);
170     void visitCallInst(CallInst &I);
171     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
172
173     // Arithmetic operators
174     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
175     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
176     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
177     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
178                     unsigned DestReg, const Type *DestTy,
179                     unsigned Op0Reg, unsigned Op1Reg);
180     void doMultiplyConst(MachineBasicBlock *MBB, 
181                          MachineBasicBlock::iterator MBBI,
182                          unsigned DestReg, const Type *DestTy,
183                          unsigned Op0Reg, unsigned Op1Val);
184     void visitMul(BinaryOperator &B);
185
186     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
187     void visitRem(BinaryOperator &B) { visitDivRem(B); }
188     void visitDivRem(BinaryOperator &B);
189
190     // Bitwise operators
191     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
192     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
193     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
194
195     // Comparison operators...
196     void visitSetCondInst(SetCondInst &I);
197     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
198                             MachineBasicBlock *MBB,
199                             MachineBasicBlock::iterator MBBI);
200     
201     // Memory Instructions
202     void visitLoadInst(LoadInst &I);
203     void visitStoreInst(StoreInst &I);
204     void visitGetElementPtrInst(GetElementPtrInst &I);
205     void visitAllocaInst(AllocaInst &I);
206     void visitMallocInst(MallocInst &I);
207     void visitFreeInst(FreeInst &I);
208     
209     // Other operators
210     void visitShiftInst(ShiftInst &I);
211     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
212     void visitCastInst(CastInst &I);
213     void visitVANextInst(VANextInst &I);
214     void visitVAArgInst(VAArgInst &I);
215
216     void visitInstruction(Instruction &I) {
217       std::cerr << "Cannot instruction select: " << I;
218       abort();
219     }
220
221     /// promote32 - Make a value 32-bits wide, and put it somewhere.
222     ///
223     void promote32(unsigned targetReg, const ValueRecord &VR);
224
225     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
226     /// constant expression GEP support.
227     ///
228     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
229                           Value *Src, User::op_iterator IdxBegin,
230                           User::op_iterator IdxEnd, unsigned TargetReg);
231
232     /// emitCastOperation - Common code shared between visitCastInst and
233     /// constant expression cast support.
234     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
235                            Value *Src, const Type *DestTy, unsigned TargetReg);
236
237     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
238     /// and constant expression support.
239     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
240                                    MachineBasicBlock::iterator IP,
241                                    Value *Op0, Value *Op1,
242                                    unsigned OperatorClass, unsigned TargetReg);
243
244     void emitDivRemOperation(MachineBasicBlock *BB,
245                              MachineBasicBlock::iterator IP,
246                              unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
247                              const Type *Ty, unsigned TargetReg);
248
249     /// emitSetCCOperation - Common code shared between visitSetCondInst and
250     /// constant expression support.
251     void emitSetCCOperation(MachineBasicBlock *BB,
252                             MachineBasicBlock::iterator IP,
253                             Value *Op0, Value *Op1, unsigned Opcode,
254                             unsigned TargetReg);
255
256     /// emitShiftOperation - Common code shared between visitShiftInst and
257     /// constant expression support.
258     void emitShiftOperation(MachineBasicBlock *MBB,
259                             MachineBasicBlock::iterator IP,
260                             Value *Op, Value *ShiftAmount, bool isLeftShift,
261                             const Type *ResultTy, unsigned DestReg);
262       
263
264     /// copyConstantToRegister - Output the instructions required to put the
265     /// specified constant into the specified register.
266     ///
267     void copyConstantToRegister(MachineBasicBlock *MBB,
268                                 MachineBasicBlock::iterator MBBI,
269                                 Constant *C, unsigned Reg);
270
271     /// makeAnotherReg - This method returns the next register number we haven't
272     /// yet used.
273     ///
274     /// Long values are handled somewhat specially.  They are always allocated
275     /// as pairs of 32 bit integer values.  The register number returned is the
276     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
277     /// of the long value.
278     ///
279     unsigned makeAnotherReg(const Type *Ty) {
280       assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
281              "Current target doesn't have X86 reg info??");
282       const X86RegisterInfo *MRI =
283         static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
284       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
285         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
286         // Create the lower part
287         F->getSSARegMap()->createVirtualRegister(RC);
288         // Create the upper part.
289         return F->getSSARegMap()->createVirtualRegister(RC)-1;
290       }
291
292       // Add the mapping of regnumber => reg class to MachineFunction
293       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
294       return F->getSSARegMap()->createVirtualRegister(RC);
295     }
296
297     /// getReg - This method turns an LLVM value into a register number.  This
298     /// is guaranteed to produce the same register number for a particular value
299     /// every time it is queried.
300     ///
301     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
302     unsigned getReg(Value *V) {
303       // Just append to the end of the current bb.
304       MachineBasicBlock::iterator It = BB->end();
305       return getReg(V, BB, It);
306     }
307     unsigned getReg(Value *V, MachineBasicBlock *MBB,
308                     MachineBasicBlock::iterator IPt) {
309       unsigned &Reg = RegMap[V];
310       if (Reg == 0) {
311         Reg = makeAnotherReg(V->getType());
312         RegMap[V] = Reg;
313       }
314
315       // If this operand is a constant, emit the code to copy the constant into
316       // the register here...
317       //
318       if (Constant *C = dyn_cast<Constant>(V)) {
319         copyConstantToRegister(MBB, IPt, C, Reg);
320         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
321       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
322         // Move the address of the global into the register
323         BMI(MBB, IPt, X86::MOVri32, 1, Reg).addGlobalAddress(GV);
324         RegMap.erase(V);  // Assign a new name to this address if ref'd again
325       }
326
327       return Reg;
328     }
329   };
330 }
331
332 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
333 /// Representation.
334 ///
335 enum TypeClass {
336   cByte, cShort, cInt, cFP, cLong
337 };
338
339 /// getClass - Turn a primitive type into a "class" number which is based on the
340 /// size of the type, and whether or not it is floating point.
341 ///
342 static inline TypeClass getClass(const Type *Ty) {
343   switch (Ty->getPrimitiveID()) {
344   case Type::SByteTyID:
345   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
346   case Type::ShortTyID:
347   case Type::UShortTyID:  return cShort;     // Short operands are class #1
348   case Type::IntTyID:
349   case Type::UIntTyID:
350   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
351
352   case Type::FloatTyID:
353   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
354
355   case Type::LongTyID:
356   case Type::ULongTyID:   return cLong;      // Longs are class #4
357   default:
358     assert(0 && "Invalid type to getClass!");
359     return cByte;  // not reached
360   }
361 }
362
363 // getClassB - Just like getClass, but treat boolean values as bytes.
364 static inline TypeClass getClassB(const Type *Ty) {
365   if (Ty == Type::BoolTy) return cByte;
366   return getClass(Ty);
367 }
368
369
370 /// copyConstantToRegister - Output the instructions required to put the
371 /// specified constant into the specified register.
372 ///
373 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
374                                   MachineBasicBlock::iterator IP,
375                                   Constant *C, unsigned R) {
376   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
377     unsigned Class = 0;
378     switch (CE->getOpcode()) {
379     case Instruction::GetElementPtr:
380       emitGEPOperation(MBB, IP, CE->getOperand(0),
381                        CE->op_begin()+1, CE->op_end(), R);
382       return;
383     case Instruction::Cast:
384       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
385       return;
386
387     case Instruction::Xor: ++Class; // FALL THROUGH
388     case Instruction::Or:  ++Class; // FALL THROUGH
389     case Instruction::And: ++Class; // FALL THROUGH
390     case Instruction::Sub: ++Class; // FALL THROUGH
391     case Instruction::Add:
392       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
393                                 Class, R);
394       return;
395
396     case Instruction::Mul: {
397       unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
398       unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
399       doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
400       return;
401     }
402     case Instruction::Div:
403     case Instruction::Rem: {
404       unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
405       unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
406       emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
407                           CE->getOpcode() == Instruction::Div,
408                           CE->getType(), R);
409       return;
410     }
411
412     case Instruction::SetNE:
413     case Instruction::SetEQ:
414     case Instruction::SetLT:
415     case Instruction::SetGT:
416     case Instruction::SetLE:
417     case Instruction::SetGE:
418       emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
419                          CE->getOpcode(), R);
420       return;
421
422     case Instruction::Shl:
423     case Instruction::Shr:
424       emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
425                          CE->getOpcode() == Instruction::Shl, CE->getType(), R);
426       return;
427
428     default:
429       std::cerr << "Offending expr: " << C << "\n";
430       assert(0 && "Constant expression not yet handled!\n");
431     }
432   }
433
434   if (C->getType()->isIntegral()) {
435     unsigned Class = getClassB(C->getType());
436
437     if (Class == cLong) {
438       // Copy the value into the register pair.
439       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
440       BMI(MBB, IP, X86::MOVri32, 1, R).addZImm(Val & 0xFFFFFFFF);
441       BMI(MBB, IP, X86::MOVri32, 1, R+1).addZImm(Val >> 32);
442       return;
443     }
444
445     assert(Class <= cInt && "Type not handled yet!");
446
447     static const unsigned IntegralOpcodeTab[] = {
448       X86::MOVri8, X86::MOVri16, X86::MOVri32
449     };
450
451     if (C->getType() == Type::BoolTy) {
452       BMI(MBB, IP, X86::MOVri8, 1, R).addZImm(C == ConstantBool::True);
453     } else {
454       ConstantInt *CI = cast<ConstantInt>(C);
455       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CI->getRawValue());
456     }
457   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
458     if (CFP->isExactlyValue(+0.0))
459       BMI(MBB, IP, X86::FLD0, 0, R);
460     else if (CFP->isExactlyValue(+1.0))
461       BMI(MBB, IP, X86::FLD1, 0, R);
462     else {
463       // Otherwise we need to spill the constant to memory...
464       MachineConstantPool *CP = F->getConstantPool();
465       unsigned CPI = CP->getConstantPoolIndex(CFP);
466       const Type *Ty = CFP->getType();
467
468       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
469       unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
470       addConstantPoolReference(BMI(MBB, IP, LoadOpcode, 4, R), CPI);
471     }
472
473   } else if (isa<ConstantPointerNull>(C)) {
474     // Copy zero (null pointer) to the register.
475     BMI(MBB, IP, X86::MOVri32, 1, R).addZImm(0);
476   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
477     BMI(MBB, IP, X86::MOVri32, 1, R).addGlobalAddress(CPR->getValue());
478   } else {
479     std::cerr << "Offending constant: " << C << "\n";
480     assert(0 && "Type not handled yet!");
481   }
482 }
483
484 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
485 /// the stack into virtual registers.
486 ///
487 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
488   // Emit instructions to load the arguments...  On entry to a function on the
489   // X86, the stack frame looks like this:
490   //
491   // [ESP] -- return address
492   // [ESP + 4] -- first argument (leftmost lexically)
493   // [ESP + 8] -- second argument, if first argument is four bytes in size
494   //    ... 
495   //
496   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
497   MachineFrameInfo *MFI = F->getFrameInfo();
498
499   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
500     unsigned Reg = getReg(*I);
501     
502     int FI;          // Frame object index
503     switch (getClassB(I->getType())) {
504     case cByte:
505       FI = MFI->CreateFixedObject(1, ArgOffset);
506       addFrameReference(BuildMI(BB, X86::MOVrm8, 4, Reg), FI);
507       break;
508     case cShort:
509       FI = MFI->CreateFixedObject(2, ArgOffset);
510       addFrameReference(BuildMI(BB, X86::MOVrm16, 4, Reg), FI);
511       break;
512     case cInt:
513       FI = MFI->CreateFixedObject(4, ArgOffset);
514       addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg), FI);
515       break;
516     case cLong:
517       FI = MFI->CreateFixedObject(8, ArgOffset);
518       addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg), FI);
519       addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg+1), FI, 4);
520       ArgOffset += 4;   // longs require 4 additional bytes
521       break;
522     case cFP:
523       unsigned Opcode;
524       if (I->getType() == Type::FloatTy) {
525         Opcode = X86::FLDr32;
526         FI = MFI->CreateFixedObject(4, ArgOffset);
527       } else {
528         Opcode = X86::FLDr64;
529         FI = MFI->CreateFixedObject(8, ArgOffset);
530         ArgOffset += 4;   // doubles require 4 additional bytes
531       }
532       addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
533       break;
534     default:
535       assert(0 && "Unhandled argument type!");
536     }
537     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
538   }
539
540   // If the function takes variable number of arguments, add a frame offset for
541   // the start of the first vararg value... this is used to expand
542   // llvm.va_start.
543   if (Fn.getFunctionType()->isVarArg())
544     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
545 }
546
547
548 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
549 /// because we have to generate our sources into the source basic blocks, not
550 /// the current one.
551 ///
552 void ISel::SelectPHINodes() {
553   const TargetInstrInfo &TII = TM.getInstrInfo();
554   const Function &LF = *F->getFunction();  // The LLVM function...
555   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
556     const BasicBlock *BB = I;
557     MachineBasicBlock *MBB = MBBMap[I];
558
559     // Loop over all of the PHI nodes in the LLVM basic block...
560     MachineBasicBlock::iterator instr = MBB->begin();
561     for (BasicBlock::const_iterator I = BB->begin();
562          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
563
564       // Create a new machine instr PHI node, and insert it.
565       unsigned PHIReg = getReg(*PN);
566       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
567       MBB->insert(instr, PhiMI);
568
569       MachineInstr *LongPhiMI = 0;
570       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
571         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
572         MBB->insert(instr, LongPhiMI);
573       }
574
575       // PHIValues - Map of blocks to incoming virtual registers.  We use this
576       // so that we only initialize one incoming value for a particular block,
577       // even if the block has multiple entries in the PHI node.
578       //
579       std::map<MachineBasicBlock*, unsigned> PHIValues;
580
581       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
582         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
583         unsigned ValReg;
584         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
585           PHIValues.lower_bound(PredMBB);
586
587         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
588           // We already inserted an initialization of the register for this
589           // predecessor.  Recycle it.
590           ValReg = EntryIt->second;
591
592         } else {        
593           // Get the incoming value into a virtual register.
594           //
595           Value *Val = PN->getIncomingValue(i);
596
597           // If this is a constant or GlobalValue, we may have to insert code
598           // into the basic block to compute it into a virtual register.
599           if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
600             // Because we don't want to clobber any values which might be in
601             // physical registers with the computation of this constant (which
602             // might be arbitrarily complex if it is a constant expression),
603             // just insert the computation at the top of the basic block.
604             MachineBasicBlock::iterator PI = PredMBB->begin();
605
606             // Skip over any PHI nodes though!
607             while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
608               ++PI;
609
610             ValReg = getReg(Val, PredMBB, PI);
611           } else {
612             ValReg = getReg(Val);
613           }
614
615           // Remember that we inserted a value for this PHI for this predecessor
616           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
617         }
618
619         PhiMI->addRegOperand(ValReg);
620         PhiMI->addMachineBasicBlockOperand(PredMBB);
621         if (LongPhiMI) {
622           LongPhiMI->addRegOperand(ValReg+1);
623           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
624         }
625       }
626     }
627   }
628 }
629
630 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
631 /// compensation code on critical edges.  As such, it requires that we kill all
632 /// FP registers on the exit from any blocks that either ARE critical edges, or
633 /// branch to a block that has incoming critical edges.
634 ///
635 /// Note that this kill instruction will eventually be eliminated when
636 /// restrictions in the stackifier are relaxed.
637 ///
638 static bool RequiresFPRegKill(const BasicBlock *BB) {
639 #if 0
640   for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
641     const BasicBlock *Succ = *SI;
642     pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
643     ++PI;  // Block have at least one predecessory
644     if (PI != PE) {             // If it has exactly one, this isn't crit edge
645       // If this block has more than one predecessor, check all of the
646       // predecessors to see if they have multiple successors.  If so, then the
647       // block we are analyzing needs an FPRegKill.
648       for (PI = pred_begin(Succ); PI != PE; ++PI) {
649         const BasicBlock *Pred = *PI;
650         succ_const_iterator SI2 = succ_begin(Pred);
651         ++SI2;  // There must be at least one successor of this block.
652         if (SI2 != succ_end(Pred))
653           return true;   // Yes, we must insert the kill on this edge.
654       }
655     }
656   }
657   // If we got this far, there is no need to insert the kill instruction.
658   return false;
659 #else
660   return true;
661 #endif
662 }
663
664 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
665 // need them.  This only occurs due to the floating point stackifier not being
666 // aggressive enough to handle arbitrary global stackification.
667 //
668 // Currently we insert an FP_REG_KILL instruction into each block that uses or
669 // defines a floating point virtual register.
670 //
671 // When the global register allocators (like linear scan) finally update live
672 // variable analysis, we can keep floating point values in registers across
673 // portions of the CFG that do not involve critical edges.  This will be a big
674 // win, but we are waiting on the global allocators before we can do this.
675 //
676 // With a bit of work, the floating point stackifier pass can be enhanced to
677 // break critical edges as needed (to make a place to put compensation code),
678 // but this will require some infrastructure improvements as well.
679 //
680 void ISel::InsertFPRegKills() {
681   SSARegMap &RegMap = *F->getSSARegMap();
682   const TargetInstrInfo &TII = TM.getInstrInfo();
683
684   for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
685     bool UsesFPReg = false;
686     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
687       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
688         if (I->getOperand(i).isRegister()) {
689           unsigned Reg = I->getOperand(i).getReg();
690           if (MRegisterInfo::isVirtualRegister(Reg))
691             if (RegMap.getRegClass(Reg)->getSize() == 10) {
692               UsesFPReg = true;
693               break;
694             }
695         }
696     if (UsesFPReg) {
697       // Okay, this block uses an FP register.  If the block has successors (ie,
698       // it's not an unwind/return), insert the FP_REG_KILL instruction.
699       if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
700           RequiresFPRegKill(BB->getBasicBlock())) {
701         // Rewind past any terminator instructions that might exist.
702         MachineBasicBlock::iterator I = BB->end();
703         while (I != BB->begin() && TII.isTerminatorInstr((--I)->getOpcode()));
704         ++I;
705         BMI(BB, I, X86::FP_REG_KILL, 0);
706         ++NumFPKill;
707       }
708     }
709   }
710 }
711
712
713 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
714 // the conditional branch instruction which is the only user of the cc
715 // instruction.  This is the case if the conditional branch is the only user of
716 // the setcc, and if the setcc is in the same basic block as the conditional
717 // branch.  We also don't handle long arguments below, so we reject them here as
718 // well.
719 //
720 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
721   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
722     if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
723         SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
724       const Type *Ty = SCI->getOperand(0)->getType();
725       if (Ty != Type::LongTy && Ty != Type::ULongTy)
726         return SCI;
727     }
728   return 0;
729 }
730
731 // Return a fixed numbering for setcc instructions which does not depend on the
732 // order of the opcodes.
733 //
734 static unsigned getSetCCNumber(unsigned Opcode) {
735   switch(Opcode) {
736   default: assert(0 && "Unknown setcc instruction!");
737   case Instruction::SetEQ: return 0;
738   case Instruction::SetNE: return 1;
739   case Instruction::SetLT: return 2;
740   case Instruction::SetGE: return 3;
741   case Instruction::SetGT: return 4;
742   case Instruction::SetLE: return 5;
743   }
744 }
745
746 // LLVM  -> X86 signed  X86 unsigned
747 // -----    ----------  ------------
748 // seteq -> sete        sete
749 // setne -> setne       setne
750 // setlt -> setl        setb
751 // setge -> setge       setae
752 // setgt -> setg        seta
753 // setle -> setle       setbe
754 // ----
755 //          sets                       // Used by comparison with 0 optimization
756 //          setns
757 static const unsigned SetCCOpcodeTab[2][8] = {
758   { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
759     0, 0 },
760   { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
761     X86::SETSr, X86::SETNSr },
762 };
763
764 // EmitComparison - This function emits a comparison of the two operands,
765 // returning the extended setcc code to use.
766 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
767                               MachineBasicBlock *MBB,
768                               MachineBasicBlock::iterator IP) {
769   // The arguments are already supposed to be of the same type.
770   const Type *CompTy = Op0->getType();
771   unsigned Class = getClassB(CompTy);
772   unsigned Op0r = getReg(Op0, MBB, IP);
773
774   // Special case handling of: cmp R, i
775   if (Class == cByte || Class == cShort || Class == cInt)
776     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
777       uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
778
779       // Mask off any upper bits of the constant, if there are any...
780       Op1v &= (1ULL << (8 << Class)) - 1;
781
782       // If this is a comparison against zero, emit more efficient code.  We
783       // can't handle unsigned comparisons against zero unless they are == or
784       // !=.  These should have been strength reduced already anyway.
785       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
786         static const unsigned TESTTab[] = {
787           X86::TESTrr8, X86::TESTrr16, X86::TESTrr32
788         };
789         BMI(MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
790
791         if (OpNum == 2) return 6;   // Map jl -> js
792         if (OpNum == 3) return 7;   // Map jg -> jns
793         return OpNum;
794       }
795
796       static const unsigned CMPTab[] = {
797         X86::CMPri8, X86::CMPri16, X86::CMPri32
798       };
799
800       BMI(MBB, IP, CMPTab[Class], 2).addReg(Op0r).addZImm(Op1v);
801       return OpNum;
802     }
803
804   // Special case handling of comparison against +/- 0.0
805   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
806     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
807       BMI(MBB, IP, X86::FTST, 1).addReg(Op0r);
808       BMI(MBB, IP, X86::FNSTSWr8, 0);
809       BMI(MBB, IP, X86::SAHF, 1);
810       return OpNum;
811     }
812
813   unsigned Op1r = getReg(Op1, MBB, IP);
814   switch (Class) {
815   default: assert(0 && "Unknown type class!");
816     // Emit: cmp <var1>, <var2> (do the comparison).  We can
817     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
818     // 32-bit.
819   case cByte:
820     BMI(MBB, IP, X86::CMPrr8, 2).addReg(Op0r).addReg(Op1r);
821     break;
822   case cShort:
823     BMI(MBB, IP, X86::CMPrr16, 2).addReg(Op0r).addReg(Op1r);
824     break;
825   case cInt:
826     BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
827     break;
828   case cFP:
829     BMI(MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
830     BMI(MBB, IP, X86::FNSTSWr8, 0);
831     BMI(MBB, IP, X86::SAHF, 1);
832     break;
833
834   case cLong:
835     if (OpNum < 2) {    // seteq, setne
836       unsigned LoTmp = makeAnotherReg(Type::IntTy);
837       unsigned HiTmp = makeAnotherReg(Type::IntTy);
838       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
839       BMI(MBB, IP, X86::XORrr32, 2, LoTmp).addReg(Op0r).addReg(Op1r);
840       BMI(MBB, IP, X86::XORrr32, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
841       BMI(MBB, IP, X86::ORrr32,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
842       break;  // Allow the sete or setne to be generated from flags set by OR
843     } else {
844       // Emit a sequence of code which compares the high and low parts once
845       // each, then uses a conditional move to handle the overflow case.  For
846       // example, a setlt for long would generate code like this:
847       //
848       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
849       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
850       // dest = hi(op1) == hi(op2) ? AL : BL;
851       //
852
853       // FIXME: This would be much better if we had hierarchical register
854       // classes!  Until then, hardcode registers so that we can deal with their
855       // aliases (because we don't have conditional byte moves).
856       //
857       BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
858       BMI(MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
859       BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r+1).addReg(Op1r+1);
860       BMI(MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
861       BMI(MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
862       BMI(MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
863       BMI(MBB, IP, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
864       // NOTE: visitSetCondInst knows that the value is dumped into the BL
865       // register at this point for long values...
866       return OpNum;
867     }
868   }
869   return OpNum;
870 }
871
872
873 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
874 /// register, then move it to wherever the result should be. 
875 ///
876 void ISel::visitSetCondInst(SetCondInst &I) {
877   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
878
879   unsigned DestReg = getReg(I);
880   MachineBasicBlock::iterator MII = BB->end();
881   emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
882                      DestReg);
883 }
884
885 /// emitSetCCOperation - Common code shared between visitSetCondInst and
886 /// constant expression support.
887 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
888                               MachineBasicBlock::iterator IP,
889                               Value *Op0, Value *Op1, unsigned Opcode,
890                               unsigned TargetReg) {
891   unsigned OpNum = getSetCCNumber(Opcode);
892   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
893
894   const Type *CompTy = Op0->getType();
895   unsigned CompClass = getClassB(CompTy);
896   bool isSigned = CompTy->isSigned() && CompClass != cFP;
897
898   if (CompClass != cLong || OpNum < 2) {
899     // Handle normal comparisons with a setcc instruction...
900     BMI(MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
901   } else {
902     // Handle long comparisons by copying the value which is already in BL into
903     // the register we want...
904     BMI(MBB, IP, X86::MOVrr8, 1, TargetReg).addReg(X86::BL);
905   }
906 }
907
908
909
910
911 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
912 /// operand, in the specified target register.
913 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
914   bool isUnsigned = VR.Ty->isUnsigned();
915
916   // Make sure we have the register number for this value...
917   unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
918
919   switch (getClassB(VR.Ty)) {
920   case cByte:
921     // Extend value into target register (8->32)
922     if (isUnsigned)
923       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(Reg);
924     else
925       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(Reg);
926     break;
927   case cShort:
928     // Extend value into target register (16->32)
929     if (isUnsigned)
930       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(Reg);
931     else
932       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(Reg);
933     break;
934   case cInt:
935     // Move value into target register (32->32)
936     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(Reg);
937     break;
938   default:
939     assert(0 && "Unpromotable operand class in promote32");
940   }
941 }
942
943 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
944 /// we have the following possibilities:
945 ///
946 ///   ret void: No return value, simply emit a 'ret' instruction
947 ///   ret sbyte, ubyte : Extend value into EAX and return
948 ///   ret short, ushort: Extend value into EAX and return
949 ///   ret int, uint    : Move value into EAX and return
950 ///   ret pointer      : Move value into EAX and return
951 ///   ret long, ulong  : Move value into EAX/EDX and return
952 ///   ret float/double : Top of FP stack
953 ///
954 void ISel::visitReturnInst(ReturnInst &I) {
955   if (I.getNumOperands() == 0) {
956     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
957     return;
958   }
959
960   Value *RetVal = I.getOperand(0);
961   unsigned RetReg = getReg(RetVal);
962   switch (getClassB(RetVal->getType())) {
963   case cByte:   // integral return values: extend or move into EAX and return
964   case cShort:
965   case cInt:
966     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
967     // Declare that EAX is live on exit
968     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
969     break;
970   case cFP:                   // Floats & Doubles: Return in ST(0)
971     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
972     // Declare that top-of-stack is live on exit
973     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
974     break;
975   case cLong:
976     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
977     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
978     // Declare that EAX & EDX are live on exit
979     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
980       .addReg(X86::ESP);
981     break;
982   default:
983     visitInstruction(I);
984   }
985   // Emit a 'ret' instruction
986   BuildMI(BB, X86::RET, 0);
987 }
988
989 // getBlockAfter - Return the basic block which occurs lexically after the
990 // specified one.
991 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
992   Function::iterator I = BB; ++I;  // Get iterator to next block
993   return I != BB->getParent()->end() ? &*I : 0;
994 }
995
996 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
997 /// that since code layout is frozen at this point, that if we are trying to
998 /// jump to a block that is the immediate successor of the current block, we can
999 /// just make a fall-through (but we don't currently).
1000 ///
1001 void ISel::visitBranchInst(BranchInst &BI) {
1002   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1003
1004   if (!BI.isConditional()) {  // Unconditional branch?
1005     if (BI.getSuccessor(0) != NextBB)
1006       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1007     return;
1008   }
1009
1010   // See if we can fold the setcc into the branch itself...
1011   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1012   if (SCI == 0) {
1013     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1014     // computed some other way...
1015     unsigned condReg = getReg(BI.getCondition());
1016     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
1017     if (BI.getSuccessor(1) == NextBB) {
1018       if (BI.getSuccessor(0) != NextBB)
1019         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1020     } else {
1021       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1022       
1023       if (BI.getSuccessor(0) != NextBB)
1024         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1025     }
1026     return;
1027   }
1028
1029   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1030   MachineBasicBlock::iterator MII = BB->end();
1031   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1032
1033   const Type *CompTy = SCI->getOperand(0)->getType();
1034   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1035   
1036
1037   // LLVM  -> X86 signed  X86 unsigned
1038   // -----    ----------  ------------
1039   // seteq -> je          je
1040   // setne -> jne         jne
1041   // setlt -> jl          jb
1042   // setge -> jge         jae
1043   // setgt -> jg          ja
1044   // setle -> jle         jbe
1045   // ----
1046   //          js                  // Used by comparison with 0 optimization
1047   //          jns
1048
1049   static const unsigned OpcodeTab[2][8] = {
1050     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1051     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1052       X86::JS, X86::JNS },
1053   };
1054   
1055   if (BI.getSuccessor(0) != NextBB) {
1056     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1057     if (BI.getSuccessor(1) != NextBB)
1058       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1059   } else {
1060     // Change to the inverse condition...
1061     if (BI.getSuccessor(1) != NextBB) {
1062       OpNum ^= 1;
1063       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1064     }
1065   }
1066 }
1067
1068
1069 /// doCall - This emits an abstract call instruction, setting up the arguments
1070 /// and the return value as appropriate.  For the actual function call itself,
1071 /// it inserts the specified CallMI instruction into the stream.
1072 ///
1073 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1074                   const std::vector<ValueRecord> &Args) {
1075
1076   // Count how many bytes are to be pushed on the stack...
1077   unsigned NumBytes = 0;
1078
1079   if (!Args.empty()) {
1080     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1081       switch (getClassB(Args[i].Ty)) {
1082       case cByte: case cShort: case cInt:
1083         NumBytes += 4; break;
1084       case cLong:
1085         NumBytes += 8; break;
1086       case cFP:
1087         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1088         break;
1089       default: assert(0 && "Unknown class!");
1090       }
1091
1092     // Adjust the stack pointer for the new arguments...
1093     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
1094
1095     // Arguments go on the stack in reverse order, as specified by the ABI.
1096     unsigned ArgOffset = 0;
1097     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1098       unsigned ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1099       switch (getClassB(Args[i].Ty)) {
1100       case cByte:
1101       case cShort: {
1102         // Promote arg to 32 bits wide into a temporary register...
1103         unsigned R = makeAnotherReg(Type::UIntTy);
1104         promote32(R, Args[i]);
1105         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1106                      X86::ESP, ArgOffset).addReg(R);
1107         break;
1108       }
1109       case cInt:
1110         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1111                      X86::ESP, ArgOffset).addReg(ArgReg);
1112         break;
1113       case cLong:
1114         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1115                      X86::ESP, ArgOffset).addReg(ArgReg);
1116         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1117                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1118         ArgOffset += 4;        // 8 byte entry, not 4.
1119         break;
1120         
1121       case cFP:
1122         if (Args[i].Ty == Type::FloatTy) {
1123           addRegOffset(BuildMI(BB, X86::FSTr32, 5),
1124                        X86::ESP, ArgOffset).addReg(ArgReg);
1125         } else {
1126           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1127           addRegOffset(BuildMI(BB, X86::FSTr64, 5),
1128                        X86::ESP, ArgOffset).addReg(ArgReg);
1129           ArgOffset += 4;       // 8 byte entry, not 4.
1130         }
1131         break;
1132
1133       default: assert(0 && "Unknown class!");
1134       }
1135       ArgOffset += 4;
1136     }
1137   } else {
1138     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
1139   }
1140
1141   BB->push_back(CallMI);
1142
1143   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
1144
1145   // If there is a return value, scavenge the result from the location the call
1146   // leaves it in...
1147   //
1148   if (Ret.Ty != Type::VoidTy) {
1149     unsigned DestClass = getClassB(Ret.Ty);
1150     switch (DestClass) {
1151     case cByte:
1152     case cShort:
1153     case cInt: {
1154       // Integral results are in %eax, or the appropriate portion
1155       // thereof.
1156       static const unsigned regRegMove[] = {
1157         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
1158       };
1159       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1160       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1161       break;
1162     }
1163     case cFP:     // Floating-point return values live in %ST(0)
1164       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1165       break;
1166     case cLong:   // Long values are left in EDX:EAX
1167       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
1168       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
1169       break;
1170     default: assert(0 && "Unknown class!");
1171     }
1172   }
1173 }
1174
1175
1176 /// visitCallInst - Push args on stack and do a procedure call instruction.
1177 void ISel::visitCallInst(CallInst &CI) {
1178   MachineInstr *TheCall;
1179   if (Function *F = CI.getCalledFunction()) {
1180     // Is it an intrinsic function call?
1181     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1182       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1183       return;
1184     }
1185
1186     // Emit a CALL instruction with PC-relative displacement.
1187     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1188   } else {  // Emit an indirect call...
1189     unsigned Reg = getReg(CI.getCalledValue());
1190     TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
1191   }
1192
1193   std::vector<ValueRecord> Args;
1194   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1195     Args.push_back(ValueRecord(CI.getOperand(i)));
1196
1197   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1198   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1199 }         
1200
1201
1202 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1203 /// function, lowering any calls to unknown intrinsic functions into the
1204 /// equivalent LLVM code.
1205 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1206   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1207     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1208       if (CallInst *CI = dyn_cast<CallInst>(I++))
1209         if (Function *F = CI->getCalledFunction())
1210           switch (F->getIntrinsicID()) {
1211           case Intrinsic::not_intrinsic:
1212           case Intrinsic::va_start:
1213           case Intrinsic::va_copy:
1214           case Intrinsic::va_end:
1215           case Intrinsic::returnaddress:
1216           case Intrinsic::frameaddress:
1217           case Intrinsic::memcpy:
1218           case Intrinsic::memset:
1219             // We directly implement these intrinsics
1220             break;
1221           default:
1222             // All other intrinsic calls we must lower.
1223             Instruction *Before = CI->getPrev();
1224             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1225             if (Before) {        // Move iterator to instruction after call
1226               I = Before;  ++I;
1227             } else {
1228               I = BB->begin();
1229             }
1230           }
1231
1232 }
1233
1234 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1235   unsigned TmpReg1, TmpReg2;
1236   switch (ID) {
1237   case Intrinsic::va_start:
1238     // Get the address of the first vararg value...
1239     TmpReg1 = getReg(CI);
1240     addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
1241     return;
1242
1243   case Intrinsic::va_copy:
1244     TmpReg1 = getReg(CI);
1245     TmpReg2 = getReg(CI.getOperand(1));
1246     BuildMI(BB, X86::MOVrr32, 1, TmpReg1).addReg(TmpReg2);
1247     return;
1248   case Intrinsic::va_end: return;   // Noop on X86
1249
1250   case Intrinsic::returnaddress:
1251   case Intrinsic::frameaddress:
1252     TmpReg1 = getReg(CI);
1253     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1254       if (ID == Intrinsic::returnaddress) {
1255         // Just load the return address
1256         addFrameReference(BuildMI(BB, X86::MOVrm32, 4, TmpReg1),
1257                           ReturnAddressIndex);
1258       } else {
1259         addFrameReference(BuildMI(BB, X86::LEAr32, 4, TmpReg1),
1260                           ReturnAddressIndex, -4);
1261       }
1262     } else {
1263       // Values other than zero are not implemented yet.
1264       BuildMI(BB, X86::MOVri32, 1, TmpReg1).addZImm(0);
1265     }
1266     return;
1267
1268   case Intrinsic::memcpy: {
1269     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1270     unsigned Align = 1;
1271     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1272       Align = AlignC->getRawValue();
1273       if (Align == 0) Align = 1;
1274     }
1275
1276     // Turn the byte code into # iterations
1277     unsigned ByteReg;
1278     unsigned CountReg;
1279     unsigned Opcode;
1280     switch (Align & 3) {
1281     case 2:   // WORD aligned
1282       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1283         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1284       } else {
1285         CountReg = makeAnotherReg(Type::IntTy);
1286         BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(1);
1287       }
1288       Opcode = X86::REP_MOVSW;
1289       break;
1290     case 0:   // DWORD aligned
1291       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1292         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1293       } else {
1294         CountReg = makeAnotherReg(Type::IntTy);
1295         BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(2);
1296       }
1297       Opcode = X86::REP_MOVSD;
1298       break;
1299     case 1:   // BYTE aligned
1300     case 3:   // BYTE aligned
1301       CountReg = getReg(CI.getOperand(3));
1302       Opcode = X86::REP_MOVSB;
1303       break;
1304     }
1305
1306     // No matter what the alignment is, we put the source in ESI, the
1307     // destination in EDI, and the count in ECX.
1308     TmpReg1 = getReg(CI.getOperand(1));
1309     TmpReg2 = getReg(CI.getOperand(2));
1310     BuildMI(BB, X86::MOVrr32, 1, X86::ECX).addReg(CountReg);
1311     BuildMI(BB, X86::MOVrr32, 1, X86::EDI).addReg(TmpReg1);
1312     BuildMI(BB, X86::MOVrr32, 1, X86::ESI).addReg(TmpReg2);
1313     BuildMI(BB, Opcode, 0);
1314     return;
1315   }
1316   case Intrinsic::memset: {
1317     assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1318     unsigned Align = 1;
1319     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1320       Align = AlignC->getRawValue();
1321       if (Align == 0) Align = 1;
1322     }
1323
1324     // Turn the byte code into # iterations
1325     unsigned ByteReg;
1326     unsigned CountReg;
1327     unsigned Opcode;
1328     if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1329       unsigned Val = ValC->getRawValue() & 255;
1330
1331       // If the value is a constant, then we can potentially use larger copies.
1332       switch (Align & 3) {
1333       case 2:   // WORD aligned
1334         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1335           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1336         } else {
1337           CountReg = makeAnotherReg(Type::IntTy);
1338           BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(1);
1339         }
1340         BuildMI(BB, X86::MOVri16, 1, X86::AX).addZImm((Val << 8) | Val);
1341         Opcode = X86::REP_STOSW;
1342         break;
1343       case 0:   // DWORD aligned
1344         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1345           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1346         } else {
1347           CountReg = makeAnotherReg(Type::IntTy);
1348           BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(2);
1349         }
1350         Val = (Val << 8) | Val;
1351         BuildMI(BB, X86::MOVri32, 1, X86::EAX).addZImm((Val << 16) | Val);
1352         Opcode = X86::REP_STOSD;
1353         break;
1354       case 1:   // BYTE aligned
1355       case 3:   // BYTE aligned
1356         CountReg = getReg(CI.getOperand(3));
1357         BuildMI(BB, X86::MOVri8, 1, X86::AL).addZImm(Val);
1358         Opcode = X86::REP_STOSB;
1359         break;
1360       }
1361     } else {
1362       // If it's not a constant value we are storing, just fall back.  We could
1363       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1364       unsigned ValReg = getReg(CI.getOperand(2));
1365       BuildMI(BB, X86::MOVrr8, 1, X86::AL).addReg(ValReg);
1366       CountReg = getReg(CI.getOperand(3));
1367       Opcode = X86::REP_STOSB;
1368     }
1369
1370     // No matter what the alignment is, we put the source in ESI, the
1371     // destination in EDI, and the count in ECX.
1372     TmpReg1 = getReg(CI.getOperand(1));
1373     //TmpReg2 = getReg(CI.getOperand(2));
1374     BuildMI(BB, X86::MOVrr32, 1, X86::ECX).addReg(CountReg);
1375     BuildMI(BB, X86::MOVrr32, 1, X86::EDI).addReg(TmpReg1);
1376     BuildMI(BB, Opcode, 0);
1377     return;
1378   }
1379
1380   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1381   }
1382 }
1383
1384
1385 /// visitSimpleBinary - Implement simple binary operators for integral types...
1386 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1387 /// Xor.
1388 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1389   unsigned DestReg = getReg(B);
1390   MachineBasicBlock::iterator MI = BB->end();
1391   emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
1392                             OperatorClass, DestReg);
1393 }
1394
1395 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1396 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1397 /// Or, 4 for Xor.
1398 ///
1399 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1400 /// and constant expression support.
1401 ///
1402 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1403                                      MachineBasicBlock::iterator IP,
1404                                      Value *Op0, Value *Op1,
1405                                      unsigned OperatorClass, unsigned DestReg) {
1406   unsigned Class = getClassB(Op0->getType());
1407
1408   // sub 0, X -> neg X
1409   if (OperatorClass == 1 && Class != cLong)
1410     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1411       if (CI->isNullValue()) {
1412         unsigned op1Reg = getReg(Op1, MBB, IP);
1413         switch (Class) {
1414         default: assert(0 && "Unknown class for this function!");
1415         case cByte:
1416           BMI(MBB, IP, X86::NEGr8, 1, DestReg).addReg(op1Reg);
1417           return;
1418         case cShort:
1419           BMI(MBB, IP, X86::NEGr16, 1, DestReg).addReg(op1Reg);
1420           return;
1421         case cInt:
1422           BMI(MBB, IP, X86::NEGr32, 1, DestReg).addReg(op1Reg);
1423           return;
1424         }
1425       }
1426     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1427       if (CFP->isExactlyValue(-0.0)) {
1428         // -0.0 - X === -X
1429         unsigned op1Reg = getReg(Op1, MBB, IP);
1430         BMI(MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1431         return;
1432       }
1433
1434   if (!isa<ConstantInt>(Op1) || Class == cLong) {
1435     static const unsigned OpcodeTab[][4] = {
1436       // Arithmetic operators
1437       { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
1438       { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
1439       
1440       // Bitwise operators
1441       { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
1442       { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
1443       { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
1444     };
1445     
1446     bool isLong = false;
1447     if (Class == cLong) {
1448       isLong = true;
1449       Class = cInt;          // Bottom 32 bits are handled just like ints
1450     }
1451     
1452     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1453     assert(Opcode && "Floating point arguments to logical inst?");
1454     unsigned Op0r = getReg(Op0, MBB, IP);
1455     unsigned Op1r = getReg(Op1, MBB, IP);
1456     BMI(MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1457     
1458     if (isLong) {        // Handle the upper 32 bits of long values...
1459       static const unsigned TopTab[] = {
1460         X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1461       };
1462       BMI(MBB, IP, TopTab[OperatorClass], 2,
1463           DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1464     }
1465     return;
1466   }
1467
1468   // Special case: op Reg, <const>
1469   ConstantInt *Op1C = cast<ConstantInt>(Op1);
1470   unsigned Op0r = getReg(Op0, MBB, IP);
1471
1472   // xor X, -1 -> not X
1473   if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1474     static unsigned const NOTTab[] = { X86::NOTr8, X86::NOTr16, X86::NOTr32 };
1475     BMI(MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1476     return;
1477   }
1478
1479   // add X, -1 -> dec X
1480   if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1481     static unsigned const DECTab[] = { X86::DECr8, X86::DECr16, X86::DECr32 };
1482     BMI(MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1483     return;
1484   }
1485
1486   // add X, 1 -> inc X
1487   if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1488     static unsigned const DECTab[] = { X86::INCr8, X86::INCr16, X86::INCr32 };
1489     BMI(MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1490     return;
1491   }
1492   
1493   static const unsigned OpcodeTab[][3] = {
1494     // Arithmetic operators
1495     { X86::ADDri8, X86::ADDri16, X86::ADDri32 },  // ADD
1496     { X86::SUBri8, X86::SUBri16, X86::SUBri32 },  // SUB
1497     
1498     // Bitwise operators
1499     { X86::ANDri8, X86::ANDri16, X86::ANDri32 },  // AND
1500     { X86:: ORri8, X86:: ORri16, X86:: ORri32 },  // OR
1501     { X86::XORri8, X86::XORri16, X86::XORri32 },  // XOR
1502   };
1503   
1504   assert(Class < 3 && "General code handles 64-bit integer types!");
1505   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1506   uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1507   
1508   // Mask off any upper bits of the constant, if there are any...
1509   Op1v &= (1ULL << (8 << Class)) - 1;
1510   BMI(MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addZImm(Op1v);
1511 }
1512
1513 /// doMultiply - Emit appropriate instructions to multiply together the
1514 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1515 /// result should be given as DestTy.
1516 ///
1517 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1518                       unsigned DestReg, const Type *DestTy,
1519                       unsigned op0Reg, unsigned op1Reg) {
1520   unsigned Class = getClass(DestTy);
1521   switch (Class) {
1522   case cFP:              // Floating point multiply
1523     BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1524     return;
1525   case cInt:
1526   case cShort:
1527     BMI(BB, MBBI, Class == cInt ? X86::IMULrr32 : X86::IMULrr16, 2, DestReg)
1528       .addReg(op0Reg).addReg(op1Reg);
1529     return;
1530   case cByte:
1531     // Must use the MUL instruction, which forces use of AL...
1532     BMI(MBB, MBBI, X86::MOVrr8, 1, X86::AL).addReg(op0Reg);
1533     BMI(MBB, MBBI, X86::MULr8, 1).addReg(op1Reg);
1534     BMI(MBB, MBBI, X86::MOVrr8, 1, DestReg).addReg(X86::AL);
1535     return;
1536   default:
1537   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1538   }
1539 }
1540
1541 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1542 // returns zero when the input is not exactly a power of two.
1543 static unsigned ExactLog2(unsigned Val) {
1544   if (Val == 0) return 0;
1545   unsigned Count = 0;
1546   while (Val != 1) {
1547     if (Val & 1) return 0;
1548     Val >>= 1;
1549     ++Count;
1550   }
1551   return Count+1;
1552 }
1553
1554 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1555                            MachineBasicBlock::iterator IP,
1556                            unsigned DestReg, const Type *DestTy,
1557                            unsigned op0Reg, unsigned ConstRHS) {
1558   unsigned Class = getClass(DestTy);
1559
1560   // If the element size is exactly a power of 2, use a shift to get it.
1561   if (unsigned Shift = ExactLog2(ConstRHS)) {
1562     switch (Class) {
1563     default: assert(0 && "Unknown class for this function!");
1564     case cByte:
1565       BMI(MBB, IP, X86::SHLri32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1566       return;
1567     case cShort:
1568       BMI(MBB, IP, X86::SHLri32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1569       return;
1570     case cInt:
1571       BMI(MBB, IP, X86::SHLri32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1572       return;
1573     }
1574   }
1575   
1576   if (Class == cShort) {
1577     BMI(MBB, IP, X86::IMULrri16, 2, DestReg).addReg(op0Reg).addZImm(ConstRHS);
1578     return;
1579   } else if (Class == cInt) {
1580     BMI(MBB, IP, X86::IMULrri32, 2, DestReg).addReg(op0Reg).addZImm(ConstRHS);
1581     return;
1582   }
1583
1584   // Most general case, emit a normal multiply...
1585   static const unsigned MOVriTab[] = {
1586     X86::MOVri8, X86::MOVri16, X86::MOVri32
1587   };
1588
1589   unsigned TmpReg = makeAnotherReg(DestTy);
1590   BMI(MBB, IP, MOVriTab[Class], 1, TmpReg).addZImm(ConstRHS);
1591   
1592   // Emit a MUL to multiply the register holding the index by
1593   // elementSize, putting the result in OffsetReg.
1594   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1595 }
1596
1597 /// visitMul - Multiplies are not simple binary operators because they must deal
1598 /// with the EAX register explicitly.
1599 ///
1600 void ISel::visitMul(BinaryOperator &I) {
1601   unsigned Op0Reg  = getReg(I.getOperand(0));
1602   unsigned DestReg = getReg(I);
1603
1604   // Simple scalar multiply?
1605   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1606     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1607       unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1608       MachineBasicBlock::iterator MBBI = BB->end();
1609       doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1610     } else {
1611       unsigned Op1Reg  = getReg(I.getOperand(1));
1612       MachineBasicBlock::iterator MBBI = BB->end();
1613       doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1614     }
1615   } else {
1616     unsigned Op1Reg  = getReg(I.getOperand(1));
1617
1618     // Long value.  We have to do things the hard way...
1619     // Multiply the two low parts... capturing carry into EDX
1620     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1621     BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg);  // AL*BL
1622
1623     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1624     BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX);     // AL*BL
1625     BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1626
1627     MachineBasicBlock::iterator MBBI = BB->end();
1628     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
1629     BMI(BB, MBBI, X86::IMULrr32, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1630
1631     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1632     BuildMI(BB, X86::ADDrr32, 2,                         // AH*BL+(AL*BL >> 32)
1633             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1634     
1635     MBBI = BB->end();
1636     unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1637     BMI(BB, MBBI, X86::IMULrr32, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1638     
1639     BuildMI(BB, X86::ADDrr32, 2,               // AL*BH + AH*BL + (AL*BL >> 32)
1640             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1641   }
1642 }
1643
1644
1645 /// visitDivRem - Handle division and remainder instructions... these
1646 /// instruction both require the same instructions to be generated, they just
1647 /// select the result from a different register.  Note that both of these
1648 /// instructions work differently for signed and unsigned operands.
1649 ///
1650 void ISel::visitDivRem(BinaryOperator &I) {
1651   unsigned Op0Reg = getReg(I.getOperand(0));
1652   unsigned Op1Reg = getReg(I.getOperand(1));
1653   unsigned ResultReg = getReg(I);
1654
1655   MachineBasicBlock::iterator IP = BB->end();
1656   emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1657                       I.getType(), ResultReg);
1658 }
1659
1660 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1661                                MachineBasicBlock::iterator IP,
1662                                unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1663                                const Type *Ty, unsigned ResultReg) {
1664   unsigned Class = getClass(Ty);
1665   switch (Class) {
1666   case cFP:              // Floating point divide
1667     if (isDiv) {
1668       BMI(BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1669     } else {               // Floating point remainder...
1670       MachineInstr *TheCall =
1671         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1672       std::vector<ValueRecord> Args;
1673       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1674       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1675       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1676     }
1677     return;
1678   case cLong: {
1679     static const char *FnName[] =
1680       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1681
1682     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1683     MachineInstr *TheCall =
1684       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1685
1686     std::vector<ValueRecord> Args;
1687     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1688     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1689     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1690     return;
1691   }
1692   case cByte: case cShort: case cInt:
1693     break;          // Small integrals, handled below...
1694   default: assert(0 && "Unknown class!");
1695   }
1696
1697   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1698   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1699   static const unsigned SarOpcode[]={ X86::SARri8, X86::SARri16, X86::SARri32 };
1700   static const unsigned ClrOpcode[]={ X86::MOVri8, X86::MOVri16, X86::MOVri32 };
1701   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1702
1703   static const unsigned DivOpcode[][4] = {
1704     { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 },  // Unsigned division
1705     { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 },  // Signed division
1706   };
1707
1708   bool isSigned   = Ty->isSigned();
1709   unsigned Reg    = Regs[Class];
1710   unsigned ExtReg = ExtRegs[Class];
1711
1712   // Put the first operand into one of the A registers...
1713   BMI(BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1714
1715   if (isSigned) {
1716     // Emit a sign extension instruction...
1717     unsigned ShiftResult = makeAnotherReg(Ty);
1718     BMI(BB, IP, SarOpcode[Class], 2, ShiftResult).addReg(Op0Reg).addZImm(31);
1719     BMI(BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1720   } else {
1721     // If unsigned, emit a zeroing instruction... (reg = 0)
1722     BMI(BB, IP, ClrOpcode[Class], 2, ExtReg).addZImm(0);
1723   }
1724
1725   // Emit the appropriate divide or remainder instruction...
1726   BMI(BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1727
1728   // Figure out which register we want to pick the result out of...
1729   unsigned DestReg = isDiv ? Reg : ExtReg;
1730   
1731   // Put the result into the destination register...
1732   BMI(BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1733 }
1734
1735
1736 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1737 /// for constant immediate shift values, and for constant immediate
1738 /// shift values equal to 1. Even the general case is sort of special,
1739 /// because the shift amount has to be in CL, not just any old register.
1740 ///
1741 void ISel::visitShiftInst(ShiftInst &I) {
1742   MachineBasicBlock::iterator IP = BB->end ();
1743   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1744                       I.getOpcode () == Instruction::Shl, I.getType (),
1745                       getReg (I));
1746 }
1747
1748 /// emitShiftOperation - Common code shared between visitShiftInst and
1749 /// constant expression support.
1750 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
1751                               MachineBasicBlock::iterator IP,
1752                               Value *Op, Value *ShiftAmount, bool isLeftShift,
1753                               const Type *ResultTy, unsigned DestReg) {
1754   unsigned SrcReg = getReg (Op, MBB, IP);
1755   bool isSigned = ResultTy->isSigned ();
1756   unsigned Class = getClass (ResultTy);
1757   
1758   static const unsigned ConstantOperand[][4] = {
1759     { X86::SHRri8, X86::SHRri16, X86::SHRri32, X86::SHRDri32 },  // SHR
1760     { X86::SARri8, X86::SARri16, X86::SARri32, X86::SHRDri32 },  // SAR
1761     { X86::SHLri8, X86::SHLri16, X86::SHLri32, X86::SHLDri32 },  // SHL
1762     { X86::SHLri8, X86::SHLri16, X86::SHLri32, X86::SHLDri32 },  // SAL = SHL
1763   };
1764
1765   static const unsigned NonConstantOperand[][4] = {
1766     { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 },  // SHR
1767     { X86::SARrr8, X86::SARrr16, X86::SARrr32 },  // SAR
1768     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SHL
1769     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SAL = SHL
1770   };
1771
1772   // Longs, as usual, are handled specially...
1773   if (Class == cLong) {
1774     // If we have a constant shift, we can generate much more efficient code
1775     // than otherwise...
1776     //
1777     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1778       unsigned Amount = CUI->getValue();
1779       if (Amount < 32) {
1780         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1781         if (isLeftShift) {
1782           BMI(MBB, IP, Opc[3], 3, 
1783               DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1784           BMI(MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1785         } else {
1786           BMI(MBB, IP, Opc[3], 3,
1787               DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addZImm(Amount);
1788           BMI(MBB, IP, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1789         }
1790       } else {                 // Shifting more than 32 bits
1791         Amount -= 32;
1792         if (isLeftShift) {
1793           BMI(MBB, IP, X86::SHLri32, 2,
1794               DestReg + 1).addReg(SrcReg).addZImm(Amount);
1795           BMI(MBB, IP, X86::MOVri32, 1,
1796               DestReg).addZImm(0);
1797         } else {
1798           unsigned Opcode = isSigned ? X86::SARri32 : X86::SHRri32;
1799           BMI(MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1800           BMI(MBB, IP, X86::MOVri32, 1, DestReg+1).addZImm(0);
1801         }
1802       }
1803     } else {
1804       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1805
1806       if (!isLeftShift && isSigned) {
1807         // If this is a SHR of a Long, then we need to do funny sign extension
1808         // stuff.  TmpReg gets the value to use as the high-part if we are
1809         // shifting more than 32 bits.
1810         BMI(MBB, IP, X86::SARri32, 2, TmpReg).addReg(SrcReg).addZImm(31);
1811       } else {
1812         // Other shifts use a fixed zero value if the shift is more than 32
1813         // bits.
1814         BMI(MBB, IP, X86::MOVri32, 1, TmpReg).addZImm(0);
1815       }
1816
1817       // Initialize CL with the shift amount...
1818       unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
1819       BMI(MBB, IP, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmountReg);
1820
1821       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1822       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1823       if (isLeftShift) {
1824         // TmpReg2 = shld inHi, inLo
1825         BMI(MBB, IP, X86::SHLDrr32, 2, TmpReg2).addReg(SrcReg+1).addReg(SrcReg);
1826         // TmpReg3 = shl  inLo, CL
1827         BMI(MBB, IP, X86::SHLrr32, 1, TmpReg3).addReg(SrcReg);
1828
1829         // Set the flags to indicate whether the shift was by more than 32 bits.
1830         BMI(MBB, IP, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1831
1832         // DestHi = (>32) ? TmpReg3 : TmpReg2;
1833         BMI(MBB, IP, X86::CMOVNErr32, 2, 
1834                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1835         // DestLo = (>32) ? TmpReg : TmpReg3;
1836         BMI(MBB, IP, X86::CMOVNErr32, 2,
1837             DestReg).addReg(TmpReg3).addReg(TmpReg);
1838       } else {
1839         // TmpReg2 = shrd inLo, inHi
1840         BMI(MBB, IP, X86::SHRDrr32, 2, TmpReg2).addReg(SrcReg).addReg(SrcReg+1);
1841         // TmpReg3 = s[ah]r  inHi, CL
1842         BMI(MBB, IP, isSigned ? X86::SARrr32 : X86::SHRrr32, 1, TmpReg3)
1843                        .addReg(SrcReg+1);
1844
1845         // Set the flags to indicate whether the shift was by more than 32 bits.
1846         BMI(MBB, IP, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1847
1848         // DestLo = (>32) ? TmpReg3 : TmpReg2;
1849         BMI(MBB, IP, X86::CMOVNErr32, 2, 
1850                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1851
1852         // DestHi = (>32) ? TmpReg : TmpReg3;
1853         BMI(MBB, IP, X86::CMOVNErr32, 2, 
1854                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1855       }
1856     }
1857     return;
1858   }
1859
1860   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1861     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1862     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1863
1864     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1865     BMI(MBB, IP, Opc[Class], 2,
1866         DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1867   } else {                  // The shift amount is non-constant.
1868     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
1869     BMI(MBB, IP, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmountReg);
1870
1871     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1872     BMI(MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
1873   }
1874 }
1875
1876
1877 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1878 /// instruction.  The load and store instructions are the only place where we
1879 /// need to worry about the memory layout of the target machine.
1880 ///
1881 void ISel::visitLoadInst(LoadInst &I) {
1882   unsigned SrcAddrReg = getReg(I.getOperand(0));
1883   unsigned DestReg = getReg(I);
1884
1885   unsigned Class = getClassB(I.getType());
1886
1887   if (Class == cLong) {
1888     addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), SrcAddrReg);
1889     addRegOffset(BuildMI(BB, X86::MOVrm32, 4, DestReg+1), SrcAddrReg, 4);
1890     return;
1891   }
1892
1893   static const unsigned Opcodes[] = {
1894     X86::MOVrm8, X86::MOVrm16, X86::MOVrm32, X86::FLDr32
1895   };
1896   unsigned Opcode = Opcodes[Class];
1897   if (I.getType() == Type::DoubleTy) Opcode = X86::FLDr64;
1898   addDirectMem(BuildMI(BB, Opcode, 4, DestReg), SrcAddrReg);
1899 }
1900
1901 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1902 /// instruction.
1903 ///
1904 void ISel::visitStoreInst(StoreInst &I) {
1905   unsigned ValReg      = getReg(I.getOperand(0));
1906   unsigned AddressReg  = getReg(I.getOperand(1));
1907  
1908   const Type *ValTy = I.getOperand(0)->getType();
1909   unsigned Class = getClassB(ValTy);
1910
1911   if (Class == cLong) {
1912     addDirectMem(BuildMI(BB, X86::MOVmr32, 1+4), AddressReg).addReg(ValReg);
1913     addRegOffset(BuildMI(BB, X86::MOVmr32, 1+4), AddressReg,4).addReg(ValReg+1);
1914     return;
1915   }
1916
1917   static const unsigned Opcodes[] = {
1918     X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, X86::FSTr32
1919   };
1920   unsigned Opcode = Opcodes[Class];
1921   if (ValTy == Type::DoubleTy) Opcode = X86::FSTr64;
1922   addDirectMem(BuildMI(BB, Opcode, 1+4), AddressReg).addReg(ValReg);
1923 }
1924
1925
1926 /// visitCastInst - Here we have various kinds of copying with or without
1927 /// sign extension going on.
1928 void ISel::visitCastInst(CastInst &CI) {
1929   Value *Op = CI.getOperand(0);
1930   // If this is a cast from a 32-bit integer to a Long type, and the only uses
1931   // of the case are GEP instructions, then the cast does not need to be
1932   // generated explicitly, it will be folded into the GEP.
1933   if (CI.getType() == Type::LongTy &&
1934       (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
1935     bool AllUsesAreGEPs = true;
1936     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
1937       if (!isa<GetElementPtrInst>(*I)) {
1938         AllUsesAreGEPs = false;
1939         break;
1940       }        
1941
1942     // No need to codegen this cast if all users are getelementptr instrs...
1943     if (AllUsesAreGEPs) return;
1944   }
1945
1946   unsigned DestReg = getReg(CI);
1947   MachineBasicBlock::iterator MI = BB->end();
1948   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
1949 }
1950
1951 /// emitCastOperation - Common code shared between visitCastInst and
1952 /// constant expression cast support.
1953 void ISel::emitCastOperation(MachineBasicBlock *BB,
1954                              MachineBasicBlock::iterator IP,
1955                              Value *Src, const Type *DestTy,
1956                              unsigned DestReg) {
1957   unsigned SrcReg = getReg(Src, BB, IP);
1958   const Type *SrcTy = Src->getType();
1959   unsigned SrcClass = getClassB(SrcTy);
1960   unsigned DestClass = getClassB(DestTy);
1961
1962   // Implement casts to bool by using compare on the operand followed by set if
1963   // not zero on the result.
1964   if (DestTy == Type::BoolTy) {
1965     switch (SrcClass) {
1966     case cByte:
1967       BMI(BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
1968       break;
1969     case cShort:
1970       BMI(BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
1971       break;
1972     case cInt:
1973       BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
1974       break;
1975     case cLong: {
1976       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1977       BMI(BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
1978       break;
1979     }
1980     case cFP:
1981       assert(0 && "FIXME: implement cast FP to bool");
1982       abort();
1983     }
1984
1985     // If the zero flag is not set, then the value is true, set the byte to
1986     // true.
1987     BMI(BB, IP, X86::SETNEr, 1, DestReg);
1988     return;
1989   }
1990
1991   static const unsigned RegRegMove[] = {
1992     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1993   };
1994
1995   // Implement casts between values of the same type class (as determined by
1996   // getClass) by using a register-to-register move.
1997   if (SrcClass == DestClass) {
1998     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1999       BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2000     } else if (SrcClass == cFP) {
2001       if (SrcTy == Type::FloatTy) {  // double -> float
2002         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2003         BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2004       } else {                       // float -> double
2005         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2006                "Unknown cFP member!");
2007         // Truncate from double to float by storing to memory as short, then
2008         // reading it back.
2009         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2010         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2011         addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
2012         addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
2013       }
2014     } else if (SrcClass == cLong) {
2015       BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
2016       BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
2017     } else {
2018       assert(0 && "Cannot handle this type of cast instruction!");
2019       abort();
2020     }
2021     return;
2022   }
2023
2024   // Handle cast of SMALLER int to LARGER int using a move with sign extension
2025   // or zero extension, depending on whether the source type was signed.
2026   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2027       SrcClass < DestClass) {
2028     bool isLong = DestClass == cLong;
2029     if (isLong) DestClass = cInt;
2030
2031     static const unsigned Opc[][4] = {
2032       { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
2033       { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 }  // u
2034     };
2035     
2036     bool isUnsigned = SrcTy->isUnsigned();
2037     BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2038         DestReg).addReg(SrcReg);
2039
2040     if (isLong) {  // Handle upper 32 bits as appropriate...
2041       if (isUnsigned)     // Zero out top bits...
2042         BMI(BB, IP, X86::MOVri32, 1, DestReg+1).addZImm(0);
2043       else                // Sign extend bottom half...
2044         BMI(BB, IP, X86::SARri32, 2, DestReg+1).addReg(DestReg).addZImm(31);
2045     }
2046     return;
2047   }
2048
2049   // Special case long -> int ...
2050   if (SrcClass == cLong && DestClass == cInt) {
2051     BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
2052     return;
2053   }
2054   
2055   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2056   // move out of AX or AL.
2057   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2058       && SrcClass > DestClass) {
2059     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2060     BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2061     BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2062     return;
2063   }
2064
2065   // Handle casts from integer to floating point now...
2066   if (DestClass == cFP) {
2067     // Promote the integer to a type supported by FLD.  We do this because there
2068     // are no unsigned FLD instructions, so we must promote an unsigned value to
2069     // a larger signed value, then use FLD on the larger value.
2070     //
2071     const Type *PromoteType = 0;
2072     unsigned PromoteOpcode;
2073     unsigned RealDestReg = DestReg;
2074     switch (SrcTy->getPrimitiveID()) {
2075     case Type::BoolTyID:
2076     case Type::SByteTyID:
2077       // We don't have the facilities for directly loading byte sized data from
2078       // memory (even signed).  Promote it to 16 bits.
2079       PromoteType = Type::ShortTy;
2080       PromoteOpcode = X86::MOVSXr16r8;
2081       break;
2082     case Type::UByteTyID:
2083       PromoteType = Type::ShortTy;
2084       PromoteOpcode = X86::MOVZXr16r8;
2085       break;
2086     case Type::UShortTyID:
2087       PromoteType = Type::IntTy;
2088       PromoteOpcode = X86::MOVZXr32r16;
2089       break;
2090     case Type::UIntTyID: {
2091       // Make a 64 bit temporary... and zero out the top of it...
2092       unsigned TmpReg = makeAnotherReg(Type::LongTy);
2093       BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
2094       BMI(BB, IP, X86::MOVri32, 1, TmpReg+1).addZImm(0);
2095       SrcTy = Type::LongTy;
2096       SrcClass = cLong;
2097       SrcReg = TmpReg;
2098       break;
2099     }
2100     case Type::ULongTyID:
2101       // Don't fild into the read destination.
2102       DestReg = makeAnotherReg(Type::DoubleTy);
2103       break;
2104     default:  // No promotion needed...
2105       break;
2106     }
2107     
2108     if (PromoteType) {
2109       unsigned TmpReg = makeAnotherReg(PromoteType);
2110       unsigned Opc = SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8;
2111       BMI(BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2112       SrcTy = PromoteType;
2113       SrcClass = getClass(PromoteType);
2114       SrcReg = TmpReg;
2115     }
2116
2117     // Spill the integer to memory and reload it from there...
2118     int FrameIdx = F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2119
2120     if (SrcClass == cLong) {
2121       addFrameReference(BMI(BB, IP, X86::MOVmr32, 5), FrameIdx).addReg(SrcReg);
2122       addFrameReference(BMI(BB, IP, X86::MOVmr32, 5),
2123                         FrameIdx, 4).addReg(SrcReg+1);
2124     } else {
2125       static const unsigned Op1[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
2126       addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
2127     }
2128
2129     static const unsigned Op2[] =
2130       { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
2131     addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2132
2133     // We need special handling for unsigned 64-bit integer sources.  If the
2134     // input number has the "sign bit" set, then we loaded it incorrectly as a
2135     // negative 64-bit number.  In this case, add an offset value.
2136     if (SrcTy == Type::ULongTy) {
2137       // Emit a test instruction to see if the dynamic input value was signed.
2138       BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2139
2140       // If the sign bit is set, get a pointer to an offset, otherwise get a pointer to a zero.
2141       MachineConstantPool *CP = F->getConstantPool();
2142       unsigned Zero = makeAnotherReg(Type::IntTy);
2143       addConstantPoolReference(BMI(BB, IP, X86::LEAr32, 5, Zero), 
2144                                CP->getConstantPoolIndex(Constant::getNullValue(Type::UIntTy)));
2145       unsigned Offset = makeAnotherReg(Type::IntTy);
2146       addConstantPoolReference(BMI(BB, IP, X86::LEAr32, 5, Offset),
2147                                CP->getConstantPoolIndex(ConstantUInt::get(Type::UIntTy,
2148                                                                           0x5f800000)));
2149       unsigned Addr = makeAnotherReg(Type::IntTy);
2150       BMI(BB, IP, X86::CMOVSrr32, 2, Addr).addReg(Zero).addReg(Offset);
2151
2152       // Load the constant for an add.  FIXME: this could make an 'fadd' that
2153       // reads directly from memory, but we don't support these yet.
2154       unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2155       addDirectMem(BMI(BB, IP, X86::FLDr32, 4, ConstReg), Addr);
2156
2157       BMI(BB, IP, X86::FpADD, 2, RealDestReg).addReg(ConstReg).addReg(DestReg);
2158     }
2159
2160     return;
2161   }
2162
2163   // Handle casts from floating point to integer now...
2164   if (SrcClass == cFP) {
2165     // Change the floating point control register to use "round towards zero"
2166     // mode when truncating to an integer value.
2167     //
2168     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2169     addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
2170
2171     // Load the old value of the high byte of the control word...
2172     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2173     addFrameReference(BMI(BB, IP, X86::MOVrm8, 4, HighPartOfCW), CWFrameIdx, 1);
2174
2175     // Set the high part to be round to zero...
2176     addFrameReference(BMI(BB, IP, X86::MOVmi8, 5), CWFrameIdx, 1).addZImm(12);
2177
2178     // Reload the modified control word now...
2179     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
2180     
2181     // Restore the memory image of control word to original value
2182     addFrameReference(BMI(BB, IP, X86::MOVmr8, 5),
2183                       CWFrameIdx, 1).addReg(HighPartOfCW);
2184
2185     // We don't have the facilities for directly storing byte sized data to
2186     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
2187     // larger classes because we only have signed FP stores.
2188     unsigned StoreClass  = DestClass;
2189     const Type *StoreTy  = DestTy;
2190     if (StoreClass == cByte || DestTy->isUnsigned())
2191       switch (StoreClass) {
2192       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
2193       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
2194       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2195       // The following treatment of cLong may not be perfectly right,
2196       // but it survives chains of casts of the form
2197       // double->ulong->double.
2198       case cLong:  StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2199       default: assert(0 && "Unknown store class!");
2200       }
2201
2202     // Spill the integer to memory and reload it from there...
2203     int FrameIdx =
2204       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2205
2206     static const unsigned Op1[] =
2207       { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
2208     addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
2209
2210     if (DestClass == cLong) {
2211       addFrameReference(BMI(BB, IP, X86::MOVrm32, 4, DestReg), FrameIdx);
2212       addFrameReference(BMI(BB, IP, X86::MOVrm32, 4, DestReg+1), FrameIdx, 4);
2213     } else {
2214       static const unsigned Op2[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
2215       addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2216     }
2217
2218     // Reload the original control word now...
2219     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
2220     return;
2221   }
2222
2223   // Anything we haven't handled already, we can't (yet) handle at all.
2224   assert(0 && "Unhandled cast instruction!");
2225   abort();
2226 }
2227
2228 /// visitVANextInst - Implement the va_next instruction...
2229 ///
2230 void ISel::visitVANextInst(VANextInst &I) {
2231   unsigned VAList = getReg(I.getOperand(0));
2232   unsigned DestReg = getReg(I);
2233
2234   unsigned Size;
2235   switch (I.getArgType()->getPrimitiveID()) {
2236   default:
2237     std::cerr << I;
2238     assert(0 && "Error: bad type for va_next instruction!");
2239     return;
2240   case Type::PointerTyID:
2241   case Type::UIntTyID:
2242   case Type::IntTyID:
2243     Size = 4;
2244     break;
2245   case Type::ULongTyID:
2246   case Type::LongTyID:
2247   case Type::DoubleTyID:
2248     Size = 8;
2249     break;
2250   }
2251
2252   // Increment the VAList pointer...
2253   BuildMI(BB, X86::ADDri32, 2, DestReg).addReg(VAList).addZImm(Size);
2254 }
2255
2256 void ISel::visitVAArgInst(VAArgInst &I) {
2257   unsigned VAList = getReg(I.getOperand(0));
2258   unsigned DestReg = getReg(I);
2259
2260   switch (I.getType()->getPrimitiveID()) {
2261   default:
2262     std::cerr << I;
2263     assert(0 && "Error: bad type for va_next instruction!");
2264     return;
2265   case Type::PointerTyID:
2266   case Type::UIntTyID:
2267   case Type::IntTyID:
2268     addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), VAList);
2269     break;
2270   case Type::ULongTyID:
2271   case Type::LongTyID:
2272     addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), VAList);
2273     addRegOffset(BuildMI(BB, X86::MOVrm32, 4, DestReg+1), VAList, 4);
2274     break;
2275   case Type::DoubleTyID:
2276     addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
2277     break;
2278   }
2279 }
2280
2281
2282 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2283   unsigned outputReg = getReg(I);
2284   emitGEPOperation(BB, BB->end(), I.getOperand(0),
2285                    I.op_begin()+1, I.op_end(), outputReg);
2286 }
2287
2288 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2289                             MachineBasicBlock::iterator IP,
2290                             Value *Src, User::op_iterator IdxBegin,
2291                             User::op_iterator IdxEnd, unsigned TargetReg) {
2292   const TargetData &TD = TM.getTargetData();
2293
2294   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2295     Src = CPR->getValue();
2296
2297   std::vector<Value*> GEPOps;
2298   GEPOps.resize(IdxEnd-IdxBegin+1);
2299   GEPOps[0] = Src;
2300   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2301   
2302   std::vector<const Type*> GEPTypes;
2303   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2304                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2305
2306   // Keep emitting instructions until we consume the entire GEP instruction.
2307   while (!GEPOps.empty()) {
2308     unsigned OldSize = GEPOps.size();
2309     
2310     if (GEPTypes.empty()) {
2311       // The getGEPIndex operation didn't want to build an LEA.  Check to see if
2312       // all operands are consumed but the base pointer.  If so, just load it
2313       // into the register.
2314       if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2315         BMI(MBB, IP, X86::MOVri32, 1, TargetReg).addGlobalAddress(GV);
2316       } else {
2317         unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2318         BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2319       }
2320       break;                // we are now done
2321     } else if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2322       // It's a struct access.  CUI is the index into the structure,
2323       // which names the field. This index must have unsigned type.
2324       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2325       GEPOps.pop_back();        // Consume a GEP operand
2326       GEPTypes.pop_back();
2327
2328       // Use the TargetData structure to pick out what the layout of the
2329       // structure is in memory.  Since the structure index must be constant, we
2330       // can get its value and use it to find the right byte offset from the
2331       // StructLayout class's list of structure member offsets.
2332       unsigned idxValue = CUI->getValue();
2333       unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
2334       if (FieldOff) {
2335         unsigned Reg = makeAnotherReg(Type::UIntTy);
2336         // Emit an ADD to add FieldOff to the basePtr.
2337         BMI(MBB, IP, X86::ADDri32, 2, TargetReg).addReg(Reg).addZImm(FieldOff);
2338         --IP;            // Insert the next instruction before this one.
2339         TargetReg = Reg; // Codegen the rest of the GEP into this
2340       }
2341       
2342     } else {
2343       // It's an array or pointer access: [ArraySize x ElementType].
2344       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2345       Value *idx = GEPOps.back();
2346       GEPOps.pop_back();        // Consume a GEP operand
2347       GEPTypes.pop_back();
2348
2349       // idx is the index into the array.  Unlike with structure
2350       // indices, we may not know its actual value at code-generation
2351       // time.
2352       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2353
2354       // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2355       // operand on X86.  Handle this case directly now...
2356       if (CastInst *CI = dyn_cast<CastInst>(idx))
2357         if (CI->getOperand(0)->getType() == Type::IntTy ||
2358             CI->getOperand(0)->getType() == Type::UIntTy)
2359           idx = CI->getOperand(0);
2360
2361       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2362       // must find the size of the pointed-to type (Not coincidentally, the next
2363       // type is the type of the elements in the array).
2364       const Type *ElTy = SqTy->getElementType();
2365       unsigned elementSize = TD.getTypeSize(ElTy);
2366
2367       // If idxReg is a constant, we don't need to perform the multiply!
2368       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2369         if (!CSI->isNullValue()) {
2370           unsigned Offset = elementSize*CSI->getValue();
2371           unsigned Reg = makeAnotherReg(Type::UIntTy);
2372           BMI(MBB, IP, X86::ADDri32, 2, TargetReg).addReg(Reg).addZImm(Offset);
2373           --IP;            // Insert the next instruction before this one.
2374           TargetReg = Reg; // Codegen the rest of the GEP into this
2375         }
2376       } else if (elementSize == 1) {
2377         // If the element size is 1, we don't have to multiply, just add
2378         unsigned idxReg = getReg(idx, MBB, IP);
2379         unsigned Reg = makeAnotherReg(Type::UIntTy);
2380         BMI(MBB, IP, X86::ADDrr32, 2, TargetReg).addReg(Reg).addReg(idxReg);
2381         --IP;            // Insert the next instruction before this one.
2382         TargetReg = Reg; // Codegen the rest of the GEP into this
2383       } else {
2384         unsigned idxReg = getReg(idx, MBB, IP);
2385         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2386
2387         // Make sure we can back the iterator up to point to the first
2388         // instruction emitted.
2389         MachineBasicBlock::iterator BeforeIt = IP;
2390         if (IP == MBB->begin())
2391           BeforeIt = MBB->end();
2392         else
2393           --BeforeIt;
2394         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2395
2396         // Emit an ADD to add OffsetReg to the basePtr.
2397         unsigned Reg = makeAnotherReg(Type::UIntTy);
2398         BMI(MBB, IP, X86::ADDrr32, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2399
2400         // Step to the first instruction of the multiply.
2401         if (BeforeIt == MBB->end())
2402           IP = MBB->begin();
2403         else
2404           IP = ++BeforeIt;
2405
2406         TargetReg = Reg; // Codegen the rest of the GEP into this
2407       }
2408     }
2409   }
2410 }
2411
2412
2413 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2414 /// frame manager, otherwise do it the hard way.
2415 ///
2416 void ISel::visitAllocaInst(AllocaInst &I) {
2417   // Find the data size of the alloca inst's getAllocatedType.
2418   const Type *Ty = I.getAllocatedType();
2419   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2420
2421   // If this is a fixed size alloca in the entry block for the function,
2422   // statically stack allocate the space.
2423   //
2424   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2425     if (I.getParent() == I.getParent()->getParent()->begin()) {
2426       TySize *= CUI->getValue();   // Get total allocated size...
2427       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2428       
2429       // Create a new stack object using the frame manager...
2430       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2431       addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
2432       return;
2433     }
2434   }
2435   
2436   // Create a register to hold the temporary result of multiplying the type size
2437   // constant by the variable amount.
2438   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2439   unsigned SrcReg1 = getReg(I.getArraySize());
2440   
2441   // TotalSizeReg = mul <numelements>, <TypeSize>
2442   MachineBasicBlock::iterator MBBI = BB->end();
2443   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2444
2445   // AddedSize = add <TotalSizeReg>, 15
2446   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2447   BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
2448
2449   // AlignedSize = and <AddedSize>, ~15
2450   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2451   BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
2452   
2453   // Subtract size from stack pointer, thereby allocating some space.
2454   BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2455
2456   // Put a pointer to the space into the result register, by copying
2457   // the stack pointer.
2458   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
2459
2460   // Inform the Frame Information that we have just allocated a variable-sized
2461   // object.
2462   F->getFrameInfo()->CreateVariableSizedObject();
2463 }
2464
2465 /// visitMallocInst - Malloc instructions are code generated into direct calls
2466 /// to the library malloc.
2467 ///
2468 void ISel::visitMallocInst(MallocInst &I) {
2469   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2470   unsigned Arg;
2471
2472   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2473     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2474   } else {
2475     Arg = makeAnotherReg(Type::UIntTy);
2476     unsigned Op0Reg = getReg(I.getOperand(0));
2477     MachineBasicBlock::iterator MBBI = BB->end();
2478     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2479   }
2480
2481   std::vector<ValueRecord> Args;
2482   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2483   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2484                                   1).addExternalSymbol("malloc", true);
2485   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2486 }
2487
2488
2489 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2490 /// function.
2491 ///
2492 void ISel::visitFreeInst(FreeInst &I) {
2493   std::vector<ValueRecord> Args;
2494   Args.push_back(ValueRecord(I.getOperand(0)));
2495   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2496                                   1).addExternalSymbol("free", true);
2497   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2498 }
2499    
2500 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2501 /// into a machine code representation is a very simple peep-hole fashion.  The
2502 /// generated code sucks but the implementation is nice and simple.
2503 ///
2504 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2505   return new ISel(TM);
2506 }