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