These two virtual methods are never called.
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a simple peephole instruction selector for the x86 target
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicLowering.h"
22 #include "llvm/Pass.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/Statistic.h"
33 using namespace llvm;
34
35 namespace {
36   Statistic<>
37   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
38 }
39
40 /// BMI - A special BuildMI variant that takes an iterator to insert the
41 /// instruction at as well as a basic block.  This is the version for when you
42 /// have a destination register in mind.
43 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
44                                       MachineBasicBlock::iterator I,
45                                       int Opcode, unsigned NumOperands,
46                                       unsigned DestReg) {
47   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
48   MBB->insert(I, MI);
49   return MachineInstrBuilder(MI).addReg(DestReg, MachineOperand::Def);
50 }
51
52 /// BMI - A special BuildMI variant that takes an iterator to insert the
53 /// instruction at as well as a basic block.
54 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
55                                       MachineBasicBlock::iterator I,
56                                       int Opcode, unsigned NumOperands) {
57   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
58   MBB->insert(I, MI);
59   return MachineInstrBuilder(MI);
60 }
61
62
63 namespace {
64   struct ISel : public FunctionPass, InstVisitor<ISel> {
65     TargetMachine &TM;
66     MachineFunction *F;                 // The function we are compiling into
67     MachineBasicBlock *BB;              // The current MBB we are compiling
68     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
69     int ReturnAddressIndex;             // FrameIndex for the return address
70
71     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
72
73     // MBBMap - Mapping between LLVM BB -> Machine BB
74     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
75
76     ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
77
78     /// runOnFunction - Top level implementation of instruction selection for
79     /// the entire function.
80     ///
81     bool runOnFunction(Function &Fn) {
82       // First pass over the function, lower any unknown intrinsic functions
83       // with the IntrinsicLowering class.
84       LowerUnknownIntrinsicFunctionCalls(Fn);
85
86       F = &MachineFunction::construct(&Fn, TM);
87
88       // Create all of the machine basic blocks for the function...
89       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
90         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
91
92       BB = &F->front();
93
94       // Set up a frame object for the return address.  This is used by the
95       // llvm.returnaddress & llvm.frameaddress intrinisics.
96       ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
97
98       // Copy incoming arguments off of the stack...
99       LoadArgumentsToVirtualRegs(Fn);
100
101       // Instruction select everything except PHI nodes
102       visit(Fn);
103
104       // Select the PHI nodes
105       SelectPHINodes();
106
107       // Insert the FP_REG_KILL instructions into blocks that need them.
108       InsertFPRegKills();
109
110       RegMap.clear();
111       MBBMap.clear();
112       F = 0;
113       // We always build a machine code representation for the function
114       return true;
115     }
116
117     virtual const char *getPassName() const {
118       return "X86 Simple Instruction Selection";
119     }
120
121     /// visitBasicBlock - This method is called when we are visiting a new basic
122     /// block.  This simply creates a new MachineBasicBlock to emit code into
123     /// and adds it to the current MachineFunction.  Subsequent visit* for
124     /// instructions will be invoked for all instructions in the basic block.
125     ///
126     void visitBasicBlock(BasicBlock &LLVM_BB) {
127       BB = MBBMap[&LLVM_BB];
128     }
129
130     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
131     /// function, lowering any calls to unknown intrinsic functions into the
132     /// equivalent LLVM code.
133     void LowerUnknownIntrinsicFunctionCalls(Function &F);
134
135     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
136     /// from the stack into virtual registers.
137     ///
138     void LoadArgumentsToVirtualRegs(Function &F);
139
140     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
141     /// because we have to generate our sources into the source basic blocks,
142     /// not the current one.
143     ///
144     void SelectPHINodes();
145
146     /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
147     /// that need them.  This only occurs due to the floating point stackifier
148     /// not being aggressive enough to handle arbitrary global stackification.
149     ///
150     void InsertFPRegKills();
151
152     // Visitation methods for various instructions.  These methods simply emit
153     // fixed X86 code for each instruction.
154     //
155
156     // Control flow operators
157     void visitReturnInst(ReturnInst &RI);
158     void visitBranchInst(BranchInst &BI);
159
160     struct ValueRecord {
161       Value *Val;
162       unsigned Reg;
163       const Type *Ty;
164       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
165       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
166     };
167     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
168                 const std::vector<ValueRecord> &Args);
169     void visitCallInst(CallInst &I);
170     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
171
172     // Arithmetic operators
173     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
174     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
175     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
176     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
177                     unsigned DestReg, const Type *DestTy,
178                     unsigned Op0Reg, unsigned Op1Reg);
179     void doMultiplyConst(MachineBasicBlock *MBB, 
180                          MachineBasicBlock::iterator MBBI,
181                          unsigned DestReg, const Type *DestTy,
182                          unsigned Op0Reg, unsigned Op1Val);
183     void visitMul(BinaryOperator &B);
184
185     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
186     void visitRem(BinaryOperator &B) { visitDivRem(B); }
187     void visitDivRem(BinaryOperator &B);
188
189     // Bitwise operators
190     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
191     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
192     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
193
194     // Comparison operators...
195     void visitSetCondInst(SetCondInst &I);
196     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
197                             MachineBasicBlock *MBB,
198                             MachineBasicBlock::iterator MBBI);
199     
200     // Memory Instructions
201     void visitLoadInst(LoadInst &I);
202     void visitStoreInst(StoreInst &I);
203     void visitGetElementPtrInst(GetElementPtrInst &I);
204     void visitAllocaInst(AllocaInst &I);
205     void visitMallocInst(MallocInst &I);
206     void visitFreeInst(FreeInst &I);
207     
208     // Other operators
209     void visitShiftInst(ShiftInst &I);
210     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
211     void visitCastInst(CastInst &I);
212     void visitVANextInst(VANextInst &I);
213     void visitVAArgInst(VAArgInst &I);
214
215     void visitInstruction(Instruction &I) {
216       std::cerr << "Cannot instruction select: " << I;
217       abort();
218     }
219
220     /// promote32 - Make a value 32-bits wide, and put it somewhere.
221     ///
222     void promote32(unsigned targetReg, const ValueRecord &VR);
223
224     // getGEPIndex - This is used to fold GEP instructions into X86 addressing
225     // expressions.
226     void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
227                      std::vector<Value*> &GEPOps,
228                      std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
229                      unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
230
231     /// isGEPFoldable - Return true if the specified GEP can be completely
232     /// folded into the addressing mode of a load/store or lea instruction.
233     bool isGEPFoldable(MachineBasicBlock *MBB,
234                        Value *Src, User::op_iterator IdxBegin,
235                        User::op_iterator IdxEnd, unsigned &BaseReg,
236                        unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
237
238     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
239     /// constant expression GEP support.
240     ///
241     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
242                           Value *Src, User::op_iterator IdxBegin,
243                           User::op_iterator IdxEnd, unsigned TargetReg);
244
245     /// emitCastOperation - Common code shared between visitCastInst and
246     /// constant expression cast support.
247     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
248                            Value *Src, const Type *DestTy, unsigned TargetReg);
249
250     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
251     /// and constant expression support.
252     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
253                                    MachineBasicBlock::iterator IP,
254                                    Value *Op0, Value *Op1,
255                                    unsigned OperatorClass, unsigned TargetReg);
256
257     void emitDivRemOperation(MachineBasicBlock *BB,
258                              MachineBasicBlock::iterator IP,
259                              unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
260                              const Type *Ty, unsigned TargetReg);
261
262     /// emitSetCCOperation - Common code shared between visitSetCondInst and
263     /// constant expression support.
264     void emitSetCCOperation(MachineBasicBlock *BB,
265                             MachineBasicBlock::iterator IP,
266                             Value *Op0, Value *Op1, unsigned Opcode,
267                             unsigned TargetReg);
268
269     /// emitShiftOperation - Common code shared between visitShiftInst and
270     /// constant expression support.
271     void emitShiftOperation(MachineBasicBlock *MBB,
272                             MachineBasicBlock::iterator IP,
273                             Value *Op, Value *ShiftAmount, bool isLeftShift,
274                             const Type *ResultTy, unsigned DestReg);
275       
276
277     /// copyConstantToRegister - Output the instructions required to put the
278     /// specified constant into the specified register.
279     ///
280     void copyConstantToRegister(MachineBasicBlock *MBB,
281                                 MachineBasicBlock::iterator MBBI,
282                                 Constant *C, unsigned Reg);
283
284     /// makeAnotherReg - This method returns the next register number we haven't
285     /// yet used.
286     ///
287     /// Long values are handled somewhat specially.  They are always allocated
288     /// as pairs of 32 bit integer values.  The register number returned is the
289     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
290     /// of the long value.
291     ///
292     unsigned makeAnotherReg(const Type *Ty) {
293       assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
294              "Current target doesn't have X86 reg info??");
295       const X86RegisterInfo *MRI =
296         static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
297       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
298         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
299         // Create the lower part
300         F->getSSARegMap()->createVirtualRegister(RC);
301         // Create the upper part.
302         return F->getSSARegMap()->createVirtualRegister(RC)-1;
303       }
304
305       // Add the mapping of regnumber => reg class to MachineFunction
306       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
307       return F->getSSARegMap()->createVirtualRegister(RC);
308     }
309
310     /// getReg - This method turns an LLVM value into a register number.  This
311     /// is guaranteed to produce the same register number for a particular value
312     /// every time it is queried.
313     ///
314     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
315     unsigned getReg(Value *V) {
316       // Just append to the end of the current bb.
317       MachineBasicBlock::iterator It = BB->end();
318       return getReg(V, BB, It);
319     }
320     unsigned getReg(Value *V, MachineBasicBlock *MBB,
321                     MachineBasicBlock::iterator IPt) {
322       unsigned &Reg = RegMap[V];
323       if (Reg == 0) {
324         Reg = makeAnotherReg(V->getType());
325         RegMap[V] = Reg;
326       }
327
328       // If this operand is a constant, emit the code to copy the constant into
329       // the register here...
330       //
331       if (Constant *C = dyn_cast<Constant>(V)) {
332         copyConstantToRegister(MBB, IPt, C, Reg);
333         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
334       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
335         // Move the address of the global into the register
336         BMI(MBB, IPt, X86::MOVri32, 1, Reg).addGlobalAddress(GV);
337         RegMap.erase(V);  // Assign a new name to this address if ref'd again
338       }
339
340       return Reg;
341     }
342   };
343 }
344
345 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
346 /// Representation.
347 ///
348 enum TypeClass {
349   cByte, cShort, cInt, cFP, cLong
350 };
351
352 /// getClass - Turn a primitive type into a "class" number which is based on the
353 /// size of the type, and whether or not it is floating point.
354 ///
355 static inline TypeClass getClass(const Type *Ty) {
356   switch (Ty->getPrimitiveID()) {
357   case Type::SByteTyID:
358   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
359   case Type::ShortTyID:
360   case Type::UShortTyID:  return cShort;     // Short operands are class #1
361   case Type::IntTyID:
362   case Type::UIntTyID:
363   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
364
365   case Type::FloatTyID:
366   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
367
368   case Type::LongTyID:
369   case Type::ULongTyID:   return cLong;      // Longs are class #4
370   default:
371     assert(0 && "Invalid type to getClass!");
372     return cByte;  // not reached
373   }
374 }
375
376 // getClassB - Just like getClass, but treat boolean values as bytes.
377 static inline TypeClass getClassB(const Type *Ty) {
378   if (Ty == Type::BoolTy) return cByte;
379   return getClass(Ty);
380 }
381
382
383 /// copyConstantToRegister - Output the instructions required to put the
384 /// specified constant into the specified register.
385 ///
386 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
387                                   MachineBasicBlock::iterator IP,
388                                   Constant *C, unsigned R) {
389   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
390     unsigned Class = 0;
391     switch (CE->getOpcode()) {
392     case Instruction::GetElementPtr:
393       emitGEPOperation(MBB, IP, CE->getOperand(0),
394                        CE->op_begin()+1, CE->op_end(), R);
395       return;
396     case Instruction::Cast:
397       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
398       return;
399
400     case Instruction::Xor: ++Class; // FALL THROUGH
401     case Instruction::Or:  ++Class; // FALL THROUGH
402     case Instruction::And: ++Class; // FALL THROUGH
403     case Instruction::Sub: ++Class; // FALL THROUGH
404     case Instruction::Add:
405       emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
406                                 Class, R);
407       return;
408
409     case Instruction::Mul: {
410       unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
411       unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
412       doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
413       return;
414     }
415     case Instruction::Div:
416     case Instruction::Rem: {
417       unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
418       unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
419       emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
420                           CE->getOpcode() == Instruction::Div,
421                           CE->getType(), R);
422       return;
423     }
424
425     case Instruction::SetNE:
426     case Instruction::SetEQ:
427     case Instruction::SetLT:
428     case Instruction::SetGT:
429     case Instruction::SetLE:
430     case Instruction::SetGE:
431       emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
432                          CE->getOpcode(), R);
433       return;
434
435     case Instruction::Shl:
436     case Instruction::Shr:
437       emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
438                          CE->getOpcode() == Instruction::Shl, CE->getType(), R);
439       return;
440
441     default:
442       std::cerr << "Offending expr: " << C << "\n";
443       assert(0 && "Constant expression not yet handled!\n");
444     }
445   }
446
447   if (C->getType()->isIntegral()) {
448     unsigned Class = getClassB(C->getType());
449
450     if (Class == cLong) {
451       // Copy the value into the register pair.
452       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
453       BMI(MBB, IP, X86::MOVri32, 1, R).addZImm(Val & 0xFFFFFFFF);
454       BMI(MBB, IP, X86::MOVri32, 1, R+1).addZImm(Val >> 32);
455       return;
456     }
457
458     assert(Class <= cInt && "Type not handled yet!");
459
460     static const unsigned IntegralOpcodeTab[] = {
461       X86::MOVri8, X86::MOVri16, X86::MOVri32
462     };
463
464     if (C->getType() == Type::BoolTy) {
465       BMI(MBB, IP, X86::MOVri8, 1, R).addZImm(C == ConstantBool::True);
466     } else {
467       ConstantInt *CI = cast<ConstantInt>(C);
468       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CI->getRawValue());
469     }
470   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
471     if (CFP->isExactlyValue(+0.0))
472       BMI(MBB, IP, X86::FLD0, 0, R);
473     else if (CFP->isExactlyValue(+1.0))
474       BMI(MBB, IP, X86::FLD1, 0, R);
475     else {
476       // Otherwise we need to spill the constant to memory...
477       MachineConstantPool *CP = F->getConstantPool();
478       unsigned CPI = CP->getConstantPoolIndex(CFP);
479       const Type *Ty = CFP->getType();
480
481       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
482       unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDm32 : X86::FLDm64;
483       addConstantPoolReference(BMI(MBB, IP, LoadOpcode, 4, R), CPI);
484     }
485
486   } else if (isa<ConstantPointerNull>(C)) {
487     // Copy zero (null pointer) to the register.
488     BMI(MBB, IP, X86::MOVri32, 1, R).addZImm(0);
489   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
490     BMI(MBB, IP, X86::MOVri32, 1, R).addGlobalAddress(CPR->getValue());
491   } else {
492     std::cerr << "Offending constant: " << C << "\n";
493     assert(0 && "Type not handled yet!");
494   }
495 }
496
497 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
498 /// the stack into virtual registers.
499 ///
500 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
501   // Emit instructions to load the arguments...  On entry to a function on the
502   // X86, the stack frame looks like this:
503   //
504   // [ESP] -- return address
505   // [ESP + 4] -- first argument (leftmost lexically)
506   // [ESP + 8] -- second argument, if first argument is four bytes in size
507   //    ... 
508   //
509   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
510   MachineFrameInfo *MFI = F->getFrameInfo();
511
512   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
513     unsigned Reg = getReg(*I);
514     
515     int FI;          // Frame object index
516     switch (getClassB(I->getType())) {
517     case cByte:
518       FI = MFI->CreateFixedObject(1, ArgOffset);
519       addFrameReference(BuildMI(BB, X86::MOVrm8, 4, Reg), FI);
520       break;
521     case cShort:
522       FI = MFI->CreateFixedObject(2, ArgOffset);
523       addFrameReference(BuildMI(BB, X86::MOVrm16, 4, Reg), FI);
524       break;
525     case cInt:
526       FI = MFI->CreateFixedObject(4, ArgOffset);
527       addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg), FI);
528       break;
529     case cLong:
530       FI = MFI->CreateFixedObject(8, ArgOffset);
531       addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg), FI);
532       addFrameReference(BuildMI(BB, X86::MOVrm32, 4, Reg+1), FI, 4);
533       ArgOffset += 4;   // longs require 4 additional bytes
534       break;
535     case cFP:
536       unsigned Opcode;
537       if (I->getType() == Type::FloatTy) {
538         Opcode = X86::FLDm32;
539         FI = MFI->CreateFixedObject(4, ArgOffset);
540       } else {
541         Opcode = X86::FLDm64;
542         FI = MFI->CreateFixedObject(8, ArgOffset);
543         ArgOffset += 4;   // doubles require 4 additional bytes
544       }
545       addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
546       break;
547     default:
548       assert(0 && "Unhandled argument type!");
549     }
550     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
551   }
552
553   // If the function takes variable number of arguments, add a frame offset for
554   // the start of the first vararg value... this is used to expand
555   // llvm.va_start.
556   if (Fn.getFunctionType()->isVarArg())
557     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
558 }
559
560
561 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
562 /// because we have to generate our sources into the source basic blocks, not
563 /// the current one.
564 ///
565 void ISel::SelectPHINodes() {
566   const TargetInstrInfo &TII = TM.getInstrInfo();
567   const Function &LF = *F->getFunction();  // The LLVM function...
568   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
569     const BasicBlock *BB = I;
570     MachineBasicBlock *MBB = MBBMap[I];
571
572     // Loop over all of the PHI nodes in the LLVM basic block...
573     MachineBasicBlock::iterator instr = MBB->begin();
574     for (BasicBlock::const_iterator I = BB->begin();
575          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
576
577       // Create a new machine instr PHI node, and insert it.
578       unsigned PHIReg = getReg(*PN);
579       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
580       MBB->insert(instr, PhiMI);
581
582       MachineInstr *LongPhiMI = 0;
583       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
584         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
585         MBB->insert(instr, LongPhiMI);
586       }
587
588       // PHIValues - Map of blocks to incoming virtual registers.  We use this
589       // so that we only initialize one incoming value for a particular block,
590       // even if the block has multiple entries in the PHI node.
591       //
592       std::map<MachineBasicBlock*, unsigned> PHIValues;
593
594       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
595         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
596         unsigned ValReg;
597         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
598           PHIValues.lower_bound(PredMBB);
599
600         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
601           // We already inserted an initialization of the register for this
602           // predecessor.  Recycle it.
603           ValReg = EntryIt->second;
604
605         } else {        
606           // Get the incoming value into a virtual register.
607           //
608           Value *Val = PN->getIncomingValue(i);
609
610           // If this is a constant or GlobalValue, we may have to insert code
611           // into the basic block to compute it into a virtual register.
612           if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
613             // Because we don't want to clobber any values which might be in
614             // physical registers with the computation of this constant (which
615             // might be arbitrarily complex if it is a constant expression),
616             // just insert the computation at the top of the basic block.
617             MachineBasicBlock::iterator PI = PredMBB->begin();
618
619             // Skip over any PHI nodes though!
620             while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
621               ++PI;
622
623             ValReg = getReg(Val, PredMBB, PI);
624           } else {
625             ValReg = getReg(Val);
626           }
627
628           // Remember that we inserted a value for this PHI for this predecessor
629           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
630         }
631
632         PhiMI->addRegOperand(ValReg);
633         PhiMI->addMachineBasicBlockOperand(PredMBB);
634         if (LongPhiMI) {
635           LongPhiMI->addRegOperand(ValReg+1);
636           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
637         }
638       }
639     }
640   }
641 }
642
643 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
644 /// compensation code on critical edges.  As such, it requires that we kill all
645 /// FP registers on the exit from any blocks that either ARE critical edges, or
646 /// branch to a block that has incoming critical edges.
647 ///
648 /// Note that this kill instruction will eventually be eliminated when
649 /// restrictions in the stackifier are relaxed.
650 ///
651 static bool RequiresFPRegKill(const BasicBlock *BB) {
652 #if 0
653   for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
654     const BasicBlock *Succ = *SI;
655     pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
656     ++PI;  // Block have at least one predecessory
657     if (PI != PE) {             // If it has exactly one, this isn't crit edge
658       // If this block has more than one predecessor, check all of the
659       // predecessors to see if they have multiple successors.  If so, then the
660       // block we are analyzing needs an FPRegKill.
661       for (PI = pred_begin(Succ); PI != PE; ++PI) {
662         const BasicBlock *Pred = *PI;
663         succ_const_iterator SI2 = succ_begin(Pred);
664         ++SI2;  // There must be at least one successor of this block.
665         if (SI2 != succ_end(Pred))
666           return true;   // Yes, we must insert the kill on this edge.
667       }
668     }
669   }
670   // If we got this far, there is no need to insert the kill instruction.
671   return false;
672 #else
673   return true;
674 #endif
675 }
676
677 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
678 // need them.  This only occurs due to the floating point stackifier not being
679 // aggressive enough to handle arbitrary global stackification.
680 //
681 // Currently we insert an FP_REG_KILL instruction into each block that uses or
682 // defines a floating point virtual register.
683 //
684 // When the global register allocators (like linear scan) finally update live
685 // variable analysis, we can keep floating point values in registers across
686 // portions of the CFG that do not involve critical edges.  This will be a big
687 // win, but we are waiting on the global allocators before we can do this.
688 //
689 // With a bit of work, the floating point stackifier pass can be enhanced to
690 // break critical edges as needed (to make a place to put compensation code),
691 // but this will require some infrastructure improvements as well.
692 //
693 void ISel::InsertFPRegKills() {
694   SSARegMap &RegMap = *F->getSSARegMap();
695
696   for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
697     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
698       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
699       MachineOperand& MO = I->getOperand(i);
700         if (MO.isRegister() && MO.getReg()) {
701           unsigned Reg = MO.getReg();
702           if (MRegisterInfo::isVirtualRegister(Reg))
703             if (RegMap.getRegClass(Reg)->getSize() == 10)
704               goto UsesFPReg;
705         }
706       }
707     // If we haven't found an FP register use or def in this basic block, check
708     // to see if any of our successors has an FP PHI node, which will cause a
709     // copy to be inserted into this block.
710     for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
711            E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
712       MachineBasicBlock *SBB = MBBMap[*SI];
713       for (MachineBasicBlock::iterator I = SBB->begin();
714            I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
715         if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
716           goto UsesFPReg;
717       }
718     }
719     continue;
720   UsesFPReg:
721     // Okay, this block uses an FP register.  If the block has successors (ie,
722     // it's not an unwind/return), insert the FP_REG_KILL instruction.
723     if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
724         RequiresFPRegKill(BB->getBasicBlock())) {
725       BMI(BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
726       ++NumFPKill;
727     }
728   }
729 }
730
731
732 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
733 // the conditional branch instruction which is the only user of the cc
734 // instruction.  This is the case if the conditional branch is the only user of
735 // the setcc, and if the setcc is in the same basic block as the conditional
736 // branch.  We also don't handle long arguments below, so we reject them here as
737 // well.
738 //
739 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
740   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
741     if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
742         SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
743       const Type *Ty = SCI->getOperand(0)->getType();
744       if (Ty != Type::LongTy && Ty != Type::ULongTy)
745         return SCI;
746     }
747   return 0;
748 }
749
750 // Return a fixed numbering for setcc instructions which does not depend on the
751 // order of the opcodes.
752 //
753 static unsigned getSetCCNumber(unsigned Opcode) {
754   switch(Opcode) {
755   default: assert(0 && "Unknown setcc instruction!");
756   case Instruction::SetEQ: return 0;
757   case Instruction::SetNE: return 1;
758   case Instruction::SetLT: return 2;
759   case Instruction::SetGE: return 3;
760   case Instruction::SetGT: return 4;
761   case Instruction::SetLE: return 5;
762   }
763 }
764
765 // LLVM  -> X86 signed  X86 unsigned
766 // -----    ----------  ------------
767 // seteq -> sete        sete
768 // setne -> setne       setne
769 // setlt -> setl        setb
770 // setge -> setge       setae
771 // setgt -> setg        seta
772 // setle -> setle       setbe
773 // ----
774 //          sets                       // Used by comparison with 0 optimization
775 //          setns
776 static const unsigned SetCCOpcodeTab[2][8] = {
777   { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
778     0, 0 },
779   { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
780     X86::SETSr, X86::SETNSr },
781 };
782
783 // EmitComparison - This function emits a comparison of the two operands,
784 // returning the extended setcc code to use.
785 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
786                               MachineBasicBlock *MBB,
787                               MachineBasicBlock::iterator IP) {
788   // The arguments are already supposed to be of the same type.
789   const Type *CompTy = Op0->getType();
790   unsigned Class = getClassB(CompTy);
791   unsigned Op0r = getReg(Op0, MBB, IP);
792
793   // Special case handling of: cmp R, i
794   if (Class == cByte || Class == cShort || Class == cInt)
795     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
796       uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
797
798       // Mask off any upper bits of the constant, if there are any...
799       Op1v &= (1ULL << (8 << Class)) - 1;
800
801       // If this is a comparison against zero, emit more efficient code.  We
802       // can't handle unsigned comparisons against zero unless they are == or
803       // !=.  These should have been strength reduced already anyway.
804       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
805         static const unsigned TESTTab[] = {
806           X86::TESTrr8, X86::TESTrr16, X86::TESTrr32
807         };
808         BMI(MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
809
810         if (OpNum == 2) return 6;   // Map jl -> js
811         if (OpNum == 3) return 7;   // Map jg -> jns
812         return OpNum;
813       }
814
815       static const unsigned CMPTab[] = {
816         X86::CMPri8, X86::CMPri16, X86::CMPri32
817       };
818
819       BMI(MBB, IP, CMPTab[Class], 2).addReg(Op0r).addZImm(Op1v);
820       return OpNum;
821     }
822
823   // Special case handling of comparison against +/- 0.0
824   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
825     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
826       BMI(MBB, IP, X86::FTST, 1).addReg(Op0r);
827       BMI(MBB, IP, X86::FNSTSWr8, 0);
828       BMI(MBB, IP, X86::SAHF, 1);
829       return OpNum;
830     }
831
832   unsigned Op1r = getReg(Op1, MBB, IP);
833   switch (Class) {
834   default: assert(0 && "Unknown type class!");
835     // Emit: cmp <var1>, <var2> (do the comparison).  We can
836     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
837     // 32-bit.
838   case cByte:
839     BMI(MBB, IP, X86::CMPrr8, 2).addReg(Op0r).addReg(Op1r);
840     break;
841   case cShort:
842     BMI(MBB, IP, X86::CMPrr16, 2).addReg(Op0r).addReg(Op1r);
843     break;
844   case cInt:
845     BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
846     break;
847   case cFP:
848     BMI(MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
849     BMI(MBB, IP, X86::FNSTSWr8, 0);
850     BMI(MBB, IP, X86::SAHF, 1);
851     break;
852
853   case cLong:
854     if (OpNum < 2) {    // seteq, setne
855       unsigned LoTmp = makeAnotherReg(Type::IntTy);
856       unsigned HiTmp = makeAnotherReg(Type::IntTy);
857       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
858       BMI(MBB, IP, X86::XORrr32, 2, LoTmp).addReg(Op0r).addReg(Op1r);
859       BMI(MBB, IP, X86::XORrr32, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
860       BMI(MBB, IP, X86::ORrr32,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
861       break;  // Allow the sete or setne to be generated from flags set by OR
862     } else {
863       // Emit a sequence of code which compares the high and low parts once
864       // each, then uses a conditional move to handle the overflow case.  For
865       // example, a setlt for long would generate code like this:
866       //
867       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
868       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
869       // dest = hi(op1) == hi(op2) ? AL : BL;
870       //
871
872       // FIXME: This would be much better if we had hierarchical register
873       // classes!  Until then, hardcode registers so that we can deal with their
874       // aliases (because we don't have conditional byte moves).
875       //
876       BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
877       BMI(MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
878       BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r+1).addReg(Op1r+1);
879       BMI(MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
880       BMI(MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
881       BMI(MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
882       BMI(MBB, IP, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
883       // NOTE: visitSetCondInst knows that the value is dumped into the BL
884       // register at this point for long values...
885       return OpNum;
886     }
887   }
888   return OpNum;
889 }
890
891
892 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
893 /// register, then move it to wherever the result should be. 
894 ///
895 void ISel::visitSetCondInst(SetCondInst &I) {
896   if (canFoldSetCCIntoBranch(&I)) return;  // Fold this into a branch...
897
898   unsigned DestReg = getReg(I);
899   MachineBasicBlock::iterator MII = BB->end();
900   emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
901                      DestReg);
902 }
903
904 /// emitSetCCOperation - Common code shared between visitSetCondInst and
905 /// constant expression support.
906 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
907                               MachineBasicBlock::iterator IP,
908                               Value *Op0, Value *Op1, unsigned Opcode,
909                               unsigned TargetReg) {
910   unsigned OpNum = getSetCCNumber(Opcode);
911   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
912
913   const Type *CompTy = Op0->getType();
914   unsigned CompClass = getClassB(CompTy);
915   bool isSigned = CompTy->isSigned() && CompClass != cFP;
916
917   if (CompClass != cLong || OpNum < 2) {
918     // Handle normal comparisons with a setcc instruction...
919     BMI(MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
920   } else {
921     // Handle long comparisons by copying the value which is already in BL into
922     // the register we want...
923     BMI(MBB, IP, X86::MOVrr8, 1, TargetReg).addReg(X86::BL);
924   }
925 }
926
927
928
929
930 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
931 /// operand, in the specified target register.
932 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
933   bool isUnsigned = VR.Ty->isUnsigned();
934
935   // Make sure we have the register number for this value...
936   unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
937
938   switch (getClassB(VR.Ty)) {
939   case cByte:
940     // Extend value into target register (8->32)
941     if (isUnsigned)
942       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(Reg);
943     else
944       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(Reg);
945     break;
946   case cShort:
947     // Extend value into target register (16->32)
948     if (isUnsigned)
949       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(Reg);
950     else
951       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(Reg);
952     break;
953   case cInt:
954     // Move value into target register (32->32)
955     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(Reg);
956     break;
957   default:
958     assert(0 && "Unpromotable operand class in promote32");
959   }
960 }
961
962 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
963 /// we have the following possibilities:
964 ///
965 ///   ret void: No return value, simply emit a 'ret' instruction
966 ///   ret sbyte, ubyte : Extend value into EAX and return
967 ///   ret short, ushort: Extend value into EAX and return
968 ///   ret int, uint    : Move value into EAX and return
969 ///   ret pointer      : Move value into EAX and return
970 ///   ret long, ulong  : Move value into EAX/EDX and return
971 ///   ret float/double : Top of FP stack
972 ///
973 void ISel::visitReturnInst(ReturnInst &I) {
974   if (I.getNumOperands() == 0) {
975     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
976     return;
977   }
978
979   Value *RetVal = I.getOperand(0);
980   unsigned RetReg = getReg(RetVal);
981   switch (getClassB(RetVal->getType())) {
982   case cByte:   // integral return values: extend or move into EAX and return
983   case cShort:
984   case cInt:
985     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
986     // Declare that EAX is live on exit
987     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
988     break;
989   case cFP:                   // Floats & Doubles: Return in ST(0)
990     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
991     // Declare that top-of-stack is live on exit
992     BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
993     break;
994   case cLong:
995     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
996     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
997     // Declare that EAX & EDX are live on exit
998     BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
999       .addReg(X86::ESP);
1000     break;
1001   default:
1002     visitInstruction(I);
1003   }
1004   // Emit a 'ret' instruction
1005   BuildMI(BB, X86::RET, 0);
1006 }
1007
1008 // getBlockAfter - Return the basic block which occurs lexically after the
1009 // specified one.
1010 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1011   Function::iterator I = BB; ++I;  // Get iterator to next block
1012   return I != BB->getParent()->end() ? &*I : 0;
1013 }
1014
1015 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1016 /// that since code layout is frozen at this point, that if we are trying to
1017 /// jump to a block that is the immediate successor of the current block, we can
1018 /// just make a fall-through (but we don't currently).
1019 ///
1020 void ISel::visitBranchInst(BranchInst &BI) {
1021   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1022
1023   if (!BI.isConditional()) {  // Unconditional branch?
1024     if (BI.getSuccessor(0) != NextBB)
1025       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1026     return;
1027   }
1028
1029   // See if we can fold the setcc into the branch itself...
1030   SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1031   if (SCI == 0) {
1032     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1033     // computed some other way...
1034     unsigned condReg = getReg(BI.getCondition());
1035     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
1036     if (BI.getSuccessor(1) == NextBB) {
1037       if (BI.getSuccessor(0) != NextBB)
1038         BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1039     } else {
1040       BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1041       
1042       if (BI.getSuccessor(0) != NextBB)
1043         BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1044     }
1045     return;
1046   }
1047
1048   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1049   MachineBasicBlock::iterator MII = BB->end();
1050   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1051
1052   const Type *CompTy = SCI->getOperand(0)->getType();
1053   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1054   
1055
1056   // LLVM  -> X86 signed  X86 unsigned
1057   // -----    ----------  ------------
1058   // seteq -> je          je
1059   // setne -> jne         jne
1060   // setlt -> jl          jb
1061   // setge -> jge         jae
1062   // setgt -> jg          ja
1063   // setle -> jle         jbe
1064   // ----
1065   //          js                  // Used by comparison with 0 optimization
1066   //          jns
1067
1068   static const unsigned OpcodeTab[2][8] = {
1069     { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1070     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1071       X86::JS, X86::JNS },
1072   };
1073   
1074   if (BI.getSuccessor(0) != NextBB) {
1075     BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1076     if (BI.getSuccessor(1) != NextBB)
1077       BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1078   } else {
1079     // Change to the inverse condition...
1080     if (BI.getSuccessor(1) != NextBB) {
1081       OpNum ^= 1;
1082       BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1083     }
1084   }
1085 }
1086
1087
1088 /// doCall - This emits an abstract call instruction, setting up the arguments
1089 /// and the return value as appropriate.  For the actual function call itself,
1090 /// it inserts the specified CallMI instruction into the stream.
1091 ///
1092 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1093                   const std::vector<ValueRecord> &Args) {
1094
1095   // Count how many bytes are to be pushed on the stack...
1096   unsigned NumBytes = 0;
1097
1098   if (!Args.empty()) {
1099     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1100       switch (getClassB(Args[i].Ty)) {
1101       case cByte: case cShort: case cInt:
1102         NumBytes += 4; break;
1103       case cLong:
1104         NumBytes += 8; break;
1105       case cFP:
1106         NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1107         break;
1108       default: assert(0 && "Unknown class!");
1109       }
1110
1111     // Adjust the stack pointer for the new arguments...
1112     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
1113
1114     // Arguments go on the stack in reverse order, as specified by the ABI.
1115     unsigned ArgOffset = 0;
1116     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1117       unsigned ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1118       switch (getClassB(Args[i].Ty)) {
1119       case cByte:
1120       case cShort: {
1121         // Promote arg to 32 bits wide into a temporary register...
1122         unsigned R = makeAnotherReg(Type::UIntTy);
1123         promote32(R, Args[i]);
1124         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1125                      X86::ESP, ArgOffset).addReg(R);
1126         break;
1127       }
1128       case cInt:
1129         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1130                      X86::ESP, ArgOffset).addReg(ArgReg);
1131         break;
1132       case cLong:
1133         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1134                      X86::ESP, ArgOffset).addReg(ArgReg);
1135         addRegOffset(BuildMI(BB, X86::MOVmr32, 5),
1136                      X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1137         ArgOffset += 4;        // 8 byte entry, not 4.
1138         break;
1139         
1140       case cFP:
1141         if (Args[i].Ty == Type::FloatTy) {
1142           addRegOffset(BuildMI(BB, X86::FSTm32, 5),
1143                        X86::ESP, ArgOffset).addReg(ArgReg);
1144         } else {
1145           assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1146           addRegOffset(BuildMI(BB, X86::FSTm64, 5),
1147                        X86::ESP, ArgOffset).addReg(ArgReg);
1148           ArgOffset += 4;       // 8 byte entry, not 4.
1149         }
1150         break;
1151
1152       default: assert(0 && "Unknown class!");
1153       }
1154       ArgOffset += 4;
1155     }
1156   } else {
1157     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
1158   }
1159
1160   BB->push_back(CallMI);
1161
1162   BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
1163
1164   // If there is a return value, scavenge the result from the location the call
1165   // leaves it in...
1166   //
1167   if (Ret.Ty != Type::VoidTy) {
1168     unsigned DestClass = getClassB(Ret.Ty);
1169     switch (DestClass) {
1170     case cByte:
1171     case cShort:
1172     case cInt: {
1173       // Integral results are in %eax, or the appropriate portion
1174       // thereof.
1175       static const unsigned regRegMove[] = {
1176         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
1177       };
1178       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1179       BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1180       break;
1181     }
1182     case cFP:     // Floating-point return values live in %ST(0)
1183       BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1184       break;
1185     case cLong:   // Long values are left in EDX:EAX
1186       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
1187       BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
1188       break;
1189     default: assert(0 && "Unknown class!");
1190     }
1191   }
1192 }
1193
1194
1195 /// visitCallInst - Push args on stack and do a procedure call instruction.
1196 void ISel::visitCallInst(CallInst &CI) {
1197   MachineInstr *TheCall;
1198   if (Function *F = CI.getCalledFunction()) {
1199     // Is it an intrinsic function call?
1200     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1201       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1202       return;
1203     }
1204
1205     // Emit a CALL instruction with PC-relative displacement.
1206     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1207   } else {  // Emit an indirect call...
1208     unsigned Reg = getReg(CI.getCalledValue());
1209     TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
1210   }
1211
1212   std::vector<ValueRecord> Args;
1213   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1214     Args.push_back(ValueRecord(CI.getOperand(i)));
1215
1216   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1217   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1218 }         
1219
1220
1221 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1222 /// function, lowering any calls to unknown intrinsic functions into the
1223 /// equivalent LLVM code.
1224 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1225   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1226     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1227       if (CallInst *CI = dyn_cast<CallInst>(I++))
1228         if (Function *F = CI->getCalledFunction())
1229           switch (F->getIntrinsicID()) {
1230           case Intrinsic::not_intrinsic:
1231           case Intrinsic::va_start:
1232           case Intrinsic::va_copy:
1233           case Intrinsic::va_end:
1234           case Intrinsic::returnaddress:
1235           case Intrinsic::frameaddress:
1236           case Intrinsic::memcpy:
1237           case Intrinsic::memset:
1238             // We directly implement these intrinsics
1239             break;
1240           default:
1241             // All other intrinsic calls we must lower.
1242             Instruction *Before = CI->getPrev();
1243             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1244             if (Before) {        // Move iterator to instruction after call
1245               I = Before;  ++I;
1246             } else {
1247               I = BB->begin();
1248             }
1249           }
1250
1251 }
1252
1253 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1254   unsigned TmpReg1, TmpReg2;
1255   switch (ID) {
1256   case Intrinsic::va_start:
1257     // Get the address of the first vararg value...
1258     TmpReg1 = getReg(CI);
1259     addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
1260     return;
1261
1262   case Intrinsic::va_copy:
1263     TmpReg1 = getReg(CI);
1264     TmpReg2 = getReg(CI.getOperand(1));
1265     BuildMI(BB, X86::MOVrr32, 1, TmpReg1).addReg(TmpReg2);
1266     return;
1267   case Intrinsic::va_end: return;   // Noop on X86
1268
1269   case Intrinsic::returnaddress:
1270   case Intrinsic::frameaddress:
1271     TmpReg1 = getReg(CI);
1272     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1273       if (ID == Intrinsic::returnaddress) {
1274         // Just load the return address
1275         addFrameReference(BuildMI(BB, X86::MOVrm32, 4, TmpReg1),
1276                           ReturnAddressIndex);
1277       } else {
1278         addFrameReference(BuildMI(BB, X86::LEAr32, 4, TmpReg1),
1279                           ReturnAddressIndex, -4);
1280       }
1281     } else {
1282       // Values other than zero are not implemented yet.
1283       BuildMI(BB, X86::MOVri32, 1, TmpReg1).addZImm(0);
1284     }
1285     return;
1286
1287   case Intrinsic::memcpy: {
1288     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1289     unsigned Align = 1;
1290     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1291       Align = AlignC->getRawValue();
1292       if (Align == 0) Align = 1;
1293     }
1294
1295     // Turn the byte code into # iterations
1296     unsigned CountReg;
1297     unsigned Opcode;
1298     switch (Align & 3) {
1299     case 2:   // WORD aligned
1300       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1301         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1302       } else {
1303         CountReg = makeAnotherReg(Type::IntTy);
1304         unsigned ByteReg = getReg(CI.getOperand(3));
1305         BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(1);
1306       }
1307       Opcode = X86::REP_MOVSW;
1308       break;
1309     case 0:   // DWORD aligned
1310       if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1311         CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1312       } else {
1313         CountReg = makeAnotherReg(Type::IntTy);
1314         unsigned ByteReg = getReg(CI.getOperand(3));
1315         BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(2);
1316       }
1317       Opcode = X86::REP_MOVSD;
1318       break;
1319     default:  // BYTE aligned
1320       CountReg = getReg(CI.getOperand(3));
1321       Opcode = X86::REP_MOVSB;
1322       break;
1323     }
1324
1325     // No matter what the alignment is, we put the source in ESI, the
1326     // destination in EDI, and the count in ECX.
1327     TmpReg1 = getReg(CI.getOperand(1));
1328     TmpReg2 = getReg(CI.getOperand(2));
1329     BuildMI(BB, X86::MOVrr32, 1, X86::ECX).addReg(CountReg);
1330     BuildMI(BB, X86::MOVrr32, 1, X86::EDI).addReg(TmpReg1);
1331     BuildMI(BB, X86::MOVrr32, 1, X86::ESI).addReg(TmpReg2);
1332     BuildMI(BB, Opcode, 0);
1333     return;
1334   }
1335   case Intrinsic::memset: {
1336     assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1337     unsigned Align = 1;
1338     if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1339       Align = AlignC->getRawValue();
1340       if (Align == 0) Align = 1;
1341     }
1342
1343     // Turn the byte code into # iterations
1344     unsigned CountReg;
1345     unsigned Opcode;
1346     if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1347       unsigned Val = ValC->getRawValue() & 255;
1348
1349       // If the value is a constant, then we can potentially use larger copies.
1350       switch (Align & 3) {
1351       case 2:   // WORD aligned
1352         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1353           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1354         } else {
1355           CountReg = makeAnotherReg(Type::IntTy);
1356           unsigned ByteReg = getReg(CI.getOperand(3));
1357           BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(1);
1358         }
1359         BuildMI(BB, X86::MOVri16, 1, X86::AX).addZImm((Val << 8) | Val);
1360         Opcode = X86::REP_STOSW;
1361         break;
1362       case 0:   // DWORD aligned
1363         if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1364           CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1365         } else {
1366           CountReg = makeAnotherReg(Type::IntTy);
1367           unsigned ByteReg = getReg(CI.getOperand(3));
1368           BuildMI(BB, X86::SHRri32, 2, CountReg).addReg(ByteReg).addZImm(2);
1369         }
1370         Val = (Val << 8) | Val;
1371         BuildMI(BB, X86::MOVri32, 1, X86::EAX).addZImm((Val << 16) | Val);
1372         Opcode = X86::REP_STOSD;
1373         break;
1374       default:  // BYTE aligned
1375         CountReg = getReg(CI.getOperand(3));
1376         BuildMI(BB, X86::MOVri8, 1, X86::AL).addZImm(Val);
1377         Opcode = X86::REP_STOSB;
1378         break;
1379       }
1380     } else {
1381       // If it's not a constant value we are storing, just fall back.  We could
1382       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1383       unsigned ValReg = getReg(CI.getOperand(2));
1384       BuildMI(BB, X86::MOVrr8, 1, X86::AL).addReg(ValReg);
1385       CountReg = getReg(CI.getOperand(3));
1386       Opcode = X86::REP_STOSB;
1387     }
1388
1389     // No matter what the alignment is, we put the source in ESI, the
1390     // destination in EDI, and the count in ECX.
1391     TmpReg1 = getReg(CI.getOperand(1));
1392     //TmpReg2 = getReg(CI.getOperand(2));
1393     BuildMI(BB, X86::MOVrr32, 1, X86::ECX).addReg(CountReg);
1394     BuildMI(BB, X86::MOVrr32, 1, X86::EDI).addReg(TmpReg1);
1395     BuildMI(BB, Opcode, 0);
1396     return;
1397   }
1398
1399   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1400   }
1401 }
1402
1403
1404 /// visitSimpleBinary - Implement simple binary operators for integral types...
1405 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1406 /// Xor.
1407 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1408   unsigned DestReg = getReg(B);
1409   MachineBasicBlock::iterator MI = BB->end();
1410   emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
1411                             OperatorClass, DestReg);
1412 }
1413
1414 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1415 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1416 /// Or, 4 for Xor.
1417 ///
1418 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1419 /// and constant expression support.
1420 ///
1421 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1422                                      MachineBasicBlock::iterator IP,
1423                                      Value *Op0, Value *Op1,
1424                                      unsigned OperatorClass, unsigned DestReg) {
1425   unsigned Class = getClassB(Op0->getType());
1426
1427   // sub 0, X -> neg X
1428   if (OperatorClass == 1 && Class != cLong)
1429     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1430       if (CI->isNullValue()) {
1431         unsigned op1Reg = getReg(Op1, MBB, IP);
1432         switch (Class) {
1433         default: assert(0 && "Unknown class for this function!");
1434         case cByte:
1435           BMI(MBB, IP, X86::NEGr8, 1, DestReg).addReg(op1Reg);
1436           return;
1437         case cShort:
1438           BMI(MBB, IP, X86::NEGr16, 1, DestReg).addReg(op1Reg);
1439           return;
1440         case cInt:
1441           BMI(MBB, IP, X86::NEGr32, 1, DestReg).addReg(op1Reg);
1442           return;
1443         }
1444       }
1445     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1446       if (CFP->isExactlyValue(-0.0)) {
1447         // -0.0 - X === -X
1448         unsigned op1Reg = getReg(Op1, MBB, IP);
1449         BMI(MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1450         return;
1451       }
1452
1453   if (!isa<ConstantInt>(Op1) || Class == cLong) {
1454     static const unsigned OpcodeTab[][4] = {
1455       // Arithmetic operators
1456       { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
1457       { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
1458       
1459       // Bitwise operators
1460       { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
1461       { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
1462       { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
1463     };
1464     
1465     bool isLong = false;
1466     if (Class == cLong) {
1467       isLong = true;
1468       Class = cInt;          // Bottom 32 bits are handled just like ints
1469     }
1470     
1471     unsigned Opcode = OpcodeTab[OperatorClass][Class];
1472     assert(Opcode && "Floating point arguments to logical inst?");
1473     unsigned Op0r = getReg(Op0, MBB, IP);
1474     unsigned Op1r = getReg(Op1, MBB, IP);
1475     BMI(MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1476     
1477     if (isLong) {        // Handle the upper 32 bits of long values...
1478       static const unsigned TopTab[] = {
1479         X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1480       };
1481       BMI(MBB, IP, TopTab[OperatorClass], 2,
1482           DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1483     }
1484     return;
1485   }
1486
1487   // Special case: op Reg, <const>
1488   ConstantInt *Op1C = cast<ConstantInt>(Op1);
1489   unsigned Op0r = getReg(Op0, MBB, IP);
1490
1491   // xor X, -1 -> not X
1492   if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1493     static unsigned const NOTTab[] = { X86::NOTr8, X86::NOTr16, X86::NOTr32 };
1494     BMI(MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1495     return;
1496   }
1497
1498   // add X, -1 -> dec X
1499   if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1500     static unsigned const DECTab[] = { X86::DECr8, X86::DECr16, X86::DECr32 };
1501     BMI(MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1502     return;
1503   }
1504
1505   // add X, 1 -> inc X
1506   if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1507     static unsigned const DECTab[] = { X86::INCr8, X86::INCr16, X86::INCr32 };
1508     BMI(MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1509     return;
1510   }
1511   
1512   static const unsigned OpcodeTab[][3] = {
1513     // Arithmetic operators
1514     { X86::ADDri8, X86::ADDri16, X86::ADDri32 },  // ADD
1515     { X86::SUBri8, X86::SUBri16, X86::SUBri32 },  // SUB
1516     
1517     // Bitwise operators
1518     { X86::ANDri8, X86::ANDri16, X86::ANDri32 },  // AND
1519     { X86:: ORri8, X86:: ORri16, X86:: ORri32 },  // OR
1520     { X86::XORri8, X86::XORri16, X86::XORri32 },  // XOR
1521   };
1522   
1523   assert(Class < 3 && "General code handles 64-bit integer types!");
1524   unsigned Opcode = OpcodeTab[OperatorClass][Class];
1525   uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1526   
1527   // Mask off any upper bits of the constant, if there are any...
1528   Op1v &= (1ULL << (8 << Class)) - 1;
1529   BMI(MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addZImm(Op1v);
1530 }
1531
1532 /// doMultiply - Emit appropriate instructions to multiply together the
1533 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
1534 /// result should be given as DestTy.
1535 ///
1536 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1537                       unsigned DestReg, const Type *DestTy,
1538                       unsigned op0Reg, unsigned op1Reg) {
1539   unsigned Class = getClass(DestTy);
1540   switch (Class) {
1541   case cFP:              // Floating point multiply
1542     BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1543     return;
1544   case cInt:
1545   case cShort:
1546     BMI(BB, MBBI, Class == cInt ? X86::IMULrr32 : X86::IMULrr16, 2, DestReg)
1547       .addReg(op0Reg).addReg(op1Reg);
1548     return;
1549   case cByte:
1550     // Must use the MUL instruction, which forces use of AL...
1551     BMI(MBB, MBBI, X86::MOVrr8, 1, X86::AL).addReg(op0Reg);
1552     BMI(MBB, MBBI, X86::MULr8, 1).addReg(op1Reg);
1553     BMI(MBB, MBBI, X86::MOVrr8, 1, DestReg).addReg(X86::AL);
1554     return;
1555   default:
1556   case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1557   }
1558 }
1559
1560 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1561 // returns zero when the input is not exactly a power of two.
1562 static unsigned ExactLog2(unsigned Val) {
1563   if (Val == 0) return 0;
1564   unsigned Count = 0;
1565   while (Val != 1) {
1566     if (Val & 1) return 0;
1567     Val >>= 1;
1568     ++Count;
1569   }
1570   return Count+1;
1571 }
1572
1573 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1574                            MachineBasicBlock::iterator IP,
1575                            unsigned DestReg, const Type *DestTy,
1576                            unsigned op0Reg, unsigned ConstRHS) {
1577   unsigned Class = getClass(DestTy);
1578
1579   // If the element size is exactly a power of 2, use a shift to get it.
1580   if (unsigned Shift = ExactLog2(ConstRHS)) {
1581     switch (Class) {
1582     default: assert(0 && "Unknown class for this function!");
1583     case cByte:
1584       BMI(MBB, IP, X86::SHLri32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1585       return;
1586     case cShort:
1587       BMI(MBB, IP, X86::SHLri32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1588       return;
1589     case cInt:
1590       BMI(MBB, IP, X86::SHLri32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1591       return;
1592     }
1593   }
1594   
1595   if (Class == cShort) {
1596     BMI(MBB, IP, X86::IMULrri16, 2, DestReg).addReg(op0Reg).addZImm(ConstRHS);
1597     return;
1598   } else if (Class == cInt) {
1599     BMI(MBB, IP, X86::IMULrri32, 2, DestReg).addReg(op0Reg).addZImm(ConstRHS);
1600     return;
1601   }
1602
1603   // Most general case, emit a normal multiply...
1604   static const unsigned MOVriTab[] = {
1605     X86::MOVri8, X86::MOVri16, X86::MOVri32
1606   };
1607
1608   unsigned TmpReg = makeAnotherReg(DestTy);
1609   BMI(MBB, IP, MOVriTab[Class], 1, TmpReg).addZImm(ConstRHS);
1610   
1611   // Emit a MUL to multiply the register holding the index by
1612   // elementSize, putting the result in OffsetReg.
1613   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1614 }
1615
1616 /// visitMul - Multiplies are not simple binary operators because they must deal
1617 /// with the EAX register explicitly.
1618 ///
1619 void ISel::visitMul(BinaryOperator &I) {
1620   unsigned Op0Reg  = getReg(I.getOperand(0));
1621   unsigned DestReg = getReg(I);
1622
1623   // Simple scalar multiply?
1624   if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1625     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1626       unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1627       MachineBasicBlock::iterator MBBI = BB->end();
1628       doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1629     } else {
1630       unsigned Op1Reg  = getReg(I.getOperand(1));
1631       MachineBasicBlock::iterator MBBI = BB->end();
1632       doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1633     }
1634   } else {
1635     unsigned Op1Reg  = getReg(I.getOperand(1));
1636
1637     // Long value.  We have to do things the hard way...
1638     // Multiply the two low parts... capturing carry into EDX
1639     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1640     BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg);  // AL*BL
1641
1642     unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1643     BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX);     // AL*BL
1644     BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1645
1646     MachineBasicBlock::iterator MBBI = BB->end();
1647     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
1648     BMI(BB, MBBI, X86::IMULrr32, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1649
1650     unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1651     BuildMI(BB, X86::ADDrr32, 2,                         // AH*BL+(AL*BL >> 32)
1652             AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1653     
1654     MBBI = BB->end();
1655     unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1656     BMI(BB, MBBI, X86::IMULrr32, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1657     
1658     BuildMI(BB, X86::ADDrr32, 2,               // AL*BH + AH*BL + (AL*BL >> 32)
1659             DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1660   }
1661 }
1662
1663
1664 /// visitDivRem - Handle division and remainder instructions... these
1665 /// instruction both require the same instructions to be generated, they just
1666 /// select the result from a different register.  Note that both of these
1667 /// instructions work differently for signed and unsigned operands.
1668 ///
1669 void ISel::visitDivRem(BinaryOperator &I) {
1670   unsigned Op0Reg = getReg(I.getOperand(0));
1671   unsigned Op1Reg = getReg(I.getOperand(1));
1672   unsigned ResultReg = getReg(I);
1673
1674   MachineBasicBlock::iterator IP = BB->end();
1675   emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1676                       I.getType(), ResultReg);
1677 }
1678
1679 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1680                                MachineBasicBlock::iterator IP,
1681                                unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1682                                const Type *Ty, unsigned ResultReg) {
1683   unsigned Class = getClass(Ty);
1684   switch (Class) {
1685   case cFP:              // Floating point divide
1686     if (isDiv) {
1687       BMI(BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1688     } else {               // Floating point remainder...
1689       MachineInstr *TheCall =
1690         BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1691       std::vector<ValueRecord> Args;
1692       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1693       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1694       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1695     }
1696     return;
1697   case cLong: {
1698     static const char *FnName[] =
1699       { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1700
1701     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1702     MachineInstr *TheCall =
1703       BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1704
1705     std::vector<ValueRecord> Args;
1706     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1707     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1708     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1709     return;
1710   }
1711   case cByte: case cShort: case cInt:
1712     break;          // Small integrals, handled below...
1713   default: assert(0 && "Unknown class!");
1714   }
1715
1716   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
1717   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1718   static const unsigned SarOpcode[]={ X86::SARri8, X86::SARri16, X86::SARri32 };
1719   static const unsigned ClrOpcode[]={ X86::MOVri8, X86::MOVri16, X86::MOVri32 };
1720   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
1721
1722   static const unsigned DivOpcode[][4] = {
1723     { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 },  // Unsigned division
1724     { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 },  // Signed division
1725   };
1726
1727   bool isSigned   = Ty->isSigned();
1728   unsigned Reg    = Regs[Class];
1729   unsigned ExtReg = ExtRegs[Class];
1730
1731   // Put the first operand into one of the A registers...
1732   BMI(BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1733
1734   if (isSigned) {
1735     // Emit a sign extension instruction...
1736     unsigned ShiftResult = makeAnotherReg(Ty);
1737     BMI(BB, IP, SarOpcode[Class], 2, ShiftResult).addReg(Op0Reg).addZImm(31);
1738     BMI(BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1739   } else {
1740     // If unsigned, emit a zeroing instruction... (reg = 0)
1741     BMI(BB, IP, ClrOpcode[Class], 2, ExtReg).addZImm(0);
1742   }
1743
1744   // Emit the appropriate divide or remainder instruction...
1745   BMI(BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1746
1747   // Figure out which register we want to pick the result out of...
1748   unsigned DestReg = isDiv ? Reg : ExtReg;
1749   
1750   // Put the result into the destination register...
1751   BMI(BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1752 }
1753
1754
1755 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1756 /// for constant immediate shift values, and for constant immediate
1757 /// shift values equal to 1. Even the general case is sort of special,
1758 /// because the shift amount has to be in CL, not just any old register.
1759 ///
1760 void ISel::visitShiftInst(ShiftInst &I) {
1761   MachineBasicBlock::iterator IP = BB->end ();
1762   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1763                       I.getOpcode () == Instruction::Shl, I.getType (),
1764                       getReg (I));
1765 }
1766
1767 /// emitShiftOperation - Common code shared between visitShiftInst and
1768 /// constant expression support.
1769 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
1770                               MachineBasicBlock::iterator IP,
1771                               Value *Op, Value *ShiftAmount, bool isLeftShift,
1772                               const Type *ResultTy, unsigned DestReg) {
1773   unsigned SrcReg = getReg (Op, MBB, IP);
1774   bool isSigned = ResultTy->isSigned ();
1775   unsigned Class = getClass (ResultTy);
1776   
1777   static const unsigned ConstantOperand[][4] = {
1778     { X86::SHRri8, X86::SHRri16, X86::SHRri32, X86::SHRDrr32i8 },  // SHR
1779     { X86::SARri8, X86::SARri16, X86::SARri32, X86::SHRDrr32i8 },  // SAR
1780     { X86::SHLri8, X86::SHLri16, X86::SHLri32, X86::SHLDrr32i8 },  // SHL
1781     { X86::SHLri8, X86::SHLri16, X86::SHLri32, X86::SHLDrr32i8 },  // SAL = SHL
1782   };
1783
1784   static const unsigned NonConstantOperand[][4] = {
1785     { X86::SHRrCL8, X86::SHRrCL16, X86::SHRrCL32 },  // SHR
1786     { X86::SARrCL8, X86::SARrCL16, X86::SARrCL32 },  // SAR
1787     { X86::SHLrCL8, X86::SHLrCL16, X86::SHLrCL32 },  // SHL
1788     { X86::SHLrCL8, X86::SHLrCL16, X86::SHLrCL32 },  // SAL = SHL
1789   };
1790
1791   // Longs, as usual, are handled specially...
1792   if (Class == cLong) {
1793     // If we have a constant shift, we can generate much more efficient code
1794     // than otherwise...
1795     //
1796     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1797       unsigned Amount = CUI->getValue();
1798       if (Amount < 32) {
1799         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1800         if (isLeftShift) {
1801           BMI(MBB, IP, Opc[3], 3, 
1802               DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1803           BMI(MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1804         } else {
1805           BMI(MBB, IP, Opc[3], 3,
1806               DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addZImm(Amount);
1807           BMI(MBB, IP, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1808         }
1809       } else {                 // Shifting more than 32 bits
1810         Amount -= 32;
1811         if (isLeftShift) {
1812           BMI(MBB, IP, X86::SHLri32, 2,
1813               DestReg + 1).addReg(SrcReg).addZImm(Amount);
1814           BMI(MBB, IP, X86::MOVri32, 1,
1815               DestReg).addZImm(0);
1816         } else {
1817           unsigned Opcode = isSigned ? X86::SARri32 : X86::SHRri32;
1818           BMI(MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1819           BMI(MBB, IP, X86::MOVri32, 1, DestReg+1).addZImm(0);
1820         }
1821       }
1822     } else {
1823       unsigned TmpReg = makeAnotherReg(Type::IntTy);
1824
1825       if (!isLeftShift && isSigned) {
1826         // If this is a SHR of a Long, then we need to do funny sign extension
1827         // stuff.  TmpReg gets the value to use as the high-part if we are
1828         // shifting more than 32 bits.
1829         BMI(MBB, IP, X86::SARri32, 2, TmpReg).addReg(SrcReg).addZImm(31);
1830       } else {
1831         // Other shifts use a fixed zero value if the shift is more than 32
1832         // bits.
1833         BMI(MBB, IP, X86::MOVri32, 1, TmpReg).addZImm(0);
1834       }
1835
1836       // Initialize CL with the shift amount...
1837       unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
1838       BMI(MBB, IP, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmountReg);
1839
1840       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1841       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1842       if (isLeftShift) {
1843         // TmpReg2 = shld inHi, inLo
1844         BMI(MBB, IP, X86::SHLDrrCL32,2,TmpReg2).addReg(SrcReg+1).addReg(SrcReg);
1845         // TmpReg3 = shl  inLo, CL
1846         BMI(MBB, IP, X86::SHLrCL32, 1, TmpReg3).addReg(SrcReg);
1847
1848         // Set the flags to indicate whether the shift was by more than 32 bits.
1849         BMI(MBB, IP, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1850
1851         // DestHi = (>32) ? TmpReg3 : TmpReg2;
1852         BMI(MBB, IP, X86::CMOVNErr32, 2, 
1853                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1854         // DestLo = (>32) ? TmpReg : TmpReg3;
1855         BMI(MBB, IP, X86::CMOVNErr32, 2,
1856             DestReg).addReg(TmpReg3).addReg(TmpReg);
1857       } else {
1858         // TmpReg2 = shrd inLo, inHi
1859         BMI(MBB, IP, X86::SHRDrrCL32,2,TmpReg2).addReg(SrcReg).addReg(SrcReg+1);
1860         // TmpReg3 = s[ah]r  inHi, CL
1861         BMI(MBB, IP, isSigned ? X86::SARrCL32 : X86::SHRrCL32, 1, TmpReg3)
1862                        .addReg(SrcReg+1);
1863
1864         // Set the flags to indicate whether the shift was by more than 32 bits.
1865         BMI(MBB, IP, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1866
1867         // DestLo = (>32) ? TmpReg3 : TmpReg2;
1868         BMI(MBB, IP, X86::CMOVNErr32, 2, 
1869                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1870
1871         // DestHi = (>32) ? TmpReg : TmpReg3;
1872         BMI(MBB, IP, X86::CMOVNErr32, 2, 
1873                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1874       }
1875     }
1876     return;
1877   }
1878
1879   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1880     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1881     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1882
1883     const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1884     BMI(MBB, IP, Opc[Class], 2,
1885         DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1886   } else {                  // The shift amount is non-constant.
1887     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
1888     BMI(MBB, IP, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmountReg);
1889
1890     const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1891     BMI(MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
1892   }
1893 }
1894
1895
1896 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1897 /// instruction.  The load and store instructions are the only place where we
1898 /// need to worry about the memory layout of the target machine.
1899 ///
1900 void ISel::visitLoadInst(LoadInst &I) {
1901   unsigned DestReg = getReg(I);
1902   unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
1903   Value *Addr = I.getOperand(0);
1904   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1905     if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1906                        BaseReg, Scale, IndexReg, Disp))
1907       Addr = 0;  // Address is consumed!
1908   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1909     if (CE->getOpcode() == Instruction::GetElementPtr)
1910       if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1911                         BaseReg, Scale, IndexReg, Disp))
1912         Addr = 0;
1913   }
1914
1915   if (Addr) {
1916     // If it's not foldable, reset addr mode.
1917     BaseReg = getReg(Addr);
1918     Scale = 1; IndexReg = 0; Disp = 0;
1919   }
1920
1921   unsigned Class = getClassB(I.getType());
1922   if (Class == cLong) {
1923     addFullAddress(BuildMI(BB, X86::MOVrm32, 4, DestReg),
1924                    BaseReg, Scale, IndexReg, Disp);
1925     addFullAddress(BuildMI(BB, X86::MOVrm32, 4, DestReg+1),
1926                    BaseReg, Scale, IndexReg, Disp+4);
1927     return;
1928   }
1929
1930   static const unsigned Opcodes[] = {
1931     X86::MOVrm8, X86::MOVrm16, X86::MOVrm32, X86::FLDm32
1932   };
1933   unsigned Opcode = Opcodes[Class];
1934   if (I.getType() == Type::DoubleTy) Opcode = X86::FLDm64;
1935   addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
1936                  BaseReg, Scale, IndexReg, Disp);
1937 }
1938
1939 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1940 /// instruction.
1941 ///
1942 void ISel::visitStoreInst(StoreInst &I) {
1943   unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
1944   Value *Addr = I.getOperand(1);
1945   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1946     if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1947                        BaseReg, Scale, IndexReg, Disp))
1948       Addr = 0;  // Address is consumed!
1949   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1950     if (CE->getOpcode() == Instruction::GetElementPtr)
1951       if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1952                         BaseReg, Scale, IndexReg, Disp))
1953         Addr = 0;
1954   }
1955
1956   if (Addr) {
1957     // If it's not foldable, reset addr mode.
1958     BaseReg = getReg(Addr);
1959     Scale = 1; IndexReg = 0; Disp = 0;
1960   }
1961
1962   const Type *ValTy = I.getOperand(0)->getType();
1963   unsigned Class = getClassB(ValTy);
1964
1965   if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
1966     uint64_t Val = CI->getRawValue();
1967     if (Class == cLong) {
1968       addFullAddress(BuildMI(BB, X86::MOVmi32, 5),
1969                      BaseReg, Scale, IndexReg, Disp).addZImm(Val & ~0U);
1970       addFullAddress(BuildMI(BB, X86::MOVmi32, 5),
1971                      BaseReg, Scale, IndexReg, Disp+4).addZImm(Val>>32);
1972     } else {
1973       static const unsigned Opcodes[] = {
1974         X86::MOVmi8, X86::MOVmi16, X86::MOVmi32
1975       };
1976       unsigned Opcode = Opcodes[Class];
1977       addFullAddress(BuildMI(BB, Opcode, 5),
1978                      BaseReg, Scale, IndexReg, Disp).addZImm(Val);
1979     }
1980   } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
1981     addFullAddress(BuildMI(BB, X86::MOVmi8, 5),
1982                    BaseReg, Scale, IndexReg, Disp).addZImm(CB->getValue());
1983   } else {    
1984     if (Class == cLong) {
1985       unsigned ValReg = getReg(I.getOperand(0));
1986       addFullAddress(BuildMI(BB, X86::MOVmr32, 5),
1987                      BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
1988       addFullAddress(BuildMI(BB, X86::MOVmr32, 5),
1989                      BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
1990     } else {
1991       unsigned ValReg = getReg(I.getOperand(0));
1992       static const unsigned Opcodes[] = {
1993         X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, X86::FSTm32
1994       };
1995       unsigned Opcode = Opcodes[Class];
1996       if (ValTy == Type::DoubleTy) Opcode = X86::FSTm64;
1997       addFullAddress(BuildMI(BB, Opcode, 1+4),
1998                      BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
1999     }
2000   }
2001 }
2002
2003
2004 /// visitCastInst - Here we have various kinds of copying with or without
2005 /// sign extension going on.
2006 void ISel::visitCastInst(CastInst &CI) {
2007   Value *Op = CI.getOperand(0);
2008   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2009   // of the case are GEP instructions, then the cast does not need to be
2010   // generated explicitly, it will be folded into the GEP.
2011   if (CI.getType() == Type::LongTy &&
2012       (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2013     bool AllUsesAreGEPs = true;
2014     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2015       if (!isa<GetElementPtrInst>(*I)) {
2016         AllUsesAreGEPs = false;
2017         break;
2018       }        
2019
2020     // No need to codegen this cast if all users are getelementptr instrs...
2021     if (AllUsesAreGEPs) return;
2022   }
2023
2024   unsigned DestReg = getReg(CI);
2025   MachineBasicBlock::iterator MI = BB->end();
2026   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2027 }
2028
2029 /// emitCastOperation - Common code shared between visitCastInst and
2030 /// constant expression cast support.
2031 void ISel::emitCastOperation(MachineBasicBlock *BB,
2032                              MachineBasicBlock::iterator IP,
2033                              Value *Src, const Type *DestTy,
2034                              unsigned DestReg) {
2035   unsigned SrcReg = getReg(Src, BB, IP);
2036   const Type *SrcTy = Src->getType();
2037   unsigned SrcClass = getClassB(SrcTy);
2038   unsigned DestClass = getClassB(DestTy);
2039
2040   // Implement casts to bool by using compare on the operand followed by set if
2041   // not zero on the result.
2042   if (DestTy == Type::BoolTy) {
2043     switch (SrcClass) {
2044     case cByte:
2045       BMI(BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
2046       break;
2047     case cShort:
2048       BMI(BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
2049       break;
2050     case cInt:
2051       BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
2052       break;
2053     case cLong: {
2054       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2055       BMI(BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2056       break;
2057     }
2058     case cFP:
2059       BMI(BB, IP, X86::FTST, 1).addReg(SrcReg);
2060       BMI(BB, IP, X86::FNSTSWr8, 0);
2061       BMI(BB, IP, X86::SAHF, 1);
2062       break;
2063     }
2064
2065     // If the zero flag is not set, then the value is true, set the byte to
2066     // true.
2067     BMI(BB, IP, X86::SETNEr, 1, DestReg);
2068     return;
2069   }
2070
2071   static const unsigned RegRegMove[] = {
2072     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
2073   };
2074
2075   // Implement casts between values of the same type class (as determined by
2076   // getClass) by using a register-to-register move.
2077   if (SrcClass == DestClass) {
2078     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2079       BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2080     } else if (SrcClass == cFP) {
2081       if (SrcTy == Type::FloatTy) {  // double -> float
2082         assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2083         BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2084       } else {                       // float -> double
2085         assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2086                "Unknown cFP member!");
2087         // Truncate from double to float by storing to memory as short, then
2088         // reading it back.
2089         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2090         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2091         addFrameReference(BMI(BB, IP, X86::FSTm32, 5), FrameIdx).addReg(SrcReg);
2092         addFrameReference(BMI(BB, IP, X86::FLDm32, 5, DestReg), FrameIdx);
2093       }
2094     } else if (SrcClass == cLong) {
2095       BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
2096       BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
2097     } else {
2098       assert(0 && "Cannot handle this type of cast instruction!");
2099       abort();
2100     }
2101     return;
2102   }
2103
2104   // Handle cast of SMALLER int to LARGER int using a move with sign extension
2105   // or zero extension, depending on whether the source type was signed.
2106   if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2107       SrcClass < DestClass) {
2108     bool isLong = DestClass == cLong;
2109     if (isLong) DestClass = cInt;
2110
2111     static const unsigned Opc[][4] = {
2112       { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
2113       { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 }  // u
2114     };
2115     
2116     bool isUnsigned = SrcTy->isUnsigned();
2117     BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2118         DestReg).addReg(SrcReg);
2119
2120     if (isLong) {  // Handle upper 32 bits as appropriate...
2121       if (isUnsigned)     // Zero out top bits...
2122         BMI(BB, IP, X86::MOVri32, 1, DestReg+1).addZImm(0);
2123       else                // Sign extend bottom half...
2124         BMI(BB, IP, X86::SARri32, 2, DestReg+1).addReg(DestReg).addZImm(31);
2125     }
2126     return;
2127   }
2128
2129   // Special case long -> int ...
2130   if (SrcClass == cLong && DestClass == cInt) {
2131     BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
2132     return;
2133   }
2134   
2135   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2136   // move out of AX or AL.
2137   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2138       && SrcClass > DestClass) {
2139     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2140     BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2141     BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2142     return;
2143   }
2144
2145   // Handle casts from integer to floating point now...
2146   if (DestClass == cFP) {
2147     // Promote the integer to a type supported by FLD.  We do this because there
2148     // are no unsigned FLD instructions, so we must promote an unsigned value to
2149     // a larger signed value, then use FLD on the larger value.
2150     //
2151     const Type *PromoteType = 0;
2152     unsigned PromoteOpcode;
2153     unsigned RealDestReg = DestReg;
2154     switch (SrcTy->getPrimitiveID()) {
2155     case Type::BoolTyID:
2156     case Type::SByteTyID:
2157       // We don't have the facilities for directly loading byte sized data from
2158       // memory (even signed).  Promote it to 16 bits.
2159       PromoteType = Type::ShortTy;
2160       PromoteOpcode = X86::MOVSXr16r8;
2161       break;
2162     case Type::UByteTyID:
2163       PromoteType = Type::ShortTy;
2164       PromoteOpcode = X86::MOVZXr16r8;
2165       break;
2166     case Type::UShortTyID:
2167       PromoteType = Type::IntTy;
2168       PromoteOpcode = X86::MOVZXr32r16;
2169       break;
2170     case Type::UIntTyID: {
2171       // Make a 64 bit temporary... and zero out the top of it...
2172       unsigned TmpReg = makeAnotherReg(Type::LongTy);
2173       BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
2174       BMI(BB, IP, X86::MOVri32, 1, TmpReg+1).addZImm(0);
2175       SrcTy = Type::LongTy;
2176       SrcClass = cLong;
2177       SrcReg = TmpReg;
2178       break;
2179     }
2180     case Type::ULongTyID:
2181       // Don't fild into the read destination.
2182       DestReg = makeAnotherReg(Type::DoubleTy);
2183       break;
2184     default:  // No promotion needed...
2185       break;
2186     }
2187     
2188     if (PromoteType) {
2189       unsigned TmpReg = makeAnotherReg(PromoteType);
2190       unsigned Opc = SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8;
2191       BMI(BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2192       SrcTy = PromoteType;
2193       SrcClass = getClass(PromoteType);
2194       SrcReg = TmpReg;
2195     }
2196
2197     // Spill the integer to memory and reload it from there...
2198     int FrameIdx =
2199       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2200
2201     if (SrcClass == cLong) {
2202       addFrameReference(BMI(BB, IP, X86::MOVmr32, 5), FrameIdx).addReg(SrcReg);
2203       addFrameReference(BMI(BB, IP, X86::MOVmr32, 5),
2204                         FrameIdx, 4).addReg(SrcReg+1);
2205     } else {
2206       static const unsigned Op1[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
2207       addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
2208     }
2209
2210     static const unsigned Op2[] =
2211       { 0/*byte*/, X86::FILDm16, X86::FILDm32, 0/*FP*/, X86::FILDm64 };
2212     addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2213
2214     // We need special handling for unsigned 64-bit integer sources.  If the
2215     // input number has the "sign bit" set, then we loaded it incorrectly as a
2216     // negative 64-bit number.  In this case, add an offset value.
2217     if (SrcTy == Type::ULongTy) {
2218       // Emit a test instruction to see if the dynamic input value was signed.
2219       BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2220
2221       // If the sign bit is set, get a pointer to an offset, otherwise get a
2222       // pointer to a zero.
2223       MachineConstantPool *CP = F->getConstantPool();
2224       unsigned Zero = makeAnotherReg(Type::IntTy);
2225       Constant *Null = Constant::getNullValue(Type::UIntTy);
2226       addConstantPoolReference(BMI(BB, IP, X86::LEAr32, 5, Zero), 
2227                                CP->getConstantPoolIndex(Null));
2228       unsigned Offset = makeAnotherReg(Type::IntTy);
2229       Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2230                                              
2231       addConstantPoolReference(BMI(BB, IP, X86::LEAr32, 5, Offset),
2232                                CP->getConstantPoolIndex(OffsetCst));
2233       unsigned Addr = makeAnotherReg(Type::IntTy);
2234       BMI(BB, IP, X86::CMOVSrr32, 2, Addr).addReg(Zero).addReg(Offset);
2235
2236       // Load the constant for an add.  FIXME: this could make an 'fadd' that
2237       // reads directly from memory, but we don't support these yet.
2238       unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2239       addDirectMem(BMI(BB, IP, X86::FLDm32, 4, ConstReg), Addr);
2240
2241       BMI(BB, IP, X86::FpADD, 2, RealDestReg).addReg(ConstReg).addReg(DestReg);
2242     }
2243
2244     return;
2245   }
2246
2247   // Handle casts from floating point to integer now...
2248   if (SrcClass == cFP) {
2249     // Change the floating point control register to use "round towards zero"
2250     // mode when truncating to an integer value.
2251     //
2252     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2253     addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
2254
2255     // Load the old value of the high byte of the control word...
2256     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2257     addFrameReference(BMI(BB, IP, X86::MOVrm8, 4, HighPartOfCW), CWFrameIdx, 1);
2258
2259     // Set the high part to be round to zero...
2260     addFrameReference(BMI(BB, IP, X86::MOVmi8, 5), CWFrameIdx, 1).addZImm(12);
2261
2262     // Reload the modified control word now...
2263     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
2264     
2265     // Restore the memory image of control word to original value
2266     addFrameReference(BMI(BB, IP, X86::MOVmr8, 5),
2267                       CWFrameIdx, 1).addReg(HighPartOfCW);
2268
2269     // We don't have the facilities for directly storing byte sized data to
2270     // memory.  Promote it to 16 bits.  We also must promote unsigned values to
2271     // larger classes because we only have signed FP stores.
2272     unsigned StoreClass  = DestClass;
2273     const Type *StoreTy  = DestTy;
2274     if (StoreClass == cByte || DestTy->isUnsigned())
2275       switch (StoreClass) {
2276       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
2277       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
2278       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2279       // The following treatment of cLong may not be perfectly right,
2280       // but it survives chains of casts of the form
2281       // double->ulong->double.
2282       case cLong:  StoreTy = Type::LongTy;  StoreClass = cLong;  break;
2283       default: assert(0 && "Unknown store class!");
2284       }
2285
2286     // Spill the integer to memory and reload it from there...
2287     int FrameIdx =
2288       F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2289
2290     static const unsigned Op1[] =
2291       { 0, X86::FISTm16, X86::FISTm32, 0, X86::FISTPm64 };
2292     addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
2293
2294     if (DestClass == cLong) {
2295       addFrameReference(BMI(BB, IP, X86::MOVrm32, 4, DestReg), FrameIdx);
2296       addFrameReference(BMI(BB, IP, X86::MOVrm32, 4, DestReg+1), FrameIdx, 4);
2297     } else {
2298       static const unsigned Op2[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
2299       addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2300     }
2301
2302     // Reload the original control word now...
2303     addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
2304     return;
2305   }
2306
2307   // Anything we haven't handled already, we can't (yet) handle at all.
2308   assert(0 && "Unhandled cast instruction!");
2309   abort();
2310 }
2311
2312 /// visitVANextInst - Implement the va_next instruction...
2313 ///
2314 void ISel::visitVANextInst(VANextInst &I) {
2315   unsigned VAList = getReg(I.getOperand(0));
2316   unsigned DestReg = getReg(I);
2317
2318   unsigned Size;
2319   switch (I.getArgType()->getPrimitiveID()) {
2320   default:
2321     std::cerr << I;
2322     assert(0 && "Error: bad type for va_next instruction!");
2323     return;
2324   case Type::PointerTyID:
2325   case Type::UIntTyID:
2326   case Type::IntTyID:
2327     Size = 4;
2328     break;
2329   case Type::ULongTyID:
2330   case Type::LongTyID:
2331   case Type::DoubleTyID:
2332     Size = 8;
2333     break;
2334   }
2335
2336   // Increment the VAList pointer...
2337   BuildMI(BB, X86::ADDri32, 2, DestReg).addReg(VAList).addZImm(Size);
2338 }
2339
2340 void ISel::visitVAArgInst(VAArgInst &I) {
2341   unsigned VAList = getReg(I.getOperand(0));
2342   unsigned DestReg = getReg(I);
2343
2344   switch (I.getType()->getPrimitiveID()) {
2345   default:
2346     std::cerr << I;
2347     assert(0 && "Error: bad type for va_next instruction!");
2348     return;
2349   case Type::PointerTyID:
2350   case Type::UIntTyID:
2351   case Type::IntTyID:
2352     addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), VAList);
2353     break;
2354   case Type::ULongTyID:
2355   case Type::LongTyID:
2356     addDirectMem(BuildMI(BB, X86::MOVrm32, 4, DestReg), VAList);
2357     addRegOffset(BuildMI(BB, X86::MOVrm32, 4, DestReg+1), VAList, 4);
2358     break;
2359   case Type::DoubleTyID:
2360     addDirectMem(BuildMI(BB, X86::FLDm64, 4, DestReg), VAList);
2361     break;
2362   }
2363 }
2364
2365
2366 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2367   // If this GEP instruction will be folded into all of its users, we don't need
2368   // to explicitly calculate it!
2369   unsigned A, B, C, D;
2370   if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2371     // Check all of the users of the instruction to see if they are loads and
2372     // stores.
2373     bool AllWillFold = true;
2374     for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2375       if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2376         if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2377             cast<Instruction>(*UI)->getOperand(0) == &I) {
2378           AllWillFold = false;
2379           break;
2380         }
2381
2382     // If the instruction is foldable, and will be folded into all users, don't
2383     // emit it!
2384     if (AllWillFold) return;
2385   }
2386
2387   unsigned outputReg = getReg(I);
2388   emitGEPOperation(BB, BB->end(), I.getOperand(0),
2389                    I.op_begin()+1, I.op_end(), outputReg);
2390 }
2391
2392 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2393 /// GEPTypes (the derived types being stepped through at each level).  On return
2394 /// from this function, if some indexes of the instruction are representable as
2395 /// an X86 lea instruction, the machine operands are put into the Ops
2396 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2397 /// lists.  Otherwise, GEPOps.size() is returned.  If this returns a an
2398 /// addressing mode that only partially consumes the input, the BaseReg input of
2399 /// the addressing mode must be left free.
2400 ///
2401 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2402 ///
2403 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2404                        std::vector<Value*> &GEPOps,
2405                        std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2406                        unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2407   const TargetData &TD = TM.getTargetData();
2408
2409   // Clear out the state we are working with...
2410   BaseReg = 0;    // No base register
2411   Scale = 1;      // Unit scale
2412   IndexReg = 0;   // No index register
2413   Disp = 0;       // No displacement
2414
2415   // While there are GEP indexes that can be folded into the current address,
2416   // keep processing them.
2417   while (!GEPTypes.empty()) {
2418     if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2419       // It's a struct access.  CUI is the index into the structure,
2420       // which names the field. This index must have unsigned type.
2421       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2422       
2423       // Use the TargetData structure to pick out what the layout of the
2424       // structure is in memory.  Since the structure index must be constant, we
2425       // can get its value and use it to find the right byte offset from the
2426       // StructLayout class's list of structure member offsets.
2427       Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2428       GEPOps.pop_back();        // Consume a GEP operand
2429       GEPTypes.pop_back();
2430     } else {
2431       // It's an array or pointer access: [ArraySize x ElementType].
2432       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2433       Value *idx = GEPOps.back();
2434
2435       // idx is the index into the array.  Unlike with structure
2436       // indices, we may not know its actual value at code-generation
2437       // time.
2438       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2439
2440       // If idx is a constant, fold it into the offset.
2441       unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2442       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2443         Disp += TypeSize*CSI->getValue();
2444       } else {
2445         // If the index reg is already taken, we can't handle this index.
2446         if (IndexReg) return;
2447
2448         // If this is a size that we can handle, then add the index as 
2449         switch (TypeSize) {
2450         case 1: case 2: case 4: case 8:
2451           // These are all acceptable scales on X86.
2452           Scale = TypeSize;
2453           break;
2454         default:
2455           // Otherwise, we can't handle this scale
2456           return;
2457         }
2458
2459         if (CastInst *CI = dyn_cast<CastInst>(idx))
2460           if (CI->getOperand(0)->getType() == Type::IntTy ||
2461               CI->getOperand(0)->getType() == Type::UIntTy)
2462             idx = CI->getOperand(0);
2463
2464         IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2465       }
2466
2467       GEPOps.pop_back();        // Consume a GEP operand
2468       GEPTypes.pop_back();
2469     }
2470   }
2471
2472   // GEPTypes is empty, which means we have a single operand left.  See if we
2473   // can set it as the base register.
2474   //
2475   // FIXME: When addressing modes are more powerful/correct, we could load
2476   // global addresses directly as 32-bit immediates.
2477   assert(BaseReg == 0);
2478   BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2479   GEPOps.pop_back();        // Consume the last GEP operand
2480 }
2481
2482
2483 /// isGEPFoldable - Return true if the specified GEP can be completely
2484 /// folded into the addressing mode of a load/store or lea instruction.
2485 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2486                          Value *Src, User::op_iterator IdxBegin,
2487                          User::op_iterator IdxEnd, unsigned &BaseReg,
2488                          unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2489   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2490     Src = CPR->getValue();
2491
2492   std::vector<Value*> GEPOps;
2493   GEPOps.resize(IdxEnd-IdxBegin+1);
2494   GEPOps[0] = Src;
2495   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2496   
2497   std::vector<const Type*> GEPTypes;
2498   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2499                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2500
2501   MachineBasicBlock::iterator IP;
2502   if (MBB) IP = MBB->end();
2503   getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2504
2505   // We can fold it away iff the getGEPIndex call eliminated all operands.
2506   return GEPOps.empty();
2507 }
2508
2509 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2510                             MachineBasicBlock::iterator IP,
2511                             Value *Src, User::op_iterator IdxBegin,
2512                             User::op_iterator IdxEnd, unsigned TargetReg) {
2513   const TargetData &TD = TM.getTargetData();
2514   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2515     Src = CPR->getValue();
2516
2517   std::vector<Value*> GEPOps;
2518   GEPOps.resize(IdxEnd-IdxBegin+1);
2519   GEPOps[0] = Src;
2520   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2521   
2522   std::vector<const Type*> GEPTypes;
2523   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2524                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2525
2526   // Keep emitting instructions until we consume the entire GEP instruction.
2527   while (!GEPOps.empty()) {
2528     unsigned OldSize = GEPOps.size();
2529     unsigned BaseReg, Scale, IndexReg, Disp;
2530     getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2531     
2532     if (GEPOps.size() != OldSize) {
2533       // getGEPIndex consumed some of the input.  Build an LEA instruction here.
2534       unsigned NextTarget = 0;
2535       if (!GEPOps.empty()) {
2536         assert(BaseReg == 0 &&
2537            "getGEPIndex should have left the base register open for chaining!");
2538         NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2539       }
2540
2541       if (IndexReg == 0 && Disp == 0)
2542         BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2543       else
2544         addFullAddress(BMI(MBB, IP, X86::LEAr32, 5, TargetReg),
2545                        BaseReg, Scale, IndexReg, Disp);
2546       --IP;
2547       TargetReg = NextTarget;
2548     } else if (GEPTypes.empty()) {
2549       // The getGEPIndex operation didn't want to build an LEA.  Check to see if
2550       // all operands are consumed but the base pointer.  If so, just load it
2551       // into the register.
2552       if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2553         BMI(MBB, IP, X86::MOVri32, 1, TargetReg).addGlobalAddress(GV);
2554       } else {
2555         unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2556         BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2557       }
2558       break;                // we are now done
2559
2560     } else {
2561       // It's an array or pointer access: [ArraySize x ElementType].
2562       const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2563       Value *idx = GEPOps.back();
2564       GEPOps.pop_back();        // Consume a GEP operand
2565       GEPTypes.pop_back();
2566
2567       // idx is the index into the array.  Unlike with structure
2568       // indices, we may not know its actual value at code-generation
2569       // time.
2570       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2571
2572       // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2573       // operand on X86.  Handle this case directly now...
2574       if (CastInst *CI = dyn_cast<CastInst>(idx))
2575         if (CI->getOperand(0)->getType() == Type::IntTy ||
2576             CI->getOperand(0)->getType() == Type::UIntTy)
2577           idx = CI->getOperand(0);
2578
2579       // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2580       // must find the size of the pointed-to type (Not coincidentally, the next
2581       // type is the type of the elements in the array).
2582       const Type *ElTy = SqTy->getElementType();
2583       unsigned elementSize = TD.getTypeSize(ElTy);
2584
2585       // If idxReg is a constant, we don't need to perform the multiply!
2586       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2587         if (!CSI->isNullValue()) {
2588           unsigned Offset = elementSize*CSI->getValue();
2589           unsigned Reg = makeAnotherReg(Type::UIntTy);
2590           BMI(MBB, IP, X86::ADDri32, 2, TargetReg).addReg(Reg).addZImm(Offset);
2591           --IP;            // Insert the next instruction before this one.
2592           TargetReg = Reg; // Codegen the rest of the GEP into this
2593         }
2594       } else if (elementSize == 1) {
2595         // If the element size is 1, we don't have to multiply, just add
2596         unsigned idxReg = getReg(idx, MBB, IP);
2597         unsigned Reg = makeAnotherReg(Type::UIntTy);
2598         BMI(MBB, IP, X86::ADDrr32, 2, TargetReg).addReg(Reg).addReg(idxReg);
2599         --IP;            // Insert the next instruction before this one.
2600         TargetReg = Reg; // Codegen the rest of the GEP into this
2601       } else {
2602         unsigned idxReg = getReg(idx, MBB, IP);
2603         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2604
2605         // Make sure we can back the iterator up to point to the first
2606         // instruction emitted.
2607         MachineBasicBlock::iterator BeforeIt = IP;
2608         if (IP == MBB->begin())
2609           BeforeIt = MBB->end();
2610         else
2611           --BeforeIt;
2612         doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2613
2614         // Emit an ADD to add OffsetReg to the basePtr.
2615         unsigned Reg = makeAnotherReg(Type::UIntTy);
2616         BMI(MBB, IP, X86::ADDrr32, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2617
2618         // Step to the first instruction of the multiply.
2619         if (BeforeIt == MBB->end())
2620           IP = MBB->begin();
2621         else
2622           IP = ++BeforeIt;
2623
2624         TargetReg = Reg; // Codegen the rest of the GEP into this
2625       }
2626     }
2627   }
2628 }
2629
2630
2631 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2632 /// frame manager, otherwise do it the hard way.
2633 ///
2634 void ISel::visitAllocaInst(AllocaInst &I) {
2635   // Find the data size of the alloca inst's getAllocatedType.
2636   const Type *Ty = I.getAllocatedType();
2637   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2638
2639   // If this is a fixed size alloca in the entry block for the function,
2640   // statically stack allocate the space.
2641   //
2642   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2643     if (I.getParent() == I.getParent()->getParent()->begin()) {
2644       TySize *= CUI->getValue();   // Get total allocated size...
2645       unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2646       
2647       // Create a new stack object using the frame manager...
2648       int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2649       addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
2650       return;
2651     }
2652   }
2653   
2654   // Create a register to hold the temporary result of multiplying the type size
2655   // constant by the variable amount.
2656   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2657   unsigned SrcReg1 = getReg(I.getArraySize());
2658   
2659   // TotalSizeReg = mul <numelements>, <TypeSize>
2660   MachineBasicBlock::iterator MBBI = BB->end();
2661   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2662
2663   // AddedSize = add <TotalSizeReg>, 15
2664   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2665   BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
2666
2667   // AlignedSize = and <AddedSize>, ~15
2668   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2669   BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
2670   
2671   // Subtract size from stack pointer, thereby allocating some space.
2672   BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2673
2674   // Put a pointer to the space into the result register, by copying
2675   // the stack pointer.
2676   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
2677
2678   // Inform the Frame Information that we have just allocated a variable-sized
2679   // object.
2680   F->getFrameInfo()->CreateVariableSizedObject();
2681 }
2682
2683 /// visitMallocInst - Malloc instructions are code generated into direct calls
2684 /// to the library malloc.
2685 ///
2686 void ISel::visitMallocInst(MallocInst &I) {
2687   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2688   unsigned Arg;
2689
2690   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2691     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2692   } else {
2693     Arg = makeAnotherReg(Type::UIntTy);
2694     unsigned Op0Reg = getReg(I.getOperand(0));
2695     MachineBasicBlock::iterator MBBI = BB->end();
2696     doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2697   }
2698
2699   std::vector<ValueRecord> Args;
2700   Args.push_back(ValueRecord(Arg, Type::UIntTy));
2701   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2702                                   1).addExternalSymbol("malloc", true);
2703   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2704 }
2705
2706
2707 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2708 /// function.
2709 ///
2710 void ISel::visitFreeInst(FreeInst &I) {
2711   std::vector<ValueRecord> Args;
2712   Args.push_back(ValueRecord(I.getOperand(0)));
2713   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2714                                   1).addExternalSymbol("free", true);
2715   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2716 }
2717    
2718 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2719 /// into a machine code representation is a very simple peep-hole fashion.  The
2720 /// generated code sucks but the implementation is nice and simple.
2721 ///
2722 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2723   return new ISel(TM);
2724 }