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