* Simplify Value classes
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 platform
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/Target/TargetMachine.h"
24 #include "llvm/Support/InstVisitor.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include <map>
27
28 /// BMI - A special BuildMI variant that takes an iterator to insert the
29 /// instruction at as well as a basic block.
30 /// this is the version for when you have a destination register in mind.
31 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
32                                       MachineBasicBlock::iterator &I,
33                                       MachineOpCode Opcode,
34                                       unsigned NumOperands,
35                                       unsigned DestReg) {
36   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
37   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
38   I = MBB->insert(I, MI)+1;
39   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
40 }
41
42 /// BMI - A special BuildMI variant that takes an iterator to insert the
43 /// instruction at as well as a basic block.
44 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
45                                       MachineBasicBlock::iterator &I,
46                                       MachineOpCode Opcode,
47                                       unsigned NumOperands) {
48   assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
49   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
50   I = MBB->insert(I, MI)+1;
51   return MachineInstrBuilder(MI);
52 }
53
54
55 namespace {
56   struct ISel : public FunctionPass, InstVisitor<ISel> {
57     TargetMachine &TM;
58     MachineFunction *F;                    // The function we are compiling into
59     MachineBasicBlock *BB;                 // The current MBB we are compiling
60
61     unsigned CurReg;
62     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
63
64     // MBBMap - Mapping between LLVM BB -> Machine BB
65     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
66
67     ISel(TargetMachine &tm)
68       : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
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       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
77         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
78
79       // Emit instructions to load the arguments...  The function's arguments
80       // look like this:
81       //
82       // [EBP]     -- copy of old EBP
83       // [EBP + 4] -- return address
84       // [EBP + 8] -- first argument (leftmost lexically)
85       //
86       // So we want to start with counter = 2.
87       //
88       BB = &F->front();
89       unsigned ArgOffset = 8;
90       for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E;
91            ++I, ArgOffset += 4) {
92         unsigned Reg = getReg(*I);
93
94         // Load it out of the stack frame at EBP + 4*argPos.
95
96         // FIXME: This should load the argument of the appropriate size!!
97         addRegOffset(BuildMI(BB, X86::MOVmr32, 4, Reg), X86::EBP, ArgOffset);
98       }
99
100       // Instruction select everything except PHI nodes
101       visit(Fn);
102
103       // Select the PHI nodes
104       SelectPHINodes();
105
106       RegMap.clear();
107       MBBMap.clear();
108       CurReg = MRegisterInfo::FirstVirtualRegister;
109       F = 0;
110       return false;  // We never modify the LLVM itself.
111     }
112
113     virtual const char *getPassName() const {
114       return "X86 Simple Instruction Selection";
115     }
116
117     /// visitBasicBlock - This method is called when we are visiting a new basic
118     /// block.  This simply creates a new MachineBasicBlock to emit code into
119     /// and adds it to the current MachineFunction.  Subsequent visit* for
120     /// instructions will be invoked for all instructions in the basic block.
121     ///
122     void visitBasicBlock(BasicBlock &LLVM_BB) {
123       BB = MBBMap[&LLVM_BB];
124     }
125
126
127     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
128     /// because we have to generate our sources into the source basic blocks,
129     /// not the current one.
130     ///
131     void SelectPHINodes();
132
133     // Visitation methods for various instructions.  These methods simply emit
134     // fixed X86 code for each instruction.
135     //
136
137     // Control flow operators
138     void visitReturnInst(ReturnInst &RI);
139     void visitBranchInst(BranchInst &BI);
140     void visitCallInst(CallInst &I);
141
142     // Arithmetic operators
143     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
144     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
145     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
146     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
147                     unsigned destReg, const Type *resultType,
148                     unsigned op0Reg, unsigned op1Reg);
149     void visitMul(BinaryOperator &B);
150
151     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
152     void visitRem(BinaryOperator &B) { visitDivRem(B); }
153     void visitDivRem(BinaryOperator &B);
154
155     // Bitwise operators
156     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
157     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
158     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
159
160     // Binary comparison operators
161     void visitSetCCInst(SetCondInst &I, unsigned OpNum);
162     void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
163     void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
164     void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
165     void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
166     void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
167     void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
168
169     // Memory Instructions
170     void visitLoadInst(LoadInst &I);
171     void visitStoreInst(StoreInst &I);
172     void visitGetElementPtrInst(GetElementPtrInst &I);
173     void visitMallocInst(MallocInst &I);
174     void visitFreeInst(FreeInst &I);
175     void visitAllocaInst(AllocaInst &I);
176     
177     // Other operators
178     void visitShiftInst(ShiftInst &I);
179     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
180     void visitCastInst(CastInst &I);
181
182     void visitInstruction(Instruction &I) {
183       std::cerr << "Cannot instruction select: " << I;
184       abort();
185     }
186
187     /// promote32 - Make a value 32-bits wide, and put it somewhere.
188     void promote32 (const unsigned targetReg, Value *v);
189     
190     // emitGEPOperation - Common code shared between visitGetElementPtrInst and
191     // constant expression GEP support.
192     //
193     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
194                           Value *Src, User::op_iterator IdxBegin,
195                           User::op_iterator IdxEnd, unsigned TargetReg);
196
197     /// copyConstantToRegister - Output the instructions required to put the
198     /// specified constant into the specified register.
199     ///
200     void copyConstantToRegister(MachineBasicBlock *MBB,
201                                 MachineBasicBlock::iterator &MBBI,
202                                 Constant *C, unsigned Reg);
203
204     /// makeAnotherReg - This method returns the next register number
205     /// we haven't yet used.
206     unsigned makeAnotherReg(const Type *Ty) {
207       // Add the mapping of regnumber => reg class to MachineFunction
208       const TargetRegisterClass *RC =
209         TM.getRegisterInfo()->getRegClassForType(Ty);
210       F->getSSARegMap()->addRegMap(CurReg, RC);
211       return CurReg++;
212     }
213
214     /// getReg - This method turns an LLVM value into a register number.  This
215     /// is guaranteed to produce the same register number for a particular value
216     /// every time it is queried.
217     ///
218     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
219     unsigned getReg(Value *V) {
220       // Just append to the end of the current bb.
221       MachineBasicBlock::iterator It = BB->end();
222       return getReg(V, BB, It);
223     }
224     unsigned getReg(Value *V, MachineBasicBlock *MBB,
225                     MachineBasicBlock::iterator &IPt) {
226       unsigned &Reg = RegMap[V];
227       if (Reg == 0) {
228         Reg = makeAnotherReg(V->getType());
229         RegMap[V] = Reg;
230       }
231
232       // If this operand is a constant, emit the code to copy the constant into
233       // the register here...
234       //
235       if (Constant *C = dyn_cast<Constant>(V)) {
236         copyConstantToRegister(MBB, IPt, C, Reg);
237         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
238       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
239         // Move the address of the global into the register
240         BMI(MBB, IPt, X86::MOVir32, 1, Reg).addReg(GV);
241         RegMap.erase(V);  // Assign a new name to this address if ref'd again
242       }
243
244       return Reg;
245     }
246   };
247 }
248
249 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
250 /// Representation.
251 ///
252 enum TypeClass {
253   cByte, cShort, cInt, cFP, cLong
254 };
255
256 /// getClass - Turn a primitive type into a "class" number which is based on the
257 /// size of the type, and whether or not it is floating point.
258 ///
259 static inline TypeClass getClass(const Type *Ty) {
260   switch (Ty->getPrimitiveID()) {
261   case Type::SByteTyID:
262   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
263   case Type::ShortTyID:
264   case Type::UShortTyID:  return cShort;     // Short operands are class #1
265   case Type::IntTyID:
266   case Type::UIntTyID:
267   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
268
269   case Type::FloatTyID:
270   case Type::DoubleTyID:  return cFP;        // Floating Point is #3
271   case Type::LongTyID:
272   case Type::ULongTyID:   //return cLong;      // Longs are class #3
273     return cInt;          // FIXME: LONGS ARE TREATED AS INTS!
274   default:
275     assert(0 && "Invalid type to getClass!");
276     return cByte;  // not reached
277   }
278 }
279
280 // getClassB - Just like getClass, but treat boolean values as bytes.
281 static inline TypeClass getClassB(const Type *Ty) {
282   if (Ty == Type::BoolTy) return cByte;
283   return getClass(Ty);
284 }
285
286
287 /// copyConstantToRegister - Output the instructions required to put the
288 /// specified constant into the specified register.
289 ///
290 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
291                                   MachineBasicBlock::iterator &IP,
292                                   Constant *C, unsigned R) {
293   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
294     if (CE->getOpcode() == Instruction::GetElementPtr) {
295       emitGEPOperation(MBB, IP, CE->getOperand(0),
296                        CE->op_begin()+1, CE->op_end(), R);
297       return;
298     }
299
300     std::cerr << "Offending expr: " << C << "\n";
301     assert(0 && "Constant expressions not yet handled!\n");
302   }
303
304   if (C->getType()->isIntegral()) {
305     unsigned Class = getClassB(C->getType());
306     assert(Class <= cInt && "Type not handled yet!");
307
308     static const unsigned IntegralOpcodeTab[] = {
309       X86::MOVir8, X86::MOVir16, X86::MOVir32
310     };
311
312     if (C->getType() == Type::BoolTy) {
313       BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
314     } else if (C->getType()->isSigned()) {
315       ConstantSInt *CSI = cast<ConstantSInt>(C);
316       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
317     } else {
318       ConstantUInt *CUI = cast<ConstantUInt>(C);
319       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
320     }
321   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
322     double Value = CFP->getValue();
323     if (Value == +0.0)
324       BMI(MBB, IP, X86::FLD0, 0, R);
325     else if (Value == +1.0)
326       BMI(MBB, IP, X86::FLD1, 0, R);
327     else {
328       std::cerr << "Cannot load constant '" << Value << "'!\n";
329       assert(0);
330     }
331
332   } else if (isa<ConstantPointerNull>(C)) {
333     // Copy zero (null pointer) to the register.
334     BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
335   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
336     unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
337     BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
338   } else {
339     std::cerr << "Offending constant: " << C << "\n";
340     assert(0 && "Type not handled yet!");
341   }
342 }
343
344 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
345 /// because we have to generate our sources into the source basic blocks, not
346 /// the current one.
347 ///
348 void ISel::SelectPHINodes() {
349   const Function &LF = *F->getFunction();  // The LLVM function...
350   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
351     const BasicBlock *BB = I;
352     MachineBasicBlock *MBB = MBBMap[I];
353
354     // Loop over all of the PHI nodes in the LLVM basic block...
355     unsigned NumPHIs = 0;
356     for (BasicBlock::const_iterator I = BB->begin();
357          PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
358       // Create a new machine instr PHI node, and insert it.
359       MachineInstr *MI = BuildMI(X86::PHI, PN->getNumOperands(), getReg(*PN));
360       MBB->insert(MBB->begin()+NumPHIs++, MI); // Insert it at the top of the BB
361
362       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
363         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
364
365         // Get the incoming value into a virtual register.  If it is not already
366         // available in a virtual register, insert the computation code into
367         // PredMBB
368         //
369
370         MachineBasicBlock::iterator PI = PredMBB->begin();
371         while ((*PI)->getOpcode() == X86::PHI) ++PI;
372         
373         MI->addRegOperand(getReg(PN->getIncomingValue(i), PredMBB, PI));
374         MI->addMachineBasicBlockOperand(PredMBB);
375       }
376     }
377   }
378 }
379
380
381
382 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
383 /// register, then move it to wherever the result should be. 
384 /// We handle FP setcc instructions by pushing them, doing a
385 /// compare-and-pop-twice, and then copying the concodes to the main
386 /// processor's concodes (I didn't make this up, it's in the Intel manual)
387 ///
388 void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
389   // The arguments are already supposed to be of the same type.
390   const Type *CompTy = I.getOperand(0)->getType();
391   unsigned reg1 = getReg(I.getOperand(0));
392   unsigned reg2 = getReg(I.getOperand(1));
393
394   unsigned Class = getClass(CompTy);
395   switch (Class) {
396     // Emit: cmp <var1>, <var2> (do the comparison).  We can
397     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
398     // 32-bit.
399   case cByte:
400     BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
401     break;
402   case cShort:
403     BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
404     break;
405   case cInt:
406     BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
407     break;
408
409 #if 0
410     // Push the variables on the stack with fldl opcodes.
411     // FIXME: assuming var1, var2 are in memory, if not, spill to
412     // stack first
413   case cFP:  // Floats
414     BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
415     BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
416     break;
417   case cFP (doubles):  // Doubles
418     BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
419     BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
420     break;
421 #endif
422   case cLong:
423   default:
424     visitInstruction(I);
425   }
426
427 #if 0
428   if (CompTy->isFloatingPoint()) {
429     // (Non-trapping) compare and pop twice.
430     BuildMI (BB, X86::FUCOMPP, 0);
431     // Move fp status word (concodes) to ax.
432     BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
433     // Load real concodes from ax.
434     BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
435   }
436 #endif
437
438   // Emit setOp instruction (extract concode; clobbers ax),
439   // using the following mapping:
440   // LLVM  -> X86 signed  X86 unsigned
441   // -----    -----       -----
442   // seteq -> sete        sete
443   // setne -> setne       setne
444   // setlt -> setl        setb
445   // setgt -> setg        seta
446   // setle -> setle       setbe
447   // setge -> setge       setae
448
449   static const unsigned OpcodeTab[2][6] = {
450     {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
451     {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
452   };
453
454   BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, getReg(I));
455 }
456
457 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
458 /// operand, in the specified target register.
459 void ISel::promote32 (unsigned targetReg, Value *v) {
460   unsigned vReg = getReg(v);
461   bool isUnsigned = v->getType()->isUnsigned();
462   switch (getClass(v->getType())) {
463   case cByte:
464     // Extend value into target register (8->32)
465     if (isUnsigned)
466       BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(vReg);
467     else
468       BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(vReg);
469     break;
470   case cShort:
471     // Extend value into target register (16->32)
472     if (isUnsigned)
473       BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(vReg);
474     else
475       BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(vReg);
476     break;
477   case cInt:
478     // Move value into target register (32->32)
479     BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(vReg);
480     break;
481   default:
482     assert(0 && "Unpromotable operand class in promote32");
483   }
484 }
485
486 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
487 /// we have the following possibilities:
488 ///
489 ///   ret void: No return value, simply emit a 'ret' instruction
490 ///   ret sbyte, ubyte : Extend value into EAX and return
491 ///   ret short, ushort: Extend value into EAX and return
492 ///   ret int, uint    : Move value into EAX and return
493 ///   ret pointer      : Move value into EAX and return
494 ///   ret long, ulong  : Move value into EAX/EDX and return
495 ///   ret float/double : Top of FP stack
496 ///
497 void ISel::visitReturnInst (ReturnInst &I) {
498   if (I.getNumOperands() == 0) {
499     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
500     return;
501   }
502
503   Value *RetVal = I.getOperand(0);
504   switch (getClass(RetVal->getType())) {
505   case cByte:   // integral return values: extend or move into EAX and return
506   case cShort:
507   case cInt:
508     promote32(X86::EAX, RetVal);
509     break;
510   case cFP:                   // Floats & Doubles: Return in ST(0)
511     BuildMI(BB, X86::FpMOV, 1, X86::ST0).addReg(getReg(RetVal));
512     break;
513   case cLong:
514     // ret long: use EAX(least significant 32 bits)/EDX (most
515     // significant 32)...
516   default:
517     visitInstruction (I);
518   }
519   // Emit a 'ret' instruction
520   BuildMI(BB, X86::RET, 0);
521 }
522
523 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
524 /// that since code layout is frozen at this point, that if we are trying to
525 /// jump to a block that is the immediate successor of the current block, we can
526 /// just make a fall-through. (but we don't currently).
527 ///
528 void ISel::visitBranchInst(BranchInst &BI) {
529   if (BI.isConditional()) {
530     BasicBlock *ifTrue  = BI.getSuccessor(0);
531     BasicBlock *ifFalse = BI.getSuccessor(1);
532
533     // Compare condition with zero, followed by jump-if-equal to ifFalse, and
534     // jump-if-nonequal to ifTrue
535     unsigned int condReg = getReg(BI.getCondition());
536     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
537     BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
538     BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
539   } else { // unconditional branch
540     BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
541   }
542 }
543
544 /// visitCallInst - Push args on stack and do a procedure call instruction.
545 void ISel::visitCallInst(CallInst &CI) {
546   // keep a counter of how many bytes we pushed on the stack
547   unsigned bytesPushed = 0;
548
549   // Push the arguments on the stack in reverse order, as specified by
550   // the ABI.
551   for (unsigned i = CI.getNumOperands()-1; i >= 1; --i) {
552     Value *v = CI.getOperand(i);
553     switch (getClass(v->getType())) {
554     case cByte:
555     case cShort:
556       // Promote V to 32 bits wide, and move the result into EAX,
557       // then push EAX.
558       promote32 (X86::EAX, v);
559       BuildMI(BB, X86::PUSHr32, 1).addReg(X86::EAX);
560       bytesPushed += 4;
561       break;
562     case cInt: {
563       unsigned Reg = getReg(v);
564       BuildMI(BB, X86::PUSHr32, 1).addReg(Reg);
565       bytesPushed += 4;
566       break;
567     }
568     default:
569       // FIXME: long/ulong/float/double args not handled.
570       visitInstruction(CI);
571       break;
572     }
573   }
574
575   if (Function *F = CI.getCalledFunction()) {
576     // Emit a CALL instruction with PC-relative displacement.
577     BuildMI(BB, X86::CALLpcrel32, 1).addPCDisp(F);
578   } else {
579     unsigned Reg = getReg(CI.getCalledValue());
580     BuildMI(BB, X86::CALLr32, 1).addReg(Reg);
581   }
582
583   // Adjust the stack by `bytesPushed' amount if non-zero
584   if (bytesPushed > 0)
585     BuildMI(BB, X86::ADDri32,2, X86::ESP).addReg(X86::ESP).addZImm(bytesPushed);
586
587   // If there is a return value, scavenge the result from the location the call
588   // leaves it in...
589   //
590   if (CI.getType() != Type::VoidTy) {
591     unsigned resultTypeClass = getClass(CI.getType());
592     switch (resultTypeClass) {
593     case cByte:
594     case cShort:
595     case cInt: {
596       // Integral results are in %eax, or the appropriate portion
597       // thereof.
598       static const unsigned regRegMove[] = {
599         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
600       };
601       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
602       BuildMI(BB, regRegMove[resultTypeClass], 1, getReg(CI))
603                  .addReg(AReg[resultTypeClass]);
604       break;
605     }
606     case cFP:     // Floating-point return values live in %ST(0)
607       BuildMI(BB, X86::FpMOV, 1, getReg(CI)).addReg(X86::ST0);
608       break;
609     default:
610       std::cerr << "Cannot get return value for call of type '"
611                 << *CI.getType() << "'\n";
612       visitInstruction(CI);
613     }
614   }
615 }
616
617 /// visitSimpleBinary - Implement simple binary operators for integral types...
618 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
619 /// 4 for Xor.
620 ///
621 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
622   if (B.getType() == Type::BoolTy)  // FIXME: Handle bools for logicals
623     visitInstruction(B);
624
625   unsigned Class = getClass(B.getType());
626   if (Class > cFP)  // FIXME: Handle longs
627     visitInstruction(B);
628
629   static const unsigned OpcodeTab[][4] = {
630     // Arithmetic operators
631     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD },  // ADD
632     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB },  // SUB
633
634     // Bitwise operators
635     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
636     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
637     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
638   };
639   
640   unsigned Opcode = OpcodeTab[OperatorClass][Class];
641   assert(Opcode && "Floating point arguments to logical inst?");
642   unsigned Op0r = getReg(B.getOperand(0));
643   unsigned Op1r = getReg(B.getOperand(1));
644   BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
645 }
646
647 /// doMultiply - Emit appropriate instructions to multiply together
648 /// the registers op0Reg and op1Reg, and put the result in destReg.
649 /// The type of the result should be given as resultType.
650 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
651                       unsigned destReg, const Type *resultType,
652                       unsigned op0Reg, unsigned op1Reg) {
653   unsigned Class = getClass(resultType);
654   switch (Class) {
655   case cFP:              // Floating point multiply
656     BuildMI(BB, X86::FpMUL, 2, destReg).addReg(op0Reg).addReg(op1Reg);
657     return;
658   default:
659   case cLong:
660     assert(0 && "doMultiply not implemented for this class yet!");
661   case cByte:
662   case cShort:
663   case cInt:          // Small integerals, handled below...
664     break;
665   }
666  
667   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
668   static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
669   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
670   unsigned Reg     = Regs[Class];
671
672   // Emit a MOV to put the first operand into the appropriately-sized
673   // subreg of EAX.
674   BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg (op0Reg);
675   
676   // Emit the appropriate multiply instruction.
677   BMI(MBB, MBBI, MulOpcode[Class], 1).addReg (op1Reg);
678
679   // Emit another MOV to put the result into the destination register.
680   BMI(MBB, MBBI, MovOpcode[Class], 1, destReg).addReg (Reg);
681 }
682
683 /// visitMul - Multiplies are not simple binary operators because they must deal
684 /// with the EAX register explicitly.
685 ///
686 void ISel::visitMul(BinaryOperator &I) {
687   unsigned DestReg = getReg(I);
688   unsigned Op0Reg  = getReg(I.getOperand(0));
689   unsigned Op1Reg  = getReg(I.getOperand(1));
690   MachineBasicBlock::iterator MBBI = BB->end();
691   doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
692 }
693
694
695 /// visitDivRem - Handle division and remainder instructions... these
696 /// instruction both require the same instructions to be generated, they just
697 /// select the result from a different register.  Note that both of these
698 /// instructions work differently for signed and unsigned operands.
699 ///
700 void ISel::visitDivRem(BinaryOperator &I) {
701   unsigned Class     = getClass(I.getType());
702   unsigned Op0Reg    = getReg(I.getOperand(0));
703   unsigned Op1Reg    = getReg(I.getOperand(1));
704   unsigned ResultReg = getReg(I);
705
706   switch (Class) {
707   case cFP:              // Floating point multiply
708     if (I.getOpcode() == Instruction::Div)
709       BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
710     else
711       BuildMI(BB, X86::FpREM, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
712     return;
713   default:
714   case cLong:
715     assert(0 && "div/rem not implemented for this class yet!");
716   case cByte:
717   case cShort:
718   case cInt:          // Small integerals, handled below...
719     break;
720   }
721
722   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
723   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
724   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
725   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
726   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
727
728   static const unsigned DivOpcode[][4] = {
729     { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 },  // Unsigned division
730     { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 },  // Signed division
731   };
732
733   bool isSigned   = I.getType()->isSigned();
734   unsigned Reg    = Regs[Class];
735   unsigned ExtReg = ExtRegs[Class];
736
737   // Put the first operand into one of the A registers...
738   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
739
740   if (isSigned) {
741     // Emit a sign extension instruction...
742     BuildMI(BB, ExtOpcode[Class], 0);
743   } else {
744     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
745     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
746   }
747
748   // Emit the appropriate divide or remainder instruction...
749   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
750
751   // Figure out which register we want to pick the result out of...
752   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
753   
754   // Put the result into the destination register...
755   BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
756 }
757
758
759 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
760 /// for constant immediate shift values, and for constant immediate
761 /// shift values equal to 1. Even the general case is sort of special,
762 /// because the shift amount has to be in CL, not just any old register.
763 ///
764 void ISel::visitShiftInst (ShiftInst &I) {
765   unsigned Op0r = getReg (I.getOperand(0));
766   unsigned DestReg = getReg(I);
767   bool isLeftShift = I.getOpcode() == Instruction::Shl;
768   bool isOperandSigned = I.getType()->isUnsigned();
769   unsigned OperandClass = getClass(I.getType());
770
771   if (OperandClass > cInt)
772     visitInstruction(I); // Can't handle longs yet!
773
774   if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
775     {
776       // The shift amount is constant, guaranteed to be a ubyte. Get its value.
777       assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
778       unsigned char shAmt = CUI->getValue();
779
780       static const unsigned ConstantOperand[][4] = {
781         { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 },  // SHR
782         { X86::SARir8, X86::SARir16, X86::SARir32, 0 },  // SAR
783         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SHL
784         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SAL = SHL
785       };
786
787       const unsigned *OpTab = // Figure out the operand table to use
788         ConstantOperand[isLeftShift*2+isOperandSigned];
789
790       // Emit: <insn> reg, shamt  (shift-by-immediate opcode "ir" form.)
791       BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
792     }
793   else
794     {
795       // The shift amount is non-constant.
796       //
797       // In fact, you can only shift with a variable shift amount if
798       // that amount is already in the CL register, so we have to put it
799       // there first.
800       //
801
802       // Emit: move cl, shiftAmount (put the shift amount in CL.)
803       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
804
805       // This is a shift right (SHR).
806       static const unsigned NonConstantOperand[][4] = {
807         { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 },  // SHR
808         { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 },  // SAR
809         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SHL
810         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SAL = SHL
811       };
812
813       const unsigned *OpTab = // Figure out the operand table to use
814         NonConstantOperand[isLeftShift*2+isOperandSigned];
815
816       BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
817     }
818 }
819
820
821 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
822 /// instruction.  The load and store instructions are the only place where we
823 /// need to worry about the memory layout of the target machine.
824 ///
825 void ISel::visitLoadInst(LoadInst &I) {
826   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
827   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
828   unsigned SrcAddrReg = getReg(I.getOperand(0));
829   unsigned DestReg = getReg(I);
830
831   unsigned Class = getClass(I.getType());
832   switch (Class) {
833   default: visitInstruction(I);   // FIXME: Handle longs...
834   case cFP: {
835     // FIXME: Handle endian swapping for FP values.
836     unsigned Opcode = I.getType() == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
837     addDirectMem(BuildMI(BB, Opcode, 4, DestReg), SrcAddrReg);
838     return;
839   }
840   case cInt:      // Integers of various sizes handled below
841   case cShort:
842   case cByte: break;
843   }
844
845   // We need to adjust the input pointer if we are emulating a big-endian
846   // long-pointer target.  On these systems, the pointer that we are interested
847   // in is in the upper part of the eight byte memory image of the pointer.  It
848   // also happens to be byte-swapped, but this will be handled later.
849   //
850   if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
851     unsigned R = makeAnotherReg(Type::UIntTy);
852     BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
853     SrcAddrReg = R;
854   }
855
856   unsigned IReg = DestReg;
857   if (!isLittleEndian) {  // If big endian we need an intermediate stage
858     IReg = makeAnotherReg(I.getType());
859     std::swap(IReg, DestReg);
860   }
861
862   static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
863   addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
864
865   if (!isLittleEndian) {
866     // Emit the byte swap instruction...
867     switch (Class) {
868     case cByte:
869       // No byteswap neccesary for 8 bit value...
870       BuildMI(BB, X86::MOVrr8, 1, IReg).addReg(DestReg);
871       break;
872     case cInt:
873       // Use the 32 bit bswap instruction to do a 32 bit swap...
874       BuildMI(BB, X86::BSWAPr32, 1, IReg).addReg(DestReg);
875       break;
876
877     case cShort:
878       // For 16 bit we have to use an xchg instruction, because there is no
879       // 16-bit bswap.  XCHG is neccesarily not in SSA form, so we force things
880       // into AX to do the xchg.
881       //
882       BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(DestReg);
883       BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
884                                   .addReg(X86::AH, MOTy::UseAndDef);
885       BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
886       break;
887     default: assert(0 && "Class not handled yet!");
888     }
889   }
890 }
891
892
893 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
894 /// instruction.
895 ///
896 void ISel::visitStoreInst(StoreInst &I) {
897   bool isLittleEndian  = TM.getTargetData().isLittleEndian();
898   bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
899   unsigned ValReg = getReg(I.getOperand(0));
900   unsigned AddressReg = getReg(I.getOperand(1));
901
902   unsigned Class = getClass(I.getOperand(0)->getType());
903   switch (Class) {
904   default: visitInstruction(I);   // FIXME: Handle longs...
905   case cFP: {
906     // FIXME: Handle endian swapping for FP values.
907     unsigned Opcode = I.getOperand(0)->getType() == Type::FloatTy ?
908                             X86::FSTr32 : X86::FSTr64;
909     addDirectMem(BuildMI(BB, Opcode, 1+4), AddressReg).addReg(ValReg);
910     return;
911   }
912   case cInt:      // Integers of various sizes handled below
913   case cShort:
914   case cByte: break;
915   }
916
917   if (!isLittleEndian && hasLongPointers &&
918       isa<PointerType>(I.getOperand(0)->getType())) {
919     unsigned R = makeAnotherReg(Type::UIntTy);
920     BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
921     AddressReg = R;
922   }
923
924   if (!isLittleEndian && Class != cByte) {
925     // Emit a byte swap instruction...
926     switch (Class) {
927     case cInt: {
928       unsigned R = makeAnotherReg(I.getOperand(0)->getType());
929       BuildMI(BB, X86::BSWAPr32, 1, R).addReg(ValReg);
930       ValReg = R;
931       break;
932     }
933     case cShort:
934       // For 16 bit we have to use an xchg instruction, because there is no
935       // 16-bit bswap.  XCHG is neccesarily not in SSA form, so we force things
936       // into AX to do the xchg.
937       //
938       BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(ValReg);
939       BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
940                                   .addReg(X86::AH, MOTy::UseAndDef);
941       ValReg = X86::AX;
942       break;
943     default: assert(0 && "Unknown class!");
944     }
945   }
946
947   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
948   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
949 }
950
951
952 /// visitCastInst - Here we have various kinds of copying with or without
953 /// sign extension going on.
954 void
955 ISel::visitCastInst (CastInst &CI)
956 {
957   const Type *targetType = CI.getType ();
958   Value *operand = CI.getOperand (0);
959   unsigned int operandReg = getReg (operand);
960   const Type *sourceType = operand->getType ();
961   unsigned int destReg = getReg (CI);
962   //
963   // Currently we handle:
964   //
965   // 1) cast * to bool
966   //
967   // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
968   //    cast {short, ushort} to {ushort, short}
969   //    cast {int, uint, ptr} to {int, uint, ptr}
970   //
971   // 3) cast {sbyte, ubyte} to {ushort, short}
972   //    cast {sbyte, ubyte} to {int, uint, ptr}
973   //    cast {short, ushort} to {int, uint, ptr}
974   //
975   // 4) cast {int, uint, ptr} to {short, ushort}
976   //    cast {int, uint, ptr} to {sbyte, ubyte}
977   //    cast {short, ushort} to {sbyte, ubyte}
978
979   // 1) Implement casts to bool by using compare on the operand followed
980   // by set if not zero on the result.
981   if (targetType == Type::BoolTy)
982     {
983       BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
984       BuildMI (BB, X86::SETNEr, 1, destReg);
985       return;
986     }
987
988   // 2) Implement casts between values of the same type class (as determined
989   // by getClass) by using a register-to-register move.
990   unsigned srcClass = getClassB(sourceType);
991   unsigned targClass = getClass(targetType);
992   static const unsigned regRegMove[] = {
993     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
994   };
995
996   if (srcClass <= cInt && targClass <= cInt && srcClass == targClass) {
997     BuildMI(BB, regRegMove[srcClass], 1, destReg).addReg(operandReg);
998     return;
999   }
1000   // 3) Handle cast of SMALLER int to LARGER int using a move with sign
1001   // extension or zero extension, depending on whether the source type
1002   // was signed.
1003   if ((srcClass <= cInt) && (targClass <= cInt) && (srcClass < targClass))
1004     {
1005       static const unsigned ops[] = {
1006         X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
1007         X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
1008       };
1009       unsigned srcSigned = sourceType->isSigned ();
1010       BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
1011                destReg).addReg (operandReg);
1012       return;
1013     }
1014   // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
1015   // followed by a move out of AX or AL.
1016   if ((srcClass <= cInt) && (targClass <= cInt) && (srcClass > targClass))
1017     {
1018       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1019       BuildMI (BB, regRegMove[srcClass], 1,
1020                AReg[srcClass]).addReg (operandReg);
1021       BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
1022       return;
1023     }
1024   // Anything we haven't handled already, we can't (yet) handle at all.
1025   //
1026   // FP to integral casts can be handled with FISTP to store onto the
1027   // stack while converting to integer, followed by a MOV to load from
1028   // the stack into the result register. Integral to FP casts can be
1029   // handled with MOV to store onto the stack, followed by a FILD to
1030   // load from the stack while converting to FP. For the moment, I
1031   // can't quite get straight in my head how to borrow myself some
1032   // stack space and write on it. Otherwise, this would be trivial.
1033   visitInstruction (CI);
1034 }
1035
1036 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
1037 // returns zero when the input is not exactly a power of two.
1038 static unsigned ExactLog2(unsigned Val) {
1039   if (Val == 0) return 0;
1040   unsigned Count = 0;
1041   while (Val != 1) {
1042     if (Val & 1) return 0;
1043     Val >>= 1;
1044     ++Count;
1045   }
1046   return Count+1;
1047 }
1048
1049 /// visitGetElementPtrInst - I don't know, most programs don't have
1050 /// getelementptr instructions, right? That means we can put off
1051 /// implementing this, right? Right. This method emits machine
1052 /// instructions to perform type-safe pointer arithmetic. I am
1053 /// guessing this could be cleaned up somewhat to use fewer temporary
1054 /// registers.
1055 void
1056 ISel::visitGetElementPtrInst (GetElementPtrInst &I)
1057 {
1058   unsigned outputReg = getReg (I);
1059   MachineBasicBlock::iterator MI = BB->end();
1060   emitGEPOperation(BB, MI, I.getOperand(0),
1061                    I.op_begin()+1, I.op_end(), outputReg);
1062 }
1063
1064 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1065                             MachineBasicBlock::iterator &IP,
1066                             Value *Src, User::op_iterator IdxBegin,
1067                             User::op_iterator IdxEnd, unsigned TargetReg) {
1068   const TargetData &TD = TM.getTargetData();
1069   const Type *Ty = Src->getType();
1070   unsigned basePtrReg = getReg(Src, MBB, IP);
1071
1072   // GEPs have zero or more indices; we must perform a struct access
1073   // or array access for each one.
1074   for (GetElementPtrInst::op_iterator oi = IdxBegin,
1075          oe = IdxEnd; oi != oe; ++oi) {
1076     Value *idx = *oi;
1077     unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
1078     if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
1079       // It's a struct access.  idx is the index into the structure,
1080       // which names the field. This index must have ubyte type.
1081       const ConstantUInt *CUI = cast <ConstantUInt> (idx);
1082       assert (CUI->getType () == Type::UByteTy
1083               && "Funny-looking structure index in GEP");
1084       // Use the TargetData structure to pick out what the layout of
1085       // the structure is in memory.  Since the structure index must
1086       // be constant, we can get its value and use it to find the
1087       // right byte offset from the StructLayout class's list of
1088       // structure member offsets.
1089       unsigned idxValue = CUI->getValue();
1090       unsigned memberOffset =
1091         TD.getStructLayout (StTy)->MemberOffsets[idxValue];
1092       // Emit an ADD to add memberOffset to the basePtr.
1093       BMI(MBB, IP, X86::ADDri32, 2,
1094           nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
1095       // The next type is the member of the structure selected by the
1096       // index.
1097       Ty = StTy->getElementTypes ()[idxValue];
1098     } else if (const SequentialType *SqTy = cast <SequentialType>(Ty)) {
1099       // It's an array or pointer access: [ArraySize x ElementType].
1100
1101       // idx is the index into the array.  Unlike with structure
1102       // indices, we may not know its actual value at code-generation
1103       // time.
1104       assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1105
1106       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
1107       // must find the size of the pointed-to type (Not coincidentally, the next
1108       // type is the type of the elements in the array).
1109       Ty = SqTy->getElementType();
1110       unsigned elementSize = TD.getTypeSize(Ty);
1111
1112       // If idxReg is a constant, we don't need to perform the multiply!
1113       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1114         if (CSI->isNullValue()) {
1115           BMI(MBB, IP, X86::MOVrr32, 1, nextBasePtrReg).addReg(basePtrReg);
1116         } else {
1117           unsigned Offset = elementSize*CSI->getValue();
1118
1119           BMI(MBB, IP, X86::ADDri32, 2,
1120               nextBasePtrReg).addReg(basePtrReg).addZImm(Offset);
1121         }
1122       } else if (elementSize == 1) {
1123         // If the element size is 1, we don't have to multiply, just add
1124         unsigned idxReg = getReg(idx, MBB, IP);
1125         BMI(MBB, IP, X86::ADDrr32, 2,
1126             nextBasePtrReg).addReg(basePtrReg).addReg(idxReg);
1127       } else {
1128         unsigned idxReg = getReg(idx, MBB, IP);
1129         unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1130         if (unsigned Shift = ExactLog2(elementSize)) {
1131           // If the element size is exactly a power of 2, use a shift to get it.
1132
1133           BMI(MBB, IP, X86::SHLir32, 2,
1134               OffsetReg).addReg(idxReg).addZImm(Shift-1);
1135         } else {
1136           // Most general case, emit a multiply...
1137           unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1138           BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1139         
1140           // Emit a MUL to multiply the register holding the index by
1141           // elementSize, putting the result in OffsetReg.
1142           doMultiply(MBB, IP, OffsetReg, Type::LongTy, idxReg, elementSizeReg);
1143         }
1144         // Emit an ADD to add OffsetReg to the basePtr.
1145         BMI(MBB, IP, X86::ADDrr32, 2,
1146             nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
1147       }
1148     }
1149     // Now that we are here, further indices refer to subtypes of this
1150     // one, so we don't need to worry about basePtrReg itself, anymore.
1151     basePtrReg = nextBasePtrReg;
1152   }
1153   // After we have processed all the indices, the result is left in
1154   // basePtrReg.  Move it to the register where we were expected to
1155   // put the answer.  A 32-bit move should do it, because we are in
1156   // ILP32 land.
1157   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
1158 }
1159
1160
1161 /// visitMallocInst - I know that personally, whenever I want to remember
1162 /// something, I have to clear off some space in my brain.
1163 void
1164 ISel::visitMallocInst (MallocInst &I)
1165 {
1166   // We assume that by this point, malloc instructions have been
1167   // lowered to calls, and dlsym will magically find malloc for us.
1168   // So we do not want to see malloc instructions here.
1169   visitInstruction (I);
1170 }
1171
1172
1173 /// visitFreeInst - same story as MallocInst
1174 void
1175 ISel::visitFreeInst (FreeInst &I)
1176 {
1177   // We assume that by this point, free instructions have been
1178   // lowered to calls, and dlsym will magically find free for us.
1179   // So we do not want to see free instructions here.
1180   visitInstruction (I);
1181 }
1182
1183
1184 /// visitAllocaInst - I want some stack space. Come on, man, I said I
1185 /// want some freakin' stack space.
1186 void
1187 ISel::visitAllocaInst (AllocaInst &I)
1188 {
1189   // Find the data size of the alloca inst's getAllocatedType.
1190   const Type *allocatedType = I.getAllocatedType ();
1191   const TargetData &TD = TM.DataLayout;
1192   unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
1193   // Keep stack 32-bit aligned.
1194   unsigned int allocatedTypeWords = allocatedTypeSize / 4;
1195   if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
1196   // Subtract size from stack pointer, thereby allocating some space.
1197   BuildMI(BB, X86::SUBri32, 2,
1198           X86::ESP).addReg(X86::ESP).addZImm(allocatedTypeWords * 4);
1199   // Put a pointer to the space into the result register, by copying
1200   // the stack pointer.
1201   BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
1202 }
1203     
1204
1205 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1206 /// into a machine code representation is a very simple peep-hole fashion.  The
1207 /// generated code sucks but the implementation is nice and simple.
1208 ///
1209 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1210   return new ISel(TM);
1211 }