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