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