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