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