Do not use the inefficient, fixed function, CBW, CDQ, ... instructions
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 target
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "X86.h"
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Constants.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/SSARegMap.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Support/InstVisitor.h"
24
25 /// BMI - A special BuildMI variant that takes an iterator to insert the
26 /// instruction at as well as a basic block.  This is the version for when you
27 /// have a destination register in mind.
28 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
29                                       MachineBasicBlock::iterator &I,
30                                       int Opcode, unsigned NumOperands,
31                                       unsigned DestReg) {
32   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
33   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
34   I = MBB->insert(I, MI)+1;
35   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
36 }
37
38 /// BMI - A special BuildMI variant that takes an iterator to insert the
39 /// instruction at as well as a basic block.
40 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
41                                       MachineBasicBlock::iterator &I,
42                                       int Opcode, unsigned NumOperands) {
43   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
44   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
45   I = MBB->insert(I, MI)+1;
46   return MachineInstrBuilder(MI);
47 }
48
49
50 namespace {
51   struct ISel : public FunctionPass, InstVisitor<ISel> {
52     TargetMachine &TM;
53     MachineFunction *F;                 // The function we are compiling into
54     MachineBasicBlock *BB;              // The current MBB we are compiling
55     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
56
57     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
58
59     // MBBMap - Mapping between LLVM BB -> Machine BB
60     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
61
62     ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
63
64     /// runOnFunction - Top level implementation of instruction selection for
65     /// the entire function.
66     ///
67     bool runOnFunction(Function &Fn) {
68       F = &MachineFunction::construct(&Fn, TM);
69
70       // Create all of the machine basic blocks for the function...
71       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
72         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
73
74       BB = &F->front();
75
76       // Copy incoming arguments off of the stack...
77       LoadArgumentsToVirtualRegs(Fn);
78
79       // Instruction select everything except PHI nodes
80       visit(Fn);
81
82       // Select the PHI nodes
83       SelectPHINodes();
84
85       RegMap.clear();
86       MBBMap.clear();
87       F = 0;
88       return false;  // We never modify the LLVM itself.
89     }
90
91     virtual const char *getPassName() const {
92       return "X86 Simple Instruction Selection";
93     }
94
95     /// visitBasicBlock - This method is called when we are visiting a new basic
96     /// block.  This simply creates a new MachineBasicBlock to emit code into
97     /// and adds it to the current MachineFunction.  Subsequent visit* for
98     /// instructions will be invoked for all instructions in the basic block.
99     ///
100     void visitBasicBlock(BasicBlock &LLVM_BB) {
101       BB = MBBMap[&LLVM_BB];
102     }
103
104     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
105     /// from the stack into virtual registers.
106     ///
107     void LoadArgumentsToVirtualRegs(Function &F);
108
109     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
110     /// because we have to generate our sources into the source basic blocks,
111     /// not the current one.
112     ///
113     void SelectPHINodes();
114
115     // Visitation methods for various instructions.  These methods simply emit
116     // fixed X86 code for each instruction.
117     //
118
119     // Control flow operators
120     void visitReturnInst(ReturnInst &RI);
121     void visitBranchInst(BranchInst &BI);
122
123     struct ValueRecord {
124       unsigned Reg;
125       const Type *Ty;
126       ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
127     };
128     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
129                 const std::vector<ValueRecord> &Args);
130     void visitCallInst(CallInst &I);
131     void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
132
133     // Arithmetic operators
134     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
135     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
136     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
137     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
138                     unsigned DestReg, const Type *DestTy,
139                     unsigned Op0Reg, unsigned Op1Reg);
140     void visitMul(BinaryOperator &B);
141
142     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
143     void visitRem(BinaryOperator &B) { visitDivRem(B); }
144     void visitDivRem(BinaryOperator &B);
145
146     // Bitwise operators
147     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
148     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
149     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
150
151     // Comparison operators...
152     void visitSetCondInst(SetCondInst &I);
153     bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
154
155     // Memory Instructions
156     MachineInstr *doFPLoad(MachineBasicBlock *MBB,
157                            MachineBasicBlock::iterator &MBBI,
158                            const Type *Ty, unsigned DestReg);
159     void visitLoadInst(LoadInst &I);
160     void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
161     void visitStoreInst(StoreInst &I);
162     void visitGetElementPtrInst(GetElementPtrInst &I);
163     void visitAllocaInst(AllocaInst &I);
164     void visitMallocInst(MallocInst &I);
165     void visitFreeInst(FreeInst &I);
166     
167     // Other operators
168     void visitShiftInst(ShiftInst &I);
169     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
170     void visitCastInst(CastInst &I);
171     void visitVarArgInst(VarArgInst &I);
172
173     void visitInstruction(Instruction &I) {
174       std::cerr << "Cannot instruction select: " << I;
175       abort();
176     }
177
178     /// promote32 - Make a value 32-bits wide, and put it somewhere.
179     ///
180     void promote32(unsigned targetReg, const ValueRecord &VR);
181
182     /// EmitByteSwap - Byteswap SrcReg into DestReg.
183     ///
184     void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
185     
186     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
187     /// constant expression GEP support.
188     ///
189     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
190                           Value *Src, User::op_iterator IdxBegin,
191                           User::op_iterator IdxEnd, unsigned TargetReg);
192
193     /// emitCastOperation - Common code shared between visitCastInst and
194     /// constant expression cast support.
195     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
196                            Value *Src, const Type *DestTy, unsigned TargetReg);
197
198     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
199     /// and constant expression support.
200     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
201                                    MachineBasicBlock::iterator &IP,
202                                    Value *Op0, Value *Op1,
203                                    unsigned OperatorClass, unsigned TargetReg);
204
205     /// copyConstantToRegister - Output the instructions required to put the
206     /// specified constant into the specified register.
207     ///
208     void copyConstantToRegister(MachineBasicBlock *MBB,
209                                 MachineBasicBlock::iterator &MBBI,
210                                 Constant *C, unsigned Reg);
211
212     /// makeAnotherReg - This method returns the next register number we haven't
213     /// yet used.
214     ///
215     /// Long values are handled somewhat specially.  They are always allocated
216     /// as pairs of 32 bit integer values.  The register number returned is the
217     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
218     /// of the long value.
219     ///
220     unsigned makeAnotherReg(const Type *Ty) {
221       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
222         const TargetRegisterClass *RC =
223           TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
224         // Create the lower part
225         F->getSSARegMap()->createVirtualRegister(RC);
226         // Create the upper part.
227         return F->getSSARegMap()->createVirtualRegister(RC)-1;
228       }
229
230       // Add the mapping of regnumber => reg class to MachineFunction
231       const TargetRegisterClass *RC =
232         TM.getRegisterInfo()->getRegClassForType(Ty);
233       return F->getSSARegMap()->createVirtualRegister(RC);
234     }
235
236     /// getReg - This method turns an LLVM value into a register number.  This
237     /// is guaranteed to produce the same register number for a particular value
238     /// every time it is queried.
239     ///
240     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
241     unsigned getReg(Value *V) {
242       // Just append to the end of the current bb.
243       MachineBasicBlock::iterator It = BB->end();
244       return getReg(V, BB, It);
245     }
246     unsigned getReg(Value *V, MachineBasicBlock *MBB,
247                     MachineBasicBlock::iterator &IPt) {
248       unsigned &Reg = RegMap[V];
249       if (Reg == 0) {
250         Reg = makeAnotherReg(V->getType());
251         RegMap[V] = Reg;
252       }
253
254       // If this operand is a constant, emit the code to copy the constant into
255       // the register here...
256       //
257       if (Constant *C = dyn_cast<Constant>(V)) {
258         copyConstantToRegister(MBB, IPt, C, Reg);
259         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
260       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
261         // Move the address of the global into the register
262         BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
263         RegMap.erase(V);  // Assign a new name to this address if ref'd again
264       }
265
266       return Reg;
267     }
268   };
269 }
270
271 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
272 /// Representation.
273 ///
274 enum TypeClass {
275   cByte, cShort, cInt, cFP, cLong
276 };
277
278 /// getClass - Turn a primitive type into a "class" number which is based on the
279 /// size of the type, and whether or not it is floating point.
280 ///
281 static inline TypeClass getClass(const Type *Ty) {
282   switch (Ty->getPrimitiveID()) {
283   case Type::SByteTyID:
284   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
285   case Type::ShortTyID:
286   case Type::UShortTyID:  return cShort;     // Short operands are class #1
287   case Type::IntTyID:
288   case Type::UIntTyID:
289   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
290
291   case Type::FloatTyID:
292   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
293
294   case Type::LongTyID:
295   case Type::ULongTyID:   return cLong;      // Longs are class #4
296   default:
297     assert(0 && "Invalid type to getClass!");
298     return cByte;  // not reached
299   }
300 }
301
302 // getClassB - Just like getClass, but treat boolean values as bytes.
303 static inline TypeClass getClassB(const Type *Ty) {
304   if (Ty == Type::BoolTy) return cByte;
305   return getClass(Ty);
306 }
307
308
309 /// copyConstantToRegister - Output the instructions required to put the
310 /// specified constant into the specified register.
311 ///
312 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
313                                   MachineBasicBlock::iterator &IP,
314                                   Constant *C, unsigned R) {
315   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
316     unsigned Class = 0;
317     switch (CE->getOpcode()) {
318     case Instruction::GetElementPtr:
319       emitGEPOperation(MBB, IP, CE->getOperand(0),
320                        CE->op_begin()+1, CE->op_end(), R);
321       return;
322     case Instruction::Cast:
323       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
324       return;
325
326     case Instruction::Xor: ++Class; // FALL THROUGH
327     case Instruction::Or:  ++Class; // FALL THROUGH
328     case Instruction::And: ++Class; // FALL THROUGH
329     case Instruction::Sub: ++Class; // FALL THROUGH
330     case Instruction::Add:
331       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
332                                 Class, R);
333       return;
334
335     default:
336       std::cerr << "Offending expr: " << C << "\n";
337       assert(0 && "Constant expressions not yet handled!\n");
338     }
339   }
340
341   if (C->getType()->isIntegral()) {
342     unsigned Class = getClassB(C->getType());
343
344     if (Class == cLong) {
345       // Copy the value into the register pair.
346       uint64_t Val;
347       if (C->getType()->isSigned())
348         Val = cast<ConstantSInt>(C)->getValue();
349       else
350         Val = cast<ConstantUInt>(C)->getValue();
351
352       BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
353       BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
354       return;
355     }
356
357     assert(Class <= cInt && "Type not handled yet!");
358
359     static const unsigned IntegralOpcodeTab[] = {
360       X86::MOVir8, X86::MOVir16, X86::MOVir32
361     };
362
363     if (C->getType() == Type::BoolTy) {
364       BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
365     } else if (C->getType()->isSigned()) {
366       ConstantSInt *CSI = cast<ConstantSInt>(C);
367       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
368     } else {
369       ConstantUInt *CUI = cast<ConstantUInt>(C);
370       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
371     }
372   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
373     double Value = CFP->getValue();
374     if (Value == +0.0)
375       BMI(MBB, IP, X86::FLD0, 0, R);
376     else if (Value == +1.0)
377       BMI(MBB, IP, X86::FLD1, 0, R);
378     else {
379       // Otherwise we need to spill the constant to memory...
380       MachineConstantPool *CP = F->getConstantPool();
381       unsigned CPI = CP->getConstantPoolIndex(CFP);
382       addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
383     }
384
385   } else if (isa<ConstantPointerNull>(C)) {
386     // Copy zero (null pointer) to the register.
387     BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
388   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
389     unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
390     BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
391   } else {
392     std::cerr << "Offending constant: " << C << "\n";
393     assert(0 && "Type not handled yet!");
394   }
395 }
396
397 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
398 /// the stack into virtual registers.
399 ///
400 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
401   // Emit instructions to load the arguments...  On entry to a function on the
402   // X86, the stack frame looks like this:
403   //
404   // [ESP] -- return address
405   // [ESP + 4] -- first argument (leftmost lexically)
406   // [ESP + 8] -- second argument, if first argument is four bytes in size
407   //    ... 
408   //
409   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
410   MachineFrameInfo *MFI = F->getFrameInfo();
411
412   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
413     unsigned Reg = getReg(*I);
414     
415     int FI;          // Frame object index
416     switch (getClassB(I->getType())) {
417     case cByte:
418       FI = MFI->CreateFixedObject(1, ArgOffset);
419       addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
420       break;
421     case cShort:
422       FI = MFI->CreateFixedObject(2, ArgOffset);
423       addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
424       break;
425     case cInt:
426       FI = MFI->CreateFixedObject(4, ArgOffset);
427       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
428       break;
429     case cLong:
430       FI = MFI->CreateFixedObject(8, ArgOffset);
431       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
432       addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
433       ArgOffset += 4;   // longs require 4 additional bytes
434       break;
435     case cFP:
436       unsigned Opcode;
437       if (I->getType() == Type::FloatTy) {
438         Opcode = X86::FLDr32;
439         FI = MFI->CreateFixedObject(4, ArgOffset);
440       } else {
441         Opcode = X86::FLDr64;
442         FI = MFI->CreateFixedObject(8, ArgOffset);
443         ArgOffset += 4;   // doubles require 4 additional bytes
444       }
445       addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
446       break;
447     default:
448       assert(0 && "Unhandled argument type!");
449     }
450     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
451   }
452
453   // If the function takes variable number of arguments, add a frame offset for
454   // the start of the first vararg value... this is used to expand
455   // llvm.va_start.
456   if (Fn.getFunctionType()->isVarArg())
457     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
458 }
459
460
461 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
462 /// because we have to generate our sources into the source basic blocks, not
463 /// the current one.
464 ///
465 void ISel::SelectPHINodes() {
466   const TargetInstrInfo &TII = TM.getInstrInfo();
467   const Function &LF = *F->getFunction();  // The LLVM function...
468   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
469     const BasicBlock *BB = I;
470     MachineBasicBlock *MBB = MBBMap[I];
471
472     // Loop over all of the PHI nodes in the LLVM basic block...
473     unsigned NumPHIs = 0;
474     for (BasicBlock::const_iterator I = BB->begin();
475          PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
476
477       // Create a new machine instr PHI node, and insert it.
478       unsigned PHIReg = getReg(*PN);
479       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
480       MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
481
482       MachineInstr *LongPhiMI = 0;
483       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
484         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
485         MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
486       }
487
488       // PHIValues - Map of blocks to incoming virtual registers.  We use this
489       // so that we only initialize one incoming value for a particular block,
490       // even if the block has multiple entries in the PHI node.
491       //
492       std::map<MachineBasicBlock*, unsigned> PHIValues;
493
494       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
495         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
496         unsigned ValReg;
497         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
498           PHIValues.lower_bound(PredMBB);
499
500         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
501           // We already inserted an initialization of the register for this
502           // predecessor.  Recycle it.
503           ValReg = EntryIt->second;
504
505         } else {        
506           // Get the incoming value into a virtual register.  If it is not
507           // already available in a virtual register, insert the computation
508           // code into PredMBB
509           //
510           MachineBasicBlock::iterator PI = PredMBB->end();
511           while (PI != PredMBB->begin() &&
512                  TII.isTerminatorInstr((*(PI-1))->getOpcode()))
513             --PI;
514           ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
515
516           // Remember that we inserted a value for this PHI for this predecessor
517           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
518         }
519
520         PhiMI->addRegOperand(ValReg);
521         PhiMI->addMachineBasicBlockOperand(PredMBB);
522         if (LongPhiMI) {
523           LongPhiMI->addRegOperand(ValReg+1);
524           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
525         }
526       }
527     }
528   }
529 }
530
531 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
532 // the conditional branch instruction which is the only user of the cc
533 // instruction.  This is the case if the conditional branch is the only user of
534 // the setcc, and if the setcc is in the same basic block as the conditional
535 // branch.  We also don't handle long arguments below, so we reject them here as
536 // well.
537 //
538 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
539   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
540     if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
541         SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
542       const Type *Ty = SCI->getOperand(0)->getType();
543       if (Ty != Type::LongTy && Ty != Type::ULongTy)
544         return SCI;
545     }
546   return 0;
547 }
548
549 // Return a fixed numbering for setcc instructions which does not depend on the
550 // order of the opcodes.
551 //
552 static unsigned getSetCCNumber(unsigned Opcode) {
553   switch(Opcode) {
554   default: assert(0 && "Unknown setcc instruction!");
555   case Instruction::SetEQ: return 0;
556   case Instruction::SetNE: return 1;
557   case Instruction::SetLT: return 2;
558   case Instruction::SetGE: return 3;
559   case Instruction::SetGT: return 4;
560   case Instruction::SetLE: return 5;
561   }
562 }
563
564 // LLVM  -> X86 signed  X86 unsigned
565 // -----    ----------  ------------
566 // seteq -> sete        sete
567 // setne -> setne       setne
568 // setlt -> setl        setb
569 // setge -> setge       setae
570 // setgt -> setg        seta
571 // setle -> setle       setbe
572 static const unsigned SetCCOpcodeTab[2][6] = {
573   {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
574   {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
575 };
576
577 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
578
579   // The arguments are already supposed to be of the same type.
580   const Type *CompTy = Op0->getType();
581   bool isSigned = CompTy->isSigned();
582   unsigned Class = getClassB(CompTy);
583   unsigned Op0r = getReg(Op0);
584
585   // Special case handling of: cmp R, i
586   if (Class == cByte || Class == cShort || Class == cInt)
587     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
588       uint64_t Op1v;
589       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
590         Op1v = CSI->getValue();
591       else
592         Op1v = cast<ConstantUInt>(CI)->getValue();
593       // Mask off any upper bits of the constant, if there are any...
594       Op1v &= (1ULL << (8 << Class)) - 1;
595
596       switch (Class) {
597       case cByte:  BuildMI(BB, X86::CMPri8, 2).addReg(Op0r).addZImm(Op1v);break;
598       case cShort: BuildMI(BB, X86::CMPri16,2).addReg(Op0r).addZImm(Op1v);break;
599       case cInt:   BuildMI(BB, X86::CMPri32,2).addReg(Op0r).addZImm(Op1v);break;
600       default:
601         assert(0 && "Invalid class!");
602       }
603       return isSigned;
604     }
605
606   unsigned Op1r = getReg(Op1);
607   switch (Class) {
608   default: assert(0 && "Unknown type class!");
609     // Emit: cmp <var1>, <var2> (do the comparison).  We can
610     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
611     // 32-bit.
612   case cByte:
613     BuildMI(BB, X86::CMPrr8, 2).addReg(Op0r).addReg(Op1r);
614     break;
615   case cShort:
616     BuildMI(BB, X86::CMPrr16, 2).addReg(Op0r).addReg(Op1r);
617     break;
618   case cInt:
619     BuildMI(BB, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
620     break;
621   case cFP:
622     BuildMI(BB, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
623     BuildMI(BB, X86::FNSTSWr8, 0);
624     BuildMI(BB, X86::SAHF, 1);
625     isSigned = false;   // Compare with unsigned operators
626     break;
627
628   case cLong:
629     if (OpNum < 2) {    // seteq, setne
630       unsigned LoTmp = makeAnotherReg(Type::IntTy);
631       unsigned HiTmp = makeAnotherReg(Type::IntTy);
632       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
633       BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(Op0r).addReg(Op1r);
634       BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
635       BuildMI(BB, X86::ORrr32,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
636       break;  // Allow the sete or setne to be generated from flags set by OR
637     } else {
638       // Emit a sequence of code which compares the high and low parts once
639       // each, then uses a conditional move to handle the overflow case.  For
640       // example, a setlt for long would generate code like this:
641       //
642       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
643       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
644       // dest = hi(op1) == hi(op2) ? AL : BL;
645       //
646
647       // FIXME: This would be much better if we had hierarchical register
648       // classes!  Until then, hardcode registers so that we can deal with their
649       // aliases (because we don't have conditional byte moves).
650       //
651       BuildMI(BB, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
652       BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
653       BuildMI(BB, X86::CMPrr32, 2).addReg(Op0r+1).addReg(Op1r+1);
654       BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
655       BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
656       // NOTE: visitSetCondInst knows that the value is dumped into the BL
657       // register at this point for long values...
658       return isSigned;
659     }
660   }
661   return isSigned;
662 }
663
664
665 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
666 /// register, then move it to wherever the result should be. 
667 ///
668 void ISel::visitSetCondInst(SetCondInst &I) {
669   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
670
671   unsigned OpNum = getSetCCNumber(I.getOpcode());
672   unsigned DestReg = getReg(I);
673   bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
674                                               I.getOperand(1));
675
676   if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
677     // Handle normal comparisons with a setcc instruction...
678     BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
679   } else {
680     // Handle long comparisons by copying the value which is already in BL into
681     // the register we want...
682     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
683   }
684 }
685
686 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
687 /// operand, in the specified target register.
688 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
689   bool isUnsigned = VR.Ty->isUnsigned();
690   switch (getClassB(VR.Ty)) {
691   case cByte:
692     // Extend value into target register (8->32)
693     if (isUnsigned)
694       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
695     else
696       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
697     break;
698   case cShort:
699     // Extend value into target register (16->32)
700     if (isUnsigned)
701       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
702     else
703       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
704     break;
705   case cInt:
706     // Move value into target register (32->32)
707     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
708     break;
709   default:
710     assert(0 && "Unpromotable operand class in promote32");
711   }
712 }
713
714 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
715 /// we have the following possibilities:
716 ///
717 ///   ret void: No return value, simply emit a 'ret' instruction
718 ///   ret sbyte, ubyte : Extend value into EAX and return
719 ///   ret short, ushort: Extend value into EAX and return
720 ///   ret int, uint    : Move value into EAX and return
721 ///   ret pointer      : Move value into EAX and return
722 ///   ret long, ulong  : Move value into EAX/EDX and return
723 ///   ret float/double : Top of FP stack
724 ///
725 void ISel::visitReturnInst(ReturnInst &I) {
726   if (I.getNumOperands() == 0) {
727     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
728     return;
729   }
730
731   Value *RetVal = I.getOperand(0);
732   unsigned RetReg = getReg(RetVal);
733   switch (getClassB(RetVal->getType())) {
734   case cByte:   // integral return values: extend or move into EAX and return
735   case cShort:
736   case cInt:
737     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
738     // Declare that EAX is live on exit
739     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
740     break;
741   case cFP:                   // Floats & Doubles: Return in ST(0)
742     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
743     // Declare that top-of-stack is live on exit
744     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
745     break;
746   case cLong:
747     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
748     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
749     // Declare that EAX & EDX are live on exit
750     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
751     break;
752   default:
753     visitInstruction(I);
754   }
755   // Emit a 'ret' instruction
756   BuildMI(BB, X86::RET, 0);
757 }
758
759 // getBlockAfter - Return the basic block which occurs lexically after the
760 // specified one.
761 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
762   Function::iterator I = BB; ++I;  // Get iterator to next block
763   return I != BB->getParent()->end() ? &*I : 0;
764 }
765
766 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
767 /// that since code layout is frozen at this point, that if we are trying to
768 /// jump to a block that is the immediate successor of the current block, we can
769 /// just make a fall-through (but we don't currently).
770 ///
771 void ISel::visitBranchInst(BranchInst &BI) {
772   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
773
774   if (!BI.isConditional()) {  // Unconditional branch?
775     if (BI.getSuccessor(0) != NextBB)
776       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
777     return;
778   }
779
780   // See if we can fold the setcc into the branch itself...
781   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
782   if (SCI == 0) {
783     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
784     // computed some other way...
785     unsigned condReg = getReg(BI.getCondition());
786     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
787     if (BI.getSuccessor(1) == NextBB) {
788       if (BI.getSuccessor(0) != NextBB)
789         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
790     } else {
791       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
792       
793       if (BI.getSuccessor(0) != NextBB)
794         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
795     }
796     return;
797   }
798
799   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
800   bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
801                                               SCI->getOperand(1));
802   
803   // LLVM  -> X86 signed  X86 unsigned
804   // -----    ----------  ------------
805   // seteq -> je          je
806   // setne -> jne         jne
807   // setlt -> jl          jb
808   // setge -> jge         jae
809   // setgt -> jg          ja
810   // setle -> jle         jbe
811   static const unsigned OpcodeTab[2][6] = {
812     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
813     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
814   };
815   
816   if (BI.getSuccessor(0) != NextBB) {
817     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
818     if (BI.getSuccessor(1) != NextBB)
819       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
820   } else {
821     // Change to the inverse condition...
822     if (BI.getSuccessor(1) != NextBB) {
823       OpNum ^= 1;
824       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
825     }
826   }
827 }
828
829
830 /// doCall - This emits an abstract call instruction, setting up the arguments
831 /// and the return value as appropriate.  For the actual function call itself,
832 /// it inserts the specified CallMI instruction into the stream.
833 ///
834 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
835                   const std::vector<ValueRecord> &Args) {
836
837   // Count how many bytes are to be pushed on the stack...
838   unsigned NumBytes = 0;
839
840   if (!Args.empty()) {
841     for (unsigned i = 0, e = Args.size(); i != e; ++i)
842       switch (getClassB(Args[i].Ty)) {
843       case cByte: case cShort: case cInt:
844         NumBytes += 4; break;
845       case cLong:
846         NumBytes += 8; break;
847       case cFP:
848         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
849         break;
850       default: assert(0 && "Unknown class!");
851       }
852
853     // Adjust the stack pointer for the new arguments...
854     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
855
856     // Arguments go on the stack in reverse order, as specified by the ABI.
857     unsigned ArgOffset = 0;
858     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
859       unsigned ArgReg = Args[i].Reg;
860       switch (getClassB(Args[i].Ty)) {
861       case cByte:
862       case cShort: {
863         // Promote arg to 32 bits wide into a temporary register...
864         unsigned R = makeAnotherReg(Type::UIntTy);
865         promote32(R, Args[i]);
866         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
867                      X86::ESP, ArgOffset).addReg(R);
868         break;
869       }
870       case cInt:
871         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
872                      X86::ESP, ArgOffset).addReg(ArgReg);
873         break;
874       case cLong:
875         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
876                      X86::ESP, ArgOffset).addReg(ArgReg);
877         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
878                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
879         ArgOffset += 4;        // 8 byte entry, not 4.
880         break;
881         
882       case cFP:
883         if (Args[i].Ty == Type::FloatTy) {
884           addRegOffset(BuildMI(BB, X86::FSTr32, 5),
885                        X86::ESP, ArgOffset).addReg(ArgReg);
886         } else {
887           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
888           addRegOffset(BuildMI(BB, X86::FSTr64, 5),
889                        X86::ESP, ArgOffset).addReg(ArgReg);
890           ArgOffset += 4;       // 8 byte entry, not 4.
891         }
892         break;
893
894       default: assert(0 && "Unknown class!");
895       }
896       ArgOffset += 4;
897     }
898   } else {
899     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
900   }
901
902   BB->push_back(CallMI);
903
904   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
905
906   // If there is a return value, scavenge the result from the location the call
907   // leaves it in...
908   //
909   if (Ret.Ty != Type::VoidTy) {
910     unsigned DestClass = getClassB(Ret.Ty);
911     switch (DestClass) {
912     case cByte:
913     case cShort:
914     case cInt: {
915       // Integral results are in %eax, or the appropriate portion
916       // thereof.
917       static const unsigned regRegMove[] = {
918         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
919       };
920       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
921       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
922       break;
923     }
924     case cFP:     // Floating-point return values live in %ST(0)
925       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
926       break;
927     case cLong:   // Long values are left in EDX:EAX
928       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
929       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
930       break;
931     default: assert(0 && "Unknown class!");
932     }
933   }
934 }
935
936
937 /// visitCallInst - Push args on stack and do a procedure call instruction.
938 void ISel::visitCallInst(CallInst &CI) {
939   MachineInstr *TheCall;
940   if (Function *F = CI.getCalledFunction()) {
941     // Is it an intrinsic function call?
942     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
943       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
944       return;
945     }
946
947     // Emit a CALL instruction with PC-relative displacement.
948     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
949   } else {  // Emit an indirect call...
950     unsigned Reg = getReg(CI.getCalledValue());
951     TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
952   }
953
954   std::vector<ValueRecord> Args;
955   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
956     Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
957                                CI.getOperand(i)->getType()));
958
959   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
960   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
961 }        
962
963 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
964   unsigned TmpReg1, TmpReg2;
965   switch (ID) {
966   case LLVMIntrinsic::va_start:
967     // Get the address of the first vararg value...
968     TmpReg1 = makeAnotherReg(Type::UIntTy);
969     addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
970     TmpReg2 = getReg(CI.getOperand(1));
971     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
972     return;
973
974   case LLVMIntrinsic::va_end: return;   // Noop on X86
975   case LLVMIntrinsic::va_copy:
976     TmpReg1 = getReg(CI.getOperand(2));  // Get existing va_list
977     TmpReg2 = getReg(CI.getOperand(1));  // Get va_list* to store into
978     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
979     return;
980
981   default: assert(0 && "Unknown intrinsic for X86!");
982   }
983 }
984
985
986 /// visitSimpleBinary - Implement simple binary operators for integral types...
987 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
988 /// Xor.
989 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
990   unsigned DestReg = getReg(B);
991   MachineBasicBlock::iterator MI = BB->end();
992   emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
993                             OperatorClass, DestReg);
994 }
995
996 /// visitSimpleBinary - Implement simple binary operators for integral types...
997 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
998 /// 4 for Xor.
999 ///
1000 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1001 /// and constant expression support.
1002 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
1003                                      MachineBasicBlock::iterator &IP,
1004                                      Value *Op0, Value *Op1,
1005                                      unsigned OperatorClass,unsigned TargetReg){
1006   unsigned Class = getClassB(Op0->getType());
1007   if (!isa<ConstantInt>(Op1) || Class == cLong) {
1008     static const unsigned OpcodeTab[][4] = {
1009       // Arithmetic operators
1010       { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
1011       { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
1012       
1013       // Bitwise operators
1014       { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
1015       { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
1016       { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
1017     };
1018     
1019     bool isLong = false;
1020     if (Class == cLong) {
1021       isLong = true;
1022       Class = cInt;          // Bottom 32 bits are handled just like ints
1023     }
1024     
1025     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1026     assert(Opcode && "Floating point arguments to logical inst?");
1027     unsigned Op0r = getReg(Op0, BB, IP);
1028     unsigned Op1r = getReg(Op1, BB, IP);
1029     BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
1030     
1031     if (isLong) {        // Handle the upper 32 bits of long values...
1032       static const unsigned TopTab[] = {
1033         X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1034       };
1035       BMI(BB, IP, TopTab[OperatorClass], 2,
1036           TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
1037     }
1038   } else {
1039     // Special case: op Reg, <const>
1040     ConstantInt *Op1C = cast<ConstantInt>(Op1);
1041
1042     static const unsigned OpcodeTab[][3] = {
1043       // Arithmetic operators
1044       { X86::ADDri8, X86::ADDri16, X86::ADDri32 },  // ADD
1045       { X86::SUBri8, X86::SUBri16, X86::SUBri32 },  // SUB
1046       
1047       // Bitwise operators
1048       { X86::ANDri8, X86::ANDri16, X86::ANDri32 },  // AND
1049       { X86:: ORri8, X86:: ORri16, X86:: ORri32 },  // OR
1050       { X86::XORri8, X86::XORri16, X86::XORri32 },  // XOR
1051     };
1052
1053     assert(Class < 3 && "General code handles 64-bit integer types!");
1054     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1055     unsigned Op0r = getReg(Op0, BB, IP);
1056     uint64_t Op1v;
1057     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op1C))
1058       Op1v = CSI->getValue();
1059     else
1060       Op1v = cast<ConstantUInt>(Op1C)->getValue();
1061
1062     // Mask off any upper bits of the constant, if there are any...
1063     Op1v &= (1ULL << (8 << Class)) - 1;
1064     BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addZImm(Op1v);
1065   }
1066 }
1067
1068 /// doMultiply - Emit appropriate instructions to multiply together the
1069 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1070 /// result should be given as DestTy.
1071 ///
1072 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
1073                       unsigned DestReg, const Type *DestTy,
1074                       unsigned op0Reg, unsigned op1Reg) {
1075   unsigned Class = getClass(DestTy);
1076   switch (Class) {
1077   case cFP:              // Floating point multiply
1078     BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1079     return;
1080   case cInt:
1081   case cShort:
1082     BMI(BB, MBBI, Class == cInt ? X86::IMULr32 : X86::IMULr16, 2, DestReg)
1083       .addReg(op0Reg).addReg(op1Reg);
1084     return;
1085   case cByte:
1086     // Must use the MUL instruction, which forces use of AL...
1087     BMI(MBB, MBBI, X86::MOVrr8, 1, X86::AL).addReg(op0Reg);
1088     BMI(MBB, MBBI, X86::MULr8, 1).addReg(op1Reg);
1089     BMI(MBB, MBBI, X86::MOVrr8, 1, DestReg).addReg(X86::AL);
1090     return;
1091   default:
1092   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1093   }
1094 }
1095
1096 /// visitMul - Multiplies are not simple binary operators because they must deal
1097 /// with the EAX register explicitly.
1098 ///
1099 void ISel::visitMul(BinaryOperator &I) {
1100   unsigned Op0Reg  = getReg(I.getOperand(0));
1101   unsigned Op1Reg  = getReg(I.getOperand(1));
1102   unsigned DestReg = getReg(I);
1103
1104   // Simple scalar multiply?
1105   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1106     MachineBasicBlock::iterator MBBI = BB->end();
1107     doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1108   } else {
1109     // Long value.  We have to do things the hard way...
1110     // Multiply the two low parts... capturing carry into EDX
1111     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1112     BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg);  // AL*BL
1113
1114     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1115     BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX);     // AL*BL
1116     BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1117
1118     MachineBasicBlock::iterator MBBI = BB->end();
1119     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
1120     BMI(BB, MBBI, X86::IMULr32, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1121
1122     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1123     BuildMI(BB, X86::ADDrr32, 2,                         // AH*BL+(AL*BL >> 32)
1124             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1125     
1126     MBBI = BB->end();
1127     unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1128     BMI(BB, MBBI, X86::IMULr32, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1129     
1130     BuildMI(BB, X86::ADDrr32, 2,               // AL*BH + AH*BL + (AL*BL >> 32)
1131             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1132   }
1133 }
1134
1135
1136 /// visitDivRem - Handle division and remainder instructions... these
1137 /// instruction both require the same instructions to be generated, they just
1138 /// select the result from a different register.  Note that both of these
1139 /// instructions work differently for signed and unsigned operands.
1140 ///
1141 void ISel::visitDivRem(BinaryOperator &I) {
1142   unsigned Class     = getClass(I.getType());
1143   unsigned Op0Reg    = getReg(I.getOperand(0));
1144   unsigned Op1Reg    = getReg(I.getOperand(1));
1145   unsigned ResultReg = getReg(I);
1146
1147   switch (Class) {
1148   case cFP:              // Floating point divide
1149     if (I.getOpcode() == Instruction::Div)
1150       BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1151     else {               // Floating point remainder...
1152       MachineInstr *TheCall =
1153         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1154       std::vector<ValueRecord> Args;
1155       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1156       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1157       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1158     }
1159     return;
1160   case cLong: {
1161     static const char *FnName[] =
1162       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1163
1164     unsigned NameIdx = I.getType()->isUnsigned()*2;
1165     NameIdx += I.getOpcode() == Instruction::Div;
1166     MachineInstr *TheCall =
1167       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1168
1169     std::vector<ValueRecord> Args;
1170     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1171     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1172     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1173     return;
1174   }
1175   case cByte: case cShort: case cInt:
1176     break;          // Small integerals, handled below...
1177   default: assert(0 && "Unknown class!");
1178   }
1179
1180   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1181   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1182   static const unsigned SarOpcode[]={ X86::SARir8, X86::SARir16, X86::SARir32 };
1183   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1184   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1185
1186   static const unsigned DivOpcode[][4] = {
1187     { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 },  // Unsigned division
1188     { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 },  // Signed division
1189   };
1190
1191   bool isSigned   = I.getType()->isSigned();
1192   unsigned Reg    = Regs[Class];
1193   unsigned ExtReg = ExtRegs[Class];
1194
1195   // Put the first operand into one of the A registers...
1196   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1197
1198   if (isSigned) {
1199     // Emit a sign extension instruction...
1200     unsigned ShiftResult = makeAnotherReg(I.getType());
1201     BuildMI(BB, SarOpcode[Class], 2, ShiftResult).addReg(Op0Reg).addZImm(31);
1202     BuildMI(BB, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1203   } else {
1204     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1205     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1206   }
1207
1208   // Emit the appropriate divide or remainder instruction...
1209   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1210
1211   // Figure out which register we want to pick the result out of...
1212   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1213   
1214   // Put the result into the destination register...
1215   BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1216 }
1217
1218
1219 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1220 /// for constant immediate shift values, and for constant immediate
1221 /// shift values equal to 1. Even the general case is sort of special,
1222 /// because the shift amount has to be in CL, not just any old register.
1223 ///
1224 void ISel::visitShiftInst(ShiftInst &I) {
1225   unsigned SrcReg = getReg(I.getOperand(0));
1226   unsigned DestReg = getReg(I);
1227   bool isLeftShift = I.getOpcode() == Instruction::Shl;
1228   bool isSigned = I.getType()->isSigned();
1229   unsigned Class = getClass(I.getType());
1230   
1231   static const unsigned ConstantOperand[][4] = {
1232     { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 },  // SHR
1233     { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 },  // SAR
1234     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SHL
1235     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SAL = SHL
1236   };
1237
1238   static const unsigned NonConstantOperand[][4] = {
1239     { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 },  // SHR
1240     { X86::SARrr8, X86::SARrr16, X86::SARrr32 },  // SAR
1241     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SHL
1242     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SAL = SHL
1243   };
1244
1245   // Longs, as usual, are handled specially...
1246   if (Class == cLong) {
1247     // If we have a constant shift, we can generate much more efficient code
1248     // than otherwise...
1249     //
1250     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1251       unsigned Amount = CUI->getValue();
1252       if (Amount < 32) {
1253         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1254         if (isLeftShift) {
1255           BuildMI(BB, Opc[3], 3, 
1256                   DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1257           BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1258         } else {
1259           BuildMI(BB, Opc[3], 3,
1260                   DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addZImm(Amount);
1261           BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1262         }
1263       } else {                 // Shifting more than 32 bits
1264         Amount -= 32;
1265         if (isLeftShift) {
1266           BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1267           BuildMI(BB, X86::MOVir32, 1,DestReg  ).addZImm(0);
1268         } else {
1269           unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1270           BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1271           BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1272         }
1273       }
1274     } else {
1275       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1276
1277       if (!isLeftShift && isSigned) {
1278         // If this is a SHR of a Long, then we need to do funny sign extension
1279         // stuff.  TmpReg gets the value to use as the high-part if we are
1280         // shifting more than 32 bits.
1281         BuildMI(BB, X86::SARir32, 2, TmpReg).addReg(SrcReg).addZImm(31);
1282       } else {
1283         // Other shifts use a fixed zero value if the shift is more than 32
1284         // bits.
1285         BuildMI(BB, X86::MOVir32, 1, TmpReg).addZImm(0);
1286       }
1287
1288       // Initialize CL with the shift amount...
1289       unsigned ShiftAmount = getReg(I.getOperand(1));
1290       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmount);
1291
1292       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1293       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1294       if (isLeftShift) {
1295         // TmpReg2 = shld inHi, inLo
1296         BuildMI(BB, X86::SHLDrr32, 2, TmpReg2).addReg(SrcReg+1).addReg(SrcReg);
1297         // TmpReg3 = shl  inLo, CL
1298         BuildMI(BB, X86::SHLrr32, 1, TmpReg3).addReg(SrcReg);
1299
1300         // Set the flags to indicate whether the shift was by more than 32 bits.
1301         BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1302
1303         // DestHi = (>32) ? TmpReg3 : TmpReg2;
1304         BuildMI(BB, X86::CMOVNErr32, 2, 
1305                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1306         // DestLo = (>32) ? TmpReg : TmpReg3;
1307         BuildMI(BB, X86::CMOVNErr32, 2, DestReg).addReg(TmpReg3).addReg(TmpReg);
1308       } else {
1309         // TmpReg2 = shrd inLo, inHi
1310         BuildMI(BB, X86::SHRDrr32, 2, TmpReg2).addReg(SrcReg).addReg(SrcReg+1);
1311         // TmpReg3 = s[ah]r  inHi, CL
1312         BuildMI(BB, isSigned ? X86::SARrr32 : X86::SHRrr32, 1, TmpReg3)
1313                        .addReg(SrcReg+1);
1314
1315         // Set the flags to indicate whether the shift was by more than 32 bits.
1316         BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1317
1318         // DestLo = (>32) ? TmpReg3 : TmpReg2;
1319         BuildMI(BB, X86::CMOVNErr32, 2, 
1320                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1321
1322         // DestHi = (>32) ? TmpReg : TmpReg3;
1323         BuildMI(BB, X86::CMOVNErr32, 2, 
1324                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1325       }
1326     }
1327     return;
1328   }
1329
1330   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1331     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1332     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1333
1334     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1335     BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1336   } else {                  // The shift amount is non-constant.
1337     BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1338
1339     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1340     BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1341   }
1342 }
1343
1344
1345 /// doFPLoad - This method is used to load an FP value from memory using the
1346 /// current endianness.  NOTE: This method returns a partially constructed load
1347 /// instruction which needs to have the memory source filled in still.
1348 ///
1349 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1350                              MachineBasicBlock::iterator &MBBI,
1351                              const Type *Ty, unsigned DestReg) {
1352   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1353   unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1354
1355   if (TM.getTargetData().isLittleEndian()) // fast path...
1356     return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1357
1358   // If we are big-endian, start by creating an LEA instruction to represent the
1359   // address of the memory location to load from...
1360   //
1361   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1362   MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1363
1364   // Allocate a temporary stack slot to transform the value into...
1365   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1366
1367   // Perform the bswaps 32 bits at a time...
1368   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1369   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1370   addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1371   BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1372   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1373   addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1374                     FrameIdx, Offset).addReg(TmpReg2);
1375   
1376   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1377     TmpReg1 = makeAnotherReg(Type::UIntTy);
1378     TmpReg2 = makeAnotherReg(Type::UIntTy);
1379
1380     addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1381     BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1382     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1383     addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1384   }
1385
1386   // Now we can reload the final byteswapped result into the final destination.
1387   addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1388   return Result;
1389 }
1390
1391 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1392 ///
1393 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1394   // Emit the byte swap instruction...
1395   switch (Class) {
1396   case cByte:
1397     // No byteswap necessary for 8 bit value...
1398     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1399     break;
1400   case cInt:
1401     // Use the 32 bit bswap instruction to do a 32 bit swap...
1402     BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1403     break;
1404     
1405   case cShort:
1406     // For 16 bit we have to use an xchg instruction, because there is no
1407     // 16-bit bswap.  XCHG is necessarily not in SSA form, so we force things
1408     // into AX to do the xchg.
1409     //
1410     BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1411     BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1412       .addReg(X86::AH, MOTy::UseAndDef);
1413     BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1414     break;
1415   default: assert(0 && "Cannot byteswap this class!");
1416   }
1417 }
1418
1419
1420 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1421 /// instruction.  The load and store instructions are the only place where we
1422 /// need to worry about the memory layout of the target machine.
1423 ///
1424 void ISel::visitLoadInst(LoadInst &I) {
1425   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1426   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1427   unsigned SrcAddrReg = getReg(I.getOperand(0));
1428   unsigned DestReg = getReg(I);
1429
1430   unsigned Class = getClass(I.getType());
1431   switch (Class) {
1432   case cFP: {
1433     MachineBasicBlock::iterator MBBI = BB->end();
1434     addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1435     return;
1436   }
1437   case cLong: case cInt: case cShort: case cByte:
1438     break;      // Integers of various sizes handled below
1439   default: assert(0 && "Unknown memory class!");
1440   }
1441
1442   // We need to adjust the input pointer if we are emulating a big-endian
1443   // long-pointer target.  On these systems, the pointer that we are interested
1444   // in is in the upper part of the eight byte memory image of the pointer.  It
1445   // also happens to be byte-swapped, but this will be handled later.
1446   //
1447   if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1448     unsigned R = makeAnotherReg(Type::UIntTy);
1449     BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1450     SrcAddrReg = R;
1451   }
1452
1453   unsigned IReg = DestReg;
1454   if (!isLittleEndian)  // If big endian we need an intermediate stage
1455     DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1456
1457   static const unsigned Opcode[] = {
1458     X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1459   };
1460   addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1461
1462   // Handle long values now...
1463   if (Class == cLong) {
1464     if (isLittleEndian) {
1465       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1466     } else {
1467       EmitByteSwap(IReg+1, DestReg, cInt);
1468       unsigned TempReg = makeAnotherReg(Type::IntTy);
1469       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1470       EmitByteSwap(IReg, TempReg, cInt);
1471     }
1472     return;
1473   }
1474
1475   if (!isLittleEndian)
1476     EmitByteSwap(IReg, DestReg, Class);
1477 }
1478
1479
1480 /// doFPStore - This method is used to store an FP value to memory using the
1481 /// current endianness.
1482 ///
1483 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1484   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1485   unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1486
1487   if (TM.getTargetData().isLittleEndian()) {  // fast path...
1488     addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1489     return;
1490   }
1491
1492   // Allocate a temporary stack slot to transform the value into...
1493   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1494   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1495   addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1496
1497   // Store the value into a temporary stack slot...
1498   addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1499
1500   // Perform the bswaps 32 bits at a time...
1501   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1502   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1503   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1504   BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1505   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1506   addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1507                DestAddrReg, Offset).addReg(TmpReg2);
1508   
1509   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1510     TmpReg1 = makeAnotherReg(Type::UIntTy);
1511     TmpReg2 = makeAnotherReg(Type::UIntTy);
1512
1513     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1514     BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1515     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1516     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1517   }
1518 }
1519
1520
1521 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1522 /// instruction.
1523 ///
1524 void ISel::visitStoreInst(StoreInst &I) {
1525   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1526   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1527   unsigned ValReg      = getReg(I.getOperand(0));
1528   unsigned AddressReg  = getReg(I.getOperand(1));
1529
1530   unsigned Class = getClass(I.getOperand(0)->getType());
1531   switch (Class) {
1532   case cLong:
1533     if (isLittleEndian) {
1534       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1535       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1536                    AddressReg, 4).addReg(ValReg+1);
1537     } else {
1538       unsigned T1 = makeAnotherReg(Type::IntTy);
1539       unsigned T2 = makeAnotherReg(Type::IntTy);
1540       EmitByteSwap(T1, ValReg  , cInt);
1541       EmitByteSwap(T2, ValReg+1, cInt);
1542       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1543       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1544     }
1545     return;
1546   case cFP:
1547     doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1548     return;
1549   case cInt: case cShort: case cByte:
1550     break;      // Integers of various sizes handled below
1551   default: assert(0 && "Unknown memory class!");
1552   }
1553
1554   if (!isLittleEndian && hasLongPointers &&
1555       isa<PointerType>(I.getOperand(0)->getType())) {
1556     unsigned R = makeAnotherReg(Type::UIntTy);
1557     BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1558     AddressReg = R;
1559   }
1560
1561   if (!isLittleEndian && Class != cByte) {
1562     unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1563     EmitByteSwap(R, ValReg, Class);
1564     ValReg = R;
1565   }
1566
1567   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1568   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1569 }
1570
1571
1572 /// visitCastInst - Here we have various kinds of copying with or without
1573 /// sign extension going on.
1574 void ISel::visitCastInst(CastInst &CI) {
1575   Value *Op = CI.getOperand(0);
1576   // If this is a cast from a 32-bit integer to a Long type, and the only uses
1577   // of the case are GEP instructions, then the cast does not need to be
1578   // generated explicitly, it will be folded into the GEP.
1579   if (CI.getType() == Type::LongTy &&
1580       (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
1581     bool AllUsesAreGEPs = true;
1582     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
1583       if (!isa<GetElementPtrInst>(*I)) {
1584         AllUsesAreGEPs = false;
1585         break;
1586       }        
1587
1588     // No need to codegen this cast if all users are getelementptr instrs...
1589     if (AllUsesAreGEPs) return;
1590   }
1591
1592   unsigned DestReg = getReg(CI);
1593   MachineBasicBlock::iterator MI = BB->end();
1594   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
1595 }
1596
1597 /// emitCastOperation - Common code shared between visitCastInst and
1598 /// constant expression cast support.
1599 void ISel::emitCastOperation(MachineBasicBlock *BB,
1600                              MachineBasicBlock::iterator &IP,
1601                              Value *Src, const Type *DestTy,
1602                              unsigned DestReg) {
1603   unsigned SrcReg = getReg(Src, BB, IP);
1604   const Type *SrcTy = Src->getType();
1605   unsigned SrcClass = getClassB(SrcTy);
1606   unsigned DestClass = getClassB(DestTy);
1607
1608   // Implement casts to bool by using compare on the operand followed by set if
1609   // not zero on the result.
1610   if (DestTy == Type::BoolTy) {
1611     switch (SrcClass) {
1612     case cByte:
1613       BMI(BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
1614       break;
1615     case cShort:
1616       BMI(BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
1617       break;
1618     case cInt:
1619       BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
1620       break;
1621     case cLong: {
1622       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1623       BMI(BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
1624       break;
1625     }
1626     case cFP:
1627       assert(0 && "FIXME: implement cast FP to bool");
1628       abort();
1629     }
1630
1631     // If the zero flag is not set, then the value is true, set the byte to
1632     // true.
1633     BMI(BB, IP, X86::SETNEr, 1, DestReg);
1634     return;
1635   }
1636
1637   static const unsigned RegRegMove[] = {
1638     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1639   };
1640
1641   // Implement casts between values of the same type class (as determined by
1642   // getClass) by using a register-to-register move.
1643   if (SrcClass == DestClass) {
1644     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1645       BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1646     } else if (SrcClass == cFP) {
1647       if (SrcTy == Type::FloatTy) {  // double -> float
1648         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1649         BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1650       } else {                       // float -> double
1651         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1652                "Unknown cFP member!");
1653         // Truncate from double to float by storing to memory as short, then
1654         // reading it back.
1655         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1656         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1657         addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1658         addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1659       }
1660     } else if (SrcClass == cLong) {
1661       BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1662       BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1663     } else {
1664       assert(0 && "Cannot handle this type of cast instruction!");
1665       abort();
1666     }
1667     return;
1668   }
1669
1670   // Handle cast of SMALLER int to LARGER int using a move with sign extension
1671   // or zero extension, depending on whether the source type was signed.
1672   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1673       SrcClass < DestClass) {
1674     bool isLong = DestClass == cLong;
1675     if (isLong) DestClass = cInt;
1676
1677     static const unsigned Opc[][4] = {
1678       { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1679       { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 }  // u
1680     };
1681     
1682     bool isUnsigned = SrcTy->isUnsigned();
1683     BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1684         DestReg).addReg(SrcReg);
1685
1686     if (isLong) {  // Handle upper 32 bits as appropriate...
1687       if (isUnsigned)     // Zero out top bits...
1688         BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1689       else                // Sign extend bottom half...
1690         BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1691     }
1692     return;
1693   }
1694
1695   // Special case long -> int ...
1696   if (SrcClass == cLong && DestClass == cInt) {
1697     BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1698     return;
1699   }
1700   
1701   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1702   // move out of AX or AL.
1703   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1704       && SrcClass > DestClass) {
1705     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1706     BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1707     BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1708     return;
1709   }
1710
1711   // Handle casts from integer to floating point now...
1712   if (DestClass == cFP) {
1713     // Promote the integer to a type supported by FLD.  We do this because there
1714     // are no unsigned FLD instructions, so we must promote an unsigned value to
1715     // a larger signed value, then use FLD on the larger value.
1716     //
1717     const Type *PromoteType = 0;
1718     unsigned PromoteOpcode;
1719     switch (SrcTy->getPrimitiveID()) {
1720     case Type::BoolTyID:
1721     case Type::SByteTyID:
1722       // We don't have the facilities for directly loading byte sized data from
1723       // memory (even signed).  Promote it to 16 bits.
1724       PromoteType = Type::ShortTy;
1725       PromoteOpcode = X86::MOVSXr16r8;
1726       break;
1727     case Type::UByteTyID:
1728       PromoteType = Type::ShortTy;
1729       PromoteOpcode = X86::MOVZXr16r8;
1730       break;
1731     case Type::UShortTyID:
1732       PromoteType = Type::IntTy;
1733       PromoteOpcode = X86::MOVZXr32r16;
1734       break;
1735     case Type::UIntTyID: {
1736       // Make a 64 bit temporary... and zero out the top of it...
1737       unsigned TmpReg = makeAnotherReg(Type::LongTy);
1738       BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1739       BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1740       SrcTy = Type::LongTy;
1741       SrcClass = cLong;
1742       SrcReg = TmpReg;
1743       break;
1744     }
1745     case Type::ULongTyID:
1746       assert("FIXME: not implemented: cast ulong X to fp type!");
1747     default:  // No promotion needed...
1748       break;
1749     }
1750     
1751     if (PromoteType) {
1752       unsigned TmpReg = makeAnotherReg(PromoteType);
1753       BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1754           1, TmpReg).addReg(SrcReg);
1755       SrcTy = PromoteType;
1756       SrcClass = getClass(PromoteType);
1757       SrcReg = TmpReg;
1758     }
1759
1760     // Spill the integer to memory and reload it from there...
1761     int FrameIdx =
1762       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1763
1764     if (SrcClass == cLong) {
1765       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1766       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1767                         FrameIdx, 4).addReg(SrcReg+1);
1768     } else {
1769       static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1770       addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1771     }
1772
1773     static const unsigned Op2[] =
1774       { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
1775     addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1776     return;
1777   }
1778
1779   // Handle casts from floating point to integer now...
1780   if (SrcClass == cFP) {
1781     // Change the floating point control register to use "round towards zero"
1782     // mode when truncating to an integer value.
1783     //
1784     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1785     addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1786
1787     // Load the old value of the high byte of the control word...
1788     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1789     addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1790
1791     // Set the high part to be round to zero...
1792     addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1793
1794     // Reload the modified control word now...
1795     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1796     
1797     // Restore the memory image of control word to original value
1798     addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1799                       CWFrameIdx, 1).addReg(HighPartOfCW);
1800
1801     // We don't have the facilities for directly storing byte sized data to
1802     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
1803     // larger classes because we only have signed FP stores.
1804     unsigned StoreClass  = DestClass;
1805     const Type *StoreTy  = DestTy;
1806     if (StoreClass == cByte || DestTy->isUnsigned())
1807       switch (StoreClass) {
1808       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
1809       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
1810       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
1811       case cLong:
1812         assert(0 &&"FIXME not implemented: cast FP to unsigned long long");
1813         abort();
1814       default: assert(0 && "Unknown store class!");
1815       }
1816
1817     // Spill the integer to memory and reload it from there...
1818     int FrameIdx =
1819       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1820
1821     static const unsigned Op1[] =
1822       { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1823     addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1824
1825     if (DestClass == cLong) {
1826       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1827       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1828     } else {
1829       static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1830       addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1831     }
1832
1833     // Reload the original control word now...
1834     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1835     return;
1836   }
1837
1838   // Anything we haven't handled already, we can't (yet) handle at all.
1839   assert(0 && "Unhandled cast instruction!");
1840   abort();
1841 }
1842
1843 /// visitVarArgInst - Implement the va_arg instruction...
1844 ///
1845 void ISel::visitVarArgInst(VarArgInst &I) {
1846   unsigned SrcReg = getReg(I.getOperand(0));
1847   unsigned DestReg = getReg(I);
1848
1849   // Load the va_list into a register...
1850   unsigned VAList = makeAnotherReg(Type::UIntTy);
1851   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1852
1853   unsigned Size;
1854   switch (I.getType()->getPrimitiveID()) {
1855   default:
1856     std::cerr << I;
1857     assert(0 && "Error: bad type for va_arg instruction!");
1858     return;
1859   case Type::PointerTyID:
1860   case Type::UIntTyID:
1861   case Type::IntTyID:
1862     Size = 4;
1863     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1864     break;
1865   case Type::ULongTyID:
1866   case Type::LongTyID:
1867     Size = 8;
1868     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1869     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1870     break;
1871   case Type::DoubleTyID:
1872     Size = 8;
1873     addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1874     break;
1875   }
1876
1877   // Increment the VAList pointer...
1878   unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1879   BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1880
1881   // Update the VAList in memory...
1882   addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1883 }
1884
1885
1886 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1887 // returns zero when the input is not exactly a power of two.
1888 static unsigned ExactLog2(unsigned Val) {
1889   if (Val == 0) return 0;
1890   unsigned Count = 0;
1891   while (Val != 1) {
1892     if (Val & 1) return 0;
1893     Val >>= 1;
1894     ++Count;
1895   }
1896   return Count+1;
1897 }
1898
1899 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1900   unsigned outputReg = getReg(I);
1901   MachineBasicBlock::iterator MI = BB->end();
1902   emitGEPOperation(BB, MI, I.getOperand(0),
1903                    I.op_begin()+1, I.op_end(), outputReg);
1904 }
1905
1906 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1907                             MachineBasicBlock::iterator &IP,
1908                             Value *Src, User::op_iterator IdxBegin,
1909                             User::op_iterator IdxEnd, unsigned TargetReg) {
1910   const TargetData &TD = TM.getTargetData();
1911   const Type *Ty = Src->getType();
1912   unsigned BaseReg = getReg(Src, MBB, IP);
1913
1914   // GEPs have zero or more indices; we must perform a struct access
1915   // or array access for each one.
1916   for (GetElementPtrInst::op_iterator oi = IdxBegin,
1917          oe = IdxEnd; oi != oe; ++oi) {
1918     Value *idx = *oi;
1919     unsigned NextReg = BaseReg;
1920     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1921       // It's a struct access.  idx is the index into the structure,
1922       // which names the field. This index must have ubyte type.
1923       const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1924       assert(CUI->getType() == Type::UByteTy
1925               && "Funny-looking structure index in GEP");
1926       // Use the TargetData structure to pick out what the layout of
1927       // the structure is in memory.  Since the structure index must
1928       // be constant, we can get its value and use it to find the
1929       // right byte offset from the StructLayout class's list of
1930       // structure member offsets.
1931       unsigned idxValue = CUI->getValue();
1932       unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1933       if (FieldOff) {
1934         NextReg = makeAnotherReg(Type::UIntTy);
1935         // Emit an ADD to add FieldOff to the basePtr.
1936         BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1937       }
1938       // The next type is the member of the structure selected by the
1939       // index.
1940       Ty = StTy->getElementTypes()[idxValue];
1941     } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1942       // It's an array or pointer access: [ArraySize x ElementType].
1943
1944       // idx is the index into the array.  Unlike with structure
1945       // indices, we may not know its actual value at code-generation
1946       // time.
1947       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1948
1949       // Most GEP instructions use a [cast (int/uint) to LongTy] as their
1950       // operand on X86.  Handle this case directly now...
1951       if (CastInst *CI = dyn_cast<CastInst>(idx))
1952         if (CI->getOperand(0)->getType() == Type::IntTy ||
1953             CI->getOperand(0)->getType() == Type::UIntTy)
1954           idx = CI->getOperand(0);
1955
1956       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1957       // must find the size of the pointed-to type (Not coincidentally, the next
1958       // type is the type of the elements in the array).
1959       Ty = SqTy->getElementType();
1960       unsigned elementSize = TD.getTypeSize(Ty);
1961
1962       // If idxReg is a constant, we don't need to perform the multiply!
1963       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1964         if (!CSI->isNullValue()) {
1965           unsigned Offset = elementSize*CSI->getValue();
1966           NextReg = makeAnotherReg(Type::UIntTy);
1967           BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1968         }
1969       } else if (elementSize == 1) {
1970         // If the element size is 1, we don't have to multiply, just add
1971         unsigned idxReg = getReg(idx, MBB, IP);
1972         NextReg = makeAnotherReg(Type::UIntTy);
1973         BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1974       } else {
1975         unsigned idxReg = getReg(idx, MBB, IP);
1976         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1977         if (unsigned Shift = ExactLog2(elementSize)) {
1978           // If the element size is exactly a power of 2, use a shift to get it.
1979           BMI(MBB, IP, X86::SHLir32, 2,
1980               OffsetReg).addReg(idxReg).addZImm(Shift-1);
1981         } else {
1982           // Most general case, emit a multiply...
1983           unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1984           BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1985         
1986           // Emit a MUL to multiply the register holding the index by
1987           // elementSize, putting the result in OffsetReg.
1988           doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1989         }
1990         // Emit an ADD to add OffsetReg to the basePtr.
1991         NextReg = makeAnotherReg(Type::UIntTy);
1992         BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1993       }
1994     }
1995     // Now that we are here, further indices refer to subtypes of this
1996     // one, so we don't need to worry about BaseReg itself, anymore.
1997     BaseReg = NextReg;
1998   }
1999   // After we have processed all the indices, the result is left in
2000   // BaseReg.  Move it to the register where we were expected to
2001   // put the answer.  A 32-bit move should do it, because we are in
2002   // ILP32 land.
2003   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2004 }
2005
2006
2007 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2008 /// frame manager, otherwise do it the hard way.
2009 ///
2010 void ISel::visitAllocaInst(AllocaInst &I) {
2011   // Find the data size of the alloca inst's getAllocatedType.
2012   const Type *Ty = I.getAllocatedType();
2013   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2014
2015   // If this is a fixed size alloca in the entry block for the function,
2016   // statically stack allocate the space.
2017   //
2018   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2019     if (I.getParent() == I.getParent()->getParent()->begin()) {
2020       TySize *= CUI->getValue();   // Get total allocated size...
2021       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2022       
2023       // Create a new stack object using the frame manager...
2024       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2025       addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
2026       return;
2027     }
2028   }
2029   
2030   // Create a register to hold the temporary result of multiplying the type size
2031   // constant by the variable amount.
2032   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2033   unsigned SrcReg1 = getReg(I.getArraySize());
2034   unsigned SizeReg = makeAnotherReg(Type::UIntTy);
2035   BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
2036   
2037   // TotalSizeReg = mul <numelements>, <TypeSize>
2038   MachineBasicBlock::iterator MBBI = BB->end();
2039   doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
2040
2041   // AddedSize = add <TotalSizeReg>, 15
2042   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2043   BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
2044
2045   // AlignedSize = and <AddedSize>, ~15
2046   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2047   BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
2048   
2049   // Subtract size from stack pointer, thereby allocating some space.
2050   BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2051
2052   // Put a pointer to the space into the result register, by copying
2053   // the stack pointer.
2054   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
2055
2056   // Inform the Frame Information that we have just allocated a variable-sized
2057   // object.
2058   F->getFrameInfo()->CreateVariableSizedObject();
2059 }
2060
2061 /// visitMallocInst - Malloc instructions are code generated into direct calls
2062 /// to the library malloc.
2063 ///
2064 void ISel::visitMallocInst(MallocInst &I) {
2065   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2066   unsigned Arg;
2067
2068   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2069     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2070   } else {
2071     Arg = makeAnotherReg(Type::UIntTy);
2072     unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
2073     unsigned Op1Reg = getReg(I.getOperand(0));
2074     MachineBasicBlock::iterator MBBI = BB->end();
2075     doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
2076                
2077                
2078   }
2079
2080   std::vector<ValueRecord> Args;
2081   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2082   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2083                                   1).addExternalSymbol("malloc", true);
2084   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2085 }
2086
2087
2088 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2089 /// function.
2090 ///
2091 void ISel::visitFreeInst(FreeInst &I) {
2092   std::vector<ValueRecord> Args;
2093   Args.push_back(ValueRecord(getReg(I.getOperand(0)),
2094                              I.getOperand(0)->getType()));
2095   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2096                                   1).addExternalSymbol("free", true);
2097   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2098 }
2099    
2100
2101 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
2102 /// into a machine code representation is a very simple peep-hole fashion.  The
2103 /// generated code sucks but the implementation is nice and simple.
2104 ///
2105 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
2106   return new ISel(TM);
2107 }