Add direct support for integer select instructions, though we still don't support
[oota-llvm.git] / lib / Target / X86 / InstSelectSimple.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 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
747 // the conditional branch instruction which is the only user of the cc
748 // instruction.  This is the case if the conditional branch is the only user of
749 // the setcc, and if the setcc is in the same basic block as the conditional
750 // branch.  We also don't handle long arguments below, so we reject them here as
751 // well.
752 //
753 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
754   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
755     if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
756         SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
757       const Type *Ty = SCI->getOperand(0)->getType();
758       if (Ty != Type::LongTy && Ty != Type::ULongTy)
759         return SCI;
760     }
761   return 0;
762 }
763
764 // Return a fixed numbering for setcc instructions which does not depend on the
765 // order of the opcodes.
766 //
767 static unsigned getSetCCNumber(unsigned Opcode) {
768   switch(Opcode) {
769   default: assert(0 && "Unknown setcc instruction!");
770   case Instruction::SetEQ: return 0;
771   case Instruction::SetNE: return 1;
772   case Instruction::SetLT: return 2;
773   case Instruction::SetGE: return 3;
774   case Instruction::SetGT: return 4;
775   case Instruction::SetLE: return 5;
776   }
777 }
778
779 // LLVM  -> X86 signed  X86 unsigned
780 // -----    ----------  ------------
781 // seteq -> sete        sete
782 // setne -> setne       setne
783 // setlt -> setl        setb
784 // setge -> setge       setae
785 // setgt -> setg        seta
786 // setle -> setle       setbe
787 // ----
788 //          sets                       // Used by comparison with 0 optimization
789 //          setns
790 static const unsigned SetCCOpcodeTab[2][8] = {
791   { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
792     0, 0 },
793   { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
794     X86::SETSr, X86::SETNSr },
795 };
796
797 // EmitComparison - This function emits a comparison of the two operands,
798 // returning the extended setcc code to use.
799 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
800                               MachineBasicBlock *MBB,
801                               MachineBasicBlock::iterator IP) {
802   // The arguments are already supposed to be of the same type.
803   const Type *CompTy = Op0->getType();
804   unsigned Class = getClassB(CompTy);
805   unsigned Op0r = getReg(Op0, MBB, IP);
806
807   // Special case handling of: cmp R, i
808   if (Class == cByte || Class == cShort || Class == cInt)
809     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
810       uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
811
812       // Mask off any upper bits of the constant, if there are any...
813       Op1v &= (1ULL << (8 << Class)) - 1;
814
815       // If this is a comparison against zero, emit more efficient code.  We
816       // can't handle unsigned comparisons against zero unless they are == or
817       // !=.  These should have been strength reduced already anyway.
818       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
819         static const unsigned TESTTab[] = {
820           X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
821         };
822         BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
823
824         if (OpNum == 2) return 6;   // Map jl -> js
825         if (OpNum == 3) return 7;   // Map jg -> jns
826         return OpNum;
827       }
828
829       static const unsigned CMPTab[] = {
830         X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
831       };
832
833       BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
834       return OpNum;
835     }
836
837   // Special case handling of comparison against +/- 0.0
838   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
839     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
840       BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
841       BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
842       BuildMI(*MBB, IP, X86::SAHF, 1);
843       return OpNum;
844     }
845
846   unsigned Op1r = getReg(Op1, MBB, IP);
847   switch (Class) {
848   default: assert(0 && "Unknown type class!");
849     // Emit: cmp <var1>, <var2> (do the comparison).  We can
850     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
851     // 32-bit.
852   case cByte:
853     BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
854     break;
855   case cShort:
856     BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
857     break;
858   case cInt:
859     BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
860     break;
861   case cFP:
862     BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
863     BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
864     BuildMI(*MBB, IP, X86::SAHF, 1);
865     break;
866
867   case cLong:
868     if (OpNum < 2) {    // seteq, setne
869       unsigned LoTmp = makeAnotherReg(Type::IntTy);
870       unsigned HiTmp = makeAnotherReg(Type::IntTy);
871       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
872       BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
873       BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
874       BuildMI(*MBB, IP, X86::OR32rr,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
875       break;  // Allow the sete or setne to be generated from flags set by OR
876     } else {
877       // Emit a sequence of code which compares the high and low parts once
878       // each, then uses a conditional move to handle the overflow case.  For
879       // example, a setlt for long would generate code like this:
880       //
881       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
882       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
883       // dest = hi(op1) == hi(op2) ? AL : BL;
884       //
885
886       // FIXME: This would be much better if we had hierarchical register
887       // classes!  Until then, hardcode registers so that we can deal with their
888       // aliases (because we don't have conditional byte moves).
889       //
890       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
891       BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
892       BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
893       BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
894       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
895       BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
896       BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
897                                                    .addReg(X86::AX);
898       // NOTE: visitSetCondInst knows that the value is dumped into the BL
899       // register at this point for long values...
900       return OpNum;
901     }
902   }
903   return OpNum;
904 }
905
906 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
907 /// register, then move it to wherever the result should be. 
908 ///
909 void ISel::visitSetCondInst(SetCondInst &I) {
910   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
911
912   unsigned DestReg = getReg(I);
913   MachineBasicBlock::iterator MII = BB->end();
914   emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
915                      DestReg);
916 }
917
918 /// emitSetCCOperation - Common code shared between visitSetCondInst and
919 /// constant expression support.
920 ///
921 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
922                               MachineBasicBlock::iterator IP,
923                               Value *Op0, Value *Op1, unsigned Opcode,
924                               unsigned TargetReg) {
925   unsigned OpNum = getSetCCNumber(Opcode);
926   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
927
928   const Type *CompTy = Op0->getType();
929   unsigned CompClass = getClassB(CompTy);
930   bool isSigned = CompTy->isSigned() && CompClass != cFP;
931
932   if (CompClass != cLong || OpNum < 2) {
933     // Handle normal comparisons with a setcc instruction...
934     BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
935   } else {
936     // Handle long comparisons by copying the value which is already in BL into
937     // the register we want...
938     BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
939   }
940 }
941
942 void ISel::visitSelectInst(SelectInst &SI) {
943   unsigned DestReg = getReg(SI);
944   MachineBasicBlock::iterator MII = BB->end();
945   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
946                       SI.getFalseValue(), DestReg);
947 }
948  
949 /// emitSelect - Common code shared between visitSelectInst and the constant
950 /// expression support.
951 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
952                                MachineBasicBlock::iterator IP,
953                                Value *Cond, Value *TrueVal, Value *FalseVal,
954                                unsigned DestReg) {
955   unsigned SelectClass = getClassB(TrueVal->getType());
956   
957   // We don't support 8-bit conditional moves.  If we have incoming constants,
958   // transform them into 16-bit constants to avoid having a run-time conversion.
959   if (SelectClass == cByte) {
960     if (Constant *T = dyn_cast<Constant>(TrueVal))
961       TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
962     if (Constant *F = dyn_cast<Constant>(FalseVal))
963       FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
964   }
965
966   // Get the value being branched on, and use it to set the condition codes.
967   unsigned CondReg = getReg(Cond, MBB, IP);
968   BuildMI(*MBB, IP, X86::CMP8ri, 2).addReg(CondReg).addImm(0);
969
970   unsigned TrueReg  = getReg(TrueVal, MBB, IP);
971   unsigned FalseReg = getReg(FalseVal, MBB, IP);
972   unsigned RealDestReg = DestReg;
973   unsigned Opcode;
974
975   switch (SelectClass) {
976   case cFP:
977     assert(0 && "We don't support floating point selects yet, they should "
978            "have been lowered!");
979   case cByte:
980   case cShort:
981     Opcode = X86::CMOVE16rr;
982     break;
983   case cInt:
984   case cLong:
985     Opcode = X86::CMOVE32rr;
986     break;
987   }
988
989   // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves.  Because of
990   // this, we have to promote the incoming values to 16 bits, perform a 16-bit
991   // cmove, then truncate the result.
992   if (SelectClass == cByte) {
993     DestReg = makeAnotherReg(Type::ShortTy);
994     if (getClassB(TrueVal->getType()) == cByte) {
995       // Promote the true value, by storing it into AL, and reading from AX.
996       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
997       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
998       TrueReg = makeAnotherReg(Type::ShortTy);
999       BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1000     }
1001     if (getClassB(FalseVal->getType()) == cByte) {
1002       // Promote the true value, by storing it into CL, and reading from CX.
1003       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1004       BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1005       FalseReg = makeAnotherReg(Type::ShortTy);
1006       BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1007     }
1008   }
1009
1010   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1011
1012   switch (SelectClass) {
1013   case cByte:
1014     // We did the computation with 16-bit registers.  Truncate back to our
1015     // result by copying into AX then copying out AL.
1016     BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1017     BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1018     break;
1019   case cLong:
1020     // Move the upper half of the value as well.
1021     BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1022     break;
1023   }
1024 }
1025
1026
1027
1028 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1029 /// operand, in the specified target register.
1030 ///
1031 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1032   bool isUnsigned = VR.Ty->isUnsigned();
1033
1034   // Make sure we have the register number for this value...
1035   unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
1036
1037   switch (getClassB(VR.Ty)) {
1038   case cByte:
1039     // Extend value into target register (8->32)
1040     if (isUnsigned)
1041       BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1042     else
1043       BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1044     break;
1045   case cShort:
1046     // Extend value into target register (16->32)
1047     if (isUnsigned)
1048       BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1049     else
1050       BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1051     break;
1052   case cInt:
1053     // Move value into target register (32->32)
1054     BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1055     break;
1056   default:
1057     assert(0 && "Unpromotable operand class in promote32");
1058   }
1059 }
1060
1061 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
1062 /// we have the following possibilities:
1063 ///
1064 ///   ret void: No return value, simply emit a 'ret' instruction
1065 ///   ret sbyte, ubyte : Extend value into EAX and return
1066 ///   ret short, ushort: Extend value into EAX and return
1067 ///   ret int, uint    : Move value into EAX and return
1068 ///   ret pointer      : Move value into EAX and return
1069 ///   ret long, ulong  : Move value into EAX/EDX and return
1070 ///   ret float/double : Top of FP stack
1071 ///
1072 void ISel::visitReturnInst(ReturnInst &I) {
1073   if (I.getNumOperands() == 0) {
1074     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1075     return;
1076   }
1077
1078   Value *RetVal = I.getOperand(0);
1079   unsigned RetReg = getReg(RetVal);
1080   switch (getClassB(RetVal->getType())) {
1081   case cByte:   // integral return values: extend or move into EAX and return
1082   case cShort:
1083   case cInt:
1084     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
1085     // Declare that EAX is live on exit
1086     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1087     break;
1088   case cFP:                   // Floats & Doubles: Return in ST(0)
1089     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1090     // Declare that top-of-stack is live on exit
1091     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1092     break;
1093   case cLong:
1094     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1095     BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1096     // Declare that EAX & EDX are live on exit
1097     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1098       .addReg(X86::ESP);
1099     break;
1100   default:
1101     visitInstruction(I);
1102   }
1103   // Emit a 'ret' instruction
1104   BuildMI(BB, X86::RET, 0);
1105 }
1106
1107 // getBlockAfter - Return the basic block which occurs lexically after the
1108 // specified one.
1109 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1110   Function::iterator I = BB; ++I;  // Get iterator to next block
1111   return I != BB->getParent()->end() ? &*I : 0;
1112 }
1113
1114 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1115 /// that since code layout is frozen at this point, that if we are trying to
1116 /// jump to a block that is the immediate successor of the current block, we can
1117 /// just make a fall-through (but we don't currently).
1118 ///
1119 void ISel::visitBranchInst(BranchInst &BI) {
1120   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1121
1122   if (!BI.isConditional()) {  // Unconditional branch?
1123     if (BI.getSuccessor(0) != NextBB)
1124       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1125     return;
1126   }
1127
1128   // See if we can fold the setcc into the branch itself...
1129   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1130   if (SCI == 0) {
1131     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1132     // computed some other way...
1133     unsigned condReg = getReg(BI.getCondition());
1134     BuildMI(BB, X86::CMP8ri, 2).addReg(condReg).addImm(0);
1135     if (BI.getSuccessor(1) == NextBB) {
1136       if (BI.getSuccessor(0) != NextBB)
1137         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1138     } else {
1139       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1140       
1141       if (BI.getSuccessor(0) != NextBB)
1142         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1143     }
1144     return;
1145   }
1146
1147   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1148   MachineBasicBlock::iterator MII = BB->end();
1149   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1150
1151   const Type *CompTy = SCI->getOperand(0)->getType();
1152   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1153   
1154
1155   // LLVM  -> X86 signed  X86 unsigned
1156   // -----    ----------  ------------
1157   // seteq -> je          je
1158   // setne -> jne         jne
1159   // setlt -> jl          jb
1160   // setge -> jge         jae
1161   // setgt -> jg          ja
1162   // setle -> jle         jbe
1163   // ----
1164   //          js                  // Used by comparison with 0 optimization
1165   //          jns
1166
1167   static const unsigned OpcodeTab[2][8] = {
1168     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1169     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1170       X86::JS, X86::JNS },
1171   };
1172   
1173   if (BI.getSuccessor(0) != NextBB) {
1174     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1175     if (BI.getSuccessor(1) != NextBB)
1176       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1177   } else {
1178     // Change to the inverse condition...
1179     if (BI.getSuccessor(1) != NextBB) {
1180       OpNum ^= 1;
1181       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1182     }
1183   }
1184 }
1185
1186
1187 /// doCall - This emits an abstract call instruction, setting up the arguments
1188 /// and the return value as appropriate.  For the actual function call itself,
1189 /// it inserts the specified CallMI instruction into the stream.
1190 ///
1191 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1192                   const std::vector<ValueRecord> &Args) {
1193
1194   // Count how many bytes are to be pushed on the stack...
1195   unsigned NumBytes = 0;
1196
1197   if (!Args.empty()) {
1198     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1199       switch (getClassB(Args[i].Ty)) {
1200       case cByte: case cShort: case cInt:
1201         NumBytes += 4; break;
1202       case cLong:
1203         NumBytes += 8; break;
1204       case cFP:
1205         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1206         break;
1207       default: assert(0 && "Unknown class!");
1208       }
1209
1210     // Adjust the stack pointer for the new arguments...
1211     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1212
1213     // Arguments go on the stack in reverse order, as specified by the ABI.
1214     unsigned ArgOffset = 0;
1215     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1216       unsigned ArgReg;
1217       switch (getClassB(Args[i].Ty)) {
1218       case cByte:
1219       case cShort:
1220         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1221           // Zero/Sign extend constant, then stuff into memory.
1222           ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1223           Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1224           addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1225             .addImm(Val->getRawValue() & 0xFFFFFFFF);
1226         } else {
1227           // Promote arg to 32 bits wide into a temporary register...
1228           ArgReg = makeAnotherReg(Type::UIntTy);
1229           promote32(ArgReg, Args[i]);
1230           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1231                        X86::ESP, ArgOffset).addReg(ArgReg);
1232         }
1233         break;
1234       case cInt:
1235         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1236           unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1237           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1238                        X86::ESP, ArgOffset).addImm(Val);
1239         } else {
1240           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1241           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1242                        X86::ESP, ArgOffset).addReg(ArgReg);
1243         }
1244         break;
1245       case cLong:
1246         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1247         addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1248                      X86::ESP, ArgOffset).addReg(ArgReg);
1249         addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1250                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1251         ArgOffset += 4;        // 8 byte entry, not 4.
1252         break;
1253         
1254       case cFP:
1255         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1256         if (Args[i].Ty == Type::FloatTy) {
1257           addRegOffset(BuildMI(BB, X86::FST32m, 5),
1258                        X86::ESP, ArgOffset).addReg(ArgReg);
1259         } else {
1260           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1261           addRegOffset(BuildMI(BB, X86::FST64m, 5),
1262                        X86::ESP, ArgOffset).addReg(ArgReg);
1263           ArgOffset += 4;       // 8 byte entry, not 4.
1264         }
1265         break;
1266
1267       default: assert(0 && "Unknown class!");
1268       }
1269       ArgOffset += 4;
1270     }
1271   } else {
1272     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1273   }
1274
1275   BB->push_back(CallMI);
1276
1277   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1278
1279   // If there is a return value, scavenge the result from the location the call
1280   // leaves it in...
1281   //
1282   if (Ret.Ty != Type::VoidTy) {
1283     unsigned DestClass = getClassB(Ret.Ty);
1284     switch (DestClass) {
1285     case cByte:
1286     case cShort:
1287     case cInt: {
1288       // Integral results are in %eax, or the appropriate portion
1289       // thereof.
1290       static const unsigned regRegMove[] = {
1291         X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1292       };
1293       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1294       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1295       break;
1296     }
1297     case cFP:     // Floating-point return values live in %ST(0)
1298       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1299       break;
1300     case cLong:   // Long values are left in EDX:EAX
1301       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1302       BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1303       break;
1304     default: assert(0 && "Unknown class!");
1305     }
1306   }
1307 }
1308
1309
1310 /// visitCallInst - Push args on stack and do a procedure call instruction.
1311 void ISel::visitCallInst(CallInst &CI) {
1312   MachineInstr *TheCall;
1313   if (Function *F = CI.getCalledFunction()) {
1314     // Is it an intrinsic function call?
1315     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1316       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1317       return;
1318     }
1319
1320     // Emit a CALL instruction with PC-relative displacement.
1321     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1322   } else {  // Emit an indirect call...
1323     unsigned Reg = getReg(CI.getCalledValue());
1324     TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1325   }
1326
1327   std::vector<ValueRecord> Args;
1328   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1329     Args.push_back(ValueRecord(CI.getOperand(i)));
1330
1331   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1332   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1333 }         
1334
1335
1336 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1337 /// function, lowering any calls to unknown intrinsic functions into the
1338 /// equivalent LLVM code.
1339 ///
1340 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1341   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1342     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1343       if (CallInst *CI = dyn_cast<CallInst>(I++))
1344         if (Function *F = CI->getCalledFunction())
1345           switch (F->getIntrinsicID()) {
1346           case Intrinsic::not_intrinsic:
1347           case Intrinsic::vastart:
1348           case Intrinsic::vacopy:
1349           case Intrinsic::vaend:
1350           case Intrinsic::returnaddress:
1351           case Intrinsic::frameaddress:
1352           case Intrinsic::memcpy:
1353           case Intrinsic::memset:
1354             // We directly implement these intrinsics
1355             break;
1356           default:
1357             // All other intrinsic calls we must lower.
1358             Instruction *Before = CI->getPrev();
1359             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1360             if (Before) {        // Move iterator to instruction after call
1361               I = Before;  ++I;
1362             } else {
1363               I = BB->begin();
1364             }
1365           }
1366
1367 }
1368
1369 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1370   unsigned TmpReg1, TmpReg2;
1371   switch (ID) {
1372   case Intrinsic::vastart:
1373     // Get the address of the first vararg value...
1374     TmpReg1 = getReg(CI);
1375     addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1376     return;
1377
1378   case Intrinsic::vacopy:
1379     TmpReg1 = getReg(CI);
1380     TmpReg2 = getReg(CI.getOperand(1));
1381     BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1382     return;
1383   case Intrinsic::vaend: return;   // Noop on X86
1384
1385   case Intrinsic::returnaddress:
1386   case Intrinsic::frameaddress:
1387     TmpReg1 = getReg(CI);
1388     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1389       if (ID == Intrinsic::returnaddress) {
1390         // Just load the return address
1391         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1392                           ReturnAddressIndex);
1393       } else {
1394         addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1395                           ReturnAddressIndex, -4);
1396       }
1397     } else {
1398       // Values other than zero are not implemented yet.
1399       BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1400     }
1401     return;
1402
1403   case Intrinsic::memcpy: {
1404     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1405     unsigned Align = 1;
1406     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1407       Align = AlignC->getRawValue();
1408       if (Align == 0) Align = 1;
1409     }
1410
1411     // Turn the byte code into # iterations
1412     unsigned CountReg;
1413     unsigned Opcode;
1414     switch (Align & 3) {
1415     case 2:   // WORD aligned
1416       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1417         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1418       } else {
1419         CountReg = makeAnotherReg(Type::IntTy);
1420         unsigned ByteReg = getReg(CI.getOperand(3));
1421         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1422       }
1423       Opcode = X86::REP_MOVSW;
1424       break;
1425     case 0:   // DWORD aligned
1426       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1427         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1428       } else {
1429         CountReg = makeAnotherReg(Type::IntTy);
1430         unsigned ByteReg = getReg(CI.getOperand(3));
1431         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1432       }
1433       Opcode = X86::REP_MOVSD;
1434       break;
1435     default:  // BYTE aligned
1436       CountReg = getReg(CI.getOperand(3));
1437       Opcode = X86::REP_MOVSB;
1438       break;
1439     }
1440
1441     // No matter what the alignment is, we put the source in ESI, the
1442     // destination in EDI, and the count in ECX.
1443     TmpReg1 = getReg(CI.getOperand(1));
1444     TmpReg2 = getReg(CI.getOperand(2));
1445     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1446     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1447     BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1448     BuildMI(BB, Opcode, 0);
1449     return;
1450   }
1451   case Intrinsic::memset: {
1452     assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1453     unsigned Align = 1;
1454     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1455       Align = AlignC->getRawValue();
1456       if (Align == 0) Align = 1;
1457     }
1458
1459     // Turn the byte code into # iterations
1460     unsigned CountReg;
1461     unsigned Opcode;
1462     if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1463       unsigned Val = ValC->getRawValue() & 255;
1464
1465       // If the value is a constant, then we can potentially use larger copies.
1466       switch (Align & 3) {
1467       case 2:   // WORD aligned
1468         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1469           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1470         } else {
1471           CountReg = makeAnotherReg(Type::IntTy);
1472           unsigned ByteReg = getReg(CI.getOperand(3));
1473           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1474         }
1475         BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1476         Opcode = X86::REP_STOSW;
1477         break;
1478       case 0:   // DWORD aligned
1479         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1480           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1481         } else {
1482           CountReg = makeAnotherReg(Type::IntTy);
1483           unsigned ByteReg = getReg(CI.getOperand(3));
1484           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1485         }
1486         Val = (Val << 8) | Val;
1487         BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1488         Opcode = X86::REP_STOSD;
1489         break;
1490       default:  // BYTE aligned
1491         CountReg = getReg(CI.getOperand(3));
1492         BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1493         Opcode = X86::REP_STOSB;
1494         break;
1495       }
1496     } else {
1497       // If it's not a constant value we are storing, just fall back.  We could
1498       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1499       unsigned ValReg = getReg(CI.getOperand(2));
1500       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1501       CountReg = getReg(CI.getOperand(3));
1502       Opcode = X86::REP_STOSB;
1503     }
1504
1505     // No matter what the alignment is, we put the source in ESI, the
1506     // destination in EDI, and the count in ECX.
1507     TmpReg1 = getReg(CI.getOperand(1));
1508     //TmpReg2 = getReg(CI.getOperand(2));
1509     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1510     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1511     BuildMI(BB, Opcode, 0);
1512     return;
1513   }
1514
1515   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1516   }
1517 }
1518
1519 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1520   if (LI.getParent() != User.getParent())
1521     return false;
1522   BasicBlock::iterator It = &LI;
1523   // Check all of the instructions between the load and the user.  We should
1524   // really use alias analysis here, but for now we just do something simple.
1525   for (++It; It != BasicBlock::iterator(&User); ++It) {
1526     switch (It->getOpcode()) {
1527     case Instruction::Free:
1528     case Instruction::Store:
1529     case Instruction::Call:
1530     case Instruction::Invoke:
1531       return false;
1532     }
1533   }
1534   return true;
1535 }
1536
1537
1538 /// visitSimpleBinary - Implement simple binary operators for integral types...
1539 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1540 /// Xor.
1541 ///
1542 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1543   unsigned DestReg = getReg(B);
1544   MachineBasicBlock::iterator MI = BB->end();
1545   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1546
1547   // Special case: op Reg, load [mem]
1548   if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1549     if (!B.swapOperands())
1550       std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
1551
1552   unsigned Class = getClassB(B.getType());
1553   if (isa<LoadInst>(Op1) && Class < cFP &&
1554       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1555
1556     static const unsigned OpcodeTab[][3] = {
1557       // Arithmetic operators
1558       { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm },  // ADD
1559       { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm },  // SUB
1560       
1561       // Bitwise operators
1562       { X86::AND8rm, X86::AND16rm, X86::AND32rm },  // AND
1563       { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm },  // OR
1564       { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm },  // XOR
1565     };
1566   
1567     assert(Class < cFP && "General code handles 64-bit integer types!");
1568     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1569
1570     unsigned BaseReg, Scale, IndexReg, Disp;
1571     getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1572                       Scale, IndexReg, Disp);
1573
1574     unsigned Op0r = getReg(Op0);
1575     addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1576                    BaseReg, Scale, IndexReg, Disp);
1577     return;
1578   }
1579
1580   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1581 }
1582
1583 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1584 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1585 /// Or, 4 for Xor.
1586 ///
1587 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1588 /// and constant expression support.
1589 ///
1590 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1591                                      MachineBasicBlock::iterator IP,
1592                                      Value *Op0, Value *Op1,
1593                                      unsigned OperatorClass, unsigned DestReg) {
1594   unsigned Class = getClassB(Op0->getType());
1595
1596   // sub 0, X -> neg X
1597   if (OperatorClass == 1 && Class != cLong)
1598     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1599       if (CI->isNullValue()) {
1600         unsigned op1Reg = getReg(Op1, MBB, IP);
1601         switch (Class) {
1602         default: assert(0 && "Unknown class for this function!");
1603         case cByte:
1604           BuildMI(*MBB, IP, X86::NEG8r, 1, DestReg).addReg(op1Reg);
1605           return;
1606         case cShort:
1607           BuildMI(*MBB, IP, X86::NEG16r, 1, DestReg).addReg(op1Reg);
1608           return;
1609         case cInt:
1610           BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg).addReg(op1Reg);
1611           return;
1612         }
1613       }
1614     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1615       if (CFP->isExactlyValue(-0.0)) {
1616         // -0.0 - X === -X
1617         unsigned op1Reg = getReg(Op1, MBB, IP);
1618         BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1619         return;
1620       }
1621
1622   // Special case: op Reg, <const>
1623   if (Class != cLong && isa<ConstantInt>(Op1)) {
1624     ConstantInt *Op1C = cast<ConstantInt>(Op1);
1625     unsigned Op0r = getReg(Op0, MBB, IP);
1626
1627     // xor X, -1 -> not X
1628     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1629       static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
1630       BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1631       return;
1632     }
1633
1634     // add X, -1 -> dec X
1635     if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1636       static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1637       BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1638       return;
1639     }
1640
1641     // add X, 1 -> inc X
1642     if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1643       static unsigned const DECTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1644       BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1645       return;
1646     }
1647   
1648     static const unsigned OpcodeTab[][3] = {
1649       // Arithmetic operators
1650       { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri },  // ADD
1651       { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri },  // SUB
1652     
1653       // Bitwise operators
1654       { X86::AND8ri, X86::AND16ri, X86::AND32ri },  // AND
1655       { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri },  // OR
1656       { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri },  // XOR
1657     };
1658   
1659     assert(Class < cFP && "General code handles 64-bit integer types!");
1660     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1661
1662
1663     uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1664     BuildMI(*MBB, IP, Opcode, 5, DestReg).addReg(Op0r).addImm(Op1v);
1665     return;
1666   }
1667
1668   // Finally, handle the general case now.
1669   static const unsigned OpcodeTab[][4] = {
1670     // Arithmetic operators
1671     { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD },  // ADD
1672     { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB },  // SUB
1673       
1674     // Bitwise operators
1675     { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 },  // AND
1676     { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 },  // OR
1677     { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 },  // XOR
1678   };
1679     
1680   bool isLong = false;
1681   if (Class == cLong) {
1682     isLong = true;
1683     Class = cInt;          // Bottom 32 bits are handled just like ints
1684   }
1685     
1686   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1687   assert(Opcode && "Floating point arguments to logical inst?");
1688   unsigned Op0r = getReg(Op0, MBB, IP);
1689   unsigned Op1r = getReg(Op1, MBB, IP);
1690   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1691     
1692   if (isLong) {        // Handle the upper 32 bits of long values...
1693     static const unsigned TopTab[] = {
1694       X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1695     };
1696     BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1697             DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1698   }
1699 }
1700
1701 /// doMultiply - Emit appropriate instructions to multiply together the
1702 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1703 /// result should be given as DestTy.
1704 ///
1705 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1706                       unsigned DestReg, const Type *DestTy,
1707                       unsigned op0Reg, unsigned op1Reg) {
1708   unsigned Class = getClass(DestTy);
1709   switch (Class) {
1710   case cFP:              // Floating point multiply
1711     BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1712     return;
1713   case cInt:
1714   case cShort:
1715     BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
1716       .addReg(op0Reg).addReg(op1Reg);
1717     return;
1718   case cByte:
1719     // Must use the MUL instruction, which forces use of AL...
1720     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1721     BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1722     BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1723     return;
1724   default:
1725   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1726   }
1727 }
1728
1729 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1730 // returns zero when the input is not exactly a power of two.
1731 static unsigned ExactLog2(unsigned Val) {
1732   if (Val == 0) return 0;
1733   unsigned Count = 0;
1734   while (Val != 1) {
1735     if (Val & 1) return 0;
1736     Val >>= 1;
1737     ++Count;
1738   }
1739   return Count+1;
1740 }
1741
1742 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1743                            MachineBasicBlock::iterator IP,
1744                            unsigned DestReg, const Type *DestTy,
1745                            unsigned op0Reg, unsigned ConstRHS) {
1746   unsigned Class = getClass(DestTy);
1747
1748   // If the element size is exactly a power of 2, use a shift to get it.
1749   if (unsigned Shift = ExactLog2(ConstRHS)) {
1750     switch (Class) {
1751     default: assert(0 && "Unknown class for this function!");
1752     case cByte:
1753       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1754       return;
1755     case cShort:
1756       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1757       return;
1758     case cInt:
1759       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1760       return;
1761     }
1762   }
1763   
1764   if (Class == cShort) {
1765     BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1766     return;
1767   } else if (Class == cInt) {
1768     BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1769     return;
1770   }
1771
1772   // Most general case, emit a normal multiply...
1773   static const unsigned MOVriTab[] = {
1774     X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
1775   };
1776
1777   unsigned TmpReg = makeAnotherReg(DestTy);
1778   BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
1779   
1780   // Emit a MUL to multiply the register holding the index by
1781   // elementSize, putting the result in OffsetReg.
1782   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1783 }
1784
1785 /// visitMul - Multiplies are not simple binary operators because they must deal
1786 /// with the EAX register explicitly.
1787 ///
1788 void ISel::visitMul(BinaryOperator &I) {
1789   unsigned Op0Reg  = getReg(I.getOperand(0));
1790   unsigned DestReg = getReg(I);
1791
1792   // Simple scalar multiply?
1793   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1794     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1795       unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1796       MachineBasicBlock::iterator MBBI = BB->end();
1797       doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1798     } else {
1799       unsigned Op1Reg  = getReg(I.getOperand(1));
1800       MachineBasicBlock::iterator MBBI = BB->end();
1801       doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1802     }
1803   } else {
1804     unsigned Op1Reg  = getReg(I.getOperand(1));
1805
1806     // Long value.  We have to do things the hard way...
1807     // Multiply the two low parts... capturing carry into EDX
1808     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1809     BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg);  // AL*BL
1810
1811     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1812     BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);     // AL*BL
1813     BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1814
1815     MachineBasicBlock::iterator MBBI = BB->end();
1816     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
1817     BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1818
1819     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1820     BuildMI(*BB, MBBI, X86::ADD32rr, 2,                  // AH*BL+(AL*BL >> 32)
1821             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1822     
1823     MBBI = BB->end();
1824     unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1825     BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1826     
1827     BuildMI(*BB, MBBI, X86::ADD32rr, 2,         // AL*BH + AH*BL + (AL*BL >> 32)
1828             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1829   }
1830 }
1831
1832
1833 /// visitDivRem - Handle division and remainder instructions... these
1834 /// instruction both require the same instructions to be generated, they just
1835 /// select the result from a different register.  Note that both of these
1836 /// instructions work differently for signed and unsigned operands.
1837 ///
1838 void ISel::visitDivRem(BinaryOperator &I) {
1839   unsigned Op0Reg = getReg(I.getOperand(0));
1840   unsigned Op1Reg = getReg(I.getOperand(1));
1841   unsigned ResultReg = getReg(I);
1842
1843   MachineBasicBlock::iterator IP = BB->end();
1844   emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1845                       I.getType(), ResultReg);
1846 }
1847
1848 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1849                                MachineBasicBlock::iterator IP,
1850                                unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1851                                const Type *Ty, unsigned ResultReg) {
1852   unsigned Class = getClass(Ty);
1853   switch (Class) {
1854   case cFP:              // Floating point divide
1855     if (isDiv) {
1856       BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1857     } else {               // Floating point remainder...
1858       MachineInstr *TheCall =
1859         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1860       std::vector<ValueRecord> Args;
1861       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1862       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1863       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1864     }
1865     return;
1866   case cLong: {
1867     static const char *FnName[] =
1868       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1869
1870     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1871     MachineInstr *TheCall =
1872       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1873
1874     std::vector<ValueRecord> Args;
1875     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1876     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1877     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1878     return;
1879   }
1880   case cByte: case cShort: case cInt:
1881     break;          // Small integrals, handled below...
1882   default: assert(0 && "Unknown class!");
1883   }
1884
1885   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1886   static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1887   static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1888   static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
1889   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1890
1891   static const unsigned DivOpcode[][4] = {
1892     { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 },  // Unsigned division
1893     { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 },  // Signed division
1894   };
1895
1896   bool isSigned   = Ty->isSigned();
1897   unsigned Reg    = Regs[Class];
1898   unsigned ExtReg = ExtRegs[Class];
1899
1900   // Put the first operand into one of the A registers...
1901   BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1902
1903   if (isSigned) {
1904     // Emit a sign extension instruction...
1905     unsigned ShiftResult = makeAnotherReg(Ty);
1906     BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1907     BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1908   } else {
1909     // If unsigned, emit a zeroing instruction... (reg = 0)
1910     BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
1911   }
1912
1913   // Emit the appropriate divide or remainder instruction...
1914   BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1915
1916   // Figure out which register we want to pick the result out of...
1917   unsigned DestReg = isDiv ? Reg : ExtReg;
1918   
1919   // Put the result into the destination register...
1920   BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1921 }
1922
1923
1924 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1925 /// for constant immediate shift values, and for constant immediate
1926 /// shift values equal to 1. Even the general case is sort of special,
1927 /// because the shift amount has to be in CL, not just any old register.
1928 ///
1929 void ISel::visitShiftInst(ShiftInst &I) {
1930   MachineBasicBlock::iterator IP = BB->end ();
1931   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1932                       I.getOpcode () == Instruction::Shl, I.getType (),
1933                       getReg (I));
1934 }
1935
1936 /// emitShiftOperation - Common code shared between visitShiftInst and
1937 /// constant expression support.
1938 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
1939                               MachineBasicBlock::iterator IP,
1940                               Value *Op, Value *ShiftAmount, bool isLeftShift,
1941                               const Type *ResultTy, unsigned DestReg) {
1942   unsigned SrcReg = getReg (Op, MBB, IP);
1943   bool isSigned = ResultTy->isSigned ();
1944   unsigned Class = getClass (ResultTy);
1945   
1946   static const unsigned ConstantOperand[][4] = {
1947     { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 },  // SHR
1948     { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 },  // SAR
1949     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 },  // SHL
1950     { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 },  // SAL = SHL
1951   };
1952
1953   static const unsigned NonConstantOperand[][4] = {
1954     { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL },  // SHR
1955     { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL },  // SAR
1956     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SHL
1957     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SAL = SHL
1958   };
1959
1960   // Longs, as usual, are handled specially...
1961   if (Class == cLong) {
1962     // If we have a constant shift, we can generate much more efficient code
1963     // than otherwise...
1964     //
1965     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1966       unsigned Amount = CUI->getValue();
1967       if (Amount < 32) {
1968         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1969         if (isLeftShift) {
1970           BuildMI(*MBB, IP, Opc[3], 3, 
1971               DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
1972           BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
1973         } else {
1974           BuildMI(*MBB, IP, Opc[3], 3,
1975               DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addImm(Amount);
1976           BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
1977         }
1978       } else {                 // Shifting more than 32 bits
1979         Amount -= 32;
1980         if (isLeftShift) {
1981           BuildMI(*MBB, IP, X86::SHL32ri, 2,
1982               DestReg + 1).addReg(SrcReg).addImm(Amount);
1983           BuildMI(*MBB, IP, X86::MOV32ri, 1,
1984               DestReg).addImm(0);
1985         } else {
1986           unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
1987           BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
1988           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
1989         }
1990       }
1991     } else {
1992       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1993
1994       if (!isLeftShift && isSigned) {
1995         // If this is a SHR of a Long, then we need to do funny sign extension
1996         // stuff.  TmpReg gets the value to use as the high-part if we are
1997         // shifting more than 32 bits.
1998         BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
1999       } else {
2000         // Other shifts use a fixed zero value if the shift is more than 32
2001         // bits.
2002         BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
2003       }
2004
2005       // Initialize CL with the shift amount...
2006       unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
2007       BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2008
2009       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2010       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2011       if (isLeftShift) {
2012         // TmpReg2 = shld inHi, inLo
2013         BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
2014                                                     .addReg(SrcReg);
2015         // TmpReg3 = shl  inLo, CL
2016         BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
2017
2018         // Set the flags to indicate whether the shift was by more than 32 bits.
2019         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2020
2021         // DestHi = (>32) ? TmpReg3 : TmpReg2;
2022         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
2023                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2024         // DestLo = (>32) ? TmpReg : TmpReg3;
2025         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2026             DestReg).addReg(TmpReg3).addReg(TmpReg);
2027       } else {
2028         // TmpReg2 = shrd inLo, inHi
2029         BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
2030                                                     .addReg(SrcReg+1);
2031         // TmpReg3 = s[ah]r  inHi, CL
2032         BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
2033                        .addReg(SrcReg+1);
2034
2035         // Set the flags to indicate whether the shift was by more than 32 bits.
2036         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2037
2038         // DestLo = (>32) ? TmpReg3 : TmpReg2;
2039         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
2040                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2041
2042         // DestHi = (>32) ? TmpReg : TmpReg3;
2043         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
2044                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2045       }
2046     }
2047     return;
2048   }
2049
2050   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2051     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2052     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2053
2054     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2055     BuildMI(*MBB, IP, Opc[Class], 2,
2056         DestReg).addReg(SrcReg).addImm(CUI->getValue());
2057   } else {                  // The shift amount is non-constant.
2058     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2059     BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2060
2061     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
2062     BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
2063   }
2064 }
2065
2066
2067 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2068                              unsigned &IndexReg, unsigned &Disp) {
2069   BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2070   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2071     if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2072                        BaseReg, Scale, IndexReg, Disp))
2073       return;
2074   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2075     if (CE->getOpcode() == Instruction::GetElementPtr)
2076       if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2077                         BaseReg, Scale, IndexReg, Disp))
2078         return;
2079   }
2080
2081   // If it's not foldable, reset addr mode.
2082   BaseReg = getReg(Addr);
2083   Scale = 1; IndexReg = 0; Disp = 0;
2084 }
2085
2086
2087 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
2088 /// instruction.  The load and store instructions are the only place where we
2089 /// need to worry about the memory layout of the target machine.
2090 ///
2091 void ISel::visitLoadInst(LoadInst &I) {
2092   // Check to see if this load instruction is going to be folded into a binary
2093   // instruction, like add.  If so, we don't want to emit it.  Wouldn't a real
2094   // pattern matching instruction selector be nice?
2095   if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
2096     Instruction *User = cast<Instruction>(I.use_back());
2097     switch (User->getOpcode()) {
2098     default: User = 0; break;
2099     case Instruction::Add:
2100     case Instruction::Sub:
2101     case Instruction::And:
2102     case Instruction::Or:
2103     case Instruction::Xor:
2104       break;
2105     }
2106
2107     if (User) {
2108       // Okay, we found a user.  If the load is the first operand and there is
2109       // no second operand load, reverse the operand ordering.  Note that this
2110       // can fail for a subtract (ie, no change will be made).
2111       if (!isa<LoadInst>(User->getOperand(1)))
2112         cast<BinaryOperator>(User)->swapOperands();
2113       
2114       // Okay, now that everything is set up, if this load is used by the second
2115       // operand, and if there are no instructions that invalidate the load
2116       // before the binary operator, eliminate the load.
2117       if (User->getOperand(1) == &I &&
2118           isSafeToFoldLoadIntoInstruction(I, *User))
2119         return;   // Eliminate the load!
2120     }
2121   }
2122
2123   unsigned DestReg = getReg(I);
2124   unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2125   getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2126
2127   unsigned Class = getClassB(I.getType());
2128   if (Class == cLong) {
2129     addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2130                    BaseReg, Scale, IndexReg, Disp);
2131     addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2132                    BaseReg, Scale, IndexReg, Disp+4);
2133     return;
2134   }
2135
2136   static const unsigned Opcodes[] = {
2137     X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2138   };
2139   unsigned Opcode = Opcodes[Class];
2140   if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2141   addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2142                  BaseReg, Scale, IndexReg, Disp);
2143 }
2144
2145 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2146 /// instruction.
2147 ///
2148 void ISel::visitStoreInst(StoreInst &I) {
2149   unsigned BaseReg, Scale, IndexReg, Disp;
2150   getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2151
2152   const Type *ValTy = I.getOperand(0)->getType();
2153   unsigned Class = getClassB(ValTy);
2154
2155   if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2156     uint64_t Val = CI->getRawValue();
2157     if (Class == cLong) {
2158       addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2159                      BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2160       addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2161                      BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2162     } else {
2163       static const unsigned Opcodes[] = {
2164         X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2165       };
2166       unsigned Opcode = Opcodes[Class];
2167       addFullAddress(BuildMI(BB, Opcode, 5),
2168                      BaseReg, Scale, IndexReg, Disp).addImm(Val);
2169     }
2170   } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2171     addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2172                    BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2173   } else {    
2174     if (Class == cLong) {
2175       unsigned ValReg = getReg(I.getOperand(0));
2176       addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2177                      BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2178       addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2179                      BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2180     } else {
2181       unsigned ValReg = getReg(I.getOperand(0));
2182       static const unsigned Opcodes[] = {
2183         X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2184       };
2185       unsigned Opcode = Opcodes[Class];
2186       if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2187       addFullAddress(BuildMI(BB, Opcode, 1+4),
2188                      BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2189     }
2190   }
2191 }
2192
2193
2194 /// visitCastInst - Here we have various kinds of copying with or without sign
2195 /// extension going on.
2196 ///
2197 void ISel::visitCastInst(CastInst &CI) {
2198   Value *Op = CI.getOperand(0);
2199   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2200   // of the case are GEP instructions, then the cast does not need to be
2201   // generated explicitly, it will be folded into the GEP.
2202   if (CI.getType() == Type::LongTy &&
2203       (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2204     bool AllUsesAreGEPs = true;
2205     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2206       if (!isa<GetElementPtrInst>(*I)) {
2207         AllUsesAreGEPs = false;
2208         break;
2209       }        
2210
2211     // No need to codegen this cast if all users are getelementptr instrs...
2212     if (AllUsesAreGEPs) return;
2213   }
2214
2215   unsigned DestReg = getReg(CI);
2216   MachineBasicBlock::iterator MI = BB->end();
2217   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2218 }
2219
2220 /// emitCastOperation - Common code shared between visitCastInst and constant
2221 /// expression cast support.
2222 ///
2223 void ISel::emitCastOperation(MachineBasicBlock *BB,
2224                              MachineBasicBlock::iterator IP,
2225                              Value *Src, const Type *DestTy,
2226                              unsigned DestReg) {
2227   unsigned SrcReg = getReg(Src, BB, IP);
2228   const Type *SrcTy = Src->getType();
2229   unsigned SrcClass = getClassB(SrcTy);
2230   unsigned DestClass = getClassB(DestTy);
2231
2232   // Implement casts to bool by using compare on the operand followed by set if
2233   // not zero on the result.
2234   if (DestTy == Type::BoolTy) {
2235     switch (SrcClass) {
2236     case cByte:
2237       BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2238       break;
2239     case cShort:
2240       BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2241       break;
2242     case cInt:
2243       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2244       break;
2245     case cLong: {
2246       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2247       BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2248       break;
2249     }
2250     case cFP:
2251       BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2252       BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2253       BuildMI(*BB, IP, X86::SAHF, 1);
2254       break;
2255     }
2256
2257     // If the zero flag is not set, then the value is true, set the byte to
2258     // true.
2259     BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2260     return;
2261   }
2262
2263   static const unsigned RegRegMove[] = {
2264     X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2265   };
2266
2267   // Implement casts between values of the same type class (as determined by
2268   // getClass) by using a register-to-register move.
2269   if (SrcClass == DestClass) {
2270     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2271       BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2272     } else if (SrcClass == cFP) {
2273       if (SrcTy == Type::FloatTy) {  // double -> float
2274         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2275         BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2276       } else {                       // float -> double
2277         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2278                "Unknown cFP member!");
2279         // Truncate from double to float by storing to memory as short, then
2280         // reading it back.
2281         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2282         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2283         addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2284         addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
2285       }
2286     } else if (SrcClass == cLong) {
2287       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2288       BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
2289     } else {
2290       assert(0 && "Cannot handle this type of cast instruction!");
2291       abort();
2292     }
2293     return;
2294   }
2295
2296   // Handle cast of SMALLER int to LARGER int using a move with sign extension
2297   // or zero extension, depending on whether the source type was signed.
2298   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2299       SrcClass < DestClass) {
2300     bool isLong = DestClass == cLong;
2301     if (isLong) DestClass = cInt;
2302
2303     static const unsigned Opc[][4] = {
2304       { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2305       { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr }  // u
2306     };
2307     
2308     bool isUnsigned = SrcTy->isUnsigned();
2309     BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2310         DestReg).addReg(SrcReg);
2311
2312     if (isLong) {  // Handle upper 32 bits as appropriate...
2313       if (isUnsigned)     // Zero out top bits...
2314         BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2315       else                // Sign extend bottom half...
2316         BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
2317     }
2318     return;
2319   }
2320
2321   // Special case long -> int ...
2322   if (SrcClass == cLong && DestClass == cInt) {
2323     BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2324     return;
2325   }
2326   
2327   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2328   // move out of AX or AL.
2329   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2330       && SrcClass > DestClass) {
2331     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2332     BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2333     BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2334     return;
2335   }
2336
2337   // Handle casts from integer to floating point now...
2338   if (DestClass == cFP) {
2339     // Promote the integer to a type supported by FLD.  We do this because there
2340     // are no unsigned FLD instructions, so we must promote an unsigned value to
2341     // a larger signed value, then use FLD on the larger value.
2342     //
2343     const Type *PromoteType = 0;
2344     unsigned PromoteOpcode;
2345     unsigned RealDestReg = DestReg;
2346     switch (SrcTy->getPrimitiveID()) {
2347     case Type::BoolTyID:
2348     case Type::SByteTyID:
2349       // We don't have the facilities for directly loading byte sized data from
2350       // memory (even signed).  Promote it to 16 bits.
2351       PromoteType = Type::ShortTy;
2352       PromoteOpcode = X86::MOVSX16rr8;
2353       break;
2354     case Type::UByteTyID:
2355       PromoteType = Type::ShortTy;
2356       PromoteOpcode = X86::MOVZX16rr8;
2357       break;
2358     case Type::UShortTyID:
2359       PromoteType = Type::IntTy;
2360       PromoteOpcode = X86::MOVZX32rr16;
2361       break;
2362     case Type::UIntTyID: {
2363       // Make a 64 bit temporary... and zero out the top of it...
2364       unsigned TmpReg = makeAnotherReg(Type::LongTy);
2365       BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2366       BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
2367       SrcTy = Type::LongTy;
2368       SrcClass = cLong;
2369       SrcReg = TmpReg;
2370       break;
2371     }
2372     case Type::ULongTyID:
2373       // Don't fild into the read destination.
2374       DestReg = makeAnotherReg(Type::DoubleTy);
2375       break;
2376     default:  // No promotion needed...
2377       break;
2378     }
2379     
2380     if (PromoteType) {
2381       unsigned TmpReg = makeAnotherReg(PromoteType);
2382       unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
2383       BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2384       SrcTy = PromoteType;
2385       SrcClass = getClass(PromoteType);
2386       SrcReg = TmpReg;
2387     }
2388
2389     // Spill the integer to memory and reload it from there...
2390     int FrameIdx =
2391       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2392
2393     if (SrcClass == cLong) {
2394       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2395                         FrameIdx).addReg(SrcReg);
2396       addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2397                         FrameIdx, 4).addReg(SrcReg+1);
2398     } else {
2399       static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
2400       addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2401                         FrameIdx).addReg(SrcReg);
2402     }
2403
2404     static const unsigned Op2[] =
2405       { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
2406     addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2407
2408     // We need special handling for unsigned 64-bit integer sources.  If the
2409     // input number has the "sign bit" set, then we loaded it incorrectly as a
2410     // negative 64-bit number.  In this case, add an offset value.
2411     if (SrcTy == Type::ULongTy) {
2412       // Emit a test instruction to see if the dynamic input value was signed.
2413       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2414
2415       // If the sign bit is set, get a pointer to an offset, otherwise get a
2416       // pointer to a zero.
2417       MachineConstantPool *CP = F->getConstantPool();
2418       unsigned Zero = makeAnotherReg(Type::IntTy);
2419       Constant *Null = Constant::getNullValue(Type::UIntTy);
2420       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero), 
2421                                CP->getConstantPoolIndex(Null));
2422       unsigned Offset = makeAnotherReg(Type::IntTy);
2423       Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2424                                              
2425       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
2426                                CP->getConstantPoolIndex(OffsetCst));
2427       unsigned Addr = makeAnotherReg(Type::IntTy);
2428       BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
2429
2430       // Load the constant for an add.  FIXME: this could make an 'fadd' that
2431       // reads directly from memory, but we don't support these yet.
2432       unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2433       addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
2434
2435       BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2436                 .addReg(ConstReg).addReg(DestReg);
2437     }
2438
2439     return;
2440   }
2441
2442   // Handle casts from floating point to integer now...
2443   if (SrcClass == cFP) {
2444     // Change the floating point control register to use "round towards zero"
2445     // mode when truncating to an integer value.
2446     //
2447     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2448     addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
2449
2450     // Load the old value of the high byte of the control word...
2451     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2452     addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
2453                       CWFrameIdx, 1);
2454
2455     // Set the high part to be round to zero...
2456     addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
2457                       CWFrameIdx, 1).addImm(12);
2458
2459     // Reload the modified control word now...
2460     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2461     
2462     // Restore the memory image of control word to original value
2463     addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
2464                       CWFrameIdx, 1).addReg(HighPartOfCW);
2465
2466     // We don't have the facilities for directly storing byte sized data to
2467     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
2468     // larger classes because we only have signed FP stores.
2469     unsigned StoreClass  = DestClass;
2470     const Type *StoreTy  = DestTy;
2471     if (StoreClass == cByte || DestTy->isUnsigned())
2472       switch (StoreClass) {
2473       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
2474       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
2475       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2476       // The following treatment of cLong may not be perfectly right,
2477       // but it survives chains of casts of the form
2478       // double->ulong->double.
2479       case cLong:  StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2480       default: assert(0 && "Unknown store class!");
2481       }
2482
2483     // Spill the integer to memory and reload it from there...
2484     int FrameIdx =
2485       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2486
2487     static const unsigned Op1[] =
2488       { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
2489     addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2490                       FrameIdx).addReg(SrcReg);
2491
2492     if (DestClass == cLong) {
2493       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2494       addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
2495                         FrameIdx, 4);
2496     } else {
2497       static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
2498       addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2499     }
2500
2501     // Reload the original control word now...
2502     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2503     return;
2504   }
2505
2506   // Anything we haven't handled already, we can't (yet) handle at all.
2507   assert(0 && "Unhandled cast instruction!");
2508   abort();
2509 }
2510
2511 /// visitVANextInst - Implement the va_next instruction...
2512 ///
2513 void ISel::visitVANextInst(VANextInst &I) {
2514   unsigned VAList = getReg(I.getOperand(0));
2515   unsigned DestReg = getReg(I);
2516
2517   unsigned Size;
2518   switch (I.getArgType()->getPrimitiveID()) {
2519   default:
2520     std::cerr << I;
2521     assert(0 && "Error: bad type for va_next instruction!");
2522     return;
2523   case Type::PointerTyID:
2524   case Type::UIntTyID:
2525   case Type::IntTyID:
2526     Size = 4;
2527     break;
2528   case Type::ULongTyID:
2529   case Type::LongTyID:
2530   case Type::DoubleTyID:
2531     Size = 8;
2532     break;
2533   }
2534
2535   // Increment the VAList pointer...
2536   BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
2537 }
2538
2539 void ISel::visitVAArgInst(VAArgInst &I) {
2540   unsigned VAList = getReg(I.getOperand(0));
2541   unsigned DestReg = getReg(I);
2542
2543   switch (I.getType()->getPrimitiveID()) {
2544   default:
2545     std::cerr << I;
2546     assert(0 && "Error: bad type for va_next instruction!");
2547     return;
2548   case Type::PointerTyID:
2549   case Type::UIntTyID:
2550   case Type::IntTyID:
2551     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2552     break;
2553   case Type::ULongTyID:
2554   case Type::LongTyID:
2555     addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2556     addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
2557     break;
2558   case Type::DoubleTyID:
2559     addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
2560     break;
2561   }
2562 }
2563
2564 /// visitGetElementPtrInst - instruction-select GEP instructions
2565 ///
2566 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2567   // If this GEP instruction will be folded into all of its users, we don't need
2568   // to explicitly calculate it!
2569   unsigned A, B, C, D;
2570   if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2571     // Check all of the users of the instruction to see if they are loads and
2572     // stores.
2573     bool AllWillFold = true;
2574     for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2575       if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2576         if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2577             cast<Instruction>(*UI)->getOperand(0) == &I) {
2578           AllWillFold = false;
2579           break;
2580         }
2581
2582     // If the instruction is foldable, and will be folded into all users, don't
2583     // emit it!
2584     if (AllWillFold) return;
2585   }
2586
2587   unsigned outputReg = getReg(I);
2588   emitGEPOperation(BB, BB->end(), I.getOperand(0),
2589                    I.op_begin()+1, I.op_end(), outputReg);
2590 }
2591
2592 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2593 /// GEPTypes (the derived types being stepped through at each level).  On return
2594 /// from this function, if some indexes of the instruction are representable as
2595 /// an X86 lea instruction, the machine operands are put into the Ops
2596 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2597 /// lists.  Otherwise, GEPOps.size() is returned.  If this returns a an
2598 /// addressing mode that only partially consumes the input, the BaseReg input of
2599 /// the addressing mode must be left free.
2600 ///
2601 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2602 ///
2603 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2604                        std::vector<Value*> &GEPOps,
2605                        std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2606                        unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2607   const TargetData &TD = TM.getTargetData();
2608
2609   // Clear out the state we are working with...
2610   BaseReg = 0;    // No base register
2611   Scale = 1;      // Unit scale
2612   IndexReg = 0;   // No index register
2613   Disp = 0;       // No displacement
2614
2615   // While there are GEP indexes that can be folded into the current address,
2616   // keep processing them.
2617   while (!GEPTypes.empty()) {
2618     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2619       // It's a struct access.  CUI is the index into the structure,
2620       // which names the field. This index must have unsigned type.
2621       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2622       
2623       // Use the TargetData structure to pick out what the layout of the
2624       // structure is in memory.  Since the structure index must be constant, we
2625       // can get its value and use it to find the right byte offset from the
2626       // StructLayout class's list of structure member offsets.
2627       Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2628       GEPOps.pop_back();        // Consume a GEP operand
2629       GEPTypes.pop_back();
2630     } else {
2631       // It's an array or pointer access: [ArraySize x ElementType].
2632       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2633       Value *idx = GEPOps.back();
2634
2635       // idx is the index into the array.  Unlike with structure
2636       // indices, we may not know its actual value at code-generation
2637       // time.
2638       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2639
2640       // If idx is a constant, fold it into the offset.
2641       unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2642       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2643         Disp += TypeSize*CSI->getValue();
2644       } else {
2645         // If the index reg is already taken, we can't handle this index.
2646         if (IndexReg) return;
2647
2648         // If this is a size that we can handle, then add the index as 
2649         switch (TypeSize) {
2650         case 1: case 2: case 4: case 8:
2651           // These are all acceptable scales on X86.
2652           Scale = TypeSize;
2653           break;
2654         default:
2655           // Otherwise, we can't handle this scale
2656           return;
2657         }
2658
2659         if (CastInst *CI = dyn_cast<CastInst>(idx))
2660           if (CI->getOperand(0)->getType() == Type::IntTy ||
2661               CI->getOperand(0)->getType() == Type::UIntTy)
2662             idx = CI->getOperand(0);
2663
2664         IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2665       }
2666
2667       GEPOps.pop_back();        // Consume a GEP operand
2668       GEPTypes.pop_back();
2669     }
2670   }
2671
2672   // GEPTypes is empty, which means we have a single operand left.  See if we
2673   // can set it as the base register.
2674   //
2675   // FIXME: When addressing modes are more powerful/correct, we could load
2676   // global addresses directly as 32-bit immediates.
2677   assert(BaseReg == 0);
2678   BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2679   GEPOps.pop_back();        // Consume the last GEP operand
2680 }
2681
2682
2683 /// isGEPFoldable - Return true if the specified GEP can be completely
2684 /// folded into the addressing mode of a load/store or lea instruction.
2685 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2686                          Value *Src, User::op_iterator IdxBegin,
2687                          User::op_iterator IdxEnd, unsigned &BaseReg,
2688                          unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2689   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2690     Src = CPR->getValue();
2691
2692   std::vector<Value*> GEPOps;
2693   GEPOps.resize(IdxEnd-IdxBegin+1);
2694   GEPOps[0] = Src;
2695   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2696   
2697   std::vector<const Type*> GEPTypes;
2698   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2699                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2700
2701   MachineBasicBlock::iterator IP;
2702   if (MBB) IP = MBB->end();
2703   getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2704
2705   // We can fold it away iff the getGEPIndex call eliminated all operands.
2706   return GEPOps.empty();
2707 }
2708
2709 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2710                             MachineBasicBlock::iterator IP,
2711                             Value *Src, User::op_iterator IdxBegin,
2712                             User::op_iterator IdxEnd, unsigned TargetReg) {
2713   const TargetData &TD = TM.getTargetData();
2714   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2715     Src = CPR->getValue();
2716
2717   std::vector<Value*> GEPOps;
2718   GEPOps.resize(IdxEnd-IdxBegin+1);
2719   GEPOps[0] = Src;
2720   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2721   
2722   std::vector<const Type*> GEPTypes;
2723   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2724                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2725
2726   // Keep emitting instructions until we consume the entire GEP instruction.
2727   while (!GEPOps.empty()) {
2728     unsigned OldSize = GEPOps.size();
2729     unsigned BaseReg, Scale, IndexReg, Disp;
2730     getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2731     
2732     if (GEPOps.size() != OldSize) {
2733       // getGEPIndex consumed some of the input.  Build an LEA instruction here.
2734       unsigned NextTarget = 0;
2735       if (!GEPOps.empty()) {
2736         assert(BaseReg == 0 &&
2737            "getGEPIndex should have left the base register open for chaining!");
2738         NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2739       }
2740
2741       if (IndexReg == 0 && Disp == 0)
2742         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2743       else
2744         addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
2745                        BaseReg, Scale, IndexReg, Disp);
2746       --IP;
2747       TargetReg = NextTarget;
2748     } else if (GEPTypes.empty()) {
2749       // The getGEPIndex operation didn't want to build an LEA.  Check to see if
2750       // all operands are consumed but the base pointer.  If so, just load it
2751       // into the register.
2752       if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2753         BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
2754       } else {
2755         unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2756         BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2757       }
2758       break;                // we are now done
2759
2760     } else {
2761       // It's an array or pointer access: [ArraySize x ElementType].
2762       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2763       Value *idx = GEPOps.back();
2764       GEPOps.pop_back();        // Consume a GEP operand
2765       GEPTypes.pop_back();
2766
2767       // idx is the index into the array.  Unlike with structure
2768       // indices, we may not know its actual value at code-generation
2769       // time.
2770       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2771
2772       // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2773       // operand on X86.  Handle this case directly now...
2774       if (CastInst *CI = dyn_cast<CastInst>(idx))
2775         if (CI->getOperand(0)->getType() == Type::IntTy ||
2776             CI->getOperand(0)->getType() == Type::UIntTy)
2777           idx = CI->getOperand(0);
2778
2779       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2780       // must find the size of the pointed-to type (Not coincidentally, the next
2781       // type is the type of the elements in the array).
2782       const Type *ElTy = SqTy->getElementType();
2783       unsigned elementSize = TD.getTypeSize(ElTy);
2784
2785       // If idxReg is a constant, we don't need to perform the multiply!
2786       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2787         if (!CSI->isNullValue()) {
2788           unsigned Offset = elementSize*CSI->getValue();
2789           unsigned Reg = makeAnotherReg(Type::UIntTy);
2790           BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
2791                                 .addReg(Reg).addImm(Offset);
2792           --IP;            // Insert the next instruction before this one.
2793           TargetReg = Reg; // Codegen the rest of the GEP into this
2794         }
2795       } else if (elementSize == 1) {
2796         // If the element size is 1, we don't have to multiply, just add
2797         unsigned idxReg = getReg(idx, MBB, IP);
2798         unsigned Reg = makeAnotherReg(Type::UIntTy);
2799         BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
2800         --IP;            // Insert the next instruction before this one.
2801         TargetReg = Reg; // Codegen the rest of the GEP into this
2802       } else {
2803         unsigned idxReg = getReg(idx, MBB, IP);
2804         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2805
2806         // Make sure we can back the iterator up to point to the first
2807         // instruction emitted.
2808         MachineBasicBlock::iterator BeforeIt = IP;
2809         if (IP == MBB->begin())
2810           BeforeIt = MBB->end();
2811         else
2812           --BeforeIt;
2813         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2814
2815         // Emit an ADD to add OffsetReg to the basePtr.
2816         unsigned Reg = makeAnotherReg(Type::UIntTy);
2817         BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
2818                           .addReg(Reg).addReg(OffsetReg);
2819
2820         // Step to the first instruction of the multiply.
2821         if (BeforeIt == MBB->end())
2822           IP = MBB->begin();
2823         else
2824           IP = ++BeforeIt;
2825
2826         TargetReg = Reg; // Codegen the rest of the GEP into this
2827       }
2828     }
2829   }
2830 }
2831
2832
2833 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2834 /// frame manager, otherwise do it the hard way.
2835 ///
2836 void ISel::visitAllocaInst(AllocaInst &I) {
2837   // Find the data size of the alloca inst's getAllocatedType.
2838   const Type *Ty = I.getAllocatedType();
2839   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2840
2841   // If this is a fixed size alloca in the entry block for the function,
2842   // statically stack allocate the space.
2843   //
2844   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2845     if (I.getParent() == I.getParent()->getParent()->begin()) {
2846       TySize *= CUI->getValue();   // Get total allocated size...
2847       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2848       
2849       // Create a new stack object using the frame manager...
2850       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2851       addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
2852       return;
2853     }
2854   }
2855   
2856   // Create a register to hold the temporary result of multiplying the type size
2857   // constant by the variable amount.
2858   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2859   unsigned SrcReg1 = getReg(I.getArraySize());
2860   
2861   // TotalSizeReg = mul <numelements>, <TypeSize>
2862   MachineBasicBlock::iterator MBBI = BB->end();
2863   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2864
2865   // AddedSize = add <TotalSizeReg>, 15
2866   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2867   BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2868
2869   // AlignedSize = and <AddedSize>, ~15
2870   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2871   BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
2872   
2873   // Subtract size from stack pointer, thereby allocating some space.
2874   BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2875
2876   // Put a pointer to the space into the result register, by copying
2877   // the stack pointer.
2878   BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
2879
2880   // Inform the Frame Information that we have just allocated a variable-sized
2881   // object.
2882   F->getFrameInfo()->CreateVariableSizedObject();
2883 }
2884
2885 /// visitMallocInst - Malloc instructions are code generated into direct calls
2886 /// to the library malloc.
2887 ///
2888 void ISel::visitMallocInst(MallocInst &I) {
2889   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2890   unsigned Arg;
2891
2892   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2893     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2894   } else {
2895     Arg = makeAnotherReg(Type::UIntTy);
2896     unsigned Op0Reg = getReg(I.getOperand(0));
2897     MachineBasicBlock::iterator MBBI = BB->end();
2898     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2899   }
2900
2901   std::vector<ValueRecord> Args;
2902   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2903   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2904                                   1).addExternalSymbol("malloc", true);
2905   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2906 }
2907
2908
2909 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2910 /// function.
2911 ///
2912 void ISel::visitFreeInst(FreeInst &I) {
2913   std::vector<ValueRecord> Args;
2914   Args.push_back(ValueRecord(I.getOperand(0)));
2915   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2916                                   1).addExternalSymbol("free", true);
2917   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2918 }
2919    
2920 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2921 /// into a machine code representation is a very simple peep-hole fashion.  The
2922 /// generated code sucks but the implementation is nice and simple.
2923 ///
2924 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2925   return new ISel(TM);
2926 }