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