All store instructions really want 'rd' in the first field.
[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 reg1 = getReg(Op0);
583   unsigned reg2 = getReg(Op1);
584
585   unsigned Class = getClassB(CompTy);
586   switch (Class) {
587   default: assert(0 && "Unknown type class!");
588     // Emit: cmp <var1>, <var2> (do the comparison).  We can
589     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
590     // 32-bit.
591   case cByte:
592     BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
593     break;
594   case cShort:
595     BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
596     break;
597   case cInt:
598     BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
599     break;
600   case cFP:
601     BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
602     BuildMI(BB, X86::FNSTSWr8, 0);
603     BuildMI(BB, X86::SAHF, 1);
604     isSigned = false;   // Compare with unsigned operators
605     break;
606
607   case cLong:
608     if (OpNum < 2) {    // seteq, setne
609       unsigned LoTmp = makeAnotherReg(Type::IntTy);
610       unsigned HiTmp = makeAnotherReg(Type::IntTy);
611       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
612       BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
613       BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
614       BuildMI(BB, X86::ORrr32,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
615       break;  // Allow the sete or setne to be generated from flags set by OR
616     } else {
617       // Emit a sequence of code which compares the high and low parts once
618       // each, then uses a conditional move to handle the overflow case.  For
619       // example, a setlt for long would generate code like this:
620       //
621       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
622       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
623       // dest = hi(op1) == hi(op2) ? AL : BL;
624       //
625
626       // FIXME: This would be much better if we had hierarchical register
627       // classes!  Until then, hardcode registers so that we can deal with their
628       // aliases (because we don't have conditional byte moves).
629       //
630       BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
631       BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
632       BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
633       BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
634       BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
635       // NOTE: visitSetCondInst knows that the value is dumped into the BL
636       // register at this point for long values...
637       return isSigned;
638     }
639   }
640   return isSigned;
641 }
642
643
644 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
645 /// register, then move it to wherever the result should be. 
646 ///
647 void ISel::visitSetCondInst(SetCondInst &I) {
648   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
649
650   unsigned OpNum = getSetCCNumber(I.getOpcode());
651   unsigned DestReg = getReg(I);
652   bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
653                                               I.getOperand(1));
654
655   if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
656     // Handle normal comparisons with a setcc instruction...
657     BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
658   } else {
659     // Handle long comparisons by copying the value which is already in BL into
660     // the register we want...
661     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
662   }
663 }
664
665 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
666 /// operand, in the specified target register.
667 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
668   bool isUnsigned = VR.Ty->isUnsigned();
669   switch (getClassB(VR.Ty)) {
670   case cByte:
671     // Extend value into target register (8->32)
672     if (isUnsigned)
673       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
674     else
675       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
676     break;
677   case cShort:
678     // Extend value into target register (16->32)
679     if (isUnsigned)
680       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
681     else
682       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
683     break;
684   case cInt:
685     // Move value into target register (32->32)
686     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
687     break;
688   default:
689     assert(0 && "Unpromotable operand class in promote32");
690   }
691 }
692
693 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
694 /// we have the following possibilities:
695 ///
696 ///   ret void: No return value, simply emit a 'ret' instruction
697 ///   ret sbyte, ubyte : Extend value into EAX and return
698 ///   ret short, ushort: Extend value into EAX and return
699 ///   ret int, uint    : Move value into EAX and return
700 ///   ret pointer      : Move value into EAX and return
701 ///   ret long, ulong  : Move value into EAX/EDX and return
702 ///   ret float/double : Top of FP stack
703 ///
704 void ISel::visitReturnInst(ReturnInst &I) {
705   if (I.getNumOperands() == 0) {
706     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
707     return;
708   }
709
710   Value *RetVal = I.getOperand(0);
711   unsigned RetReg = getReg(RetVal);
712   switch (getClassB(RetVal->getType())) {
713   case cByte:   // integral return values: extend or move into EAX and return
714   case cShort:
715   case cInt:
716     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
717     // Declare that EAX is live on exit
718     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
719     break;
720   case cFP:                   // Floats & Doubles: Return in ST(0)
721     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
722     // Declare that top-of-stack is live on exit
723     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
724     break;
725   case cLong:
726     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
727     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
728     // Declare that EAX & EDX are live on exit
729     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
730     break;
731   default:
732     visitInstruction(I);
733   }
734   // Emit a 'ret' instruction
735   BuildMI(BB, X86::RET, 0);
736 }
737
738 // getBlockAfter - Return the basic block which occurs lexically after the
739 // specified one.
740 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
741   Function::iterator I = BB; ++I;  // Get iterator to next block
742   return I != BB->getParent()->end() ? &*I : 0;
743 }
744
745 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
746 /// that since code layout is frozen at this point, that if we are trying to
747 /// jump to a block that is the immediate successor of the current block, we can
748 /// just make a fall-through (but we don't currently).
749 ///
750 void ISel::visitBranchInst(BranchInst &BI) {
751   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
752
753   if (!BI.isConditional()) {  // Unconditional branch?
754     if (BI.getSuccessor(0) != NextBB)
755       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
756     return;
757   }
758
759   // See if we can fold the setcc into the branch itself...
760   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
761   if (SCI == 0) {
762     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
763     // computed some other way...
764     unsigned condReg = getReg(BI.getCondition());
765     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
766     if (BI.getSuccessor(1) == NextBB) {
767       if (BI.getSuccessor(0) != NextBB)
768         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
769     } else {
770       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
771       
772       if (BI.getSuccessor(0) != NextBB)
773         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
774     }
775     return;
776   }
777
778   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
779   bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
780                                               SCI->getOperand(1));
781   
782   // LLVM  -> X86 signed  X86 unsigned
783   // -----    ----------  ------------
784   // seteq -> je          je
785   // setne -> jne         jne
786   // setlt -> jl          jb
787   // setge -> jge         jae
788   // setgt -> jg          ja
789   // setle -> jle         jbe
790   static const unsigned OpcodeTab[2][6] = {
791     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
792     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
793   };
794   
795   if (BI.getSuccessor(0) != NextBB) {
796     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
797     if (BI.getSuccessor(1) != NextBB)
798       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
799   } else {
800     // Change to the inverse condition...
801     if (BI.getSuccessor(1) != NextBB) {
802       OpNum ^= 1;
803       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
804     }
805   }
806 }
807
808
809 /// doCall - This emits an abstract call instruction, setting up the arguments
810 /// and the return value as appropriate.  For the actual function call itself,
811 /// it inserts the specified CallMI instruction into the stream.
812 ///
813 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
814                   const std::vector<ValueRecord> &Args) {
815
816   // Count how many bytes are to be pushed on the stack...
817   unsigned NumBytes = 0;
818
819   if (!Args.empty()) {
820     for (unsigned i = 0, e = Args.size(); i != e; ++i)
821       switch (getClassB(Args[i].Ty)) {
822       case cByte: case cShort: case cInt:
823         NumBytes += 4; break;
824       case cLong:
825         NumBytes += 8; break;
826       case cFP:
827         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
828         break;
829       default: assert(0 && "Unknown class!");
830       }
831
832     // Adjust the stack pointer for the new arguments...
833     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
834
835     // Arguments go on the stack in reverse order, as specified by the ABI.
836     unsigned ArgOffset = 0;
837     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
838       unsigned ArgReg = Args[i].Reg;
839       switch (getClassB(Args[i].Ty)) {
840       case cByte:
841       case cShort: {
842         // Promote arg to 32 bits wide into a temporary register...
843         unsigned R = makeAnotherReg(Type::UIntTy);
844         promote32(R, Args[i]);
845         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
846                      X86::ESP, ArgOffset).addReg(R);
847         break;
848       }
849       case cInt:
850         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
851                      X86::ESP, ArgOffset).addReg(ArgReg);
852         break;
853       case cLong:
854         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
855                      X86::ESP, ArgOffset).addReg(ArgReg);
856         addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
857                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
858         ArgOffset += 4;        // 8 byte entry, not 4.
859         break;
860         
861       case cFP:
862         if (Args[i].Ty == Type::FloatTy) {
863           addRegOffset(BuildMI(BB, X86::FSTr32, 5),
864                        X86::ESP, ArgOffset).addReg(ArgReg);
865         } else {
866           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
867           addRegOffset(BuildMI(BB, X86::FSTr64, 5),
868                        X86::ESP, ArgOffset).addReg(ArgReg);
869           ArgOffset += 4;       // 8 byte entry, not 4.
870         }
871         break;
872
873       default: assert(0 && "Unknown class!");
874       }
875       ArgOffset += 4;
876     }
877   } else {
878     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
879   }
880
881   BB->push_back(CallMI);
882
883   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
884
885   // If there is a return value, scavenge the result from the location the call
886   // leaves it in...
887   //
888   if (Ret.Ty != Type::VoidTy) {
889     unsigned DestClass = getClassB(Ret.Ty);
890     switch (DestClass) {
891     case cByte:
892     case cShort:
893     case cInt: {
894       // Integral results are in %eax, or the appropriate portion
895       // thereof.
896       static const unsigned regRegMove[] = {
897         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
898       };
899       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
900       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
901       break;
902     }
903     case cFP:     // Floating-point return values live in %ST(0)
904       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
905       break;
906     case cLong:   // Long values are left in EDX:EAX
907       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
908       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
909       break;
910     default: assert(0 && "Unknown class!");
911     }
912   }
913 }
914
915
916 /// visitCallInst - Push args on stack and do a procedure call instruction.
917 void ISel::visitCallInst(CallInst &CI) {
918   MachineInstr *TheCall;
919   if (Function *F = CI.getCalledFunction()) {
920     // Is it an intrinsic function call?
921     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
922       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
923       return;
924     }
925
926     // Emit a CALL instruction with PC-relative displacement.
927     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
928   } else {  // Emit an indirect call...
929     unsigned Reg = getReg(CI.getCalledValue());
930     TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
931   }
932
933   std::vector<ValueRecord> Args;
934   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
935     Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
936                                CI.getOperand(i)->getType()));
937
938   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
939   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
940 }        
941
942 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
943   unsigned TmpReg1, TmpReg2;
944   switch (ID) {
945   case LLVMIntrinsic::va_start:
946     // Get the address of the first vararg value...
947     TmpReg1 = makeAnotherReg(Type::UIntTy);
948     addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
949     TmpReg2 = getReg(CI.getOperand(1));
950     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
951     return;
952
953   case LLVMIntrinsic::va_end: return;   // Noop on X86
954   case LLVMIntrinsic::va_copy:
955     TmpReg1 = getReg(CI.getOperand(2));  // Get existing va_list
956     TmpReg2 = getReg(CI.getOperand(1));  // Get va_list* to store into
957     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
958     return;
959
960   default: assert(0 && "Unknown intrinsic for X86!");
961   }
962 }
963
964
965 /// visitSimpleBinary - Implement simple binary operators for integral types...
966 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
967 /// Xor.
968 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
969   unsigned DestReg = getReg(B);
970   MachineBasicBlock::iterator MI = BB->end();
971   emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
972                             OperatorClass, DestReg);
973 }
974
975 /// visitSimpleBinary - Implement simple binary operators for integral types...
976 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
977 /// 4 for Xor.
978 ///
979 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
980 /// and constant expression support.
981 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
982                                      MachineBasicBlock::iterator &IP,
983                                      Value *Op0, Value *Op1,
984                                      unsigned OperatorClass,unsigned TargetReg){
985   unsigned Class = getClassB(Op0->getType());
986
987   static const unsigned OpcodeTab[][4] = {
988     // Arithmetic operators
989     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
990     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
991
992     // Bitwise operators
993     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
994     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
995     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
996   };
997
998   bool isLong = false;
999   if (Class == cLong) {
1000     isLong = true;
1001     Class = cInt;          // Bottom 32 bits are handled just like ints
1002   }
1003   
1004   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1005   assert(Opcode && "Floating point arguments to logical inst?");
1006   unsigned Op0r = getReg(Op0, BB, IP);
1007   unsigned Op1r = getReg(Op1, BB, IP);
1008   BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
1009
1010   if (isLong) {        // Handle the upper 32 bits of long values...
1011     static const unsigned TopTab[] = {
1012       X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1013     };
1014     BMI(BB, IP, TopTab[OperatorClass], 2,
1015         TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
1016   }
1017 }
1018
1019 /// doMultiply - Emit appropriate instructions to multiply together the
1020 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1021 /// result should be given as DestTy.
1022 ///
1023 /// FIXME: doMultiply should use one of the two address IMUL instructions!
1024 ///
1025 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
1026                       unsigned DestReg, const Type *DestTy,
1027                       unsigned op0Reg, unsigned op1Reg) {
1028   unsigned Class = getClass(DestTy);
1029   switch (Class) {
1030   case cFP:              // Floating point multiply
1031     BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1032     return;
1033   default:
1034   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1035   case cByte:
1036   case cShort:
1037   case cInt:          // Small integerals, handled below...
1038     break;
1039   }
1040  
1041   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1042   static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32  };
1043   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1044   unsigned Reg     = Regs[Class];
1045
1046   // Emit a MOV to put the first operand into the appropriately-sized
1047   // subreg of EAX.
1048   BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
1049   
1050   // Emit the appropriate multiply instruction.
1051   BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
1052
1053   // Emit another MOV to put the result into the destination register.
1054   BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
1055 }
1056
1057 /// visitMul - Multiplies are not simple binary operators because they must deal
1058 /// with the EAX register explicitly.
1059 ///
1060 void ISel::visitMul(BinaryOperator &I) {
1061   unsigned Op0Reg  = getReg(I.getOperand(0));
1062   unsigned Op1Reg  = getReg(I.getOperand(1));
1063   unsigned DestReg = getReg(I);
1064
1065   // Simple scalar multiply?
1066   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1067     MachineBasicBlock::iterator MBBI = BB->end();
1068     doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1069   } else {
1070     // Long value.  We have to do things the hard way...
1071     // Multiply the two low parts... capturing carry into EDX
1072     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1073     BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg);  // AL*BL
1074
1075     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1076     BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX);     // AL*BL
1077     BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1078
1079     MachineBasicBlock::iterator MBBI = BB->end();
1080     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1081     doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1082
1083     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1084     BuildMI(BB, X86::ADDrr32, 2,                         // AH*BL+(AL*BL >> 32)
1085             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1086     
1087     MBBI = BB->end();
1088     unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1089     doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1090     
1091     BuildMI(BB, X86::ADDrr32, 2,               // AL*BH + AH*BL + (AL*BL >> 32)
1092             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1093   }
1094 }
1095
1096
1097 /// visitDivRem - Handle division and remainder instructions... these
1098 /// instruction both require the same instructions to be generated, they just
1099 /// select the result from a different register.  Note that both of these
1100 /// instructions work differently for signed and unsigned operands.
1101 ///
1102 void ISel::visitDivRem(BinaryOperator &I) {
1103   unsigned Class     = getClass(I.getType());
1104   unsigned Op0Reg    = getReg(I.getOperand(0));
1105   unsigned Op1Reg    = getReg(I.getOperand(1));
1106   unsigned ResultReg = getReg(I);
1107
1108   switch (Class) {
1109   case cFP:              // Floating point divide
1110     if (I.getOpcode() == Instruction::Div)
1111       BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1112     else {               // Floating point remainder...
1113       MachineInstr *TheCall =
1114         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1115       std::vector<ValueRecord> Args;
1116       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1117       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1118       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1119     }
1120     return;
1121   case cLong: {
1122     static const char *FnName[] =
1123       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1124
1125     unsigned NameIdx = I.getType()->isUnsigned()*2;
1126     NameIdx += I.getOpcode() == Instruction::Div;
1127     MachineInstr *TheCall =
1128       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1129
1130     std::vector<ValueRecord> Args;
1131     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1132     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1133     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1134     return;
1135   }
1136   case cByte: case cShort: case cInt:
1137     break;          // Small integerals, handled below...
1138   default: assert(0 && "Unknown class!");
1139   }
1140
1141   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1142   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1143   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
1144   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1145   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1146
1147   static const unsigned DivOpcode[][4] = {
1148     { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 },  // Unsigned division
1149     { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 },  // Signed division
1150   };
1151
1152   bool isSigned   = I.getType()->isSigned();
1153   unsigned Reg    = Regs[Class];
1154   unsigned ExtReg = ExtRegs[Class];
1155
1156   // Put the first operand into one of the A registers...
1157   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1158
1159   if (isSigned) {
1160     // Emit a sign extension instruction...
1161     BuildMI(BB, ExtOpcode[Class], 0);
1162   } else {
1163     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1164     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1165   }
1166
1167   // Emit the appropriate divide or remainder instruction...
1168   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1169
1170   // Figure out which register we want to pick the result out of...
1171   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1172   
1173   // Put the result into the destination register...
1174   BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1175 }
1176
1177
1178 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1179 /// for constant immediate shift values, and for constant immediate
1180 /// shift values equal to 1. Even the general case is sort of special,
1181 /// because the shift amount has to be in CL, not just any old register.
1182 ///
1183 void ISel::visitShiftInst(ShiftInst &I) {
1184   unsigned SrcReg = getReg(I.getOperand(0));
1185   unsigned DestReg = getReg(I);
1186   bool isLeftShift = I.getOpcode() == Instruction::Shl;
1187   bool isSigned = I.getType()->isSigned();
1188   unsigned Class = getClass(I.getType());
1189   
1190   static const unsigned ConstantOperand[][4] = {
1191     { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 },  // SHR
1192     { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 },  // SAR
1193     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SHL
1194     { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 },  // SAL = SHL
1195   };
1196
1197   static const unsigned NonConstantOperand[][4] = {
1198     { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 },  // SHR
1199     { X86::SARrr8, X86::SARrr16, X86::SARrr32 },  // SAR
1200     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SHL
1201     { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 },  // SAL = SHL
1202   };
1203
1204   // Longs, as usual, are handled specially...
1205   if (Class == cLong) {
1206     // If we have a constant shift, we can generate much more efficient code
1207     // than otherwise...
1208     //
1209     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1210       unsigned Amount = CUI->getValue();
1211       if (Amount < 32) {
1212         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1213         if (isLeftShift) {
1214           BuildMI(BB, Opc[3], 3, 
1215                   DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1216           BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1217         } else {
1218           BuildMI(BB, Opc[3], 3,
1219                   DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addZImm(Amount);
1220           BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1221         }
1222       } else {                 // Shifting more than 32 bits
1223         Amount -= 32;
1224         if (isLeftShift) {
1225           BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1226           BuildMI(BB, X86::MOVir32, 1,DestReg  ).addZImm(0);
1227         } else {
1228           unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1229           BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1230           BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1231         }
1232       }
1233     } else {
1234       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1235
1236       if (!isLeftShift && isSigned) {
1237         // If this is a SHR of a Long, then we need to do funny sign extension
1238         // stuff.  TmpReg gets the value to use as the high-part if we are
1239         // shifting more than 32 bits.
1240         BuildMI(BB, X86::SARir32, 2, TmpReg).addReg(SrcReg).addZImm(31);
1241       } else {
1242         // Other shifts use a fixed zero value if the shift is more than 32
1243         // bits.
1244         BuildMI(BB, X86::MOVir32, 1, TmpReg).addZImm(0);
1245       }
1246
1247       // Initialize CL with the shift amount...
1248       unsigned ShiftAmount = getReg(I.getOperand(1));
1249       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmount);
1250
1251       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1252       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1253       if (isLeftShift) {
1254         // TmpReg2 = shld inHi, inLo
1255         BuildMI(BB, X86::SHLDrr32, 2, TmpReg2).addReg(SrcReg+1).addReg(SrcReg);
1256         // TmpReg3 = shl  inLo, CL
1257         BuildMI(BB, X86::SHLrr32, 1, TmpReg3).addReg(SrcReg);
1258
1259         // Set the flags to indicate whether the shift was by more than 32 bits.
1260         BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1261
1262         // DestHi = (>32) ? TmpReg3 : TmpReg2;
1263         BuildMI(BB, X86::CMOVNErr32, 2, 
1264                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1265         // DestLo = (>32) ? TmpReg : TmpReg3;
1266         BuildMI(BB, X86::CMOVNErr32, 2, DestReg).addReg(TmpReg3).addReg(TmpReg);
1267       } else {
1268         // TmpReg2 = shrd inLo, inHi
1269         BuildMI(BB, X86::SHRDrr32, 2, TmpReg2).addReg(SrcReg).addReg(SrcReg+1);
1270         // TmpReg3 = s[ah]r  inHi, CL
1271         BuildMI(BB, isSigned ? X86::SARrr32 : X86::SHRrr32, 1, TmpReg3)
1272                        .addReg(SrcReg+1);
1273
1274         // Set the flags to indicate whether the shift was by more than 32 bits.
1275         BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1276
1277         // DestLo = (>32) ? TmpReg3 : TmpReg2;
1278         BuildMI(BB, X86::CMOVNErr32, 2, 
1279                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1280
1281         // DestHi = (>32) ? TmpReg : TmpReg3;
1282         BuildMI(BB, X86::CMOVNErr32, 2, 
1283                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1284       }
1285     }
1286     return;
1287   }
1288
1289   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1290     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1291     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1292
1293     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1294     BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1295   } else {                  // The shift amount is non-constant.
1296     BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1297
1298     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1299     BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1300   }
1301 }
1302
1303
1304 /// doFPLoad - This method is used to load an FP value from memory using the
1305 /// current endianness.  NOTE: This method returns a partially constructed load
1306 /// instruction which needs to have the memory source filled in still.
1307 ///
1308 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1309                              MachineBasicBlock::iterator &MBBI,
1310                              const Type *Ty, unsigned DestReg) {
1311   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1312   unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1313
1314   if (TM.getTargetData().isLittleEndian()) // fast path...
1315     return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1316
1317   // If we are big-endian, start by creating an LEA instruction to represent the
1318   // address of the memory location to load from...
1319   //
1320   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1321   MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1322
1323   // Allocate a temporary stack slot to transform the value into...
1324   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1325
1326   // Perform the bswaps 32 bits at a time...
1327   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1328   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1329   addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1330   BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1331   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1332   addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1333                     FrameIdx, Offset).addReg(TmpReg2);
1334   
1335   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1336     TmpReg1 = makeAnotherReg(Type::UIntTy);
1337     TmpReg2 = makeAnotherReg(Type::UIntTy);
1338
1339     addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1340     BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1341     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1342     addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1343   }
1344
1345   // Now we can reload the final byteswapped result into the final destination.
1346   addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1347   return Result;
1348 }
1349
1350 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1351 ///
1352 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1353   // Emit the byte swap instruction...
1354   switch (Class) {
1355   case cByte:
1356     // No byteswap necessary for 8 bit value...
1357     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1358     break;
1359   case cInt:
1360     // Use the 32 bit bswap instruction to do a 32 bit swap...
1361     BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1362     break;
1363     
1364   case cShort:
1365     // For 16 bit we have to use an xchg instruction, because there is no
1366     // 16-bit bswap.  XCHG is necessarily not in SSA form, so we force things
1367     // into AX to do the xchg.
1368     //
1369     BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1370     BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1371       .addReg(X86::AH, MOTy::UseAndDef);
1372     BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1373     break;
1374   default: assert(0 && "Cannot byteswap this class!");
1375   }
1376 }
1377
1378
1379 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1380 /// instruction.  The load and store instructions are the only place where we
1381 /// need to worry about the memory layout of the target machine.
1382 ///
1383 void ISel::visitLoadInst(LoadInst &I) {
1384   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1385   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1386   unsigned SrcAddrReg = getReg(I.getOperand(0));
1387   unsigned DestReg = getReg(I);
1388
1389   unsigned Class = getClass(I.getType());
1390   switch (Class) {
1391   case cFP: {
1392     MachineBasicBlock::iterator MBBI = BB->end();
1393     addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1394     return;
1395   }
1396   case cLong: case cInt: case cShort: case cByte:
1397     break;      // Integers of various sizes handled below
1398   default: assert(0 && "Unknown memory class!");
1399   }
1400
1401   // We need to adjust the input pointer if we are emulating a big-endian
1402   // long-pointer target.  On these systems, the pointer that we are interested
1403   // in is in the upper part of the eight byte memory image of the pointer.  It
1404   // also happens to be byte-swapped, but this will be handled later.
1405   //
1406   if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1407     unsigned R = makeAnotherReg(Type::UIntTy);
1408     BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1409     SrcAddrReg = R;
1410   }
1411
1412   unsigned IReg = DestReg;
1413   if (!isLittleEndian)  // If big endian we need an intermediate stage
1414     DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1415
1416   static const unsigned Opcode[] = {
1417     X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1418   };
1419   addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1420
1421   // Handle long values now...
1422   if (Class == cLong) {
1423     if (isLittleEndian) {
1424       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1425     } else {
1426       EmitByteSwap(IReg+1, DestReg, cInt);
1427       unsigned TempReg = makeAnotherReg(Type::IntTy);
1428       addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1429       EmitByteSwap(IReg, TempReg, cInt);
1430     }
1431     return;
1432   }
1433
1434   if (!isLittleEndian)
1435     EmitByteSwap(IReg, DestReg, Class);
1436 }
1437
1438
1439 /// doFPStore - This method is used to store an FP value to memory using the
1440 /// current endianness.
1441 ///
1442 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1443   assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1444   unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1445
1446   if (TM.getTargetData().isLittleEndian()) {  // fast path...
1447     addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1448     return;
1449   }
1450
1451   // Allocate a temporary stack slot to transform the value into...
1452   int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1453   unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1454   addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1455
1456   // Store the value into a temporary stack slot...
1457   addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1458
1459   // Perform the bswaps 32 bits at a time...
1460   unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1461   unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1462   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1463   BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1464   unsigned Offset = (Ty == Type::DoubleTy) << 2;
1465   addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1466                DestAddrReg, Offset).addReg(TmpReg2);
1467   
1468   if (Ty == Type::DoubleTy) {   // Swap the other 32 bits of a double value...
1469     TmpReg1 = makeAnotherReg(Type::UIntTy);
1470     TmpReg2 = makeAnotherReg(Type::UIntTy);
1471
1472     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1473     BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1474     unsigned Offset = (Ty == Type::DoubleTy) << 2;
1475     addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1476   }
1477 }
1478
1479
1480 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1481 /// instruction.
1482 ///
1483 void ISel::visitStoreInst(StoreInst &I) {
1484   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
1485   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1486   unsigned ValReg      = getReg(I.getOperand(0));
1487   unsigned AddressReg  = getReg(I.getOperand(1));
1488
1489   unsigned Class = getClass(I.getOperand(0)->getType());
1490   switch (Class) {
1491   case cLong:
1492     if (isLittleEndian) {
1493       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1494       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1495                    AddressReg, 4).addReg(ValReg+1);
1496     } else {
1497       unsigned T1 = makeAnotherReg(Type::IntTy);
1498       unsigned T2 = makeAnotherReg(Type::IntTy);
1499       EmitByteSwap(T1, ValReg  , cInt);
1500       EmitByteSwap(T2, ValReg+1, cInt);
1501       addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1502       addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1503     }
1504     return;
1505   case cFP:
1506     doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1507     return;
1508   case cInt: case cShort: case cByte:
1509     break;      // Integers of various sizes handled below
1510   default: assert(0 && "Unknown memory class!");
1511   }
1512
1513   if (!isLittleEndian && hasLongPointers &&
1514       isa<PointerType>(I.getOperand(0)->getType())) {
1515     unsigned R = makeAnotherReg(Type::UIntTy);
1516     BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1517     AddressReg = R;
1518   }
1519
1520   if (!isLittleEndian && Class != cByte) {
1521     unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1522     EmitByteSwap(R, ValReg, Class);
1523     ValReg = R;
1524   }
1525
1526   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1527   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1528 }
1529
1530
1531 /// visitCastInst - Here we have various kinds of copying with or without
1532 /// sign extension going on.
1533 void ISel::visitCastInst(CastInst &CI) {
1534   unsigned DestReg = getReg(CI);
1535   MachineBasicBlock::iterator MI = BB->end();
1536   emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1537 }
1538
1539 /// emitCastOperation - Common code shared between visitCastInst and
1540 /// constant expression cast support.
1541 void ISel::emitCastOperation(MachineBasicBlock *BB,
1542                              MachineBasicBlock::iterator &IP,
1543                              Value *Src, const Type *DestTy,
1544                              unsigned DestReg) {
1545   unsigned SrcReg = getReg(Src, BB, IP);
1546   const Type *SrcTy = Src->getType();
1547   unsigned SrcClass = getClassB(SrcTy);
1548   unsigned DestClass = getClassB(DestTy);
1549
1550   // Implement casts to bool by using compare on the operand followed by set if
1551   // not zero on the result.
1552   if (DestTy == Type::BoolTy) {
1553     switch (SrcClass) {
1554     case cByte:
1555       BMI(BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
1556       break;
1557     case cShort:
1558       BMI(BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
1559       break;
1560     case cInt:
1561       BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
1562       break;
1563     case cLong: {
1564       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1565       BMI(BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
1566       break;
1567     }
1568     case cFP:
1569       assert(0 && "FIXME: implement cast FP to bool");
1570       abort();
1571     }
1572
1573     // If the zero flag is not set, then the value is true, set the byte to
1574     // true.
1575     BMI(BB, IP, X86::SETNEr, 1, DestReg);
1576     return;
1577   }
1578
1579   static const unsigned RegRegMove[] = {
1580     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1581   };
1582
1583   // Implement casts between values of the same type class (as determined by
1584   // getClass) by using a register-to-register move.
1585   if (SrcClass == DestClass) {
1586     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1587       BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1588     } else if (SrcClass == cFP) {
1589       if (SrcTy == Type::FloatTy) {  // double -> float
1590         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1591         BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1592       } else {                       // float -> double
1593         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1594                "Unknown cFP member!");
1595         // Truncate from double to float by storing to memory as short, then
1596         // reading it back.
1597         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1598         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1599         addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1600         addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1601       }
1602     } else if (SrcClass == cLong) {
1603       BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1604       BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1605     } else {
1606       assert(0 && "Cannot handle this type of cast instruction!");
1607       abort();
1608     }
1609     return;
1610   }
1611
1612   // Handle cast of SMALLER int to LARGER int using a move with sign extension
1613   // or zero extension, depending on whether the source type was signed.
1614   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1615       SrcClass < DestClass) {
1616     bool isLong = DestClass == cLong;
1617     if (isLong) DestClass = cInt;
1618
1619     static const unsigned Opc[][4] = {
1620       { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1621       { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 }  // u
1622     };
1623     
1624     bool isUnsigned = SrcTy->isUnsigned();
1625     BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1626         DestReg).addReg(SrcReg);
1627
1628     if (isLong) {  // Handle upper 32 bits as appropriate...
1629       if (isUnsigned)     // Zero out top bits...
1630         BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1631       else                // Sign extend bottom half...
1632         BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1633     }
1634     return;
1635   }
1636
1637   // Special case long -> int ...
1638   if (SrcClass == cLong && DestClass == cInt) {
1639     BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1640     return;
1641   }
1642   
1643   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1644   // move out of AX or AL.
1645   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1646       && SrcClass > DestClass) {
1647     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1648     BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1649     BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1650     return;
1651   }
1652
1653   // Handle casts from integer to floating point now...
1654   if (DestClass == cFP) {
1655     // Promote the integer to a type supported by FLD.  We do this because there
1656     // are no unsigned FLD instructions, so we must promote an unsigned value to
1657     // a larger signed value, then use FLD on the larger value.
1658     //
1659     const Type *PromoteType = 0;
1660     unsigned PromoteOpcode;
1661     switch (SrcTy->getPrimitiveID()) {
1662     case Type::BoolTyID:
1663     case Type::SByteTyID:
1664       // We don't have the facilities for directly loading byte sized data from
1665       // memory (even signed).  Promote it to 16 bits.
1666       PromoteType = Type::ShortTy;
1667       PromoteOpcode = X86::MOVSXr16r8;
1668       break;
1669     case Type::UByteTyID:
1670       PromoteType = Type::ShortTy;
1671       PromoteOpcode = X86::MOVZXr16r8;
1672       break;
1673     case Type::UShortTyID:
1674       PromoteType = Type::IntTy;
1675       PromoteOpcode = X86::MOVZXr32r16;
1676       break;
1677     case Type::UIntTyID: {
1678       // Make a 64 bit temporary... and zero out the top of it...
1679       unsigned TmpReg = makeAnotherReg(Type::LongTy);
1680       BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1681       BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1682       SrcTy = Type::LongTy;
1683       SrcClass = cLong;
1684       SrcReg = TmpReg;
1685       break;
1686     }
1687     case Type::ULongTyID:
1688       assert("FIXME: not implemented: cast ulong X to fp type!");
1689     default:  // No promotion needed...
1690       break;
1691     }
1692     
1693     if (PromoteType) {
1694       unsigned TmpReg = makeAnotherReg(PromoteType);
1695       BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1696           1, TmpReg).addReg(SrcReg);
1697       SrcTy = PromoteType;
1698       SrcClass = getClass(PromoteType);
1699       SrcReg = TmpReg;
1700     }
1701
1702     // Spill the integer to memory and reload it from there...
1703     int FrameIdx =
1704       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1705
1706     if (SrcClass == cLong) {
1707       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1708       addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1709                         FrameIdx, 4).addReg(SrcReg+1);
1710     } else {
1711       static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1712       addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1713     }
1714
1715     static const unsigned Op2[] =
1716       { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
1717     addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1718     return;
1719   }
1720
1721   // Handle casts from floating point to integer now...
1722   if (SrcClass == cFP) {
1723     // Change the floating point control register to use "round towards zero"
1724     // mode when truncating to an integer value.
1725     //
1726     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1727     addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1728
1729     // Load the old value of the high byte of the control word...
1730     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1731     addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1732
1733     // Set the high part to be round to zero...
1734     addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1735
1736     // Reload the modified control word now...
1737     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1738     
1739     // Restore the memory image of control word to original value
1740     addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1741                       CWFrameIdx, 1).addReg(HighPartOfCW);
1742
1743     // We don't have the facilities for directly storing byte sized data to
1744     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
1745     // larger classes because we only have signed FP stores.
1746     unsigned StoreClass  = DestClass;
1747     const Type *StoreTy  = DestTy;
1748     if (StoreClass == cByte || DestTy->isUnsigned())
1749       switch (StoreClass) {
1750       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
1751       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
1752       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
1753       case cLong:
1754         assert(0 &&"FIXME not implemented: cast FP to unsigned long long");
1755         abort();
1756       default: assert(0 && "Unknown store class!");
1757       }
1758
1759     // Spill the integer to memory and reload it from there...
1760     int FrameIdx =
1761       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1762
1763     static const unsigned Op1[] =
1764       { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1765     addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1766
1767     if (DestClass == cLong) {
1768       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1769       addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1770     } else {
1771       static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1772       addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1773     }
1774
1775     // Reload the original control word now...
1776     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1777     return;
1778   }
1779
1780   // Anything we haven't handled already, we can't (yet) handle at all.
1781   assert(0 && "Unhandled cast instruction!");
1782   abort();
1783 }
1784
1785 /// visitVarArgInst - Implement the va_arg instruction...
1786 ///
1787 void ISel::visitVarArgInst(VarArgInst &I) {
1788   unsigned SrcReg = getReg(I.getOperand(0));
1789   unsigned DestReg = getReg(I);
1790
1791   // Load the va_list into a register...
1792   unsigned VAList = makeAnotherReg(Type::UIntTy);
1793   addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1794
1795   unsigned Size;
1796   switch (I.getType()->getPrimitiveID()) {
1797   default:
1798     std::cerr << I;
1799     assert(0 && "Error: bad type for va_arg instruction!");
1800     return;
1801   case Type::PointerTyID:
1802   case Type::UIntTyID:
1803   case Type::IntTyID:
1804     Size = 4;
1805     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1806     break;
1807   case Type::ULongTyID:
1808   case Type::LongTyID:
1809     Size = 8;
1810     addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1811     addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1812     break;
1813   case Type::DoubleTyID:
1814     Size = 8;
1815     addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1816     break;
1817   }
1818
1819   // Increment the VAList pointer...
1820   unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1821   BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1822
1823   // Update the VAList in memory...
1824   addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1825 }
1826
1827
1828 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1829 // returns zero when the input is not exactly a power of two.
1830 static unsigned ExactLog2(unsigned Val) {
1831   if (Val == 0) return 0;
1832   unsigned Count = 0;
1833   while (Val != 1) {
1834     if (Val & 1) return 0;
1835     Val >>= 1;
1836     ++Count;
1837   }
1838   return Count+1;
1839 }
1840
1841 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1842   unsigned outputReg = getReg(I);
1843   MachineBasicBlock::iterator MI = BB->end();
1844   emitGEPOperation(BB, MI, I.getOperand(0),
1845                    I.op_begin()+1, I.op_end(), outputReg);
1846 }
1847
1848 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1849                             MachineBasicBlock::iterator &IP,
1850                             Value *Src, User::op_iterator IdxBegin,
1851                             User::op_iterator IdxEnd, unsigned TargetReg) {
1852   const TargetData &TD = TM.getTargetData();
1853   const Type *Ty = Src->getType();
1854   unsigned BaseReg = getReg(Src, MBB, IP);
1855
1856   // GEPs have zero or more indices; we must perform a struct access
1857   // or array access for each one.
1858   for (GetElementPtrInst::op_iterator oi = IdxBegin,
1859          oe = IdxEnd; oi != oe; ++oi) {
1860     Value *idx = *oi;
1861     unsigned NextReg = BaseReg;
1862     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1863       // It's a struct access.  idx is the index into the structure,
1864       // which names the field. This index must have ubyte type.
1865       const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1866       assert(CUI->getType() == Type::UByteTy
1867               && "Funny-looking structure index in GEP");
1868       // Use the TargetData structure to pick out what the layout of
1869       // the structure is in memory.  Since the structure index must
1870       // be constant, we can get its value and use it to find the
1871       // right byte offset from the StructLayout class's list of
1872       // structure member offsets.
1873       unsigned idxValue = CUI->getValue();
1874       unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1875       if (FieldOff) {
1876         NextReg = makeAnotherReg(Type::UIntTy);
1877         // Emit an ADD to add FieldOff to the basePtr.
1878         BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1879       }
1880       // The next type is the member of the structure selected by the
1881       // index.
1882       Ty = StTy->getElementTypes()[idxValue];
1883     } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1884       // It's an array or pointer access: [ArraySize x ElementType].
1885
1886       // idx is the index into the array.  Unlike with structure
1887       // indices, we may not know its actual value at code-generation
1888       // time.
1889       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1890
1891       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1892       // must find the size of the pointed-to type (Not coincidentally, the next
1893       // type is the type of the elements in the array).
1894       Ty = SqTy->getElementType();
1895       unsigned elementSize = TD.getTypeSize(Ty);
1896
1897       // If idxReg is a constant, we don't need to perform the multiply!
1898       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1899         if (!CSI->isNullValue()) {
1900           unsigned Offset = elementSize*CSI->getValue();
1901           NextReg = makeAnotherReg(Type::UIntTy);
1902           BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1903         }
1904       } else if (elementSize == 1) {
1905         // If the element size is 1, we don't have to multiply, just add
1906         unsigned idxReg = getReg(idx, MBB, IP);
1907         NextReg = makeAnotherReg(Type::UIntTy);
1908         BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1909       } else {
1910         unsigned idxReg = getReg(idx, MBB, IP);
1911         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1912         if (unsigned Shift = ExactLog2(elementSize)) {
1913           // If the element size is exactly a power of 2, use a shift to get it.
1914           BMI(MBB, IP, X86::SHLir32, 2,
1915               OffsetReg).addReg(idxReg).addZImm(Shift-1);
1916         } else {
1917           // Most general case, emit a multiply...
1918           unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1919           BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1920         
1921           // Emit a MUL to multiply the register holding the index by
1922           // elementSize, putting the result in OffsetReg.
1923           doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1924         }
1925         // Emit an ADD to add OffsetReg to the basePtr.
1926         NextReg = makeAnotherReg(Type::UIntTy);
1927         BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1928       }
1929     }
1930     // Now that we are here, further indices refer to subtypes of this
1931     // one, so we don't need to worry about BaseReg itself, anymore.
1932     BaseReg = NextReg;
1933   }
1934   // After we have processed all the indices, the result is left in
1935   // BaseReg.  Move it to the register where we were expected to
1936   // put the answer.  A 32-bit move should do it, because we are in
1937   // ILP32 land.
1938   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
1939 }
1940
1941
1942 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1943 /// frame manager, otherwise do it the hard way.
1944 ///
1945 void ISel::visitAllocaInst(AllocaInst &I) {
1946   // Find the data size of the alloca inst's getAllocatedType.
1947   const Type *Ty = I.getAllocatedType();
1948   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1949
1950   // If this is a fixed size alloca in the entry block for the function,
1951   // statically stack allocate the space.
1952   //
1953   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1954     if (I.getParent() == I.getParent()->getParent()->begin()) {
1955       TySize *= CUI->getValue();   // Get total allocated size...
1956       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1957       
1958       // Create a new stack object using the frame manager...
1959       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1960       addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1961       return;
1962     }
1963   }
1964   
1965   // Create a register to hold the temporary result of multiplying the type size
1966   // constant by the variable amount.
1967   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1968   unsigned SrcReg1 = getReg(I.getArraySize());
1969   unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1970   BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1971   
1972   // TotalSizeReg = mul <numelements>, <TypeSize>
1973   MachineBasicBlock::iterator MBBI = BB->end();
1974   doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1975
1976   // AddedSize = add <TotalSizeReg>, 15
1977   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1978   BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1979
1980   // AlignedSize = and <AddedSize>, ~15
1981   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1982   BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1983   
1984   // Subtract size from stack pointer, thereby allocating some space.
1985   BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
1986
1987   // Put a pointer to the space into the result register, by copying
1988   // the stack pointer.
1989   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1990
1991   // Inform the Frame Information that we have just allocated a variable-sized
1992   // object.
1993   F->getFrameInfo()->CreateVariableSizedObject();
1994 }
1995
1996 /// visitMallocInst - Malloc instructions are code generated into direct calls
1997 /// to the library malloc.
1998 ///
1999 void ISel::visitMallocInst(MallocInst &I) {
2000   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2001   unsigned Arg;
2002
2003   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2004     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2005   } else {
2006     Arg = makeAnotherReg(Type::UIntTy);
2007     unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
2008     unsigned Op1Reg = getReg(I.getOperand(0));
2009     MachineBasicBlock::iterator MBBI = BB->end();
2010     doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
2011                
2012                
2013   }
2014
2015   std::vector<ValueRecord> Args;
2016   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2017   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2018                                   1).addExternalSymbol("malloc", true);
2019   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2020 }
2021
2022
2023 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2024 /// function.
2025 ///
2026 void ISel::visitFreeInst(FreeInst &I) {
2027   std::vector<ValueRecord> Args;
2028   Args.push_back(ValueRecord(getReg(I.getOperand(0)),
2029                              I.getOperand(0)->getType()));
2030   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2031                                   1).addExternalSymbol("free", true);
2032   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2033 }
2034    
2035
2036 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
2037 /// into a machine code representation is a very simple peep-hole fashion.  The
2038 /// generated code sucks but the implementation is nice and simple.
2039 ///
2040 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
2041   return new ISel(TM);
2042 }