blob: 7d231e92966369d56856423990ac1fb63164b4fa [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2//
Chris Lattner3e130a22003-01-13 00:32:26 +00003// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +00004//
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 Lattnereca195e2003-05-08 19:44:13 +000020#include "llvm/Intrinsics.h"
Chris Lattner341a9372002-10-29 17:43:55 +000021#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000022#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner94af4142002-12-25 05:13:53 +000023#include "llvm/CodeGen/SSARegMap.h"
Chris Lattneraa09b752002-12-28 21:08:28 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner3e130a22003-01-13 00:32:26 +000025#include "llvm/CodeGen/MachineConstantPool.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000026#include "llvm/Target/TargetMachine.h"
Chris Lattner72614082002-10-25 22:55:53 +000027#include "llvm/Support/InstVisitor.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000028#include "llvm/Target/MRegisterInfo.h"
29#include <map>
Chris Lattner72614082002-10-25 22:55:53 +000030
Chris Lattner333b2fa2002-12-13 10:09:43 +000031/// BMI - A special BuildMI variant that takes an iterator to insert the
Chris Lattner8bdd1292003-04-25 21:58:54 +000032/// instruction at as well as a basic block. This is the version for when you
33/// have a destination register in mind.
Brian Gaeke71794c02002-12-13 11:22:48 +000034inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattner333b2fa2002-12-13 10:09:43 +000035 MachineBasicBlock::iterator &I,
36 MachineOpCode Opcode,
37 unsigned NumOperands,
38 unsigned DestReg) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000039 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattner333b2fa2002-12-13 10:09:43 +000040 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000041 I = MBB->insert(I, MI)+1;
Chris Lattner333b2fa2002-12-13 10:09:43 +000042 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
43}
44
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000045/// BMI - A special BuildMI variant that takes an iterator to insert the
46/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000047inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000048 MachineBasicBlock::iterator &I,
49 MachineOpCode Opcode,
50 unsigned NumOperands) {
Chris Lattner8bdd1292003-04-25 21:58:54 +000051 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000052 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000053 I = MBB->insert(I, MI)+1;
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000054 return MachineInstrBuilder(MI);
55}
56
Chris Lattner333b2fa2002-12-13 10:09:43 +000057
Chris Lattner72614082002-10-25 22:55:53 +000058namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000059 struct ISel : public FunctionPass, InstVisitor<ISel> {
60 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000061 MachineFunction *F; // The function we are compiling into
62 MachineBasicBlock *BB; // The current MBB we are compiling
63 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner72614082002-10-25 22:55:53 +000064
Chris Lattner72614082002-10-25 22:55:53 +000065 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
66
Chris Lattner333b2fa2002-12-13 10:09:43 +000067 // MBBMap - Mapping between LLVM BB -> Machine BB
68 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
69
Chris Lattner3e130a22003-01-13 00:32:26 +000070 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000071
72 /// runOnFunction - Top level implementation of instruction selection for
73 /// the entire function.
74 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000075 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000076 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000077
Chris Lattner065faeb2002-12-28 20:24:02 +000078 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000079 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
80 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
81
Chris Lattner14aa7fe2002-12-16 22:54:46 +000082 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +000083
Chris Lattnerdbd73722003-05-06 21:32:22 +000084 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +000085 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000086
Chris Lattner333b2fa2002-12-13 10:09:43 +000087 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000088 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000089
90 // Select the PHI nodes
91 SelectPHINodes();
92
Chris Lattner72614082002-10-25 22:55:53 +000093 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000094 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000095 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000096 return false; // We never modify the LLVM itself.
97 }
98
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000099 virtual const char *getPassName() const {
100 return "X86 Simple Instruction Selection";
101 }
102
Chris Lattner72614082002-10-25 22:55:53 +0000103 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000104 /// block. This simply creates a new MachineBasicBlock to emit code into
105 /// and adds it to the current MachineFunction. Subsequent visit* for
106 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000107 ///
108 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000109 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000110 }
111
Chris Lattner065faeb2002-12-28 20:24:02 +0000112 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113 /// from the stack into virtual registers.
114 ///
115 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000116
117 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
118 /// because we have to generate our sources into the source basic blocks,
119 /// not the current one.
120 ///
121 void SelectPHINodes();
122
Chris Lattner72614082002-10-25 22:55:53 +0000123 // Visitation methods for various instructions. These methods simply emit
124 // fixed X86 code for each instruction.
125 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000126
127 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000128 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000129 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000130
131 struct ValueRecord {
132 unsigned Reg;
133 const Type *Ty;
134 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
135 };
136 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
137 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000138 void visitCallInst(CallInst &I);
Chris Lattnereca195e2003-05-08 19:44:13 +0000139 void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000140
141 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000142 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000143 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
144 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattner8a307e82002-12-16 19:32:50 +0000145 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000146 unsigned DestReg, const Type *DestTy,
147 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000148 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000149
Chris Lattnerf01729e2002-11-02 20:54:46 +0000150 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
151 void visitRem(BinaryOperator &B) { visitDivRem(B); }
152 void visitDivRem(BinaryOperator &B);
153
Chris Lattnere2954c82002-11-02 20:04:26 +0000154 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000155 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
156 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
157 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000158
Chris Lattner6d40c192003-01-16 16:43:00 +0000159 // Comparison operators...
160 void visitSetCondInst(SetCondInst &I);
161 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000162
163 // Memory Instructions
Chris Lattner3e130a22003-01-13 00:32:26 +0000164 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
165 MachineBasicBlock::iterator &MBBI,
166 const Type *Ty, unsigned DestReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000167 void visitLoadInst(LoadInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000168 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000169 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000170 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000171 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000172 void visitMallocInst(MallocInst &I);
173 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000174
Chris Lattnere2954c82002-11-02 20:04:26 +0000175 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000176 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000177 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000178 void visitCastInst(CastInst &I);
Chris Lattnereca195e2003-05-08 19:44:13 +0000179 void visitVarArgInst(VarArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000180
181 void visitInstruction(Instruction &I) {
182 std::cerr << "Cannot instruction select: " << I;
183 abort();
184 }
185
Brian Gaeke95780cc2002-12-13 07:56:18 +0000186 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000187 ///
188 void promote32(unsigned targetReg, const ValueRecord &VR);
189
190 /// EmitByteSwap - Byteswap SrcReg into DestReg.
191 ///
192 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
Brian Gaeke95780cc2002-12-13 07:56:18 +0000193
Chris Lattner3e130a22003-01-13 00:32:26 +0000194 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
195 /// constant expression GEP support.
196 ///
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000197 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000198 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000199 User::op_iterator IdxEnd, unsigned TargetReg);
200
Chris Lattner548f61d2003-04-23 17:22:12 +0000201 /// emitCastOperation - Common code shared between visitCastInst and
202 /// constant expression cast support.
203 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
204 Value *Src, const Type *DestTy, unsigned TargetReg);
205
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000206 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
207 /// and constant expression support.
208 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
209 MachineBasicBlock::iterator &IP,
210 Value *Op0, Value *Op1,
211 unsigned OperatorClass, unsigned TargetReg);
212
Chris Lattnerc5291f52002-10-27 21:16:59 +0000213 /// copyConstantToRegister - Output the instructions required to put the
214 /// specified constant into the specified register.
215 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000216 void copyConstantToRegister(MachineBasicBlock *MBB,
217 MachineBasicBlock::iterator &MBBI,
218 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000219
Chris Lattner3e130a22003-01-13 00:32:26 +0000220 /// makeAnotherReg - This method returns the next register number we haven't
221 /// yet used.
222 ///
223 /// Long values are handled somewhat specially. They are always allocated
224 /// as pairs of 32 bit integer values. The register number returned is the
225 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
226 /// of the long value.
227 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000228 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000229 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
230 const TargetRegisterClass *RC =
231 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
232 // Create the lower part
233 F->getSSARegMap()->createVirtualRegister(RC);
234 // Create the upper part.
235 return F->getSSARegMap()->createVirtualRegister(RC)-1;
236 }
237
Chris Lattnerc0812d82002-12-13 06:56:29 +0000238 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner94af4142002-12-25 05:13:53 +0000239 const TargetRegisterClass *RC =
240 TM.getRegisterInfo()->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000241 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000242 }
243
Chris Lattner72614082002-10-25 22:55:53 +0000244 /// getReg - This method turns an LLVM value into a register number. This
245 /// is guaranteed to produce the same register number for a particular value
246 /// every time it is queried.
247 ///
248 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000249 unsigned getReg(Value *V) {
250 // Just append to the end of the current bb.
251 MachineBasicBlock::iterator It = BB->end();
252 return getReg(V, BB, It);
253 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000254 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000255 MachineBasicBlock::iterator &IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000256 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000257 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000258 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000259 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000260 }
Chris Lattner72614082002-10-25 22:55:53 +0000261
Chris Lattner6f8fd252002-10-27 21:23:43 +0000262 // If this operand is a constant, emit the code to copy the constant into
263 // the register here...
264 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000265 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000266 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000267 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000268 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
269 // Move the address of the global into the register
Chris Lattner3e130a22003-01-13 00:32:26 +0000270 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000271 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000272 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000273
Chris Lattner72614082002-10-25 22:55:53 +0000274 return Reg;
275 }
Chris Lattner72614082002-10-25 22:55:53 +0000276 };
277}
278
Chris Lattner43189d12002-11-17 20:07:45 +0000279/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
280/// Representation.
281///
282enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000283 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000284};
285
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000286/// getClass - Turn a primitive type into a "class" number which is based on the
287/// size of the type, and whether or not it is floating point.
288///
Chris Lattner43189d12002-11-17 20:07:45 +0000289static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000290 switch (Ty->getPrimitiveID()) {
291 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000292 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000293 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000294 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000295 case Type::IntTyID:
296 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000297 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000298
Chris Lattner94af4142002-12-25 05:13:53 +0000299 case Type::FloatTyID:
300 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000301
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000302 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000303 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000304 default:
305 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000306 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000307 }
308}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000309
Chris Lattner6b993cc2002-12-15 08:02:15 +0000310// getClassB - Just like getClass, but treat boolean values as bytes.
311static inline TypeClass getClassB(const Type *Ty) {
312 if (Ty == Type::BoolTy) return cByte;
313 return getClass(Ty);
314}
315
Chris Lattner06925362002-11-17 21:56:38 +0000316
Chris Lattnerc5291f52002-10-27 21:16:59 +0000317/// copyConstantToRegister - Output the instructions required to put the
318/// specified constant into the specified register.
319///
Chris Lattner8a307e82002-12-16 19:32:50 +0000320void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator &IP,
322 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000324 unsigned Class = 0;
325 switch (CE->getOpcode()) {
326 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000327 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000328 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000329 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000330 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000331 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000332 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000333
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000334 case Instruction::Xor: ++Class; // FALL THROUGH
335 case Instruction::Or: ++Class; // FALL THROUGH
336 case Instruction::And: ++Class; // FALL THROUGH
337 case Instruction::Sub: ++Class; // FALL THROUGH
338 case Instruction::Add:
339 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
340 Class, R);
341 return;
342
343 default:
344 std::cerr << "Offending expr: " << C << "\n";
345 assert(0 && "Constant expressions not yet handled!\n");
346 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000347 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000348
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000349 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000350 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000351
352 if (Class == cLong) {
353 // Copy the value into the register pair.
354 uint64_t Val;
355 if (C->getType()->isSigned())
356 Val = cast<ConstantSInt>(C)->getValue();
357 else
358 Val = cast<ConstantUInt>(C)->getValue();
359
360 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
361 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
362 return;
363 }
364
Chris Lattner94af4142002-12-25 05:13:53 +0000365 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000366
367 static const unsigned IntegralOpcodeTab[] = {
368 X86::MOVir8, X86::MOVir16, X86::MOVir32
369 };
370
Chris Lattner6b993cc2002-12-15 08:02:15 +0000371 if (C->getType() == Type::BoolTy) {
372 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
373 } else if (C->getType()->isSigned()) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000374 ConstantSInt *CSI = cast<ConstantSInt>(C);
Chris Lattner3e130a22003-01-13 00:32:26 +0000375 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000376 } else {
377 ConstantUInt *CUI = cast<ConstantUInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000378 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000379 }
Chris Lattner94af4142002-12-25 05:13:53 +0000380 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
381 double Value = CFP->getValue();
382 if (Value == +0.0)
383 BMI(MBB, IP, X86::FLD0, 0, R);
384 else if (Value == +1.0)
385 BMI(MBB, IP, X86::FLD1, 0, R);
386 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000387 // Otherwise we need to spill the constant to memory...
388 MachineConstantPool *CP = F->getConstantPool();
389 unsigned CPI = CP->getConstantPoolIndex(CFP);
390 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000391 }
392
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000393 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000394 // Copy zero (null pointer) to the register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000395 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000396 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000397 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
Brian Gaeke71794c02002-12-13 11:22:48 +0000398 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000399 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000400 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000401 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000402 }
403}
404
Chris Lattner065faeb2002-12-28 20:24:02 +0000405/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
406/// the stack into virtual registers.
407///
408void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
409 // Emit instructions to load the arguments... On entry to a function on the
410 // X86, the stack frame looks like this:
411 //
412 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000413 // [ESP + 4] -- first argument (leftmost lexically)
414 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000415 // ...
416 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000417 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000418 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000419
420 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
421 unsigned Reg = getReg(*I);
422
Chris Lattner065faeb2002-12-28 20:24:02 +0000423 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000424 switch (getClassB(I->getType())) {
425 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000426 FI = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000427 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
428 break;
429 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000430 FI = MFI->CreateFixedObject(2, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000431 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
432 break;
433 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000434 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000435 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
436 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000437 case cLong:
438 FI = MFI->CreateFixedObject(8, ArgOffset);
439 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
440 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
441 ArgOffset += 4; // longs require 4 additional bytes
442 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000443 case cFP:
444 unsigned Opcode;
445 if (I->getType() == Type::FloatTy) {
446 Opcode = X86::FLDr32;
Chris Lattneraa09b752002-12-28 21:08:28 +0000447 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000448 } else {
449 Opcode = X86::FLDr64;
Chris Lattneraa09b752002-12-28 21:08:28 +0000450 FI = MFI->CreateFixedObject(8, ArgOffset);
Chris Lattner3e130a22003-01-13 00:32:26 +0000451 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000452 }
453 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
454 break;
455 default:
456 assert(0 && "Unhandled argument type!");
457 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000458 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000459 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000460
461 // If the function takes variable number of arguments, add a frame offset for
462 // the start of the first vararg value... this is used to expand
463 // llvm.va_start.
464 if (Fn.getFunctionType()->isVarArg())
465 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000466}
467
468
Chris Lattner333b2fa2002-12-13 10:09:43 +0000469/// SelectPHINodes - Insert machine code to generate phis. This is tricky
470/// because we have to generate our sources into the source basic blocks, not
471/// the current one.
472///
473void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000474 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000475 const Function &LF = *F->getFunction(); // The LLVM function...
476 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
477 const BasicBlock *BB = I;
478 MachineBasicBlock *MBB = MBBMap[I];
479
480 // Loop over all of the PHI nodes in the LLVM basic block...
481 unsigned NumPHIs = 0;
482 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattner548f61d2003-04-23 17:22:12 +0000483 PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000484
Chris Lattner333b2fa2002-12-13 10:09:43 +0000485 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000486 unsigned PHIReg = getReg(*PN);
487 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
488 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
489
490 MachineInstr *LongPhiMI = 0;
491 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
492 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
493 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
494 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000495
Chris Lattnera6e73f12003-05-12 14:22:21 +0000496 // PHIValues - Map of blocks to incoming virtual registers. We use this
497 // so that we only initialize one incoming value for a particular block,
498 // even if the block has multiple entries in the PHI node.
499 //
500 std::map<MachineBasicBlock*, unsigned> PHIValues;
501
Chris Lattner333b2fa2002-12-13 10:09:43 +0000502 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
503 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000504 unsigned ValReg;
505 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
506 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000507
Chris Lattnera6e73f12003-05-12 14:22:21 +0000508 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
509 // We already inserted an initialization of the register for this
510 // predecessor. Recycle it.
511 ValReg = EntryIt->second;
512
513 } else {
514 // Get the incoming value into a virtual register. If it is not
515 // already available in a virtual register, insert the computation
516 // code into PredMBB
517 //
518 MachineBasicBlock::iterator PI = PredMBB->end();
519 while (PI != PredMBB->begin() &&
520 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
521 --PI;
522 ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
523
524 // Remember that we inserted a value for this PHI for this predecessor
525 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
526 }
527
Chris Lattner3e130a22003-01-13 00:32:26 +0000528 PhiMI->addRegOperand(ValReg);
529 PhiMI->addMachineBasicBlockOperand(PredMBB);
530 if (LongPhiMI) {
531 LongPhiMI->addRegOperand(ValReg+1);
532 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
533 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000534 }
535 }
536 }
537}
538
Chris Lattner6d40c192003-01-16 16:43:00 +0000539// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
540// the conditional branch instruction which is the only user of the cc
541// instruction. This is the case if the conditional branch is the only user of
542// the setcc, and if the setcc is in the same basic block as the conditional
543// branch. We also don't handle long arguments below, so we reject them here as
544// well.
545//
546static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
547 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
548 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
549 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
550 const Type *Ty = SCI->getOperand(0)->getType();
551 if (Ty != Type::LongTy && Ty != Type::ULongTy)
552 return SCI;
553 }
554 return 0;
555}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000556
Chris Lattner6d40c192003-01-16 16:43:00 +0000557// Return a fixed numbering for setcc instructions which does not depend on the
558// order of the opcodes.
559//
560static unsigned getSetCCNumber(unsigned Opcode) {
561 switch(Opcode) {
562 default: assert(0 && "Unknown setcc instruction!");
563 case Instruction::SetEQ: return 0;
564 case Instruction::SetNE: return 1;
565 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000566 case Instruction::SetGE: return 3;
567 case Instruction::SetGT: return 4;
568 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000569 }
570}
Chris Lattner06925362002-11-17 21:56:38 +0000571
Chris Lattner6d40c192003-01-16 16:43:00 +0000572// LLVM -> X86 signed X86 unsigned
573// ----- ---------- ------------
574// seteq -> sete sete
575// setne -> setne setne
576// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000577// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000578// setgt -> setg seta
579// setle -> setle setbe
Chris Lattner6d40c192003-01-16 16:43:00 +0000580static const unsigned SetCCOpcodeTab[2][6] = {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000581 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
582 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
Chris Lattner6d40c192003-01-16 16:43:00 +0000583};
584
585bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
586
Brian Gaeke1749d632002-11-07 17:59:21 +0000587 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000588 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000589 bool isSigned = CompTy->isSigned();
Chris Lattner6d40c192003-01-16 16:43:00 +0000590 unsigned reg1 = getReg(Op0);
591 unsigned reg2 = getReg(Op1);
Chris Lattner05093a52002-11-21 15:52:38 +0000592
Chris Lattner3e130a22003-01-13 00:32:26 +0000593 unsigned Class = getClassB(CompTy);
594 switch (Class) {
595 default: assert(0 && "Unknown type class!");
596 // Emit: cmp <var1>, <var2> (do the comparison). We can
597 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
598 // 32-bit.
599 case cByte:
600 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
601 break;
602 case cShort:
603 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
604 break;
605 case cInt:
606 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
607 break;
608 case cFP:
609 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
610 BuildMI(BB, X86::FNSTSWr8, 0);
611 BuildMI(BB, X86::SAHF, 1);
612 isSigned = false; // Compare with unsigned operators
613 break;
614
615 case cLong:
616 if (OpNum < 2) { // seteq, setne
617 unsigned LoTmp = makeAnotherReg(Type::IntTy);
618 unsigned HiTmp = makeAnotherReg(Type::IntTy);
619 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
620 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
621 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
622 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
623 break; // Allow the sete or setne to be generated from flags set by OR
624 } else {
625 // Emit a sequence of code which compares the high and low parts once
626 // each, then uses a conditional move to handle the overflow case. For
627 // example, a setlt for long would generate code like this:
628 //
629 // AL = lo(op1) < lo(op2) // Signedness depends on operands
630 // BL = hi(op1) < hi(op2) // Always unsigned comparison
631 // dest = hi(op1) == hi(op2) ? AL : BL;
632 //
633
Chris Lattner6d40c192003-01-16 16:43:00 +0000634 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000635 // classes! Until then, hardcode registers so that we can deal with their
636 // aliases (because we don't have conditional byte moves).
637 //
638 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
Chris Lattner6d40c192003-01-16 16:43:00 +0000639 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000640 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
Chris Lattner6d40c192003-01-16 16:43:00 +0000641 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000642 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000643 // NOTE: visitSetCondInst knows that the value is dumped into the BL
644 // register at this point for long values...
645 return isSigned;
Chris Lattner3e130a22003-01-13 00:32:26 +0000646 }
647 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000648 return isSigned;
649}
Chris Lattner3e130a22003-01-13 00:32:26 +0000650
Chris Lattner6d40c192003-01-16 16:43:00 +0000651
652/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
653/// register, then move it to wherever the result should be.
654///
655void ISel::visitSetCondInst(SetCondInst &I) {
656 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
657
658 unsigned OpNum = getSetCCNumber(I.getOpcode());
659 unsigned DestReg = getReg(I);
660 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
661 I.getOperand(1));
662
663 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
664 // Handle normal comparisons with a setcc instruction...
665 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
666 } else {
667 // Handle long comparisons by copying the value which is already in BL into
668 // the register we want...
669 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
670 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000671}
Chris Lattner51b49a92002-11-02 19:45:49 +0000672
Brian Gaekec2505982002-11-30 11:57:28 +0000673/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
674/// operand, in the specified target register.
Chris Lattner3e130a22003-01-13 00:32:26 +0000675void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
676 bool isUnsigned = VR.Ty->isUnsigned();
677 switch (getClassB(VR.Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +0000678 case cByte:
679 // Extend value into target register (8->32)
680 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000681 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000682 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000683 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000684 break;
685 case cShort:
686 // Extend value into target register (16->32)
687 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000688 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000689 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000690 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000691 break;
692 case cInt:
693 // Move value into target register (32->32)
Chris Lattner3e130a22003-01-13 00:32:26 +0000694 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000695 break;
696 default:
697 assert(0 && "Unpromotable operand class in promote32");
698 }
Brian Gaekec2505982002-11-30 11:57:28 +0000699}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000700
Chris Lattner72614082002-10-25 22:55:53 +0000701/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
702/// we have the following possibilities:
703///
704/// ret void: No return value, simply emit a 'ret' instruction
705/// ret sbyte, ubyte : Extend value into EAX and return
706/// ret short, ushort: Extend value into EAX and return
707/// ret int, uint : Move value into EAX and return
708/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000709/// ret long, ulong : Move value into EAX/EDX and return
710/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000711///
Chris Lattner3e130a22003-01-13 00:32:26 +0000712void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000713 if (I.getNumOperands() == 0) {
714 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
715 return;
716 }
717
718 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +0000719 unsigned RetReg = getReg(RetVal);
720 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +0000721 case cByte: // integral return values: extend or move into EAX and return
722 case cShort:
723 case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000724 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
Chris Lattnerdbd73722003-05-06 21:32:22 +0000725 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000726 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000727 break;
728 case cFP: // Floats & Doubles: Return in ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000729 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000730 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000731 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000732 break;
733 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000734 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
735 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000736 // Declare that EAX & EDX are live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000737 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000738 break;
Chris Lattner94af4142002-12-25 05:13:53 +0000739 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000740 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +0000741 }
Chris Lattner43189d12002-11-17 20:07:45 +0000742 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +0000743 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000744}
745
Chris Lattner55f6fab2003-01-16 18:07:23 +0000746// getBlockAfter - Return the basic block which occurs lexically after the
747// specified one.
748static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
749 Function::iterator I = BB; ++I; // Get iterator to next block
750 return I != BB->getParent()->end() ? &*I : 0;
751}
752
Chris Lattner51b49a92002-11-02 19:45:49 +0000753/// visitBranchInst - Handle conditional and unconditional branches here. Note
754/// that since code layout is frozen at this point, that if we are trying to
755/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +0000756/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +0000757///
Chris Lattner94af4142002-12-25 05:13:53 +0000758void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000759 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
760
761 if (!BI.isConditional()) { // Unconditional branch?
762 if (BI.getSuccessor(0) != NextBB)
763 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +0000764 return;
765 }
766
767 // See if we can fold the setcc into the branch itself...
768 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
769 if (SCI == 0) {
770 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
771 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +0000772 unsigned condReg = getReg(BI.getCondition());
Chris Lattner94af4142002-12-25 05:13:53 +0000773 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
Chris Lattner55f6fab2003-01-16 18:07:23 +0000774 if (BI.getSuccessor(1) == NextBB) {
775 if (BI.getSuccessor(0) != NextBB)
776 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
777 } else {
778 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
779
780 if (BI.getSuccessor(0) != NextBB)
781 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
782 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000783 return;
Chris Lattner94af4142002-12-25 05:13:53 +0000784 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000785
786 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
787 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
788 SCI->getOperand(1));
789
790 // LLVM -> X86 signed X86 unsigned
791 // ----- ---------- ------------
792 // seteq -> je je
793 // setne -> jne jne
794 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000795 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +0000796 // setgt -> jg ja
797 // setle -> jle jbe
Chris Lattner6d40c192003-01-16 16:43:00 +0000798 static const unsigned OpcodeTab[2][6] = {
Chris Lattner55f6fab2003-01-16 18:07:23 +0000799 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
800 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
Chris Lattner6d40c192003-01-16 16:43:00 +0000801 };
802
Chris Lattner55f6fab2003-01-16 18:07:23 +0000803 if (BI.getSuccessor(0) != NextBB) {
804 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
805 if (BI.getSuccessor(1) != NextBB)
806 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
807 } else {
808 // Change to the inverse condition...
809 if (BI.getSuccessor(1) != NextBB) {
810 OpNum ^= 1;
811 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
812 }
813 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000814}
815
Chris Lattner3e130a22003-01-13 00:32:26 +0000816
817/// doCall - This emits an abstract call instruction, setting up the arguments
818/// and the return value as appropriate. For the actual function call itself,
819/// it inserts the specified CallMI instruction into the stream.
820///
821void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
822 const std::vector<ValueRecord> &Args) {
823
Chris Lattner065faeb2002-12-28 20:24:02 +0000824 // Count how many bytes are to be pushed on the stack...
825 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000826
Chris Lattner3e130a22003-01-13 00:32:26 +0000827 if (!Args.empty()) {
828 for (unsigned i = 0, e = Args.size(); i != e; ++i)
829 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000830 case cByte: case cShort: case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000831 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000832 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000833 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000834 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000835 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
Chris Lattner065faeb2002-12-28 20:24:02 +0000836 break;
837 default: assert(0 && "Unknown class!");
838 }
839
840 // Adjust the stack pointer for the new arguments...
841 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
842
843 // Arguments go on the stack in reverse order, as specified by the ABI.
844 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +0000845 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
846 unsigned ArgReg = Args[i].Reg;
847 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000848 case cByte:
849 case cShort: {
850 // Promote arg to 32 bits wide into a temporary register...
851 unsigned R = makeAnotherReg(Type::UIntTy);
Chris Lattner3e130a22003-01-13 00:32:26 +0000852 promote32(R, Args[i]);
Chris Lattner065faeb2002-12-28 20:24:02 +0000853 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
854 X86::ESP, ArgOffset).addReg(R);
855 break;
856 }
857 case cInt:
858 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000859 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000860 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000861 case cLong:
862 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
863 X86::ESP, ArgOffset).addReg(ArgReg);
864 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
865 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
866 ArgOffset += 4; // 8 byte entry, not 4.
867 break;
868
Chris Lattner065faeb2002-12-28 20:24:02 +0000869 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000870 if (Args[i].Ty == Type::FloatTy) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000871 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000872 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000873 } else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000874 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
875 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
876 X86::ESP, ArgOffset).addReg(ArgReg);
877 ArgOffset += 4; // 8 byte entry, not 4.
Chris Lattner065faeb2002-12-28 20:24:02 +0000878 }
879 break;
880
Chris Lattner3e130a22003-01-13 00:32:26 +0000881 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +0000882 }
883 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +0000884 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000885 } else {
886 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +0000887 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +0000888
Chris Lattner3e130a22003-01-13 00:32:26 +0000889 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000890
Chris Lattner065faeb2002-12-28 20:24:02 +0000891 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +0000892
893 // If there is a return value, scavenge the result from the location the call
894 // leaves it in...
895 //
Chris Lattner3e130a22003-01-13 00:32:26 +0000896 if (Ret.Ty != Type::VoidTy) {
897 unsigned DestClass = getClassB(Ret.Ty);
898 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000899 case cByte:
900 case cShort:
901 case cInt: {
902 // Integral results are in %eax, or the appropriate portion
903 // thereof.
904 static const unsigned regRegMove[] = {
905 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
906 };
907 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +0000908 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000909 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000910 }
Chris Lattner94af4142002-12-25 05:13:53 +0000911 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000912 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000913 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000914 case cLong: // Long values are left in EDX:EAX
915 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
916 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
917 break;
918 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000919 }
Chris Lattnera3243642002-12-04 23:45:28 +0000920 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000921}
Chris Lattner2df035b2002-11-02 19:27:56 +0000922
Chris Lattner3e130a22003-01-13 00:32:26 +0000923
924/// visitCallInst - Push args on stack and do a procedure call instruction.
925void ISel::visitCallInst(CallInst &CI) {
926 MachineInstr *TheCall;
927 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +0000928 // Is it an intrinsic function call?
929 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
930 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
931 return;
932 }
933
Chris Lattner3e130a22003-01-13 00:32:26 +0000934 // Emit a CALL instruction with PC-relative displacement.
935 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
936 } else { // Emit an indirect call...
937 unsigned Reg = getReg(CI.getCalledValue());
938 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
939 }
940
941 std::vector<ValueRecord> Args;
942 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
943 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
944 CI.getOperand(i)->getType()));
945
946 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
947 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
948}
949
Chris Lattnereca195e2003-05-08 19:44:13 +0000950void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
951 unsigned TmpReg1, TmpReg2;
952 switch (ID) {
953 case LLVMIntrinsic::va_start:
954 // Get the address of the first vararg value...
955 TmpReg1 = makeAnotherReg(Type::UIntTy);
956 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
957 TmpReg2 = getReg(CI.getOperand(1));
958 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
959 return;
960
961 case LLVMIntrinsic::va_end: return; // Noop on X86
962 case LLVMIntrinsic::va_copy:
963 TmpReg1 = getReg(CI.getOperand(2)); // Get existing va_list
964 TmpReg2 = getReg(CI.getOperand(1)); // Get va_list* to store into
965 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
966 return;
967
968 default: assert(0 && "Unknown intrinsic for X86!");
969 }
970}
971
972
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000973/// visitSimpleBinary - Implement simple binary operators for integral types...
974/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
975/// Xor.
976void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
977 unsigned DestReg = getReg(B);
978 MachineBasicBlock::iterator MI = BB->end();
979 emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
980 OperatorClass, DestReg);
981}
Chris Lattner3e130a22003-01-13 00:32:26 +0000982
Chris Lattner68aad932002-11-02 20:13:22 +0000983/// visitSimpleBinary - Implement simple binary operators for integral types...
984/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
985/// 4 for Xor.
986///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000987/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
988/// and constant expression support.
989void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
990 MachineBasicBlock::iterator &IP,
991 Value *Op0, Value *Op1,
992 unsigned OperatorClass,unsigned TargetReg){
993 unsigned Class = getClassB(Op0->getType());
Chris Lattnere2954c82002-11-02 20:04:26 +0000994
995 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000996 // Arithmetic operators
Chris Lattner94af4142002-12-25 05:13:53 +0000997 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
998 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
Chris Lattner68aad932002-11-02 20:13:22 +0000999
1000 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +00001001 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
1002 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
1003 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
1004 };
Chris Lattner3e130a22003-01-13 00:32:26 +00001005
1006 bool isLong = false;
1007 if (Class == cLong) {
1008 isLong = true;
1009 Class = cInt; // Bottom 32 bits are handled just like ints
1010 }
Chris Lattnere2954c82002-11-02 20:04:26 +00001011
1012 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner94af4142002-12-25 05:13:53 +00001013 assert(Opcode && "Floating point arguments to logical inst?");
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001014 unsigned Op0r = getReg(Op0, BB, IP);
1015 unsigned Op1r = getReg(Op1, BB, IP);
1016 BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001017
1018 if (isLong) { // Handle the upper 32 bits of long values...
1019 static const unsigned TopTab[] = {
1020 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1021 };
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001022 BMI(BB, IP, TopTab[OperatorClass], 2,
1023 TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001024 }
Chris Lattnere2954c82002-11-02 20:04:26 +00001025}
1026
Chris Lattner3e130a22003-01-13 00:32:26 +00001027/// doMultiply - Emit appropriate instructions to multiply together the
1028/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1029/// result should be given as DestTy.
1030///
1031/// FIXME: doMultiply should use one of the two address IMUL instructions!
1032///
Chris Lattner8a307e82002-12-16 19:32:50 +00001033void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00001034 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00001035 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001036 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001037 switch (Class) {
1038 case cFP: // Floating point multiply
Chris Lattner3e130a22003-01-13 00:32:26 +00001039 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001040 return;
1041 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001042 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00001043 case cByte:
1044 case cShort:
1045 case cInt: // Small integerals, handled below...
1046 break;
1047 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001048
1049 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001050 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
Brian Gaeke20244b72002-12-12 15:33:40 +00001051 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1052 unsigned Reg = Regs[Class];
1053
1054 // Emit a MOV to put the first operand into the appropriately-sized
1055 // subreg of EAX.
Chris Lattner3e130a22003-01-13 00:32:26 +00001056 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001057
1058 // Emit the appropriate multiply instruction.
Chris Lattner3e130a22003-01-13 00:32:26 +00001059 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001060
1061 // Emit another MOV to put the result into the destination register.
Chris Lattner3e130a22003-01-13 00:32:26 +00001062 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001063}
1064
Chris Lattnerca9671d2002-11-02 20:28:58 +00001065/// visitMul - Multiplies are not simple binary operators because they must deal
1066/// with the EAX register explicitly.
1067///
1068void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00001069 unsigned Op0Reg = getReg(I.getOperand(0));
1070 unsigned Op1Reg = getReg(I.getOperand(1));
Chris Lattner3e130a22003-01-13 00:32:26 +00001071 unsigned DestReg = getReg(I);
1072
1073 // Simple scalar multiply?
1074 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1075 MachineBasicBlock::iterator MBBI = BB->end();
1076 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1077 } else {
1078 // Long value. We have to do things the hard way...
1079 // Multiply the two low parts... capturing carry into EDX
1080 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1081 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1082
1083 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1084 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1085 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1086
1087 MachineBasicBlock::iterator MBBI = BB->end();
1088 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1089 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
1090
1091 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1092 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1093 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1094
1095 MBBI = BB->end();
1096 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1097 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
1098
1099 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1100 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1101 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001102}
Chris Lattnerca9671d2002-11-02 20:28:58 +00001103
Chris Lattner06925362002-11-17 21:56:38 +00001104
Chris Lattnerf01729e2002-11-02 20:54:46 +00001105/// visitDivRem - Handle division and remainder instructions... these
1106/// instruction both require the same instructions to be generated, they just
1107/// select the result from a different register. Note that both of these
1108/// instructions work differently for signed and unsigned operands.
1109///
1110void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001111 unsigned Class = getClass(I.getType());
1112 unsigned Op0Reg = getReg(I.getOperand(0));
1113 unsigned Op1Reg = getReg(I.getOperand(1));
1114 unsigned ResultReg = getReg(I);
1115
1116 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001117 case cFP: // Floating point divide
Chris Lattner94af4142002-12-25 05:13:53 +00001118 if (I.getOpcode() == Instruction::Div)
1119 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001120 else { // Floating point remainder...
1121 MachineInstr *TheCall =
1122 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1123 std::vector<ValueRecord> Args;
1124 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1125 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1126 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1127 }
Chris Lattner94af4142002-12-25 05:13:53 +00001128 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001129 case cLong: {
1130 static const char *FnName[] =
1131 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1132
1133 unsigned NameIdx = I.getType()->isUnsigned()*2;
1134 NameIdx += I.getOpcode() == Instruction::Div;
1135 MachineInstr *TheCall =
1136 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1137
1138 std::vector<ValueRecord> Args;
1139 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1140 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1141 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1142 return;
1143 }
1144 case cByte: case cShort: case cInt:
1145 break; // Small integerals, handled below...
1146 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001147 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001148
1149 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1150 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +00001151 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00001152 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1153 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1154
1155 static const unsigned DivOpcode[][4] = {
Chris Lattner3e130a22003-01-13 00:32:26 +00001156 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1157 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00001158 };
1159
1160 bool isSigned = I.getType()->isSigned();
1161 unsigned Reg = Regs[Class];
1162 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00001163
1164 // Put the first operand into one of the A registers...
1165 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1166
1167 if (isSigned) {
1168 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +00001169 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001170 } else {
1171 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1172 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1173 }
1174
Chris Lattner06925362002-11-17 21:56:38 +00001175 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +00001176 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00001177
Chris Lattnerf01729e2002-11-02 20:54:46 +00001178 // Figure out which register we want to pick the result out of...
1179 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1180
Chris Lattnerf01729e2002-11-02 20:54:46 +00001181 // Put the result into the destination register...
Chris Lattner94af4142002-12-25 05:13:53 +00001182 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00001183}
Chris Lattnere2954c82002-11-02 20:04:26 +00001184
Chris Lattner06925362002-11-17 21:56:38 +00001185
Brian Gaekea1719c92002-10-31 23:03:59 +00001186/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1187/// for constant immediate shift values, and for constant immediate
1188/// shift values equal to 1. Even the general case is sort of special,
1189/// because the shift amount has to be in CL, not just any old register.
1190///
Chris Lattner3e130a22003-01-13 00:32:26 +00001191void ISel::visitShiftInst(ShiftInst &I) {
1192 unsigned SrcReg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +00001193 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +00001194 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3e130a22003-01-13 00:32:26 +00001195 bool isSigned = I.getType()->isSigned();
1196 unsigned Class = getClass(I.getType());
1197
1198 static const unsigned ConstantOperand[][4] = {
1199 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1200 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1201 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1202 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1203 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001204
Chris Lattner3e130a22003-01-13 00:32:26 +00001205 static const unsigned NonConstantOperand[][4] = {
1206 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1207 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1208 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1209 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1210 };
Chris Lattner796df732002-11-02 00:44:25 +00001211
Chris Lattner3e130a22003-01-13 00:32:26 +00001212 // Longs, as usual, are handled specially...
1213 if (Class == cLong) {
1214 // If we have a constant shift, we can generate much more efficient code
1215 // than otherwise...
1216 //
1217 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1218 unsigned Amount = CUI->getValue();
1219 if (Amount < 32) {
1220 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1221 if (isLeftShift) {
1222 BuildMI(BB, Opc[3], 3,
1223 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1224 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1225 } else {
1226 BuildMI(BB, Opc[3], 3,
1227 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1228 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1229 }
1230 } else { // Shifting more than 32 bits
1231 Amount -= 32;
1232 if (isLeftShift) {
1233 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1234 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1235 } else {
1236 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1237 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1238 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1239 }
1240 }
1241 } else {
1242 visitInstruction(I); // FIXME: Implement long shift by non-constant
Brian Gaekea1719c92002-10-31 23:03:59 +00001243 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001244 return;
1245 }
Chris Lattnere9913f22002-11-02 01:41:55 +00001246
Chris Lattner3e130a22003-01-13 00:32:26 +00001247 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1248 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1249 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001250
Chris Lattner3e130a22003-01-13 00:32:26 +00001251 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1252 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1253 } else { // The shift amount is non-constant.
1254 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001255
Chris Lattner3e130a22003-01-13 00:32:26 +00001256 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1257 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1258 }
1259}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001260
Chris Lattner3e130a22003-01-13 00:32:26 +00001261
1262/// doFPLoad - This method is used to load an FP value from memory using the
1263/// current endianness. NOTE: This method returns a partially constructed load
1264/// instruction which needs to have the memory source filled in still.
1265///
1266MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1267 MachineBasicBlock::iterator &MBBI,
1268 const Type *Ty, unsigned DestReg) {
1269 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1270 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1271
1272 if (TM.getTargetData().isLittleEndian()) // fast path...
1273 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1274
1275 // If we are big-endian, start by creating an LEA instruction to represent the
1276 // address of the memory location to load from...
1277 //
1278 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1279 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1280
1281 // Allocate a temporary stack slot to transform the value into...
1282 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1283
1284 // Perform the bswaps 32 bits at a time...
1285 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1286 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1287 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1288 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1289 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1290 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1291 FrameIdx, Offset).addReg(TmpReg2);
1292
1293 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1294 TmpReg1 = makeAnotherReg(Type::UIntTy);
1295 TmpReg2 = makeAnotherReg(Type::UIntTy);
1296
1297 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1298 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1299 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1300 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1301 }
1302
1303 // Now we can reload the final byteswapped result into the final destination.
1304 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1305 return Result;
1306}
1307
1308/// EmitByteSwap - Byteswap SrcReg into DestReg.
1309///
1310void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1311 // Emit the byte swap instruction...
1312 switch (Class) {
1313 case cByte:
Misha Brukmanbaf06072003-04-22 17:54:23 +00001314 // No byteswap necessary for 8 bit value...
Chris Lattner3e130a22003-01-13 00:32:26 +00001315 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1316 break;
1317 case cInt:
1318 // Use the 32 bit bswap instruction to do a 32 bit swap...
1319 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1320 break;
1321
1322 case cShort:
1323 // For 16 bit we have to use an xchg instruction, because there is no
Misha Brukmanbaf06072003-04-22 17:54:23 +00001324 // 16-bit bswap. XCHG is necessarily not in SSA form, so we force things
Chris Lattner3e130a22003-01-13 00:32:26 +00001325 // into AX to do the xchg.
1326 //
1327 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1328 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1329 .addReg(X86::AH, MOTy::UseAndDef);
1330 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1331 break;
1332 default: assert(0 && "Cannot byteswap this class!");
1333 }
Brian Gaekea1719c92002-10-31 23:03:59 +00001334}
1335
Chris Lattner06925362002-11-17 21:56:38 +00001336
Chris Lattner6fc3c522002-11-17 21:11:55 +00001337/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00001338/// instruction. The load and store instructions are the only place where we
1339/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00001340///
1341void ISel::visitLoadInst(LoadInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001342 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1343 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner94af4142002-12-25 05:13:53 +00001344 unsigned SrcAddrReg = getReg(I.getOperand(0));
1345 unsigned DestReg = getReg(I);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001346
Chris Lattner6fc3c522002-11-17 21:11:55 +00001347 unsigned Class = getClass(I.getType());
Chris Lattner94af4142002-12-25 05:13:53 +00001348 switch (Class) {
Chris Lattner94af4142002-12-25 05:13:53 +00001349 case cFP: {
Chris Lattner3e130a22003-01-13 00:32:26 +00001350 MachineBasicBlock::iterator MBBI = BB->end();
1351 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001352 return;
1353 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001354 case cLong: case cInt: case cShort: case cByte:
1355 break; // Integers of various sizes handled below
1356 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001357 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001358
Chris Lattnere8f0d922002-12-24 00:03:11 +00001359 // We need to adjust the input pointer if we are emulating a big-endian
1360 // long-pointer target. On these systems, the pointer that we are interested
1361 // in is in the upper part of the eight byte memory image of the pointer. It
1362 // also happens to be byte-swapped, but this will be handled later.
1363 //
1364 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1365 unsigned R = makeAnotherReg(Type::UIntTy);
1366 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1367 SrcAddrReg = R;
1368 }
Chris Lattner94af4142002-12-25 05:13:53 +00001369
Chris Lattnere8f0d922002-12-24 00:03:11 +00001370 unsigned IReg = DestReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001371 if (!isLittleEndian) // If big endian we need an intermediate stage
1372 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001373
Chris Lattner3e130a22003-01-13 00:32:26 +00001374 static const unsigned Opcode[] = {
1375 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1376 };
Chris Lattnere8f0d922002-12-24 00:03:11 +00001377 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1378
Chris Lattner3e130a22003-01-13 00:32:26 +00001379 // Handle long values now...
1380 if (Class == cLong) {
1381 if (isLittleEndian) {
1382 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1383 } else {
1384 EmitByteSwap(IReg+1, DestReg, cInt);
1385 unsigned TempReg = makeAnotherReg(Type::IntTy);
1386 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1387 EmitByteSwap(IReg, TempReg, cInt);
Chris Lattner94af4142002-12-25 05:13:53 +00001388 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001389 return;
1390 }
1391
1392 if (!isLittleEndian)
1393 EmitByteSwap(IReg, DestReg, Class);
1394}
1395
1396
1397/// doFPStore - This method is used to store an FP value to memory using the
1398/// current endianness.
1399///
1400void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1401 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1402 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1403
1404 if (TM.getTargetData().isLittleEndian()) { // fast path...
1405 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1406 return;
1407 }
1408
1409 // Allocate a temporary stack slot to transform the value into...
1410 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1411 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1412 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1413
1414 // Store the value into a temporary stack slot...
1415 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1416
1417 // Perform the bswaps 32 bits at a time...
1418 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1419 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1420 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1421 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1422 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1423 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1424 DestAddrReg, Offset).addReg(TmpReg2);
1425
1426 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1427 TmpReg1 = makeAnotherReg(Type::UIntTy);
1428 TmpReg2 = makeAnotherReg(Type::UIntTy);
1429
1430 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1431 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1432 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1433 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001434 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001435}
1436
Chris Lattner06925362002-11-17 21:56:38 +00001437
Chris Lattner6fc3c522002-11-17 21:11:55 +00001438/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1439/// instruction.
1440///
1441void ISel::visitStoreInst(StoreInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001442 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1443 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner3e130a22003-01-13 00:32:26 +00001444 unsigned ValReg = getReg(I.getOperand(0));
1445 unsigned AddressReg = getReg(I.getOperand(1));
Chris Lattnere8f0d922002-12-24 00:03:11 +00001446
Chris Lattner94af4142002-12-25 05:13:53 +00001447 unsigned Class = getClass(I.getOperand(0)->getType());
1448 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001449 case cLong:
1450 if (isLittleEndian) {
1451 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1452 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1453 AddressReg, 4).addReg(ValReg+1);
1454 } else {
1455 unsigned T1 = makeAnotherReg(Type::IntTy);
1456 unsigned T2 = makeAnotherReg(Type::IntTy);
1457 EmitByteSwap(T1, ValReg , cInt);
1458 EmitByteSwap(T2, ValReg+1, cInt);
1459 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1460 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1461 }
Chris Lattner94af4142002-12-25 05:13:53 +00001462 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001463 case cFP:
1464 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1465 return;
1466 case cInt: case cShort: case cByte:
1467 break; // Integers of various sizes handled below
1468 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001469 }
1470
1471 if (!isLittleEndian && hasLongPointers &&
1472 isa<PointerType>(I.getOperand(0)->getType())) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001473 unsigned R = makeAnotherReg(Type::UIntTy);
1474 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1475 AddressReg = R;
1476 }
1477
Chris Lattner94af4142002-12-25 05:13:53 +00001478 if (!isLittleEndian && Class != cByte) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001479 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1480 EmitByteSwap(R, ValReg, Class);
1481 ValReg = R;
Chris Lattnere8f0d922002-12-24 00:03:11 +00001482 }
1483
Chris Lattner94af4142002-12-25 05:13:53 +00001484 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner6fc3c522002-11-17 21:11:55 +00001485 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1486}
1487
1488
Brian Gaekec11232a2002-11-26 10:43:30 +00001489/// visitCastInst - Here we have various kinds of copying with or without
1490/// sign extension going on.
Chris Lattner3e130a22003-01-13 00:32:26 +00001491void ISel::visitCastInst(CastInst &CI) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001492 unsigned DestReg = getReg(CI);
1493 MachineBasicBlock::iterator MI = BB->end();
1494 emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
1495}
1496
1497/// emitCastOperation - Common code shared between visitCastInst and
1498/// constant expression cast support.
1499void ISel::emitCastOperation(MachineBasicBlock *BB,
1500 MachineBasicBlock::iterator &IP,
1501 Value *Src, const Type *DestTy,
1502 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00001503 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001504 const Type *SrcTy = Src->getType();
1505 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00001506 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00001507
Chris Lattner3e130a22003-01-13 00:32:26 +00001508 // Implement casts to bool by using compare on the operand followed by set if
1509 // not zero on the result.
1510 if (DestTy == Type::BoolTy) {
1511 if (SrcClass == cFP || SrcClass == cLong)
Chris Lattner548f61d2003-04-23 17:22:12 +00001512 abort(); // FIXME: implement cast (long & FP) to bool
Chris Lattner3e130a22003-01-13 00:32:26 +00001513
Chris Lattner548f61d2003-04-23 17:22:12 +00001514 BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1515 BMI(BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001516 return;
1517 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001518
1519 static const unsigned RegRegMove[] = {
1520 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1521 };
1522
1523 // Implement casts between values of the same type class (as determined by
1524 // getClass) by using a register-to-register move.
1525 if (SrcClass == DestClass) {
1526 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001527 BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001528 } else if (SrcClass == cFP) {
1529 if (SrcTy == Type::FloatTy) { // double -> float
1530 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001531 BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001532 } else { // float -> double
1533 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1534 "Unknown cFP member!");
1535 // Truncate from double to float by storing to memory as short, then
1536 // reading it back.
1537 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1538 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Chris Lattner548f61d2003-04-23 17:22:12 +00001539 addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1540 addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001541 }
1542 } else if (SrcClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001543 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1544 BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001545 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00001546 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001547 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00001548 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001549 return;
1550 }
1551
1552 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1553 // or zero extension, depending on whether the source type was signed.
1554 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1555 SrcClass < DestClass) {
1556 bool isLong = DestClass == cLong;
1557 if (isLong) DestClass = cInt;
1558
1559 static const unsigned Opc[][4] = {
1560 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1561 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1562 };
1563
1564 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattner548f61d2003-04-23 17:22:12 +00001565 BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1566 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001567
1568 if (isLong) { // Handle upper 32 bits as appropriate...
1569 if (isUnsigned) // Zero out top bits...
Chris Lattner548f61d2003-04-23 17:22:12 +00001570 BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001571 else // Sign extend bottom half...
Chris Lattner548f61d2003-04-23 17:22:12 +00001572 BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00001573 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001574 return;
1575 }
1576
1577 // Special case long -> int ...
1578 if (SrcClass == cLong && DestClass == cInt) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001579 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001580 return;
1581 }
1582
1583 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1584 // move out of AX or AL.
1585 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1586 && SrcClass > DestClass) {
1587 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattner548f61d2003-04-23 17:22:12 +00001588 BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1589 BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00001590 return;
1591 }
1592
1593 // Handle casts from integer to floating point now...
1594 if (DestClass == cFP) {
1595 // unsigned int -> load as 64 bit int.
1596 // unsigned long long -> more complex
Chris Lattnerc53544a2003-05-12 20:16:58 +00001597 if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy) {
1598 assert(0 && "Cannot handle this type of cast!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001599 abort(); // don't handle unsigned src yet!
Chris Lattnerc53544a2003-05-12 20:16:58 +00001600 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001601
Chris Lattner4d5a50a2003-05-12 20:36:13 +00001602 // Promote the integer to a type supported by FLD. We do this because there
1603 // are no unsigned FLD instructions, so we must promote an unsigned value to
1604 // a larger signed value, then use FLD on the larger value.
1605 //
1606 const Type *PromoteType = 0;
1607 unsigned PromoteOpcode;
1608 switch (SrcTy->getPrimitiveID()) {
1609 case Type::BoolTyID:
1610 case Type::SByteTyID:
1611 // We don't have the facilities for directly loading byte sized data from
1612 // memory (even signed). Promote it to 16 bits.
1613 PromoteType = Type::ShortTy;
1614 PromoteOpcode = X86::MOVSXr16r8;
1615 break;
1616 case Type::UByteTyID:
1617 PromoteType = Type::ShortTy;
1618 PromoteOpcode = X86::MOVZXr16r8;
1619 break;
1620 case Type::UShortTyID:
1621 PromoteType = Type::IntTy;
1622 PromoteOpcode = X86::MOVZXr32r16;
1623 break;
1624 case Type::UIntTyID: {
1625 // Make a 64 bit temporary... and zero out the top of it...
1626 unsigned TmpReg = makeAnotherReg(Type::LongTy);
1627 BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1628 BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1629 SrcTy = Type::LongTy;
1630 SrcClass = cLong;
1631 SrcReg = TmpReg;
1632 break;
1633 }
1634 case Type::ULongTyID:
1635 assert("FIXME: not implemented: cast ulong X to fp type!");
1636 default: // No promotion needed...
1637 break;
1638 }
1639
1640 if (PromoteType) {
1641 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner548f61d2003-04-23 17:22:12 +00001642 BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1643 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00001644 SrcTy = PromoteType;
1645 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00001646 SrcReg = TmpReg;
1647 }
1648
1649 // Spill the integer to memory and reload it from there...
1650 int FrameIdx =
1651 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1652
1653 if (SrcClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001654 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1655 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +00001656 FrameIdx, 4).addReg(SrcReg+1);
1657 } else {
1658 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001659 addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001660 }
1661
1662 static const unsigned Op2[] =
Chris Lattner4d5a50a2003-05-12 20:36:13 +00001663 { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001664 addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001665 return;
1666 }
1667
1668 // Handle casts from floating point to integer now...
1669 if (SrcClass == cFP) {
1670 // Change the floating point control register to use "round towards zero"
1671 // mode when truncating to an integer value.
1672 //
1673 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Chris Lattner548f61d2003-04-23 17:22:12 +00001674 addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001675
1676 // Load the old value of the high byte of the control word...
1677 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Chris Lattner548f61d2003-04-23 17:22:12 +00001678 addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001679
1680 // Set the high part to be round to zero...
Chris Lattner548f61d2003-04-23 17:22:12 +00001681 addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00001682
1683 // Reload the modified control word now...
Chris Lattner548f61d2003-04-23 17:22:12 +00001684 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001685
1686 // Restore the memory image of control word to original value
Chris Lattner548f61d2003-04-23 17:22:12 +00001687 addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +00001688 CWFrameIdx, 1).addReg(HighPartOfCW);
1689
1690 // We don't have the facilities for directly storing byte sized data to
1691 // memory. Promote it to 16 bits. We also must promote unsigned values to
1692 // larger classes because we only have signed FP stores.
1693 unsigned StoreClass = DestClass;
1694 const Type *StoreTy = DestTy;
1695 if (StoreClass == cByte || DestTy->isUnsigned())
1696 switch (StoreClass) {
1697 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1698 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1699 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner548f61d2003-04-23 17:22:12 +00001700 case cLong: abort(); // FIXME: unsigned long long -> more complex
Chris Lattner3e130a22003-01-13 00:32:26 +00001701 default: assert(0 && "Unknown store class!");
1702 }
1703
1704 // Spill the integer to memory and reload it from there...
1705 int FrameIdx =
1706 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1707
1708 static const unsigned Op1[] =
1709 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001710 addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001711
1712 if (DestClass == cLong) {
Chris Lattner548f61d2003-04-23 17:22:12 +00001713 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1714 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00001715 } else {
1716 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
Chris Lattner548f61d2003-04-23 17:22:12 +00001717 addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001718 }
1719
1720 // Reload the original control word now...
Chris Lattner548f61d2003-04-23 17:22:12 +00001721 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00001722 return;
1723 }
1724
Brian Gaeked474e9c2002-12-06 10:49:33 +00001725 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00001726 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00001727 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00001728}
Brian Gaekea1719c92002-10-31 23:03:59 +00001729
Chris Lattnereca195e2003-05-08 19:44:13 +00001730/// visitVarArgInst - Implement the va_arg instruction...
1731///
1732void ISel::visitVarArgInst(VarArgInst &I) {
1733 unsigned SrcReg = getReg(I.getOperand(0));
1734 unsigned DestReg = getReg(I);
1735
1736 // Load the va_list into a register...
1737 unsigned VAList = makeAnotherReg(Type::UIntTy);
1738 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
1739
1740 unsigned Size;
1741 switch (I.getType()->getPrimitiveID()) {
1742 default:
1743 std::cerr << I;
1744 assert(0 && "Error: bad type for va_arg instruction!");
1745 return;
1746 case Type::PointerTyID:
1747 case Type::UIntTyID:
1748 case Type::IntTyID:
1749 Size = 4;
1750 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1751 break;
1752 case Type::ULongTyID:
1753 case Type::LongTyID:
1754 Size = 8;
1755 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1756 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1757 break;
1758 case Type::DoubleTyID:
1759 Size = 8;
1760 addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1761 break;
1762 }
1763
1764 // Increment the VAList pointer...
1765 unsigned NextVAList = makeAnotherReg(Type::UIntTy);
1766 BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
1767
1768 // Update the VAList in memory...
1769 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
1770}
1771
1772
Chris Lattner8a307e82002-12-16 19:32:50 +00001773// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1774// returns zero when the input is not exactly a power of two.
1775static unsigned ExactLog2(unsigned Val) {
1776 if (Val == 0) return 0;
1777 unsigned Count = 0;
1778 while (Val != 1) {
1779 if (Val & 1) return 0;
1780 Val >>= 1;
1781 ++Count;
1782 }
1783 return Count+1;
1784}
1785
Chris Lattner3e130a22003-01-13 00:32:26 +00001786void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1787 unsigned outputReg = getReg(I);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001788 MachineBasicBlock::iterator MI = BB->end();
1789 emitGEPOperation(BB, MI, I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00001790 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001791}
1792
Brian Gaeke71794c02002-12-13 11:22:48 +00001793void ISel::emitGEPOperation(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001794 MachineBasicBlock::iterator &IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +00001795 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +00001796 User::op_iterator IdxEnd, unsigned TargetReg) {
1797 const TargetData &TD = TM.getTargetData();
1798 const Type *Ty = Src->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +00001799 unsigned BaseReg = getReg(Src, MBB, IP);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001800
Brian Gaeke20244b72002-12-12 15:33:40 +00001801 // GEPs have zero or more indices; we must perform a struct access
1802 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +00001803 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1804 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001805 Value *idx = *oi;
Chris Lattner3e130a22003-01-13 00:32:26 +00001806 unsigned NextReg = BaseReg;
Chris Lattner065faeb2002-12-28 20:24:02 +00001807 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001808 // It's a struct access. idx is the index into the structure,
1809 // which names the field. This index must have ubyte type.
Chris Lattner065faeb2002-12-28 20:24:02 +00001810 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1811 assert(CUI->getType() == Type::UByteTy
Brian Gaeke20244b72002-12-12 15:33:40 +00001812 && "Funny-looking structure index in GEP");
1813 // Use the TargetData structure to pick out what the layout of
1814 // the structure is in memory. Since the structure index must
1815 // be constant, we can get its value and use it to find the
1816 // right byte offset from the StructLayout class's list of
1817 // structure member offsets.
Chris Lattnere8f0d922002-12-24 00:03:11 +00001818 unsigned idxValue = CUI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001819 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1820 if (FieldOff) {
1821 NextReg = makeAnotherReg(Type::UIntTy);
1822 // Emit an ADD to add FieldOff to the basePtr.
1823 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1824 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001825 // The next type is the member of the structure selected by the
1826 // index.
Chris Lattner065faeb2002-12-28 20:24:02 +00001827 Ty = StTy->getElementTypes()[idxValue];
1828 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001829 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner8a307e82002-12-16 19:32:50 +00001830
Brian Gaeke20244b72002-12-12 15:33:40 +00001831 // idx is the index into the array. Unlike with structure
1832 // indices, we may not know its actual value at code-generation
1833 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00001834 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1835
Chris Lattner3e130a22003-01-13 00:32:26 +00001836 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00001837 // must find the size of the pointed-to type (Not coincidentally, the next
1838 // type is the type of the elements in the array).
1839 Ty = SqTy->getElementType();
1840 unsigned elementSize = TD.getTypeSize(Ty);
1841
1842 // If idxReg is a constant, we don't need to perform the multiply!
1843 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001844 if (!CSI->isNullValue()) {
Chris Lattner8a307e82002-12-16 19:32:50 +00001845 unsigned Offset = elementSize*CSI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001846 NextReg = makeAnotherReg(Type::UIntTy);
1847 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
Chris Lattner8a307e82002-12-16 19:32:50 +00001848 }
1849 } else if (elementSize == 1) {
1850 // If the element size is 1, we don't have to multiply, just add
1851 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001852 NextReg = makeAnotherReg(Type::UIntTy);
1853 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001854 } else {
1855 unsigned idxReg = getReg(idx, MBB, IP);
1856 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1857 if (unsigned Shift = ExactLog2(elementSize)) {
1858 // If the element size is exactly a power of 2, use a shift to get it.
Chris Lattner8a307e82002-12-16 19:32:50 +00001859 BMI(MBB, IP, X86::SHLir32, 2,
1860 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1861 } else {
1862 // Most general case, emit a multiply...
1863 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1864 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1865
1866 // Emit a MUL to multiply the register holding the index by
1867 // elementSize, putting the result in OffsetReg.
Chris Lattner3e130a22003-01-13 00:32:26 +00001868 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001869 }
1870 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3e130a22003-01-13 00:32:26 +00001871 NextReg = makeAnotherReg(Type::UIntTy);
1872 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001873 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001874 }
1875 // Now that we are here, further indices refer to subtypes of this
Chris Lattner3e130a22003-01-13 00:32:26 +00001876 // one, so we don't need to worry about BaseReg itself, anymore.
1877 BaseReg = NextReg;
Brian Gaeke20244b72002-12-12 15:33:40 +00001878 }
1879 // After we have processed all the indices, the result is left in
Chris Lattner3e130a22003-01-13 00:32:26 +00001880 // BaseReg. Move it to the register where we were expected to
Brian Gaeke20244b72002-12-12 15:33:40 +00001881 // put the answer. A 32-bit move should do it, because we are in
1882 // ILP32 land.
Chris Lattner3e130a22003-01-13 00:32:26 +00001883 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001884}
1885
1886
Chris Lattner065faeb2002-12-28 20:24:02 +00001887/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1888/// frame manager, otherwise do it the hard way.
1889///
1890void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00001891 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00001892 const Type *Ty = I.getAllocatedType();
1893 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1894
1895 // If this is a fixed size alloca in the entry block for the function,
1896 // statically stack allocate the space.
1897 //
1898 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1899 if (I.getParent() == I.getParent()->getParent()->begin()) {
1900 TySize *= CUI->getValue(); // Get total allocated size...
1901 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1902
1903 // Create a new stack object using the frame manager...
1904 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1905 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1906 return;
1907 }
1908 }
1909
1910 // Create a register to hold the temporary result of multiplying the type size
1911 // constant by the variable amount.
1912 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1913 unsigned SrcReg1 = getReg(I.getArraySize());
1914 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1915 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1916
1917 // TotalSizeReg = mul <numelements>, <TypeSize>
1918 MachineBasicBlock::iterator MBBI = BB->end();
1919 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1920
1921 // AddedSize = add <TotalSizeReg>, 15
1922 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1923 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1924
1925 // AlignedSize = and <AddedSize>, ~15
1926 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1927 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1928
Brian Gaekee48ec012002-12-13 06:46:31 +00001929 // Subtract size from stack pointer, thereby allocating some space.
Chris Lattner3e130a22003-01-13 00:32:26 +00001930 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00001931
Brian Gaekee48ec012002-12-13 06:46:31 +00001932 // Put a pointer to the space into the result register, by copying
1933 // the stack pointer.
Chris Lattner065faeb2002-12-28 20:24:02 +00001934 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1935
Misha Brukman48196b32003-05-03 02:18:17 +00001936 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00001937 // object.
1938 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00001939}
Chris Lattner3e130a22003-01-13 00:32:26 +00001940
1941/// visitMallocInst - Malloc instructions are code generated into direct calls
1942/// to the library malloc.
1943///
1944void ISel::visitMallocInst(MallocInst &I) {
1945 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1946 unsigned Arg;
1947
1948 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1949 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1950 } else {
1951 Arg = makeAnotherReg(Type::UIntTy);
1952 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1953 unsigned Op1Reg = getReg(I.getOperand(0));
1954 MachineBasicBlock::iterator MBBI = BB->end();
1955 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1956
1957
1958 }
1959
1960 std::vector<ValueRecord> Args;
1961 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1962 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1963 1).addExternalSymbol("malloc", true);
1964 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1965}
1966
1967
1968/// visitFreeInst - Free instructions are code gen'd to call the free libc
1969/// function.
1970///
1971void ISel::visitFreeInst(FreeInst &I) {
1972 std::vector<ValueRecord> Args;
1973 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1974 I.getOperand(0)->getType()));
1975 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1976 1).addExternalSymbol("free", true);
1977 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1978}
1979
Brian Gaeke20244b72002-12-12 15:33:40 +00001980
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001981/// createSimpleX86InstructionSelector - This pass converts an LLVM function
1982/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00001983/// generated code sucks but the implementation is nice and simple.
1984///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001985Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1986 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00001987}