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