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