blob: 40d757b645af08b77d53a2cf64f455e05f39e66c [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- 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"
Chris Lattner055c9652002-10-29 21:05:24 +00008#include "X86InstrInfo.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +00009#include "X86InstrBuilder.h"
Chris Lattner72614082002-10-25 22:55:53 +000010#include "llvm/Function.h"
11#include "llvm/iTerminators.h"
Brian Gaeke1749d632002-11-07 17:59:21 +000012#include "llvm/iOperators.h"
Brian Gaekea1719c92002-10-31 23:03:59 +000013#include "llvm/iOther.h"
Chris Lattner51b49a92002-11-02 19:45:49 +000014#include "llvm/iPHINode.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "llvm/iMemory.h"
Chris Lattner72614082002-10-25 22:55:53 +000016#include "llvm/Type.h"
Brian Gaeke20244b72002-12-12 15:33:40 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerc5291f52002-10-27 21:16:59 +000018#include "llvm/Constants.h"
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000019#include "llvm/Pass.h"
Chris Lattner341a9372002-10-29 17:43:55 +000020#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000021#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/Target/TargetMachine.h"
Chris Lattner72614082002-10-25 22:55:53 +000023#include "llvm/Support/InstVisitor.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000024#include "llvm/Target/MRegisterInfo.h"
25#include <map>
Chris Lattner72614082002-10-25 22:55:53 +000026
Chris Lattner06925362002-11-17 21:56:38 +000027using namespace MOTy; // Get Use, Def, UseAndDef
28
Chris Lattner72614082002-10-25 22:55:53 +000029namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000030 struct ISel : public FunctionPass, InstVisitor<ISel> {
31 TargetMachine &TM;
Chris Lattner341a9372002-10-29 17:43:55 +000032 MachineFunction *F; // The function we are compiling into
33 MachineBasicBlock *BB; // The current MBB we are compiling
Chris Lattner72614082002-10-25 22:55:53 +000034
35 unsigned CurReg;
36 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
37
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000038 ISel(TargetMachine &tm)
39 : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
Chris Lattner72614082002-10-25 22:55:53 +000040
41 /// runOnFunction - Top level implementation of instruction selection for
42 /// the entire function.
43 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000044 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000045 F = &MachineFunction::construct(&Fn, TM);
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000046 visit(Fn);
Chris Lattner72614082002-10-25 22:55:53 +000047 RegMap.clear();
Chris Lattner94e8ee22002-11-21 17:26:58 +000048 CurReg = MRegisterInfo::FirstVirtualRegister;
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000049 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000050 return false; // We never modify the LLVM itself.
51 }
52
53 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000054 /// block. This simply creates a new MachineBasicBlock to emit code into
55 /// and adds it to the current MachineFunction. Subsequent visit* for
56 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +000057 ///
58 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner42c77862002-10-30 00:47:40 +000059 BB = new MachineBasicBlock(&LLVM_BB);
Chris Lattner72614082002-10-25 22:55:53 +000060 // FIXME: Use the auto-insert form when it's available
61 F->getBasicBlockList().push_back(BB);
62 }
63
64 // Visitation methods for various instructions. These methods simply emit
65 // fixed X86 code for each instruction.
66 //
Brian Gaekefa8d5712002-11-22 11:07:01 +000067
68 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +000069 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +000070 void visitBranchInst(BranchInst &BI);
Brian Gaekefa8d5712002-11-22 11:07:01 +000071 void visitCallInst(CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +000072
73 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +000074 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +000075 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
76 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Brian Gaeke20244b72002-12-12 15:33:40 +000077 void doMultiply(unsigned destReg, const Type *resultType,
78 unsigned op0Reg, unsigned op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +000079 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +000080
Chris Lattnerf01729e2002-11-02 20:54:46 +000081 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
82 void visitRem(BinaryOperator &B) { visitDivRem(B); }
83 void visitDivRem(BinaryOperator &B);
84
Chris Lattnere2954c82002-11-02 20:04:26 +000085 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +000086 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
87 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
88 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +000089
90 // Binary comparison operators
Chris Lattner05093a52002-11-21 15:52:38 +000091 void visitSetCCInst(SetCondInst &I, unsigned OpNum);
92 void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
93 void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
94 void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
95 void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
96 void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
97 void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
Chris Lattner6fc3c522002-11-17 21:11:55 +000098
99 // Memory Instructions
100 void visitLoadInst(LoadInst &I);
101 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000102 void visitGetElementPtrInst(GetElementPtrInst &I);
103 void visitMallocInst(MallocInst &I);
Brian Gaekee48ec012002-12-13 06:46:31 +0000104 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000105 void visitAllocaInst(AllocaInst &I);
106
Chris Lattnere2954c82002-11-02 20:04:26 +0000107 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000108 void visitShiftInst(ShiftInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000109 void visitPHINode(PHINode &I);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000110 void visitCastInst(CastInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000111
112 void visitInstruction(Instruction &I) {
113 std::cerr << "Cannot instruction select: " << I;
114 abort();
115 }
116
Brian Gaeke95780cc2002-12-13 07:56:18 +0000117 /// promote32 - Make a value 32-bits wide, and put it somewhere.
118 void promote32 (const unsigned targetReg, Value *v);
119
120 // emitGEPOperation - Common code shared between visitGetElementPtrInst and
Chris Lattnerc0812d82002-12-13 06:56:29 +0000121 // constant expression GEP support.
122 //
123 void emitGEPOperation(Value *Src, User::op_iterator IdxBegin,
124 User::op_iterator IdxEnd, unsigned TargetReg);
125
Chris Lattnerc5291f52002-10-27 21:16:59 +0000126 /// copyConstantToRegister - Output the instructions required to put the
127 /// specified constant into the specified register.
128 ///
129 void copyConstantToRegister(Constant *C, unsigned Reg);
130
Brian Gaeke20244b72002-12-12 15:33:40 +0000131 /// makeAnotherReg - This method returns the next register number
132 /// we haven't yet used.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000133 unsigned makeAnotherReg(const Type *Ty) {
134 // Add the mapping of regnumber => reg class to MachineFunction
135 F->addRegMap(CurReg, TM.getRegisterInfo()->getRegClassForType(Ty));
136 return CurReg++;
Brian Gaeke20244b72002-12-12 15:33:40 +0000137 }
138
Chris Lattner72614082002-10-25 22:55:53 +0000139 /// getReg - This method turns an LLVM value into a register number. This
140 /// is guaranteed to produce the same register number for a particular value
141 /// every time it is queried.
142 ///
143 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
144 unsigned getReg(Value *V) {
145 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000146 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000147 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000148 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000149 }
Chris Lattner72614082002-10-25 22:55:53 +0000150
Chris Lattner6f8fd252002-10-27 21:23:43 +0000151 // If this operand is a constant, emit the code to copy the constant into
152 // the register here...
153 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000154 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerc5291f52002-10-27 21:16:59 +0000155 copyConstantToRegister(C, Reg);
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000156 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
157 // Move the address of the global into the register
158 BuildMI(BB, X86::MOVir32, 1, Reg).addReg(GV);
Chris Lattnerd6c4cfa2002-12-04 17:15:34 +0000159 } else if (Argument *A = dyn_cast<Argument>(V)) {
Brian Gaeke95780cc2002-12-13 07:56:18 +0000160 // Find the position of the argument in the argument list.
161 const Function *f = F->getFunction ();
162 int counter = 0, argPosition = -1;
163 for (Function::const_aiterator ai = f->abegin (), ae = f->aend ();
164 ai != ae; ++ai) {
165 ++counter;
166 if (&(*ai) == A) {
167 argPosition = counter;
168 }
169 }
170 assert (argPosition != -1
171 && "Argument not found in current function's argument list");
172 // Load it out of the stack frame at EBP + 4*argPosition.
173 // (First, load Reg with argPosition, then load Reg with DWORD
174 // PTR [EBP + 4*Reg].)
175 BuildMI (BB, X86::MOVir32, 1, Reg).addZImm (argPosition);
176 BuildMI (BB, X86::MOVmr32, 4,
177 Reg).addReg (X86::EBP).addZImm (4).addReg (Reg).addSImm (0);
178 // std::cerr << "ERROR: Arguments not implemented in SimpleInstSel\n";
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000179 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000180
Chris Lattner72614082002-10-25 22:55:53 +0000181 return Reg;
182 }
Chris Lattner72614082002-10-25 22:55:53 +0000183 };
184}
185
Chris Lattner43189d12002-11-17 20:07:45 +0000186/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
187/// Representation.
188///
189enum TypeClass {
190 cByte, cShort, cInt, cLong, cFloat, cDouble
191};
192
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000193/// getClass - Turn a primitive type into a "class" number which is based on the
194/// size of the type, and whether or not it is floating point.
195///
Chris Lattner43189d12002-11-17 20:07:45 +0000196static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000197 switch (Ty->getPrimitiveID()) {
198 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000199 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000200 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000201 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000202 case Type::IntTyID:
203 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000204 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000205
206 case Type::LongTyID:
Chris Lattnerc0812d82002-12-13 06:56:29 +0000207 case Type::ULongTyID: //return cLong; // Longs are class #3
208 return cInt; // FIXME: LONGS ARE TREATED AS INTS!
209
Chris Lattner43189d12002-11-17 20:07:45 +0000210 case Type::FloatTyID: return cFloat; // Float is class #4
211 case Type::DoubleTyID: return cDouble; // Doubles are class #5
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000212 default:
213 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000214 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000215 }
216}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000217
Chris Lattner06925362002-11-17 21:56:38 +0000218
Chris Lattnerc5291f52002-10-27 21:16:59 +0000219/// copyConstantToRegister - Output the instructions required to put the
220/// specified constant into the specified register.
221///
222void ISel::copyConstantToRegister(Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000223 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
224 if (CE->getOpcode() == Instruction::GetElementPtr) {
225 emitGEPOperation(CE->getOperand(0), CE->op_begin()+1, CE->op_end(), R);
226 return;
227 }
228
Brian Gaeke20244b72002-12-12 15:33:40 +0000229 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerc0812d82002-12-13 06:56:29 +0000230 assert (0 && "Constant expressions not yet handled!\n");
Brian Gaeke20244b72002-12-12 15:33:40 +0000231 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000232
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000233 if (C->getType()->isIntegral()) {
234 unsigned Class = getClass(C->getType());
235 assert(Class != 3 && "Type not handled yet!");
236
237 static const unsigned IntegralOpcodeTab[] = {
238 X86::MOVir8, X86::MOVir16, X86::MOVir32
239 };
240
241 if (C->getType()->isSigned()) {
242 ConstantSInt *CSI = cast<ConstantSInt>(C);
243 BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
244 } else {
245 ConstantUInt *CUI = cast<ConstantUInt>(C);
246 BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
247 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000248 } else if (isa <ConstantPointerNull> (C)) {
249 // Copy zero (null pointer) to the register.
250 BuildMI (BB, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000251 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
252 unsigned SrcReg = getReg(CPR->getValue());
253 BuildMI (BB, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000254 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000255 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000256 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000257 }
258}
259
Chris Lattner06925362002-11-17 21:56:38 +0000260
Brian Gaeke1749d632002-11-07 17:59:21 +0000261/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
262/// register, then move it to wherever the result should be.
263/// We handle FP setcc instructions by pushing them, doing a
264/// compare-and-pop-twice, and then copying the concodes to the main
265/// processor's concodes (I didn't make this up, it's in the Intel manual)
266///
Chris Lattner05093a52002-11-21 15:52:38 +0000267void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000268 // The arguments are already supposed to be of the same type.
Chris Lattner05093a52002-11-21 15:52:38 +0000269 const Type *CompTy = I.getOperand(0)->getType();
270 unsigned reg1 = getReg(I.getOperand(0));
271 unsigned reg2 = getReg(I.getOperand(1));
272
273 unsigned Class = getClass(CompTy);
274 switch (Class) {
275 // Emit: cmp <var1>, <var2> (do the comparison). We can
276 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
277 // 32-bit.
278 case cByte:
279 BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
280 break;
281 case cShort:
282 BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
283 break;
284 case cInt:
285 BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
286 break;
287
288 // Push the variables on the stack with fldl opcodes.
289 // FIXME: assuming var1, var2 are in memory, if not, spill to
290 // stack first
291 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000292 BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
293 BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000294 break;
295 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000296 BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
297 BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000298 break;
299 case cLong:
300 default:
301 visitInstruction(I);
302 }
303
304 if (CompTy->isFloatingPoint()) {
305 // (Non-trapping) compare and pop twice.
306 BuildMI (BB, X86::FUCOMPP, 0);
307 // Move fp status word (concodes) to ax.
308 BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
309 // Load real concodes from ax.
310 BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
311 }
312
Brian Gaeke1749d632002-11-07 17:59:21 +0000313 // Emit setOp instruction (extract concode; clobbers ax),
314 // using the following mapping:
315 // LLVM -> X86 signed X86 unsigned
316 // ----- ----- -----
317 // seteq -> sete sete
318 // setne -> setne setne
319 // setlt -> setl setb
320 // setgt -> setg seta
321 // setle -> setle setbe
322 // setge -> setge setae
Chris Lattner05093a52002-11-21 15:52:38 +0000323
324 static const unsigned OpcodeTab[2][6] = {
Chris Lattner4b4e9dd2002-11-21 16:19:42 +0000325 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
326 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
Chris Lattner05093a52002-11-21 15:52:38 +0000327 };
328
329 BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
330
Brian Gaeke1749d632002-11-07 17:59:21 +0000331 // Put it in the result using a move.
Chris Lattner05093a52002-11-21 15:52:38 +0000332 BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
Brian Gaeke1749d632002-11-07 17:59:21 +0000333}
Chris Lattner51b49a92002-11-02 19:45:49 +0000334
Brian Gaekec2505982002-11-30 11:57:28 +0000335/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
336/// operand, in the specified target register.
337void
Chris Lattnerc0812d82002-12-13 06:56:29 +0000338ISel::promote32 (unsigned targetReg, Value *v)
Brian Gaekec2505982002-11-30 11:57:28 +0000339{
340 unsigned vReg = getReg (v);
341 unsigned Class = getClass (v->getType ());
342 bool isUnsigned = v->getType ()->isUnsigned ();
343 assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
344 && "Unpromotable operand class in promote32");
345 switch (Class)
346 {
347 case cByte:
348 // Extend value into target register (8->32)
349 if (isUnsigned)
350 BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
351 else
352 BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
353 break;
354 case cShort:
355 // Extend value into target register (16->32)
356 if (isUnsigned)
357 BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
358 else
359 BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
360 break;
361 case cInt:
362 // Move value into target register (32->32)
363 BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
364 break;
365 }
366}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000367
Chris Lattner72614082002-10-25 22:55:53 +0000368/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
369/// we have the following possibilities:
370///
371/// ret void: No return value, simply emit a 'ret' instruction
372/// ret sbyte, ubyte : Extend value into EAX and return
373/// ret short, ushort: Extend value into EAX and return
374/// ret int, uint : Move value into EAX and return
375/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000376/// ret long, ulong : Move value into EAX/EDX and return
377/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000378///
Brian Gaekec2505982002-11-30 11:57:28 +0000379void
380ISel::visitReturnInst (ReturnInst &I)
381{
382 if (I.getNumOperands () == 0)
383 {
384 // Emit a 'ret' instruction
385 BuildMI (BB, X86::RET, 0);
386 return;
387 }
388 Value *rv = I.getOperand (0);
389 unsigned Class = getClass (rv->getType ());
390 switch (Class)
391 {
392 // integral return values: extend or move into EAX and return.
393 case cByte:
394 case cShort:
395 case cInt:
396 promote32 (X86::EAX, rv);
397 break;
398 // ret float/double: top of FP stack
399 // FLD <val>
400 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000401 BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000402 break;
403 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000404 BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000405 break;
406 case cLong:
407 // ret long: use EAX(least significant 32 bits)/EDX (most
408 // significant 32)...uh, I think so Brain, but how do i call
409 // up the two parts of the value from inside this mouse
410 // cage? *zort*
411 default:
412 visitInstruction (I);
413 }
Chris Lattner43189d12002-11-17 20:07:45 +0000414 // Emit a 'ret' instruction
Brian Gaekec2505982002-11-30 11:57:28 +0000415 BuildMI (BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000416}
417
Chris Lattner51b49a92002-11-02 19:45:49 +0000418/// visitBranchInst - Handle conditional and unconditional branches here. Note
419/// that since code layout is frozen at this point, that if we are trying to
420/// jump to a block that is the immediate successor of the current block, we can
421/// just make a fall-through. (but we don't currently).
422///
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000423void
424ISel::visitBranchInst (BranchInst & BI)
425{
426 if (BI.isConditional ())
427 {
428 BasicBlock *ifTrue = BI.getSuccessor (0);
429 BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious
Chris Lattner2df035b2002-11-02 19:27:56 +0000430
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000431 // simplest thing I can think of: compare condition with zero,
432 // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
433 // ifTrue
434 unsigned int condReg = getReg (BI.getCondition ());
Chris Lattner97ad9e12002-11-21 01:59:50 +0000435 BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000436 BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
437 BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
438 }
439 else // unconditional branch
440 {
441 BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
442 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000443}
444
Brian Gaeke18a20212002-11-29 12:01:58 +0000445/// visitCallInst - Push args on stack and do a procedure call instruction.
446void
447ISel::visitCallInst (CallInst & CI)
448{
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000449 // keep a counter of how many bytes we pushed on the stack
450 unsigned bytesPushed = 0;
451
Brian Gaeke18a20212002-11-29 12:01:58 +0000452 // Push the arguments on the stack in reverse order, as specified by
453 // the ABI.
Chris Lattnerd852c152002-12-03 20:30:12 +0000454 for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
Brian Gaeke18a20212002-11-29 12:01:58 +0000455 {
456 Value *v = CI.getOperand (i);
Brian Gaeke18a20212002-11-29 12:01:58 +0000457 switch (getClass (v->getType ()))
458 {
Brian Gaekec2505982002-11-30 11:57:28 +0000459 case cByte:
460 case cShort:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000461 // Promote V to 32 bits wide, and move the result into EAX,
462 // then push EAX.
Brian Gaekec2505982002-11-30 11:57:28 +0000463 promote32 (X86::EAX, v);
464 BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000465 bytesPushed += 4;
Brian Gaekec2505982002-11-30 11:57:28 +0000466 break;
Brian Gaeke18a20212002-11-29 12:01:58 +0000467 case cInt:
Chris Lattner33ced562002-12-04 06:56:56 +0000468 case cFloat: {
469 unsigned Reg = getReg(v);
470 BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000471 bytesPushed += 4;
Brian Gaeke18a20212002-11-29 12:01:58 +0000472 break;
Chris Lattner33ced562002-12-04 06:56:56 +0000473 }
Brian Gaeke18a20212002-11-29 12:01:58 +0000474 default:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000475 // FIXME: long/ulong/double args not handled.
Brian Gaeke18a20212002-11-29 12:01:58 +0000476 visitInstruction (CI);
477 break;
478 }
479 }
480 // Emit a CALL instruction with PC-relative displacement.
481 BuildMI (BB, X86::CALLpcrel32, 1).addPCDisp (CI.getCalledValue ());
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000482
483 // Adjust the stack by `bytesPushed' amount if non-zero
484 if (bytesPushed > 0)
485 BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
Chris Lattnera3243642002-12-04 23:45:28 +0000486
487 // If there is a return value, scavenge the result from the location the call
488 // leaves it in...
489 //
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000490 if (CI.getType() != Type::VoidTy) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000491 unsigned resultTypeClass = getClass (CI.getType ());
492 switch (resultTypeClass) {
493 case cByte:
494 case cShort:
495 case cInt: {
496 // Integral results are in %eax, or the appropriate portion
497 // thereof.
498 static const unsigned regRegMove[] = {
499 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
500 };
501 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
502 BuildMI (BB, regRegMove[resultTypeClass], 1,
503 getReg (CI)).addReg (AReg[resultTypeClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000504 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000505 }
506 case cFloat:
507 // Floating-point return values live in %st(0) (i.e., the top of
508 // the FP stack.) The general way to approach this is to do a
509 // FSTP to save the top of the FP stack on the real stack, then
510 // do a MOV to load the top of the real stack into the target
511 // register.
512 visitInstruction (CI); // FIXME: add the right args for the calls below
513 // BuildMI (BB, X86::FSTPm32, 0);
514 // BuildMI (BB, X86::MOVmr32, 0);
515 break;
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000516 default:
517 std::cerr << "Cannot get return value for call of type '"
518 << *CI.getType() << "'\n";
519 visitInstruction(CI);
520 }
Chris Lattnera3243642002-12-04 23:45:28 +0000521 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000522}
Chris Lattner2df035b2002-11-02 19:27:56 +0000523
Chris Lattner68aad932002-11-02 20:13:22 +0000524/// visitSimpleBinary - Implement simple binary operators for integral types...
525/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
526/// 4 for Xor.
527///
528void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
529 if (B.getType() == Type::BoolTy) // FIXME: Handle bools for logicals
Chris Lattnere2954c82002-11-02 20:04:26 +0000530 visitInstruction(B);
531
532 unsigned Class = getClass(B.getType());
533 if (Class > 2) // FIXME: Handle longs
534 visitInstruction(B);
535
536 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000537 // Arithmetic operators
538 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 }, // ADD
539 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 }, // SUB
540
541 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000542 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
543 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
544 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
545 };
546
547 unsigned Opcode = OpcodeTab[OperatorClass][Class];
548 unsigned Op0r = getReg(B.getOperand(0));
549 unsigned Op1r = getReg(B.getOperand(1));
550 BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
551}
552
Brian Gaeke20244b72002-12-12 15:33:40 +0000553/// doMultiply - Emit appropriate instructions to multiply together
554/// the registers op0Reg and op1Reg, and put the result in destReg.
555/// The type of the result should be given as resultType.
556void
557ISel::doMultiply(unsigned destReg, const Type *resultType,
558 unsigned op0Reg, unsigned op1Reg)
559{
560 unsigned Class = getClass (resultType);
561
562 // FIXME:
563 assert (Class <= 2 && "Someday, we will learn how to multiply"
564 "longs and floating-point numbers. This is not that day.");
565
566 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
567 static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
568 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
569 unsigned Reg = Regs[Class];
570
571 // Emit a MOV to put the first operand into the appropriately-sized
572 // subreg of EAX.
573 BuildMI (BB, MovOpcode[Class], 1, Reg).addReg (op0Reg);
574
575 // Emit the appropriate multiply instruction.
576 BuildMI (BB, MulOpcode[Class], 1).addReg (op1Reg);
577
578 // Emit another MOV to put the result into the destination register.
579 BuildMI (BB, MovOpcode[Class], 1, destReg).addReg (Reg);
580}
581
Chris Lattnerca9671d2002-11-02 20:28:58 +0000582/// visitMul - Multiplies are not simple binary operators because they must deal
583/// with the EAX register explicitly.
584///
585void ISel::visitMul(BinaryOperator &I) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000586 doMultiply (getReg (I), I.getType (),
587 getReg (I.getOperand (0)), getReg (I.getOperand (1)));
Chris Lattnerf01729e2002-11-02 20:54:46 +0000588}
Chris Lattnerca9671d2002-11-02 20:28:58 +0000589
Chris Lattner06925362002-11-17 21:56:38 +0000590
Chris Lattnerf01729e2002-11-02 20:54:46 +0000591/// visitDivRem - Handle division and remainder instructions... these
592/// instruction both require the same instructions to be generated, they just
593/// select the result from a different register. Note that both of these
594/// instructions work differently for signed and unsigned operands.
595///
596void ISel::visitDivRem(BinaryOperator &I) {
597 unsigned Class = getClass(I.getType());
598 if (Class > 2) // FIXME: Handle longs
599 visitInstruction(I);
600
601 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
602 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +0000603 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +0000604 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
605 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
606
607 static const unsigned DivOpcode[][4] = {
608 { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 }, // Unsigned division
609 { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 }, // Signed division
610 };
611
612 bool isSigned = I.getType()->isSigned();
613 unsigned Reg = Regs[Class];
614 unsigned ExtReg = ExtRegs[Class];
Chris Lattner6fc3c522002-11-17 21:11:55 +0000615 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +0000616 unsigned Op1Reg = getReg(I.getOperand(1));
617
618 // Put the first operand into one of the A registers...
619 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
620
621 if (isSigned) {
622 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +0000623 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +0000624 } else {
625 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
626 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
627 }
628
Chris Lattner06925362002-11-17 21:56:38 +0000629 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +0000630 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +0000631
Chris Lattnerf01729e2002-11-02 20:54:46 +0000632 // Figure out which register we want to pick the result out of...
633 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
634
Chris Lattnerf01729e2002-11-02 20:54:46 +0000635 // Put the result into the destination register...
636 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000637}
Chris Lattnere2954c82002-11-02 20:04:26 +0000638
Chris Lattner06925362002-11-17 21:56:38 +0000639
Brian Gaekea1719c92002-10-31 23:03:59 +0000640/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
641/// for constant immediate shift values, and for constant immediate
642/// shift values equal to 1. Even the general case is sort of special,
643/// because the shift amount has to be in CL, not just any old register.
644///
Chris Lattnerf01729e2002-11-02 20:54:46 +0000645void ISel::visitShiftInst (ShiftInst &I) {
646 unsigned Op0r = getReg (I.getOperand(0));
647 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +0000648 bool isLeftShift = I.getOpcode() == Instruction::Shl;
649 bool isOperandSigned = I.getType()->isUnsigned();
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000650 unsigned OperandClass = getClass(I.getType());
651
652 if (OperandClass > 2)
653 visitInstruction(I); // Can't handle longs yet!
Chris Lattner796df732002-11-02 00:44:25 +0000654
Brian Gaekea1719c92002-10-31 23:03:59 +0000655 if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
656 {
Chris Lattner796df732002-11-02 00:44:25 +0000657 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
658 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
659 unsigned char shAmt = CUI->getValue();
660
Chris Lattnere9913f22002-11-02 01:41:55 +0000661 static const unsigned ConstantOperand[][4] = {
662 { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 }, // SHR
663 { X86::SARir8, X86::SARir16, X86::SARir32, 0 }, // SAR
664 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SHL
665 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000666 };
667
Chris Lattnere9913f22002-11-02 01:41:55 +0000668 const unsigned *OpTab = // Figure out the operand table to use
669 ConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000670
Brian Gaekea1719c92002-10-31 23:03:59 +0000671 // Emit: <insn> reg, shamt (shift-by-immediate opcode "ir" form.)
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000672 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
Brian Gaekea1719c92002-10-31 23:03:59 +0000673 }
674 else
675 {
676 // The shift amount is non-constant.
677 //
678 // In fact, you can only shift with a variable shift amount if
679 // that amount is already in the CL register, so we have to put it
680 // there first.
681 //
Chris Lattnere9913f22002-11-02 01:41:55 +0000682
Brian Gaekea1719c92002-10-31 23:03:59 +0000683 // Emit: move cl, shiftAmount (put the shift amount in CL.)
Chris Lattnerca9671d2002-11-02 20:28:58 +0000684 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000685
686 // This is a shift right (SHR).
Chris Lattnere9913f22002-11-02 01:41:55 +0000687 static const unsigned NonConstantOperand[][4] = {
688 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 }, // SHR
689 { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 }, // SAR
690 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SHL
691 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000692 };
693
Chris Lattnere9913f22002-11-02 01:41:55 +0000694 const unsigned *OpTab = // Figure out the operand table to use
695 NonConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000696
Chris Lattner3a9a6932002-11-21 22:49:20 +0000697 BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
Brian Gaekea1719c92002-10-31 23:03:59 +0000698 }
699}
700
Chris Lattner06925362002-11-17 21:56:38 +0000701
Chris Lattner6fc3c522002-11-17 21:11:55 +0000702/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
703/// instruction.
704///
705void ISel::visitLoadInst(LoadInst &I) {
706 unsigned Class = getClass(I.getType());
707 if (Class > 2) // FIXME: Handle longs and others...
708 visitInstruction(I);
709
710 static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
711
712 unsigned AddressReg = getReg(I.getOperand(0));
713 addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
714}
715
Chris Lattner06925362002-11-17 21:56:38 +0000716
Chris Lattner6fc3c522002-11-17 21:11:55 +0000717/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
718/// instruction.
719///
720void ISel::visitStoreInst(StoreInst &I) {
721 unsigned Class = getClass(I.getOperand(0)->getType());
722 if (Class > 2) // FIXME: Handle longs and others...
723 visitInstruction(I);
724
725 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
726
727 unsigned ValReg = getReg(I.getOperand(0));
728 unsigned AddressReg = getReg(I.getOperand(1));
729 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
730}
731
732
Chris Lattnere2954c82002-11-02 20:04:26 +0000733/// visitPHINode - Turn an LLVM PHI node into an X86 PHI node...
734///
735void ISel::visitPHINode(PHINode &PN) {
736 MachineInstr *MI = BuildMI(BB, X86::PHI, PN.getNumOperands(), getReg(PN));
Chris Lattner72614082002-10-25 22:55:53 +0000737
Chris Lattnere2954c82002-11-02 20:04:26 +0000738 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
739 // FIXME: This will put constants after the PHI nodes in the block, which
740 // is invalid. They should be put inline into the PHI node eventually.
741 //
742 MI->addRegOperand(getReg(PN.getIncomingValue(i)));
743 MI->addPCDispOperand(PN.getIncomingBlock(i));
744 }
Chris Lattner72614082002-10-25 22:55:53 +0000745}
746
Brian Gaekec11232a2002-11-26 10:43:30 +0000747/// visitCastInst - Here we have various kinds of copying with or without
748/// sign extension going on.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000749void
750ISel::visitCastInst (CastInst &CI)
751{
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000752 const Type *targetType = CI.getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000753 Value *operand = CI.getOperand (0);
754 unsigned int operandReg = getReg (operand);
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000755 const Type *sourceType = operand->getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000756 unsigned int destReg = getReg (CI);
Brian Gaeked474e9c2002-12-06 10:49:33 +0000757 //
758 // Currently we handle:
759 //
760 // 1) cast * to bool
761 //
762 // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
763 // cast {short, ushort} to {ushort, short}
764 // cast {int, uint, ptr} to {int, uint, ptr}
765 //
766 // 3) cast {sbyte, ubyte} to {ushort, short}
767 // cast {sbyte, ubyte} to {int, uint, ptr}
768 // cast {short, ushort} to {int, uint, ptr}
769 //
770 // 4) cast {int, uint, ptr} to {short, ushort}
771 // cast {int, uint, ptr} to {sbyte, ubyte}
772 // cast {short, ushort} to {sbyte, ubyte}
773 //
774 // 1) Implement casts to bool by using compare on the operand followed
775 // by set if not zero on the result.
776 if (targetType == Type::BoolTy)
777 {
778 BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
779 BuildMI (BB, X86::SETNEr, 1, destReg);
780 return;
781 }
782 // 2) Implement casts between values of the same type class (as determined
783 // by getClass) by using a register-to-register move.
784 unsigned int srcClass = getClass (sourceType);
785 unsigned int targClass = getClass (targetType);
786 static const unsigned regRegMove[] = {
787 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
788 };
789 if ((srcClass < 3) && (targClass < 3) && (srcClass == targClass))
790 {
791 BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
792 return;
793 }
794 // 3) Handle cast of SMALLER int to LARGER int using a move with sign
795 // extension or zero extension, depending on whether the source type
796 // was signed.
797 if ((srcClass < 3) && (targClass < 3) && (srcClass < targClass))
798 {
799 static const unsigned ops[] = {
800 X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
801 X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
802 };
803 unsigned srcSigned = sourceType->isSigned ();
804 BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
805 destReg).addReg (operandReg);
806 return;
807 }
808 // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
809 // followed by a move out of AX or AL.
810 if ((srcClass < 3) && (targClass < 3) && (srcClass > targClass))
811 {
812 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
813 BuildMI (BB, regRegMove[srcClass], 1,
814 AReg[srcClass]).addReg (operandReg);
815 BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
816 return;
817 }
818 // Anything we haven't handled already, we can't (yet) handle at all.
Brian Gaeke20244b72002-12-12 15:33:40 +0000819 //
820 // FP to integral casts can be handled with FISTP to store onto the
821 // stack while converting to integer, followed by a MOV to load from
822 // the stack into the result register. Integral to FP casts can be
823 // handled with MOV to store onto the stack, followed by a FILD to
824 // load from the stack while converting to FP. For the moment, I
825 // can't quite get straight in my head how to borrow myself some
826 // stack space and write on it. Otherwise, this would be trivial.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000827 visitInstruction (CI);
828}
Brian Gaekea1719c92002-10-31 23:03:59 +0000829
Brian Gaeke20244b72002-12-12 15:33:40 +0000830/// visitGetElementPtrInst - I don't know, most programs don't have
831/// getelementptr instructions, right? That means we can put off
832/// implementing this, right? Right. This method emits machine
833/// instructions to perform type-safe pointer arithmetic. I am
834/// guessing this could be cleaned up somewhat to use fewer temporary
835/// registers.
836void
837ISel::visitGetElementPtrInst (GetElementPtrInst &I)
838{
Chris Lattnerc0812d82002-12-13 06:56:29 +0000839 emitGEPOperation(I.getOperand(0), I.op_begin()+1, I.op_end(), getReg(I));
840}
841
842void ISel::emitGEPOperation(Value *Src, User::op_iterator IdxBegin,
843 User::op_iterator IdxEnd, unsigned TargetReg) {
844 const TargetData &TD = TM.getTargetData();
845 const Type *Ty = Src->getType();
846 unsigned basePtrReg = getReg(Src);
847
Brian Gaeke20244b72002-12-12 15:33:40 +0000848 // GEPs have zero or more indices; we must perform a struct access
849 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000850 for (GetElementPtrInst::op_iterator oi = IdxBegin,
851 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000852 Value *idx = *oi;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000853 unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
Brian Gaeke20244b72002-12-12 15:33:40 +0000854 if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
855 // It's a struct access. idx is the index into the structure,
856 // which names the field. This index must have ubyte type.
857 const ConstantUInt *CUI = cast <ConstantUInt> (idx);
858 assert (CUI->getType () == Type::UByteTy
859 && "Funny-looking structure index in GEP");
860 // Use the TargetData structure to pick out what the layout of
861 // the structure is in memory. Since the structure index must
862 // be constant, we can get its value and use it to find the
863 // right byte offset from the StructLayout class's list of
864 // structure member offsets.
865 unsigned idxValue = CUI->getValue ();
866 unsigned memberOffset =
867 TD.getStructLayout (StTy)->MemberOffsets[idxValue];
868 // Emit an ADD to add memberOffset to the basePtr.
869 BuildMI (BB, X86::ADDri32, 2,
870 nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
871 // The next type is the member of the structure selected by the
872 // index.
873 Ty = StTy->getElementTypes ()[idxValue];
874 } else if (const SequentialType *SqTy = cast <SequentialType> (Ty)) {
875 // It's an array or pointer access: [ArraySize x ElementType].
Brian Gaeke20244b72002-12-12 15:33:40 +0000876 const Type *typeOfSequentialTypeIndex = SqTy->getIndexType ();
877 // idx is the index into the array. Unlike with structure
878 // indices, we may not know its actual value at code-generation
879 // time.
880 assert (idx->getType () == typeOfSequentialTypeIndex
881 && "Funny-looking array index in GEP");
882 // We want to add basePtrReg to (idxReg * sizeof
883 // ElementType). First, we must find the size of the pointed-to
884 // type. (Not coincidentally, the next type is the type of the
885 // elements in the array.)
886 Ty = SqTy->getElementType ();
887 unsigned elementSize = TD.getTypeSize (Ty);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000888 unsigned elementSizeReg = makeAnotherReg(Type::UIntTy);
Brian Gaeke20244b72002-12-12 15:33:40 +0000889 copyConstantToRegister (ConstantInt::get (typeOfSequentialTypeIndex,
890 elementSize),
891 elementSizeReg);
892 unsigned idxReg = getReg (idx);
893 // Emit a MUL to multiply the register holding the index by
894 // elementSize, putting the result in memberOffsetReg.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000895 unsigned memberOffsetReg = makeAnotherReg(Type::UIntTy);
Brian Gaeke20244b72002-12-12 15:33:40 +0000896 doMultiply (memberOffsetReg, typeOfSequentialTypeIndex,
897 elementSizeReg, idxReg);
898 // Emit an ADD to add memberOffsetReg to the basePtr.
899 BuildMI (BB, X86::ADDrr32, 2,
900 nextBasePtrReg).addReg (basePtrReg).addReg (memberOffsetReg);
901 }
902 // Now that we are here, further indices refer to subtypes of this
903 // one, so we don't need to worry about basePtrReg itself, anymore.
904 basePtrReg = nextBasePtrReg;
905 }
906 // After we have processed all the indices, the result is left in
907 // basePtrReg. Move it to the register where we were expected to
908 // put the answer. A 32-bit move should do it, because we are in
909 // ILP32 land.
Chris Lattnerc0812d82002-12-13 06:56:29 +0000910 BuildMI (BB, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000911}
912
913
914/// visitMallocInst - I know that personally, whenever I want to remember
915/// something, I have to clear off some space in my brain.
916void
917ISel::visitMallocInst (MallocInst &I)
918{
Brian Gaekee48ec012002-12-13 06:46:31 +0000919 // We assume that by this point, malloc instructions have been
920 // lowered to calls, and dlsym will magically find malloc for us.
921 // So we do not want to see malloc instructions here.
922 visitInstruction (I);
923}
924
925
926/// visitFreeInst - same story as MallocInst
927void
928ISel::visitFreeInst (FreeInst &I)
929{
930 // We assume that by this point, free instructions have been
931 // lowered to calls, and dlsym will magically find free for us.
932 // So we do not want to see free instructions here.
Brian Gaeke20244b72002-12-12 15:33:40 +0000933 visitInstruction (I);
934}
935
936
937/// visitAllocaInst - I want some stack space. Come on, man, I said I
938/// want some freakin' stack space.
939void
940ISel::visitAllocaInst (AllocaInst &I)
941{
Brian Gaekee48ec012002-12-13 06:46:31 +0000942 // Find the data size of the alloca inst's getAllocatedType.
943 const Type *allocatedType = I.getAllocatedType ();
944 const TargetData &TD = TM.DataLayout;
945 unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
946 // Keep stack 32-bit aligned.
947 unsigned int allocatedTypeWords = allocatedTypeSize / 4;
948 if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
949 // Subtract size from stack pointer, thereby allocating some space.
950 BuildMI (BB, X86::SUBri32, 1, X86::ESP).addZImm (allocatedTypeWords * 4);
951 // Put a pointer to the space into the result register, by copying
952 // the stack pointer.
953 BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
Brian Gaeke20244b72002-12-12 15:33:40 +0000954}
955
956
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000957/// createSimpleX86InstructionSelector - This pass converts an LLVM function
958/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +0000959/// generated code sucks but the implementation is nice and simple.
960///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000961Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
962 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +0000963}