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