Consider 64-bit registers to be FP as well.
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- X86ISelSimple.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/Pass.h"
22 #include "llvm/CodeGen/IntrinsicLowering.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/ADT/Statistic.h"
32 using namespace llvm;
33
34 namespace {
35   Statistic<>
36   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
37
38   /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
39   /// Representation.
40   ///
41   enum TypeClass {
42     cByte, cShort, cInt, cFP, cLong
43   };
44 }
45
46 /// getClass - Turn a primitive type into a "class" number which is based on the
47 /// size of the type, and whether or not it is floating point.
48 ///
49 static inline TypeClass getClass(const Type *Ty) {
50   switch (Ty->getTypeID()) {
51   case Type::SByteTyID:
52   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
53   case Type::ShortTyID:
54   case Type::UShortTyID:  return cShort;     // Short operands are class #1
55   case Type::IntTyID:
56   case Type::UIntTyID:
57   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
58
59   case Type::FloatTyID:
60   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
61
62   case Type::LongTyID:
63   case Type::ULongTyID:   return cLong;      // Longs are class #4
64   default:
65     assert(0 && "Invalid type to getClass!");
66     return cByte;  // not reached
67   }
68 }
69
70 // getClassB - Just like getClass, but treat boolean values as bytes.
71 static inline TypeClass getClassB(const Type *Ty) {
72   if (Ty == Type::BoolTy) return cByte;
73   return getClass(Ty);
74 }
75
76 namespace {
77   struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
78     TargetMachine &TM;
79     MachineFunction *F;                 // The function we are compiling into
80     MachineBasicBlock *BB;              // The current MBB we are compiling
81     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
82     int ReturnAddressIndex;             // FrameIndex for the return address
83
84     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
85
86     // MBBMap - Mapping between LLVM BB -> Machine BB
87     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
89     // AllocaMap - Mapping from fixed sized alloca instructions to the
90     // FrameIndex for the alloca.
91     std::map<AllocaInst*, unsigned> AllocaMap;
92
93     X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
94
95     /// runOnFunction - Top level implementation of instruction selection for
96     /// the entire function.
97     ///
98     bool runOnFunction(Function &Fn) {
99       // First pass over the function, lower any unknown intrinsic functions
100       // with the IntrinsicLowering class.
101       LowerUnknownIntrinsicFunctionCalls(Fn);
102
103       F = &MachineFunction::construct(&Fn, TM);
104
105       // Create all of the machine basic blocks for the function...
106       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
107         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
108
109       BB = &F->front();
110
111       // Set up a frame object for the return address.  This is used by the
112       // llvm.returnaddress & llvm.frameaddress intrinisics.
113       ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
114
115       // Copy incoming arguments off of the stack...
116       LoadArgumentsToVirtualRegs(Fn);
117
118       // Instruction select everything except PHI nodes
119       visit(Fn);
120
121       // Select the PHI nodes
122       SelectPHINodes();
123
124       // Insert the FP_REG_KILL instructions into blocks that need them.
125       InsertFPRegKills();
126
127       RegMap.clear();
128       MBBMap.clear();
129       AllocaMap.clear();
130       F = 0;
131       // We always build a machine code representation for the function
132       return true;
133     }
134
135     virtual const char *getPassName() const {
136       return "X86 Simple Instruction Selection";
137     }
138
139     /// visitBasicBlock - This method is called when we are visiting a new basic
140     /// block.  This simply creates a new MachineBasicBlock to emit code into
141     /// and adds it to the current MachineFunction.  Subsequent visit* for
142     /// instructions will be invoked for all instructions in the basic block.
143     ///
144     void visitBasicBlock(BasicBlock &LLVM_BB) {
145       BB = MBBMap[&LLVM_BB];
146     }
147
148     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
149     /// function, lowering any calls to unknown intrinsic functions into the
150     /// equivalent LLVM code.
151     ///
152     void LowerUnknownIntrinsicFunctionCalls(Function &F);
153
154     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
155     /// from the stack into virtual registers.
156     ///
157     void LoadArgumentsToVirtualRegs(Function &F);
158
159     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
160     /// because we have to generate our sources into the source basic blocks,
161     /// not the current one.
162     ///
163     void SelectPHINodes();
164
165     /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
166     /// that need them.  This only occurs due to the floating point stackifier
167     /// not being aggressive enough to handle arbitrary global stackification.
168     ///
169     void InsertFPRegKills();
170
171     // Visitation methods for various instructions.  These methods simply emit
172     // fixed X86 code for each instruction.
173     //
174
175     // Control flow operators
176     void visitReturnInst(ReturnInst &RI);
177     void visitBranchInst(BranchInst &BI);
178     void visitUnreachableInst(UnreachableInst &UI) {}
179
180     struct ValueRecord {
181       Value *Val;
182       unsigned Reg;
183       const Type *Ty;
184       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
185       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
186     };
187     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
188                 const std::vector<ValueRecord> &Args);
189     void visitCallInst(CallInst &I);
190     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
191
192     // Arithmetic operators
193     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
194     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
195     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
196     void visitMul(BinaryOperator &B);
197
198     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
199     void visitRem(BinaryOperator &B) { visitDivRem(B); }
200     void visitDivRem(BinaryOperator &B);
201
202     // Bitwise operators
203     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
204     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
205     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
206
207     // Comparison operators...
208     void visitSetCondInst(SetCondInst &I);
209     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
210                             MachineBasicBlock *MBB,
211                             MachineBasicBlock::iterator MBBI);
212     void visitSelectInst(SelectInst &SI);
213     
214     
215     // Memory Instructions
216     void visitLoadInst(LoadInst &I);
217     void visitStoreInst(StoreInst &I);
218     void visitGetElementPtrInst(GetElementPtrInst &I);
219     void visitAllocaInst(AllocaInst &I);
220     void visitMallocInst(MallocInst &I);
221     void visitFreeInst(FreeInst &I);
222     
223     // Other operators
224     void visitShiftInst(ShiftInst &I);
225     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
226     void visitCastInst(CastInst &I);
227     void visitVANextInst(VANextInst &I);
228     void visitVAArgInst(VAArgInst &I);
229
230     void visitInstruction(Instruction &I) {
231       std::cerr << "Cannot instruction select: " << I;
232       abort();
233     }
234
235     /// promote32 - Make a value 32-bits wide, and put it somewhere.
236     ///
237     void promote32(unsigned targetReg, const ValueRecord &VR);
238
239     /// getAddressingMode - Get the addressing mode to use to address the
240     /// specified value.  The returned value should be used with addFullAddress.
241     void getAddressingMode(Value *Addr, X86AddressMode &AM);
242
243
244     /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
245     /// expressions.
246     void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
247                      std::vector<Value*> &GEPOps,
248                      std::vector<const Type*> &GEPTypes,
249                      X86AddressMode &AM);
250
251     /// isGEPFoldable - Return true if the specified GEP can be completely
252     /// folded into the addressing mode of a load/store or lea instruction.
253     bool isGEPFoldable(MachineBasicBlock *MBB,
254                        Value *Src, User::op_iterator IdxBegin,
255                        User::op_iterator IdxEnd, X86AddressMode &AM);
256
257     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
258     /// constant expression GEP support.
259     ///
260     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
261                           Value *Src, User::op_iterator IdxBegin,
262                           User::op_iterator IdxEnd, unsigned TargetReg);
263
264     /// emitCastOperation - Common code shared between visitCastInst and
265     /// constant expression cast support.
266     ///
267     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
268                            Value *Src, const Type *DestTy, unsigned TargetReg);
269
270     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
271     /// and constant expression support.
272     ///
273     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
274                                    MachineBasicBlock::iterator IP,
275                                    Value *Op0, Value *Op1,
276                                    unsigned OperatorClass, unsigned TargetReg);
277
278     /// emitBinaryFPOperation - This method handles emission of floating point
279     /// Add (0), Sub (1), Mul (2), and Div (3) operations.
280     void emitBinaryFPOperation(MachineBasicBlock *BB,
281                                MachineBasicBlock::iterator IP,
282                                Value *Op0, Value *Op1,
283                                unsigned OperatorClass, unsigned TargetReg);
284
285     void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
286                       Value *Op0, Value *Op1, unsigned TargetReg);
287
288     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
289                     unsigned DestReg, const Type *DestTy,
290                     unsigned Op0Reg, unsigned Op1Reg);
291     void doMultiplyConst(MachineBasicBlock *MBB, 
292                          MachineBasicBlock::iterator MBBI,
293                          unsigned DestReg, const Type *DestTy,
294                          unsigned Op0Reg, unsigned Op1Val);
295
296     void emitDivRemOperation(MachineBasicBlock *BB,
297                              MachineBasicBlock::iterator IP,
298                              Value *Op0, Value *Op1, bool isDiv,
299                              unsigned TargetReg);
300
301     /// emitSetCCOperation - Common code shared between visitSetCondInst and
302     /// constant expression support.
303     ///
304     void emitSetCCOperation(MachineBasicBlock *BB,
305                             MachineBasicBlock::iterator IP,
306                             Value *Op0, Value *Op1, unsigned Opcode,
307                             unsigned TargetReg);
308
309     /// emitShiftOperation - Common code shared between visitShiftInst and
310     /// constant expression support.
311     ///
312     void emitShiftOperation(MachineBasicBlock *MBB,
313                             MachineBasicBlock::iterator IP,
314                             Value *Op, Value *ShiftAmount, bool isLeftShift,
315                             const Type *ResultTy, unsigned DestReg);
316
317     // Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
318     // constant.
319     void doSHLDConst(MachineBasicBlock *MBB, 
320                      MachineBasicBlock::iterator MBBI,
321                      unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
322                      unsigned Op1Val);
323       
324     /// emitSelectOperation - Common code shared between visitSelectInst and the
325     /// constant expression support.
326     void emitSelectOperation(MachineBasicBlock *MBB,
327                              MachineBasicBlock::iterator IP,
328                              Value *Cond, Value *TrueVal, Value *FalseVal,
329                              unsigned DestReg);
330
331     /// copyConstantToRegister - Output the instructions required to put the
332     /// specified constant into the specified register.
333     ///
334     void copyConstantToRegister(MachineBasicBlock *MBB,
335                                 MachineBasicBlock::iterator MBBI,
336                                 Constant *C, unsigned Reg);
337
338     void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
339                    unsigned LHS, unsigned RHS);
340
341     /// makeAnotherReg - This method returns the next register number we haven't
342     /// yet used.
343     ///
344     /// Long values are handled somewhat specially.  They are always allocated
345     /// as pairs of 32 bit integer values.  The register number returned is the
346     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
347     /// of the long value.
348     ///
349     unsigned makeAnotherReg(const Type *Ty) {
350       assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
351              "Current target doesn't have X86 reg info??");
352       const X86RegisterInfo *MRI =
353         static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
354       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
355         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
356         // Create the lower part
357         F->getSSARegMap()->createVirtualRegister(RC);
358         // Create the upper part.
359         return F->getSSARegMap()->createVirtualRegister(RC)-1;
360       }
361
362       // Add the mapping of regnumber => reg class to MachineFunction
363       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
364       return F->getSSARegMap()->createVirtualRegister(RC);
365     }
366
367     /// getReg - This method turns an LLVM value into a register number.
368     ///
369     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
370     unsigned getReg(Value *V) {
371       // Just append to the end of the current bb.
372       MachineBasicBlock::iterator It = BB->end();
373       return getReg(V, BB, It);
374     }
375     unsigned getReg(Value *V, MachineBasicBlock *MBB,
376                     MachineBasicBlock::iterator IPt);
377
378     /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
379     /// that is to be statically allocated with the initial stack frame
380     /// adjustment.
381     unsigned getFixedSizedAllocaFI(AllocaInst *AI);
382   };
383 }
384
385 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
386 /// instruction in the entry block, return it.  Otherwise, return a null
387 /// pointer.
388 static AllocaInst *dyn_castFixedAlloca(Value *V) {
389   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
390     BasicBlock *BB = AI->getParent();
391     if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
392       return AI;
393   }
394   return 0;
395 }
396
397 /// getReg - This method turns an LLVM value into a register number.
398 ///
399 unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
400                          MachineBasicBlock::iterator IPt) {
401   // If this operand is a constant, emit the code to copy the constant into
402   // the register here...
403   if (Constant *C = dyn_cast<Constant>(V)) {
404     unsigned Reg = makeAnotherReg(V->getType());
405     copyConstantToRegister(MBB, IPt, C, Reg);
406     return Reg;
407   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
408     // Do not emit noop casts at all, unless it's a double -> float cast.
409     if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
410         (CI->getType() != Type::FloatTy || 
411          CI->getOperand(0)->getType() != Type::DoubleTy))
412       return getReg(CI->getOperand(0), MBB, IPt);
413   } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
414     // If the alloca address couldn't be folded into the instruction addressing,
415     // emit an explicit LEA as appropriate.
416     unsigned Reg = makeAnotherReg(V->getType());
417     unsigned FI = getFixedSizedAllocaFI(AI);
418     addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
419     return Reg;
420   }
421
422   unsigned &Reg = RegMap[V];
423   if (Reg == 0) {
424     Reg = makeAnotherReg(V->getType());
425     RegMap[V] = Reg;
426   }
427
428   return Reg;
429 }
430
431 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
432 /// that is to be statically allocated with the initial stack frame
433 /// adjustment.
434 unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
435   // Already computed this?
436   std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
437   if (I != AllocaMap.end() && I->first == AI) return I->second;
438
439   const Type *Ty = AI->getAllocatedType();
440   ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
441   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
442   TySize *= CUI->getValue();   // Get total allocated size...
443   unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
444       
445   // Create a new stack object using the frame manager...
446   int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
447   AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
448   return FrameIdx;
449 }
450
451
452 /// copyConstantToRegister - Output the instructions required to put the
453 /// specified constant into the specified register.
454 ///
455 void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
456                                      MachineBasicBlock::iterator IP,
457                                      Constant *C, unsigned R) {
458   if (isa<UndefValue>(C)) {
459     switch (getClassB(C->getType())) {
460     case cFP:
461       // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
462       BuildMI(*MBB, IP, X86::FLD0, 0, R);
463       return;
464     case cLong:
465       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R+1);
466       // FALL THROUGH
467     default:
468       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R);
469       return;
470     }
471   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
472     unsigned Class = 0;
473     switch (CE->getOpcode()) {
474     case Instruction::GetElementPtr:
475       emitGEPOperation(MBB, IP, CE->getOperand(0),
476                        CE->op_begin()+1, CE->op_end(), R);
477       return;
478     case Instruction::Cast:
479       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
480       return;
481
482     case Instruction::Xor: ++Class; // FALL THROUGH
483     case Instruction::Or:  ++Class; // FALL THROUGH
484     case Instruction::And: ++Class; // FALL THROUGH
485     case Instruction::Sub: ++Class; // FALL THROUGH
486     case Instruction::Add:
487       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
488                                 Class, R);
489       return;
490
491     case Instruction::Mul:
492       emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
493       return;
494
495     case Instruction::Div:
496     case Instruction::Rem:
497       emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
498                           CE->getOpcode() == Instruction::Div, R);
499       return;
500
501     case Instruction::SetNE:
502     case Instruction::SetEQ:
503     case Instruction::SetLT:
504     case Instruction::SetGT:
505     case Instruction::SetLE:
506     case Instruction::SetGE:
507       emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
508                          CE->getOpcode(), R);
509       return;
510
511     case Instruction::Shl:
512     case Instruction::Shr:
513       emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
514                          CE->getOpcode() == Instruction::Shl, CE->getType(), R);
515       return;
516
517     case Instruction::Select:
518       emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
519                           CE->getOperand(2), R);
520       return;
521
522     default:
523       std::cerr << "Offending expr: " << *C << "\n";
524       assert(0 && "Constant expression not yet handled!\n");
525     }
526   }
527
528   if (C->getType()->isIntegral()) {
529     unsigned Class = getClassB(C->getType());
530
531     if (Class == cLong) {
532       // Copy the value into the register pair.
533       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
534       BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
535       BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
536       return;
537     }
538
539     assert(Class <= cInt && "Type not handled yet!");
540
541     static const unsigned IntegralOpcodeTab[] = {
542       X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
543     };
544
545     if (C->getType() == Type::BoolTy) {
546       BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
547     } else {
548       ConstantInt *CI = cast<ConstantInt>(C);
549       BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
550     }
551   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
552     if (CFP->isExactlyValue(+0.0))
553       BuildMI(*MBB, IP, X86::FLD0, 0, R);
554     else if (CFP->isExactlyValue(+1.0))
555       BuildMI(*MBB, IP, X86::FLD1, 0, R);
556     else {
557       // Otherwise we need to spill the constant to memory...
558       MachineConstantPool *CP = F->getConstantPool();
559       unsigned CPI = CP->getConstantPoolIndex(CFP);
560       const Type *Ty = CFP->getType();
561
562       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
563       unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
564       addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
565     }
566
567   } else if (isa<ConstantPointerNull>(C)) {
568     // Copy zero (null pointer) to the register.
569     BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
570   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
571     BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
572   } else {
573     std::cerr << "Offending constant: " << *C << "\n";
574     assert(0 && "Type not handled yet!");
575   }
576 }
577
578 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
579 /// the stack into virtual registers.
580 ///
581 void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
582   // Emit instructions to load the arguments...  On entry to a function on the
583   // X86, the stack frame looks like this:
584   //
585   // [ESP] -- return address
586   // [ESP + 4] -- first argument (leftmost lexically)
587   // [ESP + 8] -- second argument, if first argument is four bytes in size
588   //    ... 
589   //
590   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
591   MachineFrameInfo *MFI = F->getFrameInfo();
592
593   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
594     bool ArgLive = !I->use_empty();
595     unsigned Reg = ArgLive ? getReg(*I) : 0;
596     int FI;          // Frame object index
597
598     switch (getClassB(I->getType())) {
599     case cByte:
600       if (ArgLive) {
601         FI = MFI->CreateFixedObject(1, ArgOffset);
602         addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
603       }
604       break;
605     case cShort:
606       if (ArgLive) {
607         FI = MFI->CreateFixedObject(2, ArgOffset);
608         addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
609       }
610       break;
611     case cInt:
612       if (ArgLive) {
613         FI = MFI->CreateFixedObject(4, ArgOffset);
614         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
615       }
616       break;
617     case cLong:
618       if (ArgLive) {
619         FI = MFI->CreateFixedObject(8, ArgOffset);
620         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
621         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
622       }
623       ArgOffset += 4;   // longs require 4 additional bytes
624       break;
625     case cFP:
626       if (ArgLive) {
627         unsigned Opcode;
628         if (I->getType() == Type::FloatTy) {
629           Opcode = X86::FLD32m;
630           FI = MFI->CreateFixedObject(4, ArgOffset);
631         } else {
632           Opcode = X86::FLD64m;
633           FI = MFI->CreateFixedObject(8, ArgOffset);
634         }
635         addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
636       }
637       if (I->getType() == Type::DoubleTy)
638         ArgOffset += 4;   // doubles require 4 additional bytes
639       break;
640     default:
641       assert(0 && "Unhandled argument type!");
642     }
643     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
644   }
645
646   // If the function takes variable number of arguments, add a frame offset for
647   // the start of the first vararg value... this is used to expand
648   // llvm.va_start.
649   if (Fn.getFunctionType()->isVarArg())
650     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
651 }
652
653
654 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
655 /// because we have to generate our sources into the source basic blocks, not
656 /// the current one.
657 ///
658 void X86ISel::SelectPHINodes() {
659   const TargetInstrInfo &TII = *TM.getInstrInfo();
660   const Function &LF = *F->getFunction();  // The LLVM function...
661   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
662     const BasicBlock *BB = I;
663     MachineBasicBlock &MBB = *MBBMap[I];
664
665     // Loop over all of the PHI nodes in the LLVM basic block...
666     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
667     for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
668       PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
669
670       // Create a new machine instr PHI node, and insert it.
671       unsigned PHIReg = getReg(*PN);
672       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
673                                     X86::PHI, PN->getNumOperands(), PHIReg);
674
675       MachineInstr *LongPhiMI = 0;
676       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
677         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
678                             X86::PHI, PN->getNumOperands(), PHIReg+1);
679
680       // PHIValues - Map of blocks to incoming virtual registers.  We use this
681       // so that we only initialize one incoming value for a particular block,
682       // even if the block has multiple entries in the PHI node.
683       //
684       std::map<MachineBasicBlock*, unsigned> PHIValues;
685
686       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
687         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
688         unsigned ValReg;
689         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
690           PHIValues.lower_bound(PredMBB);
691
692         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
693           // We already inserted an initialization of the register for this
694           // predecessor.  Recycle it.
695           ValReg = EntryIt->second;
696
697         } else {        
698           // Get the incoming value into a virtual register.
699           //
700           Value *Val = PN->getIncomingValue(i);
701
702           // If this is a constant or GlobalValue, we may have to insert code
703           // into the basic block to compute it into a virtual register.
704           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
705             // Simple constants get emitted at the end of the basic block,
706             // before any terminator instructions.  We "know" that the code to
707             // move a constant into a register will never clobber any flags.
708             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
709           } else {
710             // Because we don't want to clobber any values which might be in
711             // physical registers with the computation of this constant (which
712             // might be arbitrarily complex if it is a constant expression),
713             // just insert the computation at the top of the basic block.
714             MachineBasicBlock::iterator PI = PredMBB->begin();
715             
716             // Skip over any PHI nodes though!
717             while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
718               ++PI;
719             
720             ValReg = getReg(Val, PredMBB, PI);
721           }
722
723           // Remember that we inserted a value for this PHI for this predecessor
724           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
725         }
726
727         PhiMI->addRegOperand(ValReg);
728         PhiMI->addMachineBasicBlockOperand(PredMBB);
729         if (LongPhiMI) {
730           LongPhiMI->addRegOperand(ValReg+1);
731           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
732         }
733       }
734
735       // Now that we emitted all of the incoming values for the PHI node, make
736       // sure to reposition the InsertPoint after the PHI that we just added.
737       // This is needed because we might have inserted a constant into this
738       // block, right after the PHI's which is before the old insert point!
739       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
740       ++PHIInsertPoint;
741     }
742   }
743 }
744
745 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
746 /// compensation code on critical edges.  As such, it requires that we kill all
747 /// FP registers on the exit from any blocks that either ARE critical edges, or
748 /// branch to a block that has incoming critical edges.
749 ///
750 /// Note that this kill instruction will eventually be eliminated when
751 /// restrictions in the stackifier are relaxed.
752 ///
753 static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
754 #if 0
755   const BasicBlock *BB = MBB->getBasicBlock ();
756   for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
757     const BasicBlock *Succ = *SI;
758     pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
759     ++PI;  // Block have at least one predecessory
760     if (PI != PE) {             // If it has exactly one, this isn't crit edge
761       // If this block has more than one predecessor, check all of the
762       // predecessors to see if they have multiple successors.  If so, then the
763       // block we are analyzing needs an FPRegKill.
764       for (PI = pred_begin(Succ); PI != PE; ++PI) {
765         const BasicBlock *Pred = *PI;
766         succ_const_iterator SI2 = succ_begin(Pred);
767         ++SI2;  // There must be at least one successor of this block.
768         if (SI2 != succ_end(Pred))
769           return true;   // Yes, we must insert the kill on this edge.
770       }
771     }
772   }
773   // If we got this far, there is no need to insert the kill instruction.
774   return false;
775 #else
776   return true;
777 #endif
778 }
779
780 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
781 // need them.  This only occurs due to the floating point stackifier not being
782 // aggressive enough to handle arbitrary global stackification.
783 //
784 // Currently we insert an FP_REG_KILL instruction into each block that uses or
785 // defines a floating point virtual register.
786 //
787 // When the global register allocators (like linear scan) finally update live
788 // variable analysis, we can keep floating point values in registers across
789 // portions of the CFG that do not involve critical edges.  This will be a big
790 // win, but we are waiting on the global allocators before we can do this.
791 //
792 // With a bit of work, the floating point stackifier pass can be enhanced to
793 // break critical edges as needed (to make a place to put compensation code),
794 // but this will require some infrastructure improvements as well.
795 //
796 void X86ISel::InsertFPRegKills() {
797   SSARegMap &RegMap = *F->getSSARegMap();
798
799   for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
800     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
801       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
802       MachineOperand& MO = I->getOperand(i);
803         if (MO.isRegister() && MO.getReg()) {
804           unsigned Reg = MO.getReg();
805           if (MRegisterInfo::isVirtualRegister(Reg))
806             if (RegMap.getRegClass(Reg)->getSize() == 10)
807               goto UsesFPReg;
808         }
809       }
810     // If we haven't found an FP register use or def in this basic block, check
811     // to see if any of our successors has an FP PHI node, which will cause a
812     // copy to be inserted into this block.
813     for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
814          SE = BB->succ_end(); SI != SE; ++SI) {
815       MachineBasicBlock *SBB = *SI;
816       for (MachineBasicBlock::iterator I = SBB->begin();
817            I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
818         const TargetRegisterClass *RC =
819           RegMap.getRegClass(I->getOperand(0).getReg());
820         if (RC->getSize() == 10 || RC->getSize() == 8)
821           goto UsesFPReg;
822       }
823     }
824     continue;
825   UsesFPReg:
826     // Okay, this block uses an FP register.  If the block has successors (ie,
827     // it's not an unwind/return), insert the FP_REG_KILL instruction.
828     if (BB->succ_size () && RequiresFPRegKill(BB)) {
829       BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
830       ++NumFPKill;
831     }
832   }
833 }
834
835
836 void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
837   AM.BaseType = X86AddressMode::RegBase;
838   AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
839   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
840     if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
841                        AM))
842       return;
843   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
844     if (CE->getOpcode() == Instruction::GetElementPtr)
845       if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
846                         AM))
847         return;
848   } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
849     AM.BaseType = X86AddressMode::FrameIndexBase;
850     AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
851     return;
852   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
853     AM.GV = GV;
854     return;
855   }
856
857   // If it's not foldable, reset addr mode.
858   AM.BaseType = X86AddressMode::RegBase;
859   AM.Base.Reg = getReg(Addr);
860   AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
861 }
862
863 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
864 // it into the conditional branch or select instruction which is the only user
865 // of the cc instruction.  This is the case if the conditional branch is the
866 // only user of the setcc.  We also don't handle long arguments below, so we 
867 // reject them here as well.
868 //
869 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
870   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
871     if (SCI->hasOneUse()) {
872       Instruction *User = cast<Instruction>(SCI->use_back());
873       if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
874           (getClassB(SCI->getOperand(0)->getType()) != cLong ||
875            SCI->getOpcode() == Instruction::SetEQ ||
876            SCI->getOpcode() == Instruction::SetNE) &&
877           (isa<BranchInst>(User) || User->getOperand(0) == V))
878         return SCI;
879     }
880   return 0;
881 }
882
883 // Return a fixed numbering for setcc instructions which does not depend on the
884 // order of the opcodes.
885 //
886 static unsigned getSetCCNumber(unsigned Opcode) {
887   switch(Opcode) {
888   default: assert(0 && "Unknown setcc instruction!");
889   case Instruction::SetEQ: return 0;
890   case Instruction::SetNE: return 1;
891   case Instruction::SetLT: return 2;
892   case Instruction::SetGE: return 3;
893   case Instruction::SetGT: return 4;
894   case Instruction::SetLE: return 5;
895   }
896 }
897
898 // LLVM  -> X86 signed  X86 unsigned
899 // -----    ----------  ------------
900 // seteq -> sete        sete
901 // setne -> setne       setne
902 // setlt -> setl        setb
903 // setge -> setge       setae
904 // setgt -> setg        seta
905 // setle -> setle       setbe
906 // ----
907 //          sets                       // Used by comparison with 0 optimization
908 //          setns
909 static const unsigned SetCCOpcodeTab[2][8] = {
910   { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
911     0, 0 },
912   { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
913     X86::SETSr, X86::SETNSr },
914 };
915
916 /// emitUCOMr - In the future when we support processors before the P6, this
917 /// wraps the logic for emitting an FUCOMr vs FUCOMIr.
918 void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
919                         unsigned LHS, unsigned RHS) {
920   if (0) { // for processors prior to the P6
921     BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
922     BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
923     BuildMI(*MBB, IP, X86::SAHF, 1);
924   } else {
925     BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
926   }
927 }
928
929 // EmitComparison - This function emits a comparison of the two operands,
930 // returning the extended setcc code to use.
931 unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
932                                  MachineBasicBlock *MBB,
933                                  MachineBasicBlock::iterator IP) {
934   // The arguments are already supposed to be of the same type.
935   const Type *CompTy = Op0->getType();
936   unsigned Class = getClassB(CompTy);
937
938   // Special case handling of: cmp R, i
939   if (isa<ConstantPointerNull>(Op1)) {
940     unsigned Op0r = getReg(Op0, MBB, IP);
941     if (OpNum < 2)    // seteq/setne -> test
942       BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
943     else
944       BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
945     return OpNum;
946
947   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
948     if (Class == cByte || Class == cShort || Class == cInt) {
949       unsigned Op1v = CI->getRawValue();
950
951       // Mask off any upper bits of the constant, if there are any...
952       Op1v &= (1ULL << (8 << Class)) - 1;
953
954       // If this is a comparison against zero, emit more efficient code.  We
955       // can't handle unsigned comparisons against zero unless they are == or
956       // !=.  These should have been strength reduced already anyway.
957       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
958
959         // If this is a comparison against zero and the LHS is an and of a
960         // register with a constant, use the test to do the and.
961         if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
962           if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
963               isa<ConstantInt>(Op0I->getOperand(1))) {
964             static const unsigned TESTTab[] = {
965               X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
966             };
967             
968             // Emit test X, i
969             unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
970             unsigned Imm =
971               cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
972             BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
973             
974             if (OpNum == 2) return 6;   // Map jl -> js
975             if (OpNum == 3) return 7;   // Map jg -> jns
976             return OpNum;
977           }
978
979         unsigned Op0r = getReg(Op0, MBB, IP);
980         static const unsigned TESTTab[] = {
981           X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
982         };
983         BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
984
985         if (OpNum == 2) return 6;   // Map jl -> js
986         if (OpNum == 3) return 7;   // Map jg -> jns
987         return OpNum;
988       }
989
990       static const unsigned CMPTab[] = {
991         X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
992       };
993
994       unsigned Op0r = getReg(Op0, MBB, IP);
995       BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
996       return OpNum;
997     } else {
998       unsigned Op0r = getReg(Op0, MBB, IP);
999       assert(Class == cLong && "Unknown integer class!");
1000       unsigned LowCst = CI->getRawValue();
1001       unsigned HiCst = CI->getRawValue() >> 32;
1002       if (OpNum < 2) {    // seteq, setne
1003         unsigned LoTmp = Op0r;
1004         if (LowCst != 0) {
1005           LoTmp = makeAnotherReg(Type::IntTy);
1006           BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
1007         }
1008         unsigned HiTmp = Op0r+1;
1009         if (HiCst != 0) {
1010           HiTmp = makeAnotherReg(Type::IntTy);
1011           BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
1012         }
1013         unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1014         BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1015         return OpNum;
1016       } else {
1017         // Emit a sequence of code which compares the high and low parts once
1018         // each, then uses a conditional move to handle the overflow case.  For
1019         // example, a setlt for long would generate code like this:
1020         //
1021         // AL = lo(op1) < lo(op2)   // Always unsigned comparison
1022         // BL = hi(op1) < hi(op2)   // Signedness depends on operands
1023         // dest = hi(op1) == hi(op2) ? BL : AL;
1024         //
1025
1026         // FIXME: This would be much better if we had hierarchical register
1027         // classes!  Until then, hardcode registers so that we can deal with
1028         // their aliases (because we don't have conditional byte moves).
1029         //
1030         BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
1031         BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1032         BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
1033         BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
1034         BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1035         BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1036         BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1037           .addReg(X86::AX);
1038         // NOTE: visitSetCondInst knows that the value is dumped into the BL
1039         // register at this point for long values...
1040         return OpNum;
1041       }
1042     }
1043   }
1044
1045   unsigned Op0r = getReg(Op0, MBB, IP);
1046
1047   // Special case handling of comparison against +/- 0.0
1048   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
1049     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
1050       BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
1051       BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
1052       BuildMI(*MBB, IP, X86::SAHF, 1);
1053       return OpNum;
1054     }
1055
1056   unsigned Op1r = getReg(Op1, MBB, IP);
1057   switch (Class) {
1058   default: assert(0 && "Unknown type class!");
1059     // Emit: cmp <var1>, <var2> (do the comparison).  We can
1060     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1061     // 32-bit.
1062   case cByte:
1063     BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
1064     break;
1065   case cShort:
1066     BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
1067     break;
1068   case cInt:
1069     BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1070     break;
1071   case cFP:
1072     emitUCOMr(MBB, IP, Op0r, Op1r);
1073     break;
1074
1075   case cLong:
1076     if (OpNum < 2) {    // seteq, setne
1077       unsigned LoTmp = makeAnotherReg(Type::IntTy);
1078       unsigned HiTmp = makeAnotherReg(Type::IntTy);
1079       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1080       BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1081       BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1082       BuildMI(*MBB, IP, X86::OR32rr,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1083       break;  // Allow the sete or setne to be generated from flags set by OR
1084     } else {
1085       // Emit a sequence of code which compares the high and low parts once
1086       // each, then uses a conditional move to handle the overflow case.  For
1087       // example, a setlt for long would generate code like this:
1088       //
1089       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
1090       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
1091       // dest = hi(op1) == hi(op2) ? BL : AL;
1092       //
1093
1094       // FIXME: This would be much better if we had hierarchical register
1095       // classes!  Until then, hardcode registers so that we can deal with their
1096       // aliases (because we don't have conditional byte moves).
1097       //
1098       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1099       BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1100       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
1101       BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1102       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1103       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1104       BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1105                                                    .addReg(X86::AX);
1106       // NOTE: visitSetCondInst knows that the value is dumped into the BL
1107       // register at this point for long values...
1108       return OpNum;
1109     }
1110   }
1111   return OpNum;
1112 }
1113
1114 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1115 /// register, then move it to wherever the result should be. 
1116 ///
1117 void X86ISel::visitSetCondInst(SetCondInst &I) {
1118   if (canFoldSetCCIntoBranchOrSelect(&I))
1119     return;  // Fold this into a branch or select.
1120
1121   unsigned DestReg = getReg(I);
1122   MachineBasicBlock::iterator MII = BB->end();
1123   emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1124                      DestReg);
1125 }
1126
1127 /// emitSetCCOperation - Common code shared between visitSetCondInst and
1128 /// constant expression support.
1129 ///
1130 void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1131                                  MachineBasicBlock::iterator IP,
1132                                  Value *Op0, Value *Op1, unsigned Opcode,
1133                                  unsigned TargetReg) {
1134   unsigned OpNum = getSetCCNumber(Opcode);
1135   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
1136
1137   const Type *CompTy = Op0->getType();
1138   unsigned CompClass = getClassB(CompTy);
1139   bool isSigned = CompTy->isSigned() && CompClass != cFP;
1140
1141   if (CompClass != cLong || OpNum < 2) {
1142     // Handle normal comparisons with a setcc instruction...
1143     BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1144   } else {
1145     // Handle long comparisons by copying the value which is already in BL into
1146     // the register we want...
1147     BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1148   }
1149 }
1150
1151 void X86ISel::visitSelectInst(SelectInst &SI) {
1152   unsigned DestReg = getReg(SI);
1153   MachineBasicBlock::iterator MII = BB->end();
1154   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1155                       SI.getFalseValue(), DestReg);
1156 }
1157  
1158 /// emitSelect - Common code shared between visitSelectInst and the constant
1159 /// expression support.
1160 void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1161                                   MachineBasicBlock::iterator IP,
1162                                   Value *Cond, Value *TrueVal, Value *FalseVal,
1163                                   unsigned DestReg) {
1164   unsigned SelectClass = getClassB(TrueVal->getType());
1165   
1166   // We don't support 8-bit conditional moves.  If we have incoming constants,
1167   // transform them into 16-bit constants to avoid having a run-time conversion.
1168   if (SelectClass == cByte) {
1169     if (Constant *T = dyn_cast<Constant>(TrueVal))
1170       TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1171     if (Constant *F = dyn_cast<Constant>(FalseVal))
1172       FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1173   }
1174
1175   unsigned TrueReg  = getReg(TrueVal, MBB, IP);
1176   unsigned FalseReg = getReg(FalseVal, MBB, IP);
1177   if (TrueReg == FalseReg) {
1178     static const unsigned Opcode[] = {
1179       X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1180     };
1181     BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1182     if (SelectClass == cLong)
1183       BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1184     return;
1185   }
1186
1187   unsigned Opcode;
1188   if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1189     // We successfully folded the setcc into the select instruction.
1190     
1191     unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1192     OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1193                            IP);
1194
1195     const Type *CompTy = SCI->getOperand(0)->getType();
1196     bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1197   
1198     // LLVM  -> X86 signed  X86 unsigned
1199     // -----    ----------  ------------
1200     // seteq -> cmovNE      cmovNE
1201     // setne -> cmovE       cmovE
1202     // setlt -> cmovGE      cmovAE
1203     // setge -> cmovL       cmovB
1204     // setgt -> cmovLE      cmovBE
1205     // setle -> cmovG       cmovA
1206     // ----
1207     //          cmovNS              // Used by comparison with 0 optimization
1208     //          cmovS
1209     
1210     switch (SelectClass) {
1211     default: assert(0 && "Unknown value class!");
1212     case cFP: {
1213       // Annoyingly, we don't have a full set of floating point conditional
1214       // moves.  :(
1215       static const unsigned OpcodeTab[2][8] = {
1216         { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1217           X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1218         { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1219       };
1220       Opcode = OpcodeTab[isSigned][OpNum];
1221
1222       // If opcode == 0, we hit a case that we don't support.  Output a setcc
1223       // and compare the result against zero.
1224       if (Opcode == 0) {
1225         unsigned CompClass = getClassB(CompTy);
1226         unsigned CondReg;
1227         if (CompClass != cLong || OpNum < 2) {
1228           CondReg = makeAnotherReg(Type::BoolTy);
1229           // Handle normal comparisons with a setcc instruction...
1230           BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1231         } else {
1232           // Long comparisons end up in the BL register.
1233           CondReg = X86::BL;
1234         }
1235         
1236         BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1237         Opcode = X86::FCMOVE;
1238       }
1239       break;
1240     }
1241     case cByte:
1242     case cShort: {
1243       static const unsigned OpcodeTab[2][8] = {
1244         { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1245           X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1246         { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1247           X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1248       };
1249       Opcode = OpcodeTab[isSigned][OpNum];
1250       break;
1251     }
1252     case cInt:
1253     case cLong: {
1254       static const unsigned OpcodeTab[2][8] = {
1255         { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1256           X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1257         { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1258           X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1259       };
1260       Opcode = OpcodeTab[isSigned][OpNum];
1261       break;
1262     }
1263     }
1264   } else {
1265     // Get the value being branched on, and use it to set the condition codes.
1266     unsigned CondReg = getReg(Cond, MBB, IP);
1267     BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1268     switch (SelectClass) {
1269     default: assert(0 && "Unknown value class!");
1270     case cFP:    Opcode = X86::FCMOVE; break;
1271     case cByte:
1272     case cShort: Opcode = X86::CMOVE16rr; break;
1273     case cInt:
1274     case cLong:  Opcode = X86::CMOVE32rr; break;
1275     }
1276   }
1277
1278   unsigned RealDestReg = DestReg;
1279
1280
1281   // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves.  Because of
1282   // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1283   // cmove, then truncate the result.
1284   if (SelectClass == cByte) {
1285     DestReg = makeAnotherReg(Type::ShortTy);
1286     if (getClassB(TrueVal->getType()) == cByte) {
1287       // Promote the true value, by storing it into AL, and reading from AX.
1288       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1289       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1290       TrueReg = makeAnotherReg(Type::ShortTy);
1291       BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1292     }
1293     if (getClassB(FalseVal->getType()) == cByte) {
1294       // Promote the true value, by storing it into CL, and reading from CX.
1295       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1296       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1297       FalseReg = makeAnotherReg(Type::ShortTy);
1298       BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1299     }
1300   }
1301
1302   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1303
1304   switch (SelectClass) {
1305   case cByte:
1306     // We did the computation with 16-bit registers.  Truncate back to our
1307     // result by copying into AX then copying out AL.
1308     BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1309     BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1310     break;
1311   case cLong:
1312     // Move the upper half of the value as well.
1313     BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1314     break;
1315   }
1316 }
1317
1318
1319
1320 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1321 /// operand, in the specified target register.
1322 ///
1323 void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1324   bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1325
1326   Value *Val = VR.Val;
1327   const Type *Ty = VR.Ty;
1328   if (Val) {
1329     if (Constant *C = dyn_cast<Constant>(Val)) {
1330       Val = ConstantExpr::getCast(C, Type::IntTy);
1331       Ty = Type::IntTy;
1332     }
1333
1334     // If this is a simple constant, just emit a MOVri directly to avoid the
1335     // copy.
1336     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1337       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1338       BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1339       return;
1340     }
1341   }
1342
1343   // Make sure we have the register number for this value...
1344   unsigned Reg = Val ? getReg(Val) : VR.Reg;
1345
1346   switch (getClassB(Ty)) {
1347   case cByte:
1348     // Extend value into target register (8->32)
1349     if (isUnsigned)
1350       BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1351     else
1352       BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1353     break;
1354   case cShort:
1355     // Extend value into target register (16->32)
1356     if (isUnsigned)
1357       BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1358     else
1359       BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1360     break;
1361   case cInt:
1362     // Move value into target register (32->32)
1363     BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1364     break;
1365   default:
1366     assert(0 && "Unpromotable operand class in promote32");
1367   }
1368 }
1369
1370 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
1371 /// we have the following possibilities:
1372 ///
1373 ///   ret void: No return value, simply emit a 'ret' instruction
1374 ///   ret sbyte, ubyte : Extend value into EAX and return
1375 ///   ret short, ushort: Extend value into EAX and return
1376 ///   ret int, uint    : Move value into EAX and return
1377 ///   ret pointer      : Move value into EAX and return
1378 ///   ret long, ulong  : Move value into EAX/EDX and return
1379 ///   ret float/double : Top of FP stack
1380 ///
1381 void X86ISel::visitReturnInst(ReturnInst &I) {
1382   if (I.getNumOperands() == 0) {
1383     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1384     return;
1385   }
1386
1387   Value *RetVal = I.getOperand(0);
1388   switch (getClassB(RetVal->getType())) {
1389   case cByte:   // integral return values: extend or move into EAX and return
1390   case cShort:
1391   case cInt:
1392     promote32(X86::EAX, ValueRecord(RetVal));
1393     // Declare that EAX is live on exit
1394     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1395     break;
1396   case cFP: {                  // Floats & Doubles: Return in ST(0)
1397     unsigned RetReg = getReg(RetVal);
1398     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1399     // Declare that top-of-stack is live on exit
1400     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1401     break;
1402   }
1403   case cLong: {
1404     unsigned RetReg = getReg(RetVal);
1405     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1406     BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1407     // Declare that EAX & EDX are live on exit
1408     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1409       .addReg(X86::ESP);
1410     break;
1411   }
1412   default:
1413     visitInstruction(I);
1414   }
1415   // Emit a 'ret' instruction
1416   BuildMI(BB, X86::RET, 0);
1417 }
1418
1419 // getBlockAfter - Return the basic block which occurs lexically after the
1420 // specified one.
1421 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1422   Function::iterator I = BB; ++I;  // Get iterator to next block
1423   return I != BB->getParent()->end() ? &*I : 0;
1424 }
1425
1426 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1427 /// that since code layout is frozen at this point, that if we are trying to
1428 /// jump to a block that is the immediate successor of the current block, we can
1429 /// just make a fall-through (but we don't currently).
1430 ///
1431 void X86ISel::visitBranchInst(BranchInst &BI) {
1432   // Update machine-CFG edges
1433   BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1434   if (BI.isConditional())
1435     BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1436
1437   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1438
1439   if (!BI.isConditional()) {  // Unconditional branch?
1440     if (BI.getSuccessor(0) != NextBB)
1441       BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1442     return;
1443   }
1444
1445   // See if we can fold the setcc into the branch itself...
1446   SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1447   if (SCI == 0) {
1448     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1449     // computed some other way...
1450     unsigned condReg = getReg(BI.getCondition());
1451     BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1452     if (BI.getSuccessor(1) == NextBB) {
1453       if (BI.getSuccessor(0) != NextBB)
1454         BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1455     } else {
1456       BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1457       
1458       if (BI.getSuccessor(0) != NextBB)
1459         BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1460     }
1461     return;
1462   }
1463
1464   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1465   MachineBasicBlock::iterator MII = BB->end();
1466   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1467
1468   const Type *CompTy = SCI->getOperand(0)->getType();
1469   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1470   
1471
1472   // LLVM  -> X86 signed  X86 unsigned
1473   // -----    ----------  ------------
1474   // seteq -> je          je
1475   // setne -> jne         jne
1476   // setlt -> jl          jb
1477   // setge -> jge         jae
1478   // setgt -> jg          ja
1479   // setle -> jle         jbe
1480   // ----
1481   //          js                  // Used by comparison with 0 optimization
1482   //          jns
1483
1484   static const unsigned OpcodeTab[2][8] = {
1485     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1486     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1487       X86::JS, X86::JNS },
1488   };
1489   
1490   if (BI.getSuccessor(0) != NextBB) {
1491     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1492       .addMBB(MBBMap[BI.getSuccessor(0)]);
1493     if (BI.getSuccessor(1) != NextBB)
1494       BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1495   } else {
1496     // Change to the inverse condition...
1497     if (BI.getSuccessor(1) != NextBB) {
1498       OpNum ^= 1;
1499       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1500         .addMBB(MBBMap[BI.getSuccessor(1)]);
1501     }
1502   }
1503 }
1504
1505
1506 /// doCall - This emits an abstract call instruction, setting up the arguments
1507 /// and the return value as appropriate.  For the actual function call itself,
1508 /// it inserts the specified CallMI instruction into the stream.
1509 ///
1510 void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1511                      const std::vector<ValueRecord> &Args) {
1512   // Count how many bytes are to be pushed on the stack...
1513   unsigned NumBytes = 0;
1514
1515   if (!Args.empty()) {
1516     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1517       switch (getClassB(Args[i].Ty)) {
1518       case cByte: case cShort: case cInt:
1519         NumBytes += 4; break;
1520       case cLong:
1521         NumBytes += 8; break;
1522       case cFP:
1523         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1524         break;
1525       default: assert(0 && "Unknown class!");
1526       }
1527
1528     // Adjust the stack pointer for the new arguments...
1529     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1530
1531     // Arguments go on the stack in reverse order, as specified by the ABI.
1532     unsigned ArgOffset = 0;
1533     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1534       unsigned ArgReg;
1535       switch (getClassB(Args[i].Ty)) {
1536       case cByte:
1537         if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1538           addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1539             .addImm(Args[i].Val == ConstantBool::True);
1540           break;
1541         }
1542         // FALL THROUGH
1543       case cShort:
1544         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1545           // Zero/Sign extend constant, then stuff into memory.
1546           ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1547           Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1548           addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1549             .addImm(Val->getRawValue() & 0xFFFFFFFF);
1550         } else {
1551           // Promote arg to 32 bits wide into a temporary register...
1552           ArgReg = makeAnotherReg(Type::UIntTy);
1553           promote32(ArgReg, Args[i]);
1554           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1555                        X86::ESP, ArgOffset).addReg(ArgReg);
1556         }
1557         break;
1558       case cInt:
1559         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1560           unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1561           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1562                        X86::ESP, ArgOffset).addImm(Val);
1563         } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1564           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1565                        X86::ESP, ArgOffset).addImm(0);
1566         } else {
1567           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1568           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1569                        X86::ESP, ArgOffset).addReg(ArgReg);
1570         }
1571         break;
1572       case cLong:
1573         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1574           uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1575           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1576                        X86::ESP, ArgOffset).addImm(Val & ~0U);
1577           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1578                        X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1579         } else {
1580           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1581           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1582                        X86::ESP, ArgOffset).addReg(ArgReg);
1583           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1584                        X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1585         }
1586         ArgOffset += 4;        // 8 byte entry, not 4.
1587         break;
1588         
1589       case cFP:
1590         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1591         if (Args[i].Ty == Type::FloatTy) {
1592           addRegOffset(BuildMI(BB, X86::FST32m, 5),
1593                        X86::ESP, ArgOffset).addReg(ArgReg);
1594         } else {
1595           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1596           addRegOffset(BuildMI(BB, X86::FST64m, 5),
1597                        X86::ESP, ArgOffset).addReg(ArgReg);
1598           ArgOffset += 4;       // 8 byte entry, not 4.
1599         }
1600         break;
1601
1602       default: assert(0 && "Unknown class!");
1603       }
1604       ArgOffset += 4;
1605     }
1606   } else {
1607     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1608   }
1609
1610   BB->push_back(CallMI);
1611
1612   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1613
1614   // If there is a return value, scavenge the result from the location the call
1615   // leaves it in...
1616   //
1617   if (Ret.Ty != Type::VoidTy) {
1618     unsigned DestClass = getClassB(Ret.Ty);
1619     switch (DestClass) {
1620     case cByte:
1621     case cShort:
1622     case cInt: {
1623       // Integral results are in %eax, or the appropriate portion
1624       // thereof.
1625       static const unsigned regRegMove[] = {
1626         X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1627       };
1628       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1629       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1630       break;
1631     }
1632     case cFP:     // Floating-point return values live in %ST(0)
1633       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1634       break;
1635     case cLong:   // Long values are left in EDX:EAX
1636       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1637       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1638       break;
1639     default: assert(0 && "Unknown class!");
1640     }
1641   }
1642 }
1643
1644
1645 /// visitCallInst - Push args on stack and do a procedure call instruction.
1646 void X86ISel::visitCallInst(CallInst &CI) {
1647   MachineInstr *TheCall;
1648   if (Function *F = CI.getCalledFunction()) {
1649     // Is it an intrinsic function call?
1650     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1651       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1652       return;
1653     }
1654
1655     // Emit a CALL instruction with PC-relative displacement.
1656     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1657   } else {  // Emit an indirect call...
1658     unsigned Reg = getReg(CI.getCalledValue());
1659     TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1660   }
1661
1662   std::vector<ValueRecord> Args;
1663   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1664     Args.push_back(ValueRecord(CI.getOperand(i)));
1665
1666   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1667   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1668 }         
1669
1670 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1671 /// function, lowering any calls to unknown intrinsic functions into the
1672 /// equivalent LLVM code.
1673 ///
1674 void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1675   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1676     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1677       if (CallInst *CI = dyn_cast<CallInst>(I++))
1678         if (Function *F = CI->getCalledFunction())
1679           switch (F->getIntrinsicID()) {
1680           case Intrinsic::not_intrinsic:
1681           case Intrinsic::vastart:
1682           case Intrinsic::vacopy:
1683           case Intrinsic::vaend:
1684           case Intrinsic::returnaddress:
1685           case Intrinsic::frameaddress:
1686           case Intrinsic::memcpy:
1687           case Intrinsic::memset:
1688           case Intrinsic::isunordered:
1689           case Intrinsic::readport:
1690           case Intrinsic::writeport:
1691             // We directly implement these intrinsics
1692             break;
1693           case Intrinsic::readio: {
1694             // On X86, memory operations are in-order.  Lower this intrinsic
1695             // into a volatile load.
1696             Instruction *Before = CI->getPrev();
1697             LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1698             CI->replaceAllUsesWith(LI);
1699             BB->getInstList().erase(CI);
1700             break;
1701           }
1702           case Intrinsic::writeio: {
1703             // On X86, memory operations are in-order.  Lower this intrinsic
1704             // into a volatile store.
1705             Instruction *Before = CI->getPrev();
1706             StoreInst *LI = new StoreInst(CI->getOperand(1),
1707                                           CI->getOperand(2), true, CI);
1708             CI->replaceAllUsesWith(LI);
1709             BB->getInstList().erase(CI);
1710             break;
1711           }
1712           default:
1713             // All other intrinsic calls we must lower.
1714             Instruction *Before = CI->getPrev();
1715             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1716             if (Before) {        // Move iterator to instruction after call
1717               I = Before; ++I;
1718             } else {
1719               I = BB->begin();
1720             }
1721           }
1722 }
1723
1724 void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1725   unsigned TmpReg1, TmpReg2;
1726   switch (ID) {
1727   case Intrinsic::vastart:
1728     // Get the address of the first vararg value...
1729     TmpReg1 = getReg(CI);
1730     addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1731     return;
1732
1733   case Intrinsic::vacopy:
1734     TmpReg1 = getReg(CI);
1735     TmpReg2 = getReg(CI.getOperand(1));
1736     BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1737     return;
1738   case Intrinsic::vaend: return;   // Noop on X86
1739
1740   case Intrinsic::returnaddress:
1741   case Intrinsic::frameaddress:
1742     TmpReg1 = getReg(CI);
1743     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1744       if (ID == Intrinsic::returnaddress) {
1745         // Just load the return address
1746         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1747                           ReturnAddressIndex);
1748       } else {
1749         addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1750                           ReturnAddressIndex, -4);
1751       }
1752     } else {
1753       // Values other than zero are not implemented yet.
1754       BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1755     }
1756     return;
1757
1758   case Intrinsic::isunordered:
1759     TmpReg1 = getReg(CI.getOperand(1));
1760     TmpReg2 = getReg(CI.getOperand(2));
1761     emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1762     TmpReg2 = getReg(CI);
1763     BuildMI(BB, X86::SETPr, 0, TmpReg2);
1764     return;
1765
1766   case Intrinsic::memcpy: {
1767     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1768     unsigned Align = 1;
1769     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1770       Align = AlignC->getRawValue();
1771       if (Align == 0) Align = 1;
1772     }
1773
1774     // Turn the byte code into # iterations
1775     unsigned CountReg;
1776     unsigned Opcode;
1777     switch (Align & 3) {
1778     case 2:   // WORD aligned
1779       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1780         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1781       } else {
1782         CountReg = makeAnotherReg(Type::IntTy);
1783         unsigned ByteReg = getReg(CI.getOperand(3));
1784         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1785       }
1786       Opcode = X86::REP_MOVSW;
1787       break;
1788     case 0:   // DWORD aligned
1789       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1790         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1791       } else {
1792         CountReg = makeAnotherReg(Type::IntTy);
1793         unsigned ByteReg = getReg(CI.getOperand(3));
1794         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1795       }
1796       Opcode = X86::REP_MOVSD;
1797       break;
1798     default:  // BYTE aligned
1799       CountReg = getReg(CI.getOperand(3));
1800       Opcode = X86::REP_MOVSB;
1801       break;
1802     }
1803
1804     // No matter what the alignment is, we put the source in ESI, the
1805     // destination in EDI, and the count in ECX.
1806     TmpReg1 = getReg(CI.getOperand(1));
1807     TmpReg2 = getReg(CI.getOperand(2));
1808     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1809     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1810     BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1811     BuildMI(BB, Opcode, 0);
1812     return;
1813   }
1814   case Intrinsic::memset: {
1815     assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1816     unsigned Align = 1;
1817     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1818       Align = AlignC->getRawValue();
1819       if (Align == 0) Align = 1;
1820     }
1821
1822     // Turn the byte code into # iterations
1823     unsigned CountReg;
1824     unsigned Opcode;
1825     if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1826       unsigned Val = ValC->getRawValue() & 255;
1827
1828       // If the value is a constant, then we can potentially use larger copies.
1829       switch (Align & 3) {
1830       case 2:   // WORD aligned
1831         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1832           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1833         } else {
1834           CountReg = makeAnotherReg(Type::IntTy);
1835           unsigned ByteReg = getReg(CI.getOperand(3));
1836           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1837         }
1838         BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1839         Opcode = X86::REP_STOSW;
1840         break;
1841       case 0:   // DWORD aligned
1842         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1843           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1844         } else {
1845           CountReg = makeAnotherReg(Type::IntTy);
1846           unsigned ByteReg = getReg(CI.getOperand(3));
1847           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1848         }
1849         Val = (Val << 8) | Val;
1850         BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1851         Opcode = X86::REP_STOSD;
1852         break;
1853       default:  // BYTE aligned
1854         CountReg = getReg(CI.getOperand(3));
1855         BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1856         Opcode = X86::REP_STOSB;
1857         break;
1858       }
1859     } else {
1860       // If it's not a constant value we are storing, just fall back.  We could
1861       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1862       unsigned ValReg = getReg(CI.getOperand(2));
1863       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1864       CountReg = getReg(CI.getOperand(3));
1865       Opcode = X86::REP_STOSB;
1866     }
1867
1868     // No matter what the alignment is, we put the source in ESI, the
1869     // destination in EDI, and the count in ECX.
1870     TmpReg1 = getReg(CI.getOperand(1));
1871     //TmpReg2 = getReg(CI.getOperand(2));
1872     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1873     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1874     BuildMI(BB, Opcode, 0);
1875     return;
1876   }
1877
1878   case Intrinsic::readport: {
1879     // First, determine that the size of the operand falls within the acceptable
1880     // range for this architecture.
1881     //
1882     if (getClassB(CI.getOperand(1)->getType()) != cShort) {
1883       std::cerr << "llvm.readport: Address size is not 16 bits\n";
1884       exit(1);
1885     }
1886
1887     // Now, move the I/O port address into the DX register and use the IN
1888     // instruction to get the input data.
1889     //
1890     unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1891     unsigned DestReg = getReg(CI);
1892
1893     // If the port is a single-byte constant, use the immediate form.
1894     if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1895       if ((C->getRawValue() & 255) == C->getRawValue()) {
1896         switch (Class) {
1897         case cByte:
1898           BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1899           BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1900           return;
1901         case cShort:
1902           BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1903           BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1904           return;
1905         case cInt:
1906           BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1907           BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1908           return;
1909         }
1910       }
1911
1912     unsigned Reg = getReg(CI.getOperand(1));
1913     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1914     switch (Class) {
1915     case cByte:
1916       BuildMI(BB, X86::IN8rr, 0);
1917       BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1918       break;
1919     case cShort:
1920       BuildMI(BB, X86::IN16rr, 0);
1921       BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1922       break;
1923     case cInt:
1924       BuildMI(BB, X86::IN32rr, 0);
1925       BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1926       break;
1927     default:
1928       std::cerr << "Cannot do input on this data type";
1929       exit (1);
1930     }
1931     return;
1932   }
1933
1934   case Intrinsic::writeport: {
1935     // First, determine that the size of the operand falls within the
1936     // acceptable range for this architecture.
1937     if (getClass(CI.getOperand(2)->getType()) != cShort) {
1938       std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1939       exit(1);
1940     }
1941
1942     unsigned Class = getClassB(CI.getOperand(1)->getType());
1943     unsigned ValReg = getReg(CI.getOperand(1));
1944     switch (Class) {
1945     case cByte:
1946       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1947       break;
1948     case cShort:
1949       BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1950       break;
1951     case cInt:
1952       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1953       break;
1954     default:
1955       std::cerr << "llvm.writeport: invalid data type for X86 target";
1956       exit(1);
1957     }
1958
1959
1960     // If the port is a single-byte constant, use the immediate form.
1961     if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1962       if ((C->getRawValue() & 255) == C->getRawValue()) {
1963         static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1964         BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1965         return;
1966       }
1967
1968     // Otherwise, move the I/O port address into the DX register and the value
1969     // to write into the AL/AX/EAX register.
1970     static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1971     unsigned Reg = getReg(CI.getOperand(2));
1972     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1973     BuildMI(BB, Opc[Class], 0);
1974     return;
1975   }
1976     
1977   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1978   }
1979 }
1980
1981 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1982   if (LI.getParent() != User.getParent())
1983     return false;
1984   BasicBlock::iterator It = &LI;
1985   // Check all of the instructions between the load and the user.  We should
1986   // really use alias analysis here, but for now we just do something simple.
1987   for (++It; It != BasicBlock::iterator(&User); ++It) {
1988     switch (It->getOpcode()) {
1989     case Instruction::Free:
1990     case Instruction::Store:
1991     case Instruction::Call:
1992     case Instruction::Invoke:
1993       return false;
1994     case Instruction::Load:
1995       if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
1996         return false;
1997       break;
1998     }
1999   }
2000   return true;
2001 }
2002
2003 /// visitSimpleBinary - Implement simple binary operators for integral types...
2004 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2005 /// Xor.
2006 ///
2007 void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
2008   unsigned DestReg = getReg(B);
2009   MachineBasicBlock::iterator MI = BB->end();
2010   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
2011   unsigned Class = getClassB(B.getType());
2012
2013   // If this is AND X, C, and it is only used by a setcc instruction, it will
2014   // be folded.  There is no need to emit this instruction.
2015   if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
2016     if (Class == cByte || Class == cShort || Class == cInt) {
2017       Instruction *Use = cast<Instruction>(B.use_back());
2018       if (isa<SetCondInst>(Use) &&
2019           Use->getOperand(1) == Constant::getNullValue(B.getType())) {
2020         switch (getSetCCNumber(Use->getOpcode())) {
2021         case 0:
2022         case 1:
2023           return;
2024         default:
2025           if (B.getType()->isSigned()) return;
2026         }
2027       }
2028     }
2029
2030   // Special case: op Reg, load [mem]
2031   if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
2032       Op0->hasOneUse() && 
2033       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
2034     if (!B.swapOperands())
2035       std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
2036
2037   if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
2038       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
2039
2040     unsigned Opcode;
2041     if (Class != cFP) {
2042       static const unsigned OpcodeTab[][3] = {
2043         // Arithmetic operators
2044         { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm },  // ADD
2045         { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm },  // SUB
2046         
2047         // Bitwise operators
2048         { X86::AND8rm, X86::AND16rm, X86::AND32rm },  // AND
2049         { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm },  // OR
2050         { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm },  // XOR
2051       };
2052       Opcode = OpcodeTab[OperatorClass][Class];
2053     } else {
2054       static const unsigned OpcodeTab[][2] = {
2055         { X86::FADD32m, X86::FADD64m },  // ADD
2056         { X86::FSUB32m, X86::FSUB64m },  // SUB
2057       };
2058       const Type *Ty = Op0->getType();
2059       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2060       Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
2061     }
2062
2063     unsigned Op0r = getReg(Op0);
2064     if (AllocaInst *AI =
2065         dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
2066       unsigned FI = getFixedSizedAllocaFI(AI);
2067       addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2068
2069     } else {
2070       X86AddressMode AM;
2071       getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
2072       
2073       addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
2074     }
2075     return;
2076   }
2077
2078   // If this is a floating point subtract, check to see if we can fold the first
2079   // operand in.
2080   if (Class == cFP && OperatorClass == 1 &&
2081       isa<LoadInst>(Op0) && 
2082       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2083     const Type *Ty = Op0->getType();
2084     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2085     unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2086
2087     unsigned Op1r = getReg(Op1);
2088     if (AllocaInst *AI =
2089         dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2090       unsigned FI = getFixedSizedAllocaFI(AI);
2091       addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2092     } else {
2093       X86AddressMode AM;
2094       getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
2095       
2096       addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
2097     }
2098     return;
2099   }
2100
2101   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
2102 }
2103
2104
2105 /// emitBinaryFPOperation - This method handles emission of floating point
2106 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
2107 void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2108                                     MachineBasicBlock::iterator IP,
2109                                     Value *Op0, Value *Op1,
2110                                     unsigned OperatorClass, unsigned DestReg) {
2111   // Special case: op Reg, <const fp>
2112   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2113     if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2114       // Create a constant pool entry for this constant.
2115       MachineConstantPool *CP = F->getConstantPool();
2116       unsigned CPI = CP->getConstantPoolIndex(Op1C);
2117       const Type *Ty = Op1->getType();
2118
2119       static const unsigned OpcodeTab[][4] = {
2120         { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m },   // Float
2121         { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m },   // Double
2122       };
2123
2124       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2125       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2126       unsigned Op0r = getReg(Op0, BB, IP);
2127       addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2128                                        DestReg).addReg(Op0r), CPI);
2129       return;
2130     }
2131   
2132   // Special case: R1 = op <const fp>, R2
2133   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2134     if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2135       // -0.0 - X === -X
2136       unsigned op1Reg = getReg(Op1, BB, IP);
2137       BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2138       return;
2139     } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
2140       // R1 = op CST, R2  -->  R1 = opr R2, CST
2141
2142       // Create a constant pool entry for this constant.
2143       MachineConstantPool *CP = F->getConstantPool();
2144       unsigned CPI = CP->getConstantPoolIndex(CFP);
2145       const Type *Ty = CFP->getType();
2146
2147       static const unsigned OpcodeTab[][4] = {
2148         { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2149         { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2150       };
2151       
2152       assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2153       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2154       unsigned Op1r = getReg(Op1, BB, IP);
2155       addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2156                                        DestReg).addReg(Op1r), CPI);
2157       return;
2158     }
2159
2160   // General case.
2161   static const unsigned OpcodeTab[4] = {
2162     X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2163   };
2164
2165   unsigned Opcode = OpcodeTab[OperatorClass];
2166   unsigned Op0r = getReg(Op0, BB, IP);
2167   unsigned Op1r = getReg(Op1, BB, IP);
2168   BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2169 }
2170
2171 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
2172 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2173 /// Or, 4 for Xor.
2174 ///
2175 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2176 /// and constant expression support.
2177 ///
2178 void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2179                                         MachineBasicBlock::iterator IP,
2180                                         Value *Op0, Value *Op1,
2181                                         unsigned OperatorClass, 
2182                                         unsigned DestReg) {
2183   unsigned Class = getClassB(Op0->getType());
2184
2185   if (Class == cFP) {
2186     assert(OperatorClass < 2 && "No logical ops for FP!");
2187     emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2188     return;
2189   }
2190
2191   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2192     if (OperatorClass == 1) {
2193       static unsigned const NEGTab[] = {
2194         X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2195       };
2196
2197       // sub 0, X -> neg X
2198       if (CI->isNullValue()) {
2199         unsigned op1Reg = getReg(Op1, MBB, IP);
2200         BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2201       
2202         if (Class == cLong) {
2203           // We just emitted: Dl = neg Sl
2204           // Now emit       : T  = addc Sh, 0
2205           //                : Dh = neg T
2206           unsigned T = makeAnotherReg(Type::IntTy);
2207           BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2208           BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2209         }
2210         return;
2211       } else if (Op1->hasOneUse() && Class != cLong) {
2212         // sub C, X -> tmp = neg X; DestReg = add tmp, C.  This is better
2213         // than copying C into a temporary register, because of register
2214         // pressure (tmp and destreg can share a register.
2215         static unsigned const ADDRITab[] = { 
2216           X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2217         };
2218         unsigned op1Reg = getReg(Op1, MBB, IP);
2219         unsigned Tmp = makeAnotherReg(Op0->getType());
2220         BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
2221         BuildMI(*MBB, IP, ADDRITab[Class], 2,
2222                 DestReg).addReg(Tmp).addImm(CI->getRawValue());
2223         return;
2224       }
2225     }
2226
2227   // Special case: op Reg, <const int>
2228   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
2229     unsigned Op0r = getReg(Op0, MBB, IP);
2230
2231     // xor X, -1 -> not X
2232     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
2233       static unsigned const NOTTab[] = {
2234         X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2235       };
2236       BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
2237       if (Class == cLong)  // Invert the top part too
2238         BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
2239       return;
2240     }
2241
2242     // add X, -1 -> dec X
2243     if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2244       // Note that we can't use dec for 64-bit decrements, because it does not
2245       // set the carry flag!
2246       static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
2247       BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2248       return;
2249     }
2250
2251     // add X, 1 -> inc X
2252     if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2253       // Note that we can't use inc for 64-bit increments, because it does not
2254       // set the carry flag!
2255       static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
2256       BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
2257       return;
2258     }
2259   
2260     static const unsigned OpcodeTab[][5] = {
2261       // Arithmetic operators
2262       { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri },  // ADD
2263       { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri },  // SUB
2264     
2265       // Bitwise operators
2266       { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri },  // AND
2267       { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri  },  // OR
2268       { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri },  // XOR
2269     };
2270   
2271     unsigned Opcode = OpcodeTab[OperatorClass][Class];
2272     unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
2273
2274     if (Class != cLong) {
2275       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2276       return;
2277     }
2278     
2279     // If this is a long value and the high or low bits have a special
2280     // property, emit some special cases.
2281     unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2282     
2283     // If the constant is zero in the low 32-bits, just copy the low part
2284     // across and apply the normal 32-bit operation to the high parts.  There
2285     // will be no carry or borrow into the top.
2286     if (Op1l == 0) {
2287       if (OperatorClass != 2) // All but and...
2288         BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2289       else
2290         BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2291       BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2292         .addReg(Op0r+1).addImm(Op1h);
2293       return;
2294     }
2295     
2296     // If this is a logical operation and the top 32-bits are zero, just
2297     // operate on the lower 32.
2298     if (Op1h == 0 && OperatorClass > 1) {
2299       BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2300         .addReg(Op0r).addImm(Op1l);
2301       if (OperatorClass != 2)  // All but and
2302         BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2303       else
2304         BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2305       return;
2306     }
2307     
2308     // TODO: We could handle lots of other special cases here, such as AND'ing
2309     // with 0xFFFFFFFF00000000 -> noop, etc.
2310     
2311     // Otherwise, code generate the full operation with a constant.
2312     static const unsigned TopTab[] = {
2313       X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2314     };
2315     
2316     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2317     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2318       .addReg(Op0r+1).addImm(Op1h);
2319     return;
2320   }
2321
2322   // Finally, handle the general case now.
2323   static const unsigned OpcodeTab[][5] = {
2324     // Arithmetic operators
2325     { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr },  // ADD
2326     { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr },  // SUB
2327       
2328     // Bitwise operators
2329     { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr },  // AND
2330     { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr },  // OR
2331     { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr },  // XOR
2332   };
2333     
2334   unsigned Opcode = OpcodeTab[OperatorClass][Class];
2335   unsigned Op0r = getReg(Op0, MBB, IP);
2336   unsigned Op1r = getReg(Op1, MBB, IP);
2337   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2338     
2339   if (Class == cLong) {        // Handle the upper 32 bits of long values...
2340     static const unsigned TopTab[] = {
2341       X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2342     };
2343     BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2344             DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2345   }
2346 }
2347
2348 /// doMultiply - Emit appropriate instructions to multiply together the
2349 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
2350 /// result should be given as DestTy.
2351 ///
2352 void X86ISel::doMultiply(MachineBasicBlock *MBB,
2353                          MachineBasicBlock::iterator MBBI,
2354                          unsigned DestReg, const Type *DestTy,
2355                          unsigned op0Reg, unsigned op1Reg) {
2356   unsigned Class = getClass(DestTy);
2357   switch (Class) {
2358   case cInt:
2359   case cShort:
2360     BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
2361       .addReg(op0Reg).addReg(op1Reg);
2362     return;
2363   case cByte:
2364     // Must use the MUL instruction, which forces use of AL...
2365     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2366     BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2367     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2368     return;
2369   default:
2370   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
2371   }
2372 }
2373
2374 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
2375 // returns zero when the input is not exactly a power of two.
2376 static unsigned ExactLog2(unsigned Val) {
2377   if (Val == 0 || (Val & (Val-1))) return 0;
2378   unsigned Count = 0;
2379   while (Val != 1) {
2380     Val >>= 1;
2381     ++Count;
2382   }
2383   return Count+1;
2384 }
2385
2386
2387 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2388 /// 16, or 32-bit integer multiply by a constant.
2389 void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2390                               MachineBasicBlock::iterator IP,
2391                               unsigned DestReg, const Type *DestTy,
2392                               unsigned op0Reg, unsigned ConstRHS) {
2393   static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2394   static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2395   static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
2396   static const unsigned NEGrTab[]  = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
2397
2398   unsigned Class = getClass(DestTy);
2399   unsigned TmpReg;
2400
2401   // Handle special cases here.
2402   switch (ConstRHS) {
2403   case -2:
2404     TmpReg = makeAnotherReg(DestTy);
2405     BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2406     BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2407     return;
2408   case -1:
2409     BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2410     return;
2411   case 0:
2412     BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2413     return;
2414   case 1:
2415     BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2416     return;
2417   case 2:
2418     BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2419     return;
2420   case 3:
2421   case 5:
2422   case 9:
2423     if (Class == cInt) {
2424       X86AddressMode AM;
2425       AM.BaseType = X86AddressMode::RegBase;
2426       AM.Base.Reg = op0Reg;
2427       AM.Scale = ConstRHS-1;
2428       AM.IndexReg = op0Reg;
2429       AM.Disp = 0;
2430       addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
2431       return;
2432     }
2433   case -3:
2434   case -5:
2435   case -9:
2436     if (Class == cInt) {
2437       TmpReg = makeAnotherReg(DestTy);
2438       X86AddressMode AM;
2439       AM.BaseType = X86AddressMode::RegBase;
2440       AM.Base.Reg = op0Reg;
2441       AM.Scale = -ConstRHS-1;
2442       AM.IndexReg = op0Reg;
2443       AM.Disp = 0;
2444       addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
2445       BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2446       return;
2447     }
2448   }
2449
2450   // If the element size is exactly a power of 2, use a shift to get it.
2451   if (unsigned Shift = ExactLog2(ConstRHS)) {
2452     switch (Class) {
2453     default: assert(0 && "Unknown class for this function!");
2454     case cByte:
2455       BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2456       return;
2457     case cShort:
2458       BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2459       return;
2460     case cInt:
2461       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2462       return;
2463     }
2464   }
2465
2466   // If the element size is a negative power of 2, use a shift/neg to get it.
2467   if (unsigned Shift = ExactLog2(-ConstRHS)) {
2468     TmpReg = makeAnotherReg(DestTy);
2469     BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2470     switch (Class) {
2471     default: assert(0 && "Unknown class for this function!");
2472     case cByte:
2473       BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2474       return;
2475     case cShort:
2476       BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2477       return;
2478     case cInt:
2479       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2480       return;
2481     }
2482   }
2483   
2484   if (Class == cShort) {
2485     BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2486     return;
2487   } else if (Class == cInt) {
2488     BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2489     return;
2490   }
2491
2492   // Most general case, emit a normal multiply...
2493   TmpReg = makeAnotherReg(DestTy);
2494   BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
2495   
2496   // Emit a MUL to multiply the register holding the index by
2497   // elementSize, putting the result in OffsetReg.
2498   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2499 }
2500
2501 /// visitMul - Multiplies are not simple binary operators because they must deal
2502 /// with the EAX register explicitly.
2503 ///
2504 void X86ISel::visitMul(BinaryOperator &I) {
2505   unsigned ResultReg = getReg(I);
2506
2507   Value *Op0 = I.getOperand(0);
2508   Value *Op1 = I.getOperand(1);
2509
2510   // Fold loads into floating point multiplies.
2511   if (getClass(Op0->getType()) == cFP) {
2512     if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2513       if (!I.swapOperands())
2514         std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
2515     if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2516       if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2517         const Type *Ty = Op0->getType();
2518         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2519         unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2520         
2521         unsigned Op0r = getReg(Op0);
2522         if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2523           unsigned FI = getFixedSizedAllocaFI(AI);
2524           addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2525         } else {
2526           X86AddressMode AM;
2527           getAddressingMode(LI->getOperand(0), AM);
2528           
2529           addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2530         }
2531         return;
2532       }
2533   }
2534
2535   MachineBasicBlock::iterator IP = BB->end();
2536   emitMultiply(BB, IP, Op0, Op1, ResultReg);
2537 }
2538
2539 void X86ISel::emitMultiply(MachineBasicBlock *MBB, 
2540                            MachineBasicBlock::iterator IP,
2541                            Value *Op0, Value *Op1, unsigned DestReg) {
2542   MachineBasicBlock &BB = *MBB;
2543   TypeClass Class = getClass(Op0->getType());
2544
2545   // Simple scalar multiply?
2546   unsigned Op0Reg  = getReg(Op0, &BB, IP);
2547   switch (Class) {
2548   case cByte:
2549   case cShort:
2550   case cInt:
2551     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2552       unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2553       doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
2554     } else {
2555       unsigned Op1Reg  = getReg(Op1, &BB, IP);
2556       doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
2557     }
2558     return;
2559   case cFP:
2560     emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2561     return;
2562   case cLong:
2563     break;
2564   }
2565
2566   // Long value.  We have to do things the hard way...
2567   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2568     unsigned CLow = CI->getRawValue();
2569     unsigned CHi  = CI->getRawValue() >> 32;
2570     
2571     if (CLow == 0) {
2572       // If the low part of the constant is all zeros, things are simple.
2573       BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2574       doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2575       return;
2576     }
2577     
2578     // Multiply the two low parts... capturing carry into EDX
2579     unsigned OverflowReg = 0;
2580     if (CLow == 1) {
2581       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2582     } else {
2583       unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2584       OverflowReg = makeAnotherReg(Type::UIntTy);
2585       BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2586       BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2587       BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL);  // AL*BL
2588       
2589       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);   // AL*BL
2590       BuildMI(BB, IP, X86::MOV32rr, 1,
2591               OverflowReg).addReg(X86::EDX);                    // AL*BL >> 32
2592     }
2593     
2594     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
2595     doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2596     
2597     unsigned AHBLplusOverflowReg;
2598     if (OverflowReg) {
2599       AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2600       BuildMI(BB, IP, X86::ADD32rr, 2,                // AH*BL+(AL*BL >> 32)
2601               AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2602     } else {
2603       AHBLplusOverflowReg = AHBLReg;
2604     }
2605     
2606     if (CHi == 0) {
2607       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2608     } else {
2609       unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2610       doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2611       
2612       BuildMI(BB, IP, X86::ADD32rr, 2,      // AL*BH + AH*BL + (AL*BL >> 32)
2613               DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2614     }
2615     return;
2616   }
2617
2618   // General 64x64 multiply
2619
2620   unsigned Op1Reg  = getReg(Op1, &BB, IP);
2621   // Multiply the two low parts... capturing carry into EDX
2622   BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2623   BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg);  // AL*BL
2624   
2625   unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2626   BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);     // AL*BL
2627   BuildMI(BB, IP, X86::MOV32rr, 1,
2628           OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2629   
2630   unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
2631   BuildMI(BB, IP, X86::IMUL32rr, 2,
2632           AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2633   
2634   unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2635   BuildMI(BB, IP, X86::ADD32rr, 2,                // AH*BL+(AL*BL >> 32)
2636           AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2637   
2638   unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2639   BuildMI(BB, IP, X86::IMUL32rr, 2,
2640           ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2641   
2642   BuildMI(BB, IP, X86::ADD32rr, 2,      // AL*BH + AH*BL + (AL*BL >> 32)
2643           DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2644 }
2645
2646
2647 /// visitDivRem - Handle division and remainder instructions... these
2648 /// instruction both require the same instructions to be generated, they just
2649 /// select the result from a different register.  Note that both of these
2650 /// instructions work differently for signed and unsigned operands.
2651 ///
2652 void X86ISel::visitDivRem(BinaryOperator &I) {
2653   unsigned ResultReg = getReg(I);
2654   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2655
2656   // Fold loads into floating point divides.
2657   if (getClass(Op0->getType()) == cFP) {
2658     if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2659       if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2660         const Type *Ty = Op0->getType();
2661         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2662         unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2663         
2664         unsigned Op0r = getReg(Op0);
2665         if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2666           unsigned FI = getFixedSizedAllocaFI(AI);
2667           addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2668         } else {
2669           X86AddressMode AM;
2670           getAddressingMode(LI->getOperand(0), AM);
2671           
2672           addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2673         }
2674         return;
2675       }
2676
2677     if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2678       if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2679         const Type *Ty = Op0->getType();
2680         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2681         unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2682         
2683         unsigned Op1r = getReg(Op1);
2684         if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2685           unsigned FI = getFixedSizedAllocaFI(AI);
2686           addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2687         } else {
2688           X86AddressMode AM;
2689           getAddressingMode(LI->getOperand(0), AM);
2690           addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
2691         }
2692         return;
2693       }
2694   }
2695
2696
2697   MachineBasicBlock::iterator IP = BB->end();
2698   emitDivRemOperation(BB, IP, Op0, Op1,
2699                       I.getOpcode() == Instruction::Div, ResultReg);
2700 }
2701
2702 void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2703                                   MachineBasicBlock::iterator IP,
2704                                   Value *Op0, Value *Op1, bool isDiv,
2705                                   unsigned ResultReg) {
2706   const Type *Ty = Op0->getType();
2707   unsigned Class = getClass(Ty);
2708   switch (Class) {
2709   case cFP:              // Floating point divide
2710     if (isDiv) {
2711       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2712       return;
2713     } else {               // Floating point remainder...
2714       unsigned Op0Reg = getReg(Op0, BB, IP);
2715       unsigned Op1Reg = getReg(Op1, BB, IP);
2716       MachineInstr *TheCall =
2717         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
2718       std::vector<ValueRecord> Args;
2719       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2720       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2721       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2722     }
2723     return;
2724   case cLong: {
2725     static const char *FnName[] =
2726       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2727     unsigned Op0Reg = getReg(Op0, BB, IP);
2728     unsigned Op1Reg = getReg(Op1, BB, IP);
2729     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2730     MachineInstr *TheCall =
2731       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2732
2733     std::vector<ValueRecord> Args;
2734     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2735     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2736     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2737     return;
2738   }
2739   case cByte: case cShort: case cInt:
2740     break;          // Small integrals, handled below...
2741   default: assert(0 && "Unknown class!");
2742   }
2743
2744   static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2745   static const unsigned NEGOpcode[]={ X86::NEG8r,  X86::NEG16r,  X86::NEG32r };
2746   static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2747   static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2748   static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2749
2750   // Special case signed division by power of 2.
2751   if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2752     if (isDiv) {
2753       assert(Class != cLong && "This doesn't handle 64-bit divides!");
2754       int V = CI->getValue();
2755
2756       if (V == 1) {       // X /s 1 => X
2757         unsigned Op0Reg = getReg(Op0, BB, IP);
2758         BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2759         return;
2760       }
2761
2762       if (V == -1) {      // X /s -1 => -X
2763         unsigned Op0Reg = getReg(Op0, BB, IP);
2764         BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2765         return;
2766       }
2767
2768       if (V == 2 || V == -2) {      // X /s 2
2769         static const unsigned CMPOpcode[] = {
2770           X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2771         };
2772         static const unsigned SBBOpcode[] = {
2773           X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2774         };
2775         unsigned Op0Reg = getReg(Op0, BB, IP);
2776         unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2777         BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2778
2779         unsigned TmpReg = makeAnotherReg(Op0->getType());
2780         BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2781
2782         unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2783         BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2784         if (V == -2) {
2785           BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2786         }
2787         return;
2788       }
2789
2790       bool isNeg = false;
2791       if (V < 0) {         // Not a positive power of 2?
2792         V = -V;
2793         isNeg = true;      // Maybe it's a negative power of 2.
2794       }
2795       if (unsigned Log = ExactLog2(V)) {
2796         --Log;
2797         unsigned Op0Reg = getReg(Op0, BB, IP);
2798         unsigned TmpReg = makeAnotherReg(Op0->getType());
2799         BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2800           .addReg(Op0Reg).addImm(Log-1);
2801         unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2802         BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2803           .addReg(TmpReg).addImm(32-Log);
2804         unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2805         BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2806           .addReg(Op0Reg).addReg(TmpReg2);
2807
2808         unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2809         BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2810           .addReg(TmpReg3).addImm(Log);
2811         if (isNeg)
2812           BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2813         return;
2814       }
2815     } else {    // X % C
2816       assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2817       int V = CI->getValue();
2818
2819       if (V == 2 || V == -2) {       // X % 2, X % -2
2820         static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2821         static const unsigned BaseReg[]    = { X86::AL , X86::AX , X86::EAX };
2822         static const unsigned SExtReg[]    = { X86::AH , X86::DX , X86::EDX };
2823         static const unsigned ANDOpcode[]  = {
2824           X86::AND8ri, X86::AND16ri, X86::AND32ri
2825         };
2826         static const unsigned XOROpcode[]  = {
2827           X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2828         };
2829         static const unsigned SUBOpcode[]  = {
2830           X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2831         };
2832
2833         // Sign extend result into reg of -1 or 0.
2834         unsigned Op0Reg = getReg(Op0, BB, IP);
2835         BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2836         BuildMI(*BB, IP, SExtOpcode[Class], 0);
2837         unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2838         BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2839
2840         unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2841         BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2842         
2843         unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2844         BuildMI(*BB, IP, XOROpcode[Class], 2,
2845                 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2846         BuildMI(*BB, IP, SUBOpcode[Class], 2,
2847                 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2848         return;
2849       }
2850     }
2851
2852   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
2853   static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
2854   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
2855
2856   static const unsigned DivOpcode[][4] = {
2857     { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 },  // Unsigned division
2858     { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 },  // Signed division
2859   };
2860
2861   unsigned Reg    = Regs[Class];
2862   unsigned ExtReg = ExtRegs[Class];
2863
2864   // Put the first operand into one of the A registers...
2865   unsigned Op0Reg = getReg(Op0, BB, IP);
2866   unsigned Op1Reg = getReg(Op1, BB, IP);
2867   BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2868
2869   if (Ty->isSigned()) {
2870     // Emit a sign extension instruction...
2871     unsigned ShiftResult = makeAnotherReg(Op0->getType());
2872     BuildMI(*BB, IP, SAROpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2873     BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
2874
2875     // Emit the appropriate divide or remainder instruction...
2876     BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
2877   } else {
2878     // If unsigned, emit a zeroing instruction... (reg = 0)
2879     BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2880
2881     // Emit the appropriate divide or remainder instruction...
2882     BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2883   }
2884
2885   // Figure out which register we want to pick the result out of...
2886   unsigned DestReg = isDiv ? Reg : ExtReg;
2887   
2888   // Put the result into the destination register...
2889   BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2890 }
2891
2892
2893 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2894 /// for constant immediate shift values, and for constant immediate
2895 /// shift values equal to 1. Even the general case is sort of special,
2896 /// because the shift amount has to be in CL, not just any old register.
2897 ///
2898 void X86ISel::visitShiftInst(ShiftInst &I) {
2899   MachineBasicBlock::iterator IP = BB->end ();
2900   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2901                       I.getOpcode () == Instruction::Shl, I.getType (),
2902                       getReg (I));
2903 }
2904
2905 /// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
2906 /// constant.
2907 void X86ISel::doSHLDConst(MachineBasicBlock *MBB, 
2908                           MachineBasicBlock::iterator IP,
2909                           unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
2910                           unsigned Amt) {
2911   // SHLD is a very inefficient operation on every processor, try to do
2912   // somethign simpler for common values of 'Amt'.
2913   if (Amt == 0) {
2914     BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2915   } else if (Amt == 1) {
2916     unsigned Tmp = makeAnotherReg(Type::UIntTy);
2917     BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
2918     BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2919   } else if (Amt == 2 || Amt == 3) {
2920     // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
2921     // shift/lea pair.  NOTE: This should not be done on the P6 family!
2922     unsigned Tmp = makeAnotherReg(Type::UIntTy);
2923     BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
2924     X86AddressMode AM;
2925     AM.BaseType = X86AddressMode::RegBase;
2926     AM.Base.Reg = Tmp;
2927     AM.Scale = 1 << Amt;
2928     AM.IndexReg = Op0Reg;
2929     AM.Disp = 0;
2930     addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
2931   } else {
2932     // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
2933     // than it is to emit a real SHLD.
2934
2935     BuildMI(*MBB, IP, X86::SHLD32rri8, 3, 
2936             DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
2937   }
2938 }
2939
2940 /// emitShiftOperation - Common code shared between visitShiftInst and
2941 /// constant expression support.
2942 void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
2943                                  MachineBasicBlock::iterator IP,
2944                                  Value *Op, Value *ShiftAmount, 
2945                                  bool isLeftShift, const Type *ResultTy, 
2946                                  unsigned DestReg) {
2947   unsigned SrcReg = getReg (Op, MBB, IP);
2948   bool isSigned = ResultTy->isSigned ();
2949   unsigned Class = getClass (ResultTy);
2950
2951   static const unsigned ConstantOperand[][3] = {
2952     { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri },  // SHR
2953     { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri },  // SAR
2954     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri },  // SHL
2955     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri },  // SAL = SHL
2956   };
2957
2958   static const unsigned NonConstantOperand[][3] = {
2959     { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL },  // SHR
2960     { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL },  // SAR
2961     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SHL
2962     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SAL = SHL
2963   };
2964
2965   // Longs, as usual, are handled specially.
2966   if (Class == cLong) {
2967     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2968       unsigned Amount = CUI->getValue();
2969       if (Amount == 1 && isLeftShift) {   // X << 1 == X+X
2970         BuildMI(*MBB, IP, X86::ADD32rr, 2,
2971                 DestReg).addReg(SrcReg).addReg(SrcReg);
2972         BuildMI(*MBB, IP, X86::ADC32rr, 2,
2973                 DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
2974       } else if (Amount < 32) {
2975         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2976         if (isLeftShift) {
2977           doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
2978           BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
2979         } else {
2980           BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
2981                   DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addImm(Amount);
2982           BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
2983         }
2984       } else if (Amount == 32) {
2985         if (isLeftShift) {
2986           BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2987           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2988         } else {
2989           BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2990           if (!isSigned) {
2991             BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2992           } else {
2993             BuildMI(*MBB, IP, X86::SAR32ri, 2,
2994                     DestReg+1).addReg(SrcReg).addImm(31);
2995           }
2996         }
2997       } else {                 // Shifting more than 32 bits
2998         Amount -= 32;
2999         if (isLeftShift) {
3000           BuildMI(*MBB, IP, X86::SHL32ri, 2,
3001                   DestReg + 1).addReg(SrcReg).addImm(Amount);
3002           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3003         } else {
3004           BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
3005                   DestReg).addReg(SrcReg+1).addImm(Amount);
3006           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3007         }
3008       }
3009     } else {
3010       unsigned TmpReg = makeAnotherReg(Type::IntTy);
3011       if (!isLeftShift && isSigned) {
3012         // If this is a SHR of a Long, then we need to do funny sign extension
3013         // stuff.  TmpReg gets the value to use as the high-part if we are
3014         // shifting more than 32 bits.
3015         BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
3016       } else {
3017         // Other shifts use a fixed zero value if the shift is more than 32
3018         // bits.
3019         BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
3020       }
3021
3022       // Initialize CL with the shift amount...
3023       unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
3024       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
3025
3026       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
3027       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3028       if (isLeftShift) {
3029         // TmpReg2 = shld inHi, inLo
3030         BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
3031                                                     .addReg(SrcReg);
3032         // TmpReg3 = shl  inLo, CL
3033         BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
3034
3035         // Set the flags to indicate whether the shift was by more than 32 bits.
3036         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3037
3038         // DestHi = (>32) ? TmpReg3 : TmpReg2;
3039         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
3040                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
3041         // DestLo = (>32) ? TmpReg : TmpReg3;
3042         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
3043             DestReg).addReg(TmpReg3).addReg(TmpReg);
3044       } else {
3045         // TmpReg2 = shrd inLo, inHi
3046         BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
3047                                                     .addReg(SrcReg+1);
3048         // TmpReg3 = s[ah]r  inHi, CL
3049         BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
3050                        .addReg(SrcReg+1);
3051
3052         // Set the flags to indicate whether the shift was by more than 32 bits.
3053         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3054
3055         // DestLo = (>32) ? TmpReg3 : TmpReg2;
3056         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
3057                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
3058
3059         // DestHi = (>32) ? TmpReg : TmpReg3;
3060         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
3061                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
3062       }
3063     }
3064     return;
3065   }
3066
3067   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
3068     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
3069     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
3070
3071     if (CUI->getValue() == 1 && isLeftShift) {    // X << 1 -> X+X
3072       static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
3073       BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
3074     } else {
3075       const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3076       BuildMI(*MBB, IP, Opc[Class], 2,
3077               DestReg).addReg(SrcReg).addImm(CUI->getValue());
3078     }
3079   } else {                  // The shift amount is non-constant.
3080     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
3081     BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
3082
3083     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
3084     BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
3085   }
3086 }
3087
3088
3089 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
3090 /// instruction.  The load and store instructions are the only place where we
3091 /// need to worry about the memory layout of the target machine.
3092 ///
3093 void X86ISel::visitLoadInst(LoadInst &I) {
3094   // Check to see if this load instruction is going to be folded into a binary
3095   // instruction, like add.  If so, we don't want to emit it.  Wouldn't a real
3096   // pattern matching instruction selector be nice?
3097   unsigned Class = getClassB(I.getType());
3098   if (I.hasOneUse()) {
3099     Instruction *User = cast<Instruction>(I.use_back());
3100     switch (User->getOpcode()) {
3101     case Instruction::Cast:
3102       // If this is a cast from a signed-integer type to a floating point type,
3103       // fold the cast here.
3104       if (getClassB(User->getType()) == cFP &&
3105           (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
3106            I.getType() == Type::LongTy)) {
3107         unsigned DestReg = getReg(User);
3108         static const unsigned Opcode[] = {
3109           0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
3110         };
3111
3112         if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3113           unsigned FI = getFixedSizedAllocaFI(AI);
3114           addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3115         } else {
3116           X86AddressMode AM;
3117           getAddressingMode(I.getOperand(0), AM);
3118           addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
3119         }
3120         return;
3121       } else {
3122         User = 0;
3123       }
3124       break;
3125
3126     case Instruction::Add:
3127     case Instruction::Sub:
3128     case Instruction::And:
3129     case Instruction::Or:
3130     case Instruction::Xor:
3131       if (Class == cLong) User = 0;
3132       break;
3133     case Instruction::Mul:
3134     case Instruction::Div:
3135       if (Class != cFP) User = 0;
3136       break;  // Folding only implemented for floating point.
3137     default: User = 0; break;
3138     }
3139
3140     if (User) {
3141       // Okay, we found a user.  If the load is the first operand and there is
3142       // no second operand load, reverse the operand ordering.  Note that this
3143       // can fail for a subtract (ie, no change will be made).
3144       bool Swapped = false;
3145       if (!isa<LoadInst>(User->getOperand(1)))
3146         Swapped = !cast<BinaryOperator>(User)->swapOperands();
3147       
3148       // Okay, now that everything is set up, if this load is used by the second
3149       // operand, and if there are no instructions that invalidate the load
3150       // before the binary operator, eliminate the load.
3151       if (User->getOperand(1) == &I &&
3152           isSafeToFoldLoadIntoInstruction(I, *User))
3153         return;   // Eliminate the load!
3154
3155       // If this is a floating point sub or div, we won't be able to swap the
3156       // operands, but we will still be able to eliminate the load.
3157       if (Class == cFP && User->getOperand(0) == &I &&
3158           !isa<LoadInst>(User->getOperand(1)) &&
3159           (User->getOpcode() == Instruction::Sub ||
3160            User->getOpcode() == Instruction::Div) &&
3161           isSafeToFoldLoadIntoInstruction(I, *User))
3162         return;  // Eliminate the load!
3163
3164       // If we swapped the operands to the instruction, but couldn't fold the
3165       // load anyway, swap them back.  We don't want to break add X, int 
3166       // folding.
3167       if (Swapped) cast<BinaryOperator>(User)->swapOperands();
3168     }
3169   }
3170
3171   static const unsigned Opcodes[] = {
3172     X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
3173   };
3174   unsigned Opcode = Opcodes[Class];
3175   if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
3176
3177   unsigned DestReg = getReg(I);
3178
3179   if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3180     unsigned FI = getFixedSizedAllocaFI(AI);
3181     if (Class == cLong) {
3182       addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3183       addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3184     } else {
3185       addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3186     }
3187   } else {
3188     X86AddressMode AM;
3189     getAddressingMode(I.getOperand(0), AM);
3190     
3191     if (Class == cLong) {
3192       addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3193       AM.Disp += 4;
3194       addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
3195     } else {
3196       addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
3197     }
3198   }
3199 }
3200
3201 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3202 /// instruction.
3203 ///
3204 void X86ISel::visitStoreInst(StoreInst &I) {
3205   X86AddressMode AM;
3206   getAddressingMode(I.getOperand(1), AM);
3207
3208   const Type *ValTy = I.getOperand(0)->getType();
3209   unsigned Class = getClassB(ValTy);
3210
3211   if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3212     uint64_t Val = CI->getRawValue();
3213     if (Class == cLong) {
3214       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3215       AM.Disp += 4;
3216       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
3217     } else {
3218       static const unsigned Opcodes[] = {
3219         X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
3220       };
3221       unsigned Opcode = Opcodes[Class];
3222       addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
3223     }
3224   } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
3225     addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
3226   } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
3227     addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
3228   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3229     // Store constant FP values with integer instructions to avoid having to
3230     // load the constants from the constant pool then do a store.
3231     if (CFP->getType() == Type::FloatTy) {
3232       union {
3233         unsigned I;
3234         float    F;
3235       } V;
3236       V.F = CFP->getValue();
3237       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
3238     } else {
3239       union {
3240         uint64_t I;
3241         double   F;
3242       } V;
3243       V.F = CFP->getValue();
3244       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3245       AM.Disp += 4;
3246       addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
3247                                                           unsigned(V.I >> 32));
3248     }
3249     
3250   } else if (Class == cLong) {
3251     unsigned ValReg = getReg(I.getOperand(0));
3252     addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3253     AM.Disp += 4;
3254     addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
3255   } else {
3256     // FIXME: stop emitting these two instructions:
3257     //    movl $global,%eax
3258     //    movl %eax,(%ebx)
3259     // when one instruction will suffice.  That includes when the global
3260     // has an offset applied to it.
3261     unsigned ValReg = getReg(I.getOperand(0));
3262     static const unsigned Opcodes[] = {
3263       X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3264     };
3265     unsigned Opcode = Opcodes[Class];
3266     if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
3267
3268     addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
3269   }
3270 }
3271
3272
3273 /// visitCastInst - Here we have various kinds of copying with or without sign
3274 /// extension going on.
3275 ///
3276 void X86ISel::visitCastInst(CastInst &CI) {
3277   Value *Op = CI.getOperand(0);
3278
3279   unsigned SrcClass = getClassB(Op->getType());
3280   unsigned DestClass = getClassB(CI.getType());
3281   // Noop casts are not emitted: getReg will return the source operand as the
3282   // register to use for any uses of the noop cast.
3283   if (DestClass == SrcClass) {
3284     // The only detail in this plan is that casts from double -> float are 
3285     // truncating operations that we have to codegen through memory (despite
3286     // the fact that the source/dest registers are the same class).
3287     if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3288       return;
3289   }
3290
3291   // If this is a cast from a 32-bit integer to a Long type, and the only uses
3292   // of the case are GEP instructions, then the cast does not need to be
3293   // generated explicitly, it will be folded into the GEP.
3294   if (DestClass == cLong && SrcClass == cInt) {
3295     bool AllUsesAreGEPs = true;
3296     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3297       if (!isa<GetElementPtrInst>(*I)) {
3298         AllUsesAreGEPs = false;
3299         break;
3300       }        
3301
3302     // No need to codegen this cast if all users are getelementptr instrs...
3303     if (AllUsesAreGEPs) return;
3304   }
3305
3306   // If this cast converts a load from a short,int, or long integer to a FP
3307   // value, we will have folded this cast away.
3308   if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3309       (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3310        Op->getType() == Type::LongTy))
3311     return;
3312
3313
3314   unsigned DestReg = getReg(CI);
3315   MachineBasicBlock::iterator MI = BB->end();
3316   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
3317 }
3318
3319 /// emitCastOperation - Common code shared between visitCastInst and constant
3320 /// expression cast support.
3321 ///
3322 void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3323                                 MachineBasicBlock::iterator IP,
3324                                 Value *Src, const Type *DestTy,
3325                                 unsigned DestReg) {
3326   const Type *SrcTy = Src->getType();
3327   unsigned SrcClass = getClassB(SrcTy);
3328   unsigned DestClass = getClassB(DestTy);
3329   unsigned SrcReg = getReg(Src, BB, IP);
3330
3331   // Implement casts to bool by using compare on the operand followed by set if
3332   // not zero on the result.
3333   if (DestTy == Type::BoolTy) {
3334     switch (SrcClass) {
3335     case cByte:
3336       BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
3337       break;
3338     case cShort:
3339       BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
3340       break;
3341     case cInt:
3342       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
3343       break;
3344     case cLong: {
3345       unsigned TmpReg = makeAnotherReg(Type::IntTy);
3346       BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
3347       break;
3348     }
3349     case cFP:
3350       BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
3351       BuildMI(*BB, IP, X86::FNSTSW8r, 0);
3352       BuildMI(*BB, IP, X86::SAHF, 1);
3353       break;
3354     }
3355
3356     // If the zero flag is not set, then the value is true, set the byte to
3357     // true.
3358     BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
3359     return;
3360   }
3361
3362   static const unsigned RegRegMove[] = {
3363     X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
3364   };
3365
3366   // Implement casts between values of the same type class (as determined by
3367   // getClass) by using a register-to-register move.
3368   if (SrcClass == DestClass) {
3369     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
3370       BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
3371     } else if (SrcClass == cFP) {
3372       if (SrcTy == Type::FloatTy) {  // double -> float
3373         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
3374         BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
3375       } else {                       // float -> double
3376         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3377                "Unknown cFP member!");
3378         // Truncate from double to float by storing to memory as short, then
3379         // reading it back.
3380         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
3381         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
3382         addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
3383         addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
3384       }
3385     } else if (SrcClass == cLong) {
3386       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3387       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
3388     } else {
3389       assert(0 && "Cannot handle this type of cast instruction!");
3390       abort();
3391     }
3392     return;
3393   }
3394
3395   // Handle cast of SMALLER int to LARGER int using a move with sign extension
3396   // or zero extension, depending on whether the source type was signed.
3397   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3398       SrcClass < DestClass) {
3399     bool isLong = DestClass == cLong;
3400     if (isLong) DestClass = cInt;
3401
3402     static const unsigned Opc[][4] = {
3403       { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3404       { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr }  // u
3405     };
3406     
3407     bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
3408     BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
3409         DestReg).addReg(SrcReg);
3410
3411     if (isLong) {  // Handle upper 32 bits as appropriate...
3412       if (isUnsigned)     // Zero out top bits...
3413         BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3414       else                // Sign extend bottom half...
3415         BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
3416     }
3417     return;
3418   }
3419
3420   // Special case long -> int ...
3421   if (SrcClass == cLong && DestClass == cInt) {
3422     BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3423     return;
3424   }
3425   
3426   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3427   // move out of AX or AL.
3428   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3429       && SrcClass > DestClass) {
3430     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
3431     BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3432     BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
3433     return;
3434   }
3435
3436   // Handle casts from integer to floating point now...
3437   if (DestClass == cFP) {
3438     // Promote the integer to a type supported by FLD.  We do this because there
3439     // are no unsigned FLD instructions, so we must promote an unsigned value to
3440     // a larger signed value, then use FLD on the larger value.
3441     //
3442     const Type *PromoteType = 0;
3443     unsigned PromoteOpcode = 0;
3444     unsigned RealDestReg = DestReg;
3445     switch (SrcTy->getTypeID()) {
3446     case Type::BoolTyID:
3447     case Type::SByteTyID:
3448       // We don't have the facilities for directly loading byte sized data from
3449       // memory (even signed).  Promote it to 16 bits.
3450       PromoteType = Type::ShortTy;
3451       PromoteOpcode = X86::MOVSX16rr8;
3452       break;
3453     case Type::UByteTyID:
3454       PromoteType = Type::ShortTy;
3455       PromoteOpcode = X86::MOVZX16rr8;
3456       break;
3457     case Type::UShortTyID:
3458       PromoteType = Type::IntTy;
3459       PromoteOpcode = X86::MOVZX32rr16;
3460       break;
3461     case Type::ULongTyID:
3462     case Type::UIntTyID:
3463       // Don't fild into the read destination.
3464       DestReg = makeAnotherReg(Type::DoubleTy);
3465       break;
3466     default:  // No promotion needed...
3467       break;
3468     }
3469     
3470     if (PromoteType) {
3471       unsigned TmpReg = makeAnotherReg(PromoteType);
3472       BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
3473       SrcTy = PromoteType;
3474       SrcClass = getClass(PromoteType);
3475       SrcReg = TmpReg;
3476     }
3477
3478     // Spill the integer to memory and reload it from there...
3479     int FrameIdx =
3480       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
3481
3482     if (SrcClass == cLong) {
3483       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3484                         FrameIdx).addReg(SrcReg);
3485       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3486                         FrameIdx, 4).addReg(SrcReg+1);
3487     } else {
3488       static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
3489       addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3490                         FrameIdx).addReg(SrcReg);
3491     }
3492
3493     static const unsigned Op2[] =
3494       { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
3495     addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
3496
3497     if (SrcTy == Type::UIntTy) {
3498       // If this is a cast from uint -> double, we need to be careful about if
3499       // the "sign" bit is set.  If so, we don't want to make a negative number,
3500       // we want to make a positive number.  Emit code to add an offset if the
3501       // sign bit is set.
3502
3503       // Compute whether the sign bit is set by shifting the reg right 31 bits.
3504       unsigned IsNeg = makeAnotherReg(Type::IntTy);
3505       BuildMI(BB, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
3506
3507       // Create a CP value that has the offset in one word and 0 in the other.
3508       static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
3509                                                         0x4f80000000000000ULL);
3510       unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
3511       BuildMI(BB, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
3512         .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
3513
3514     } else if (SrcTy == Type::ULongTy) {
3515       // We need special handling for unsigned 64-bit integer sources.  If the
3516       // input number has the "sign bit" set, then we loaded it incorrectly as a
3517       // negative 64-bit number.  In this case, add an offset value.
3518
3519       // Emit a test instruction to see if the dynamic input value was signed.
3520       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
3521
3522       // If the sign bit is set, get a pointer to an offset, otherwise get a
3523       // pointer to a zero.
3524       MachineConstantPool *CP = F->getConstantPool();
3525       unsigned Zero = makeAnotherReg(Type::IntTy);
3526       Constant *Null = Constant::getNullValue(Type::UIntTy);
3527       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero), 
3528                                CP->getConstantPoolIndex(Null));
3529       unsigned Offset = makeAnotherReg(Type::IntTy);
3530       Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3531                                              
3532       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
3533                                CP->getConstantPoolIndex(OffsetCst));
3534       unsigned Addr = makeAnotherReg(Type::IntTy);
3535       BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
3536
3537       // Load the constant for an add.  FIXME: this could make an 'fadd' that
3538       // reads directly from memory, but we don't support these yet.
3539       unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
3540       addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
3541
3542       BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3543                 .addReg(ConstReg).addReg(DestReg);
3544     }
3545
3546     return;
3547   }
3548
3549   // Handle casts from floating point to integer now...
3550   if (SrcClass == cFP) {
3551     // Change the floating point control register to use "round towards zero"
3552     // mode when truncating to an integer value.
3553     //
3554     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3555     addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
3556
3557     // Load the old value of the high byte of the control word...
3558     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
3559     addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
3560                       CWFrameIdx, 1);
3561
3562     // Set the high part to be round to zero...
3563     addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
3564                       CWFrameIdx, 1).addImm(12);
3565
3566     // Reload the modified control word now...
3567     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3568     
3569     // Restore the memory image of control word to original value
3570     addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
3571                       CWFrameIdx, 1).addReg(HighPartOfCW);
3572
3573     // We don't have the facilities for directly storing byte sized data to
3574     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
3575     // larger classes because we only have signed FP stores.
3576     unsigned StoreClass  = DestClass;
3577     const Type *StoreTy  = DestTy;
3578     if (StoreClass == cByte || DestTy->isUnsigned())
3579       switch (StoreClass) {
3580       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
3581       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
3582       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
3583       // The following treatment of cLong may not be perfectly right,
3584       // but it survives chains of casts of the form
3585       // double->ulong->double.
3586       case cLong:  StoreTy = Type::LongTy;  StoreClass = cLong;  break;
3587       default: assert(0 && "Unknown store class!");
3588       }
3589
3590     // Spill the integer to memory and reload it from there...
3591     int FrameIdx =
3592       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3593
3594     static const unsigned Op1[] =
3595       { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
3596     addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3597                       FrameIdx).addReg(SrcReg);
3598
3599     if (DestClass == cLong) {
3600       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3601       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
3602                         FrameIdx, 4);
3603     } else {
3604       static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
3605       addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
3606     }
3607
3608     // Reload the original control word now...
3609     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3610     return;
3611   }
3612
3613   // Anything we haven't handled already, we can't (yet) handle at all.
3614   assert(0 && "Unhandled cast instruction!");
3615   abort();
3616 }
3617
3618 /// visitVANextInst - Implement the va_next instruction...
3619 ///
3620 void X86ISel::visitVANextInst(VANextInst &I) {
3621   unsigned VAList = getReg(I.getOperand(0));
3622   unsigned DestReg = getReg(I);
3623
3624   unsigned Size;
3625   switch (I.getArgType()->getTypeID()) {
3626   default:
3627     std::cerr << I;
3628     assert(0 && "Error: bad type for va_next instruction!");
3629     return;
3630   case Type::PointerTyID:
3631   case Type::UIntTyID:
3632   case Type::IntTyID:
3633     Size = 4;
3634     break;
3635   case Type::ULongTyID:
3636   case Type::LongTyID:
3637   case Type::DoubleTyID:
3638     Size = 8;
3639     break;
3640   }
3641
3642   // Increment the VAList pointer...
3643   BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
3644 }
3645
3646 void X86ISel::visitVAArgInst(VAArgInst &I) {
3647   unsigned VAList = getReg(I.getOperand(0));
3648   unsigned DestReg = getReg(I);
3649
3650   switch (I.getType()->getTypeID()) {
3651   default:
3652     std::cerr << I;
3653     assert(0 && "Error: bad type for va_next instruction!");
3654     return;
3655   case Type::PointerTyID:
3656   case Type::UIntTyID:
3657   case Type::IntTyID:
3658     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3659     break;
3660   case Type::ULongTyID:
3661   case Type::LongTyID:
3662     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3663     addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
3664     break;
3665   case Type::DoubleTyID:
3666     addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
3667     break;
3668   }
3669 }
3670
3671 /// visitGetElementPtrInst - instruction-select GEP instructions
3672 ///
3673 void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3674   // If this GEP instruction will be folded into all of its users, we don't need
3675   // to explicitly calculate it!
3676   X86AddressMode AM;
3677   if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
3678     // Check all of the users of the instruction to see if they are loads and
3679     // stores.
3680     bool AllWillFold = true;
3681     for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3682       if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3683         if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3684             cast<Instruction>(*UI)->getOperand(0) == &I) {
3685           AllWillFold = false;
3686           break;
3687         }
3688
3689     // If the instruction is foldable, and will be folded into all users, don't
3690     // emit it!
3691     if (AllWillFold) return;
3692   }
3693
3694   unsigned outputReg = getReg(I);
3695   emitGEPOperation(BB, BB->end(), I.getOperand(0),
3696                    I.op_begin()+1, I.op_end(), outputReg);
3697 }
3698
3699 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3700 /// GEPTypes (the derived types being stepped through at each level).  On return
3701 /// from this function, if some indexes of the instruction are representable as
3702 /// an X86 lea instruction, the machine operands are put into the Ops
3703 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3704 /// lists.  Otherwise, GEPOps.size() is returned.  If this returns a an
3705 /// addressing mode that only partially consumes the input, the BaseReg input of
3706 /// the addressing mode must be left free.
3707 ///
3708 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3709 ///
3710 void X86ISel::getGEPIndex(MachineBasicBlock *MBB, 
3711                           MachineBasicBlock::iterator IP,
3712                           std::vector<Value*> &GEPOps,
3713                           std::vector<const Type*> &GEPTypes,
3714                           X86AddressMode &AM) {
3715   const TargetData &TD = TM.getTargetData();
3716
3717   // Clear out the state we are working with...
3718   AM.BaseType = X86AddressMode::RegBase;
3719   AM.Base.Reg = 0;   // No base register
3720   AM.Scale = 1;      // Unit scale
3721   AM.IndexReg = 0;   // No index register
3722   AM.Disp = 0;       // No displacement
3723
3724   // While there are GEP indexes that can be folded into the current address,
3725   // keep processing them.
3726   while (!GEPTypes.empty()) {
3727     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3728       // It's a struct access.  CUI is the index into the structure,
3729       // which names the field. This index must have unsigned type.
3730       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3731       
3732       // Use the TargetData structure to pick out what the layout of the
3733       // structure is in memory.  Since the structure index must be constant, we
3734       // can get its value and use it to find the right byte offset from the
3735       // StructLayout class's list of structure member offsets.
3736       AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
3737       GEPOps.pop_back();        // Consume a GEP operand
3738       GEPTypes.pop_back();
3739     } else {
3740       // It's an array or pointer access: [ArraySize x ElementType].
3741       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3742       Value *idx = GEPOps.back();
3743
3744       // idx is the index into the array.  Unlike with structure
3745       // indices, we may not know its actual value at code-generation
3746       // time.
3747
3748       // If idx is a constant, fold it into the offset.
3749       unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
3750       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
3751         AM.Disp += TypeSize*CSI->getValue();
3752       } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3753         AM.Disp += TypeSize*CUI->getValue();
3754       } else {
3755         // If the index reg is already taken, we can't handle this index.
3756         if (AM.IndexReg) return;
3757
3758         // If this is a size that we can handle, then add the index as 
3759         switch (TypeSize) {
3760         case 1: case 2: case 4: case 8:
3761           // These are all acceptable scales on X86.
3762           AM.Scale = TypeSize;
3763           break;
3764         default:
3765           // Otherwise, we can't handle this scale
3766           return;
3767         }
3768
3769         if (CastInst *CI = dyn_cast<CastInst>(idx))
3770           if (CI->getOperand(0)->getType() == Type::IntTy ||
3771               CI->getOperand(0)->getType() == Type::UIntTy)
3772             idx = CI->getOperand(0);
3773
3774         AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
3775       }
3776
3777       GEPOps.pop_back();        // Consume a GEP operand
3778       GEPTypes.pop_back();
3779     }
3780   }
3781
3782   // GEPTypes is empty, which means we have a single operand left.  Set it as
3783   // the base register.
3784   //
3785   assert(AM.Base.Reg == 0);
3786
3787   if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3788     AM.BaseType = X86AddressMode::FrameIndexBase;
3789     AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
3790     GEPOps.pop_back();
3791     return;
3792   }
3793
3794   if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
3795     AM.GV = GV;
3796     GEPOps.pop_back();
3797     return;
3798   }
3799
3800   AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
3801   GEPOps.pop_back();        // Consume the last GEP operand
3802 }
3803
3804
3805 /// isGEPFoldable - Return true if the specified GEP can be completely
3806 /// folded into the addressing mode of a load/store or lea instruction.
3807 bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3808                             Value *Src, User::op_iterator IdxBegin,
3809                             User::op_iterator IdxEnd, X86AddressMode &AM) {
3810
3811   std::vector<Value*> GEPOps;
3812   GEPOps.resize(IdxEnd-IdxBegin+1);
3813   GEPOps[0] = Src;
3814   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3815   
3816   std::vector<const Type*>
3817     GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3818              gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3819
3820   MachineBasicBlock::iterator IP;
3821   if (MBB) IP = MBB->end();
3822   getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3823
3824   // We can fold it away iff the getGEPIndex call eliminated all operands.
3825   return GEPOps.empty();
3826 }
3827
3828 void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3829                                MachineBasicBlock::iterator IP,
3830                                Value *Src, User::op_iterator IdxBegin,
3831                                User::op_iterator IdxEnd, unsigned TargetReg) {
3832   const TargetData &TD = TM.getTargetData();
3833
3834   // If this is a getelementptr null, with all constant integer indices, just
3835   // replace it with TargetReg = 42.
3836   if (isa<ConstantPointerNull>(Src)) {
3837     User::op_iterator I = IdxBegin;
3838     for (; I != IdxEnd; ++I)
3839       if (!isa<ConstantInt>(*I))
3840         break;
3841     if (I == IdxEnd) {   // All constant indices
3842       unsigned Offset = TD.getIndexedOffset(Src->getType(),
3843                                          std::vector<Value*>(IdxBegin, IdxEnd));
3844       BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3845       return;
3846     }
3847   }
3848
3849   std::vector<Value*> GEPOps;
3850   GEPOps.resize(IdxEnd-IdxBegin+1);
3851   GEPOps[0] = Src;
3852   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3853   
3854   std::vector<const Type*> GEPTypes;
3855   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3856                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3857
3858   // Keep emitting instructions until we consume the entire GEP instruction.
3859   while (!GEPOps.empty()) {
3860     unsigned OldSize = GEPOps.size();
3861     X86AddressMode AM;
3862     getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3863     
3864     if (GEPOps.size() != OldSize) {
3865       // getGEPIndex consumed some of the input.  Build an LEA instruction here.
3866       unsigned NextTarget = 0;
3867       if (!GEPOps.empty()) {
3868         assert(AM.Base.Reg == 0 &&
3869            "getGEPIndex should have left the base register open for chaining!");
3870         NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
3871       }
3872
3873       if (AM.BaseType == X86AddressMode::RegBase &&
3874           AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
3875         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
3876       else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
3877                AM.IndexReg == 0 && AM.Disp == 0)
3878         BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
3879       else
3880         addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
3881       --IP;
3882       TargetReg = NextTarget;
3883     } else if (GEPTypes.empty()) {
3884       // The getGEPIndex operation didn't want to build an LEA.  Check to see if
3885       // all operands are consumed but the base pointer.  If so, just load it
3886       // into the register.
3887       if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
3888         BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
3889       } else {
3890         unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
3891         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3892       }
3893       break;                // we are now done
3894
3895     } else {
3896       // It's an array or pointer access: [ArraySize x ElementType].
3897       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3898       Value *idx = GEPOps.back();
3899       GEPOps.pop_back();        // Consume a GEP operand
3900       GEPTypes.pop_back();
3901
3902       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3903       // operand on X86.  Handle this case directly now...
3904       if (CastInst *CI = dyn_cast<CastInst>(idx))
3905         if (CI->getOperand(0)->getType() == Type::IntTy ||
3906             CI->getOperand(0)->getType() == Type::UIntTy)
3907           idx = CI->getOperand(0);
3908
3909       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
3910       // must find the size of the pointed-to type (Not coincidentally, the next
3911       // type is the type of the elements in the array).
3912       const Type *ElTy = SqTy->getElementType();
3913       unsigned elementSize = TD.getTypeSize(ElTy);
3914
3915       // If idxReg is a constant, we don't need to perform the multiply!
3916       if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
3917         if (!CSI->isNullValue()) {
3918           unsigned Offset = elementSize*CSI->getRawValue();
3919           unsigned Reg = makeAnotherReg(Type::UIntTy);
3920           BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
3921                                 .addReg(Reg).addImm(Offset);
3922           --IP;            // Insert the next instruction before this one.
3923           TargetReg = Reg; // Codegen the rest of the GEP into this
3924         }
3925       } else if (elementSize == 1) {
3926         // If the element size is 1, we don't have to multiply, just add
3927         unsigned idxReg = getReg(idx, MBB, IP);
3928         unsigned Reg = makeAnotherReg(Type::UIntTy);
3929         BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
3930         --IP;            // Insert the next instruction before this one.
3931         TargetReg = Reg; // Codegen the rest of the GEP into this
3932       } else {
3933         unsigned idxReg = getReg(idx, MBB, IP);
3934         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
3935
3936         // Make sure we can back the iterator up to point to the first
3937         // instruction emitted.
3938         MachineBasicBlock::iterator BeforeIt = IP;
3939         if (IP == MBB->begin())
3940           BeforeIt = MBB->end();
3941         else
3942           --BeforeIt;
3943         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3944
3945         // Emit an ADD to add OffsetReg to the basePtr.
3946         unsigned Reg = makeAnotherReg(Type::UIntTy);
3947         BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
3948                           .addReg(Reg).addReg(OffsetReg);
3949
3950         // Step to the first instruction of the multiply.
3951         if (BeforeIt == MBB->end())
3952           IP = MBB->begin();
3953         else
3954           IP = ++BeforeIt;
3955
3956         TargetReg = Reg; // Codegen the rest of the GEP into this
3957       }
3958     }
3959   }
3960 }
3961
3962 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3963 /// frame manager, otherwise do it the hard way.
3964 ///
3965 void X86ISel::visitAllocaInst(AllocaInst &I) {
3966   // If this is a fixed size alloca in the entry block for the function, we
3967   // statically stack allocate the space, so we don't need to do anything here.
3968   //
3969   if (dyn_castFixedAlloca(&I)) return;
3970   
3971   // Find the data size of the alloca inst's getAllocatedType.
3972   const Type *Ty = I.getAllocatedType();
3973   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3974
3975   // Create a register to hold the temporary result of multiplying the type size
3976   // constant by the variable amount.
3977   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3978   unsigned SrcReg1 = getReg(I.getArraySize());
3979   
3980   // TotalSizeReg = mul <numelements>, <TypeSize>
3981   MachineBasicBlock::iterator MBBI = BB->end();
3982   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
3983
3984   // AddedSize = add <TotalSizeReg>, 15
3985   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3986   BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
3987
3988   // AlignedSize = and <AddedSize>, ~15
3989   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3990   BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
3991   
3992   // Subtract size from stack pointer, thereby allocating some space.
3993   BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
3994
3995   // Put a pointer to the space into the result register, by copying
3996   // the stack pointer.
3997   BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
3998
3999   // Inform the Frame Information that we have just allocated a variable-sized
4000   // object.
4001   F->getFrameInfo()->CreateVariableSizedObject();
4002 }
4003
4004 /// visitMallocInst - Malloc instructions are code generated into direct calls
4005 /// to the library malloc.
4006 ///
4007 void X86ISel::visitMallocInst(MallocInst &I) {
4008   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
4009   unsigned Arg;
4010
4011   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
4012     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
4013   } else {
4014     Arg = makeAnotherReg(Type::UIntTy);
4015     unsigned Op0Reg = getReg(I.getOperand(0));
4016     MachineBasicBlock::iterator MBBI = BB->end();
4017     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
4018   }
4019
4020   std::vector<ValueRecord> Args;
4021   Args.push_back(ValueRecord(Arg, Type::UIntTy));
4022   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
4023                                   1).addExternalSymbol("malloc", true);
4024   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
4025 }
4026
4027
4028 /// visitFreeInst - Free instructions are code gen'd to call the free libc
4029 /// function.
4030 ///
4031 void X86ISel::visitFreeInst(FreeInst &I) {
4032   std::vector<ValueRecord> Args;
4033   Args.push_back(ValueRecord(I.getOperand(0)));
4034   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
4035                                   1).addExternalSymbol("free", true);
4036   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
4037 }
4038    
4039 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
4040 /// into a machine code representation is a very simple peep-hole fashion.  The
4041 /// generated code sucks but the implementation is nice and simple.
4042 ///
4043 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
4044   return new X86ISel(TM);
4045 }