blob: a9a3ae18bc145b4faefb5436f5d1659f537131fd [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner72614082002-10-25 22:55:53 +00009//
Chris Lattner3e130a22003-01-13 00:32:26 +000010// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "X86.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "X86InstrBuilder.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000016#include "X86InstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner72614082002-10-25 22:55:53 +000019#include "llvm/Function.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000020#include "llvm/Instructions.h"
Chris Lattner44827152003-12-28 09:47:19 +000021#include "llvm/IntrinsicLowering.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000022#include "llvm/Pass.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner341a9372002-10-29 17:43:55 +000025#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner94af4142002-12-25 05:13:53 +000026#include "llvm/CodeGen/SSARegMap.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000027#include "llvm/Target/MRegisterInfo.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000028#include "llvm/Target/TargetMachine.h"
Chris Lattner3f1e8e72004-02-22 07:04:00 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000030#include "llvm/Support/InstVisitor.h"
Chris Lattnercf93cdd2004-01-30 22:13:44 +000031#include "llvm/Support/CFG.h"
Chris Lattner986618e2004-02-22 19:47:26 +000032#include "Support/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner986618e2004-02-22 19:47:26 +000035namespace {
36 Statistic<>
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
Chris Lattner427aeb42004-04-11 19:21:59 +000038
39 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
40 /// Representation.
41 ///
42 enum TypeClass {
43 cByte, cShort, cInt, cFP, cLong
44 };
45}
46
47/// getClass - Turn a primitive type into a "class" number which is based on the
48/// size of the type, and whether or not it is floating point.
49///
50static inline TypeClass getClass(const Type *Ty) {
51 switch (Ty->getPrimitiveID()) {
52 case Type::SByteTyID:
53 case Type::UByteTyID: return cByte; // Byte operands are class #0
54 case Type::ShortTyID:
55 case Type::UShortTyID: return cShort; // Short operands are class #1
56 case Type::IntTyID:
57 case Type::UIntTyID:
58 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
59
60 case Type::FloatTyID:
61 case Type::DoubleTyID: return cFP; // Floating Point is #3
62
63 case Type::LongTyID:
64 case Type::ULongTyID: return cLong; // Longs are class #4
65 default:
66 assert(0 && "Invalid type to getClass!");
67 return cByte; // not reached
68 }
69}
70
71// getClassB - Just like getClass, but treat boolean values as bytes.
72static inline TypeClass getClassB(const Type *Ty) {
73 if (Ty == Type::BoolTy) return cByte;
74 return getClass(Ty);
Chris Lattner986618e2004-02-22 19:47:26 +000075}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000076
Chris Lattner72614082002-10-25 22:55:53 +000077namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000078 struct ISel : public FunctionPass, InstVisitor<ISel> {
79 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000080 MachineFunction *F; // The function we are compiling into
81 MachineBasicBlock *BB; // The current MBB we are compiling
82 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000083 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000084
Chris Lattner72614082002-10-25 22:55:53 +000085 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
86
Chris Lattner333b2fa2002-12-13 10:09:43 +000087 // MBBMap - Mapping between LLVM BB -> Machine BB
88 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
89
Chris Lattnerf70e0c22003-12-28 21:23:38 +000090 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000091
92 /// runOnFunction - Top level implementation of instruction selection for
93 /// the entire function.
94 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000095 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000096 // First pass over the function, lower any unknown intrinsic functions
97 // with the IntrinsicLowering class.
98 LowerUnknownIntrinsicFunctionCalls(Fn);
99
Chris Lattner36b36032002-10-29 23:40:58 +0000100 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000101
Chris Lattner065faeb2002-12-28 20:24:02 +0000102 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +0000103 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
104 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
105
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000106 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +0000107
Chris Lattner0e5b79c2004-02-15 01:04:03 +0000108 // Set up a frame object for the return address. This is used by the
109 // llvm.returnaddress & llvm.frameaddress intrinisics.
110 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
111
Chris Lattnerdbd73722003-05-06 21:32:22 +0000112 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000113 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000114
Chris Lattner333b2fa2002-12-13 10:09:43 +0000115 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000116 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000117
118 // Select the PHI nodes
119 SelectPHINodes();
120
Chris Lattner986618e2004-02-22 19:47:26 +0000121 // Insert the FP_REG_KILL instructions into blocks that need them.
122 InsertFPRegKills();
123
Chris Lattner72614082002-10-25 22:55:53 +0000124 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000125 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000126 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +0000127 // We always build a machine code representation for the function
128 return true;
Chris Lattner72614082002-10-25 22:55:53 +0000129 }
130
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000131 virtual const char *getPassName() const {
132 return "X86 Simple Instruction Selection";
133 }
134
Chris Lattner72614082002-10-25 22:55:53 +0000135 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000136 /// block. This simply creates a new MachineBasicBlock to emit code into
137 /// and adds it to the current MachineFunction. Subsequent visit* for
138 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000139 ///
140 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000141 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000142 }
143
Chris Lattner44827152003-12-28 09:47:19 +0000144 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
145 /// function, lowering any calls to unknown intrinsic functions into the
146 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000147 ///
Chris Lattner44827152003-12-28 09:47:19 +0000148 void LowerUnknownIntrinsicFunctionCalls(Function &F);
149
Chris Lattner065faeb2002-12-28 20:24:02 +0000150 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
151 /// from the stack into virtual registers.
152 ///
153 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000154
155 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
156 /// because we have to generate our sources into the source basic blocks,
157 /// not the current one.
158 ///
159 void SelectPHINodes();
160
Chris Lattner986618e2004-02-22 19:47:26 +0000161 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
162 /// that need them. This only occurs due to the floating point stackifier
163 /// not being aggressive enough to handle arbitrary global stackification.
164 ///
165 void InsertFPRegKills();
166
Chris Lattner72614082002-10-25 22:55:53 +0000167 // Visitation methods for various instructions. These methods simply emit
168 // fixed X86 code for each instruction.
169 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000170
171 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000172 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000173 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000174
175 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000176 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000177 unsigned Reg;
178 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000179 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
180 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000181 };
182 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000183 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000184 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000185 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000186
187 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000188 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000189 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
190 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000191 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000192 unsigned DestReg, const Type *DestTy,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000193 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000194 void doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000195 MachineBasicBlock::iterator MBBI,
Chris Lattnerb2acc512003-10-19 21:09:10 +0000196 unsigned DestReg, const Type *DestTy,
197 unsigned Op0Reg, unsigned Op1Val);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000198 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000199
Chris Lattnerf01729e2002-11-02 20:54:46 +0000200 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
201 void visitRem(BinaryOperator &B) { visitDivRem(B); }
202 void visitDivRem(BinaryOperator &B);
203
Chris Lattnere2954c82002-11-02 20:04:26 +0000204 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000205 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
206 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
207 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000208
Chris Lattner6d40c192003-01-16 16:43:00 +0000209 // Comparison operators...
210 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000211 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
212 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000213 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000214 void visitSelectInst(SelectInst &SI);
215
Chris Lattnerb2acc512003-10-19 21:09:10 +0000216
Chris Lattner6fc3c522002-11-17 21:11:55 +0000217 // Memory Instructions
218 void visitLoadInst(LoadInst &I);
219 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000220 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000221 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000222 void visitMallocInst(MallocInst &I);
223 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000224
Chris Lattnere2954c82002-11-02 20:04:26 +0000225 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000226 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000227 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000228 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000229 void visitVANextInst(VANextInst &I);
230 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000231
232 void visitInstruction(Instruction &I) {
233 std::cerr << "Cannot instruction select: " << I;
234 abort();
235 }
236
Brian Gaeke95780cc2002-12-13 07:56:18 +0000237 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000238 ///
239 void promote32(unsigned targetReg, const ValueRecord &VR);
240
Chris Lattner721d2d42004-03-08 01:18:36 +0000241 /// getAddressingMode - Get the addressing mode to use to address the
242 /// specified value. The returned value should be used with addFullAddress.
243 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
244 unsigned &IndexReg, unsigned &Disp);
245
246
247 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
248 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000249 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
250 std::vector<Value*> &GEPOps,
251 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
252 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
253
254 /// isGEPFoldable - Return true if the specified GEP can be completely
255 /// folded into the addressing mode of a load/store or lea instruction.
256 bool isGEPFoldable(MachineBasicBlock *MBB,
257 Value *Src, User::op_iterator IdxBegin,
258 User::op_iterator IdxEnd, unsigned &BaseReg,
259 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
260
Chris Lattner3e130a22003-01-13 00:32:26 +0000261 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
262 /// constant expression GEP support.
263 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000264 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000265 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000266 User::op_iterator IdxEnd, unsigned TargetReg);
267
Chris Lattner548f61d2003-04-23 17:22:12 +0000268 /// emitCastOperation - Common code shared between visitCastInst and
269 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000270 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000271 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000272 Value *Src, const Type *DestTy, unsigned TargetReg);
273
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000274 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
275 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000276 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000277 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000278 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000279 Value *Op0, Value *Op1,
280 unsigned OperatorClass, unsigned TargetReg);
281
Chris Lattnercadff442003-10-23 17:21:43 +0000282 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000283 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +0000284 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
285 const Type *Ty, unsigned TargetReg);
286
Chris Lattner58c41fe2003-08-24 19:19:47 +0000287 /// emitSetCCOperation - Common code shared between visitSetCondInst and
288 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000289 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000290 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000291 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000292 Value *Op0, Value *Op1, unsigned Opcode,
293 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000294
295 /// emitShiftOperation - Common code shared between visitShiftInst and
296 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000297 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000298 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000299 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000300 Value *Op, Value *ShiftAmount, bool isLeftShift,
301 const Type *ResultTy, unsigned DestReg);
302
Chris Lattner12d96a02004-03-30 21:22:00 +0000303 /// emitSelectOperation - Common code shared between visitSelectInst and the
304 /// constant expression support.
305 void emitSelectOperation(MachineBasicBlock *MBB,
306 MachineBasicBlock::iterator IP,
307 Value *Cond, Value *TrueVal, Value *FalseVal,
308 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000309
Chris Lattnerc5291f52002-10-27 21:16:59 +0000310 /// copyConstantToRegister - Output the instructions required to put the
311 /// specified constant into the specified register.
312 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000313 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000314 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000315 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000316
Chris Lattner3e130a22003-01-13 00:32:26 +0000317 /// makeAnotherReg - This method returns the next register number we haven't
318 /// yet used.
319 ///
320 /// Long values are handled somewhat specially. They are always allocated
321 /// as pairs of 32 bit integer values. The register number returned is the
322 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
323 /// of the long value.
324 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000325 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000326 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
327 "Current target doesn't have X86 reg info??");
328 const X86RegisterInfo *MRI =
329 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000330 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000331 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
332 // Create the lower part
333 F->getSSARegMap()->createVirtualRegister(RC);
334 // Create the upper part.
335 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000336 }
337
Chris Lattnerc0812d82002-12-13 06:56:29 +0000338 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000339 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000340 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000341 }
342
Chris Lattner72614082002-10-25 22:55:53 +0000343 /// getReg - This method turns an LLVM value into a register number. This
344 /// is guaranteed to produce the same register number for a particular value
345 /// every time it is queried.
346 ///
347 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000348 unsigned getReg(Value *V) {
349 // Just append to the end of the current bb.
350 MachineBasicBlock::iterator It = BB->end();
351 return getReg(V, BB, It);
352 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000353 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000354 MachineBasicBlock::iterator IPt) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000355 // If this operand is a constant, emit the code to copy the constant into
356 // the register here...
357 //
358 if (Constant *C = dyn_cast<Constant>(V)) {
359 unsigned Reg = makeAnotherReg(V->getType());
360 copyConstantToRegister(MBB, IPt, C, Reg);
361 return Reg;
362 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
363 unsigned Reg = makeAnotherReg(V->getType());
364 // Move the address of the global into the register
365 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
366 return Reg;
367 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
368 // Do not emit noop casts at all.
369 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
370 return getReg(CI->getOperand(0), MBB, IPt);
371 }
372
Chris Lattner72614082002-10-25 22:55:53 +0000373 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000374 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000375 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000376 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000377 }
Chris Lattner72614082002-10-25 22:55:53 +0000378
Chris Lattner72614082002-10-25 22:55:53 +0000379 return Reg;
380 }
Chris Lattner72614082002-10-25 22:55:53 +0000381 };
382}
383
Chris Lattnerc5291f52002-10-27 21:16:59 +0000384/// copyConstantToRegister - Output the instructions required to put the
385/// specified constant into the specified register.
386///
Chris Lattner8a307e82002-12-16 19:32:50 +0000387void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000388 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000389 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000391 unsigned Class = 0;
392 switch (CE->getOpcode()) {
393 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000394 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000395 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000396 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000397 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000398 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000399 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000400
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000401 case Instruction::Xor: ++Class; // FALL THROUGH
402 case Instruction::Or: ++Class; // FALL THROUGH
403 case Instruction::And: ++Class; // FALL THROUGH
404 case Instruction::Sub: ++Class; // FALL THROUGH
405 case Instruction::Add:
406 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
407 Class, R);
408 return;
409
Chris Lattnercadff442003-10-23 17:21:43 +0000410 case Instruction::Mul: {
411 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
412 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
413 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
414 return;
415 }
416 case Instruction::Div:
417 case Instruction::Rem: {
418 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
419 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
420 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
421 CE->getOpcode() == Instruction::Div,
422 CE->getType(), R);
423 return;
424 }
425
Chris Lattner58c41fe2003-08-24 19:19:47 +0000426 case Instruction::SetNE:
427 case Instruction::SetEQ:
428 case Instruction::SetLT:
429 case Instruction::SetGT:
430 case Instruction::SetLE:
431 case Instruction::SetGE:
432 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
433 CE->getOpcode(), R);
434 return;
435
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000436 case Instruction::Shl:
437 case Instruction::Shr:
438 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000439 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
440 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000441
Chris Lattner12d96a02004-03-30 21:22:00 +0000442 case Instruction::Select:
443 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
444 CE->getOperand(2), R);
445 return;
446
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000447 default:
448 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000449 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000450 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000451 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000452
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000453 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000454 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000455
456 if (Class == cLong) {
457 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000458 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000459 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
460 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000461 return;
462 }
463
Chris Lattner94af4142002-12-25 05:13:53 +0000464 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000465
466 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000467 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000468 };
469
Chris Lattner6b993cc2002-12-15 08:02:15 +0000470 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000471 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000472 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000473 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000474 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000475 }
Chris Lattner94af4142002-12-25 05:13:53 +0000476 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000477 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000478 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000479 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000480 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000481 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000482 // Otherwise we need to spill the constant to memory...
483 MachineConstantPool *CP = F->getConstantPool();
484 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000485 const Type *Ty = CFP->getType();
486
487 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000488 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000489 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000490 }
491
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000492 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000493 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000494 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000495 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000496 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000497 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000498 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000499 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000500 }
501}
502
Chris Lattner065faeb2002-12-28 20:24:02 +0000503/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
504/// the stack into virtual registers.
505///
506void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
507 // Emit instructions to load the arguments... On entry to a function on the
508 // X86, the stack frame looks like this:
509 //
510 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000511 // [ESP + 4] -- first argument (leftmost lexically)
512 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000513 // ...
514 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000515 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000516 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000517
518 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000519 bool ArgLive = !I->use_empty();
520 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000521 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000522
Chris Lattner065faeb2002-12-28 20:24:02 +0000523 switch (getClassB(I->getType())) {
524 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000525 if (ArgLive) {
526 FI = MFI->CreateFixedObject(1, ArgOffset);
527 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
528 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000529 break;
530 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000531 if (ArgLive) {
532 FI = MFI->CreateFixedObject(2, ArgOffset);
533 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
534 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000535 break;
536 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000537 if (ArgLive) {
538 FI = MFI->CreateFixedObject(4, ArgOffset);
539 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
540 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000541 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000542 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000543 if (ArgLive) {
544 FI = MFI->CreateFixedObject(8, ArgOffset);
545 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
546 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
547 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000548 ArgOffset += 4; // longs require 4 additional bytes
549 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000550 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000551 if (ArgLive) {
552 unsigned Opcode;
553 if (I->getType() == Type::FloatTy) {
554 Opcode = X86::FLD32m;
555 FI = MFI->CreateFixedObject(4, ArgOffset);
556 } else {
557 Opcode = X86::FLD64m;
558 FI = MFI->CreateFixedObject(8, ArgOffset);
559 }
560 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000561 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000562 if (I->getType() == Type::DoubleTy)
563 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000564 break;
565 default:
566 assert(0 && "Unhandled argument type!");
567 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000568 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000569 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000570
571 // If the function takes variable number of arguments, add a frame offset for
572 // the start of the first vararg value... this is used to expand
573 // llvm.va_start.
574 if (Fn.getFunctionType()->isVarArg())
575 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000576}
577
578
Chris Lattner333b2fa2002-12-13 10:09:43 +0000579/// SelectPHINodes - Insert machine code to generate phis. This is tricky
580/// because we have to generate our sources into the source basic blocks, not
581/// the current one.
582///
583void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000584 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000585 const Function &LF = *F->getFunction(); // The LLVM function...
586 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
587 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000588 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000589
590 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000591 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000592 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000593 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000594
Chris Lattner333b2fa2002-12-13 10:09:43 +0000595 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000596 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000597 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
598 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000599
600 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000601 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
602 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
603 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000604
Chris Lattnera6e73f12003-05-12 14:22:21 +0000605 // PHIValues - Map of blocks to incoming virtual registers. We use this
606 // so that we only initialize one incoming value for a particular block,
607 // even if the block has multiple entries in the PHI node.
608 //
609 std::map<MachineBasicBlock*, unsigned> PHIValues;
610
Chris Lattner333b2fa2002-12-13 10:09:43 +0000611 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
612 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000613 unsigned ValReg;
614 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
615 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000616
Chris Lattnera6e73f12003-05-12 14:22:21 +0000617 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
618 // We already inserted an initialization of the register for this
619 // predecessor. Recycle it.
620 ValReg = EntryIt->second;
621
622 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000623 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000624 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000625 Value *Val = PN->getIncomingValue(i);
626
627 // If this is a constant or GlobalValue, we may have to insert code
628 // into the basic block to compute it into a virtual register.
629 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
Chris Lattner6f2ab042004-03-30 19:10:12 +0000630 if (isa<ConstantExpr>(Val)) {
631 // Because we don't want to clobber any values which might be in
632 // physical registers with the computation of this constant (which
633 // might be arbitrarily complex if it is a constant expression),
634 // just insert the computation at the top of the basic block.
635 MachineBasicBlock::iterator PI = PredMBB->begin();
636
637 // Skip over any PHI nodes though!
638 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
639 ++PI;
640
641 ValReg = getReg(Val, PredMBB, PI);
642 } else {
643 // Simple constants get emitted at the end of the basic block,
644 // before any terminator instructions. We "know" that the code to
645 // move a constant into a register will never clobber any flags.
646 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
647 }
Chris Lattnera81fc682003-10-19 00:26:11 +0000648 } else {
649 ValReg = getReg(Val);
650 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000651
652 // Remember that we inserted a value for this PHI for this predecessor
653 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
654 }
655
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000656 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000657 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000658 if (LongPhiMI) {
659 LongPhiMI->addRegOperand(ValReg+1);
660 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
661 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000662 }
Chris Lattner168aa902004-02-29 07:10:16 +0000663
664 // Now that we emitted all of the incoming values for the PHI node, make
665 // sure to reposition the InsertPoint after the PHI that we just added.
666 // This is needed because we might have inserted a constant into this
667 // block, right after the PHI's which is before the old insert point!
668 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
669 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000670 }
671 }
672}
673
Chris Lattner986618e2004-02-22 19:47:26 +0000674/// RequiresFPRegKill - The floating point stackifier pass cannot insert
675/// compensation code on critical edges. As such, it requires that we kill all
676/// FP registers on the exit from any blocks that either ARE critical edges, or
677/// branch to a block that has incoming critical edges.
678///
679/// Note that this kill instruction will eventually be eliminated when
680/// restrictions in the stackifier are relaxed.
681///
682static bool RequiresFPRegKill(const BasicBlock *BB) {
683#if 0
684 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
685 const BasicBlock *Succ = *SI;
686 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
687 ++PI; // Block have at least one predecessory
688 if (PI != PE) { // If it has exactly one, this isn't crit edge
689 // If this block has more than one predecessor, check all of the
690 // predecessors to see if they have multiple successors. If so, then the
691 // block we are analyzing needs an FPRegKill.
692 for (PI = pred_begin(Succ); PI != PE; ++PI) {
693 const BasicBlock *Pred = *PI;
694 succ_const_iterator SI2 = succ_begin(Pred);
695 ++SI2; // There must be at least one successor of this block.
696 if (SI2 != succ_end(Pred))
697 return true; // Yes, we must insert the kill on this edge.
698 }
699 }
700 }
701 // If we got this far, there is no need to insert the kill instruction.
702 return false;
703#else
704 return true;
705#endif
706}
707
708// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
709// need them. This only occurs due to the floating point stackifier not being
710// aggressive enough to handle arbitrary global stackification.
711//
712// Currently we insert an FP_REG_KILL instruction into each block that uses or
713// defines a floating point virtual register.
714//
715// When the global register allocators (like linear scan) finally update live
716// variable analysis, we can keep floating point values in registers across
717// portions of the CFG that do not involve critical edges. This will be a big
718// win, but we are waiting on the global allocators before we can do this.
719//
720// With a bit of work, the floating point stackifier pass can be enhanced to
721// break critical edges as needed (to make a place to put compensation code),
722// but this will require some infrastructure improvements as well.
723//
724void ISel::InsertFPRegKills() {
725 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000726
727 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000728 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000729 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
730 MachineOperand& MO = I->getOperand(i);
731 if (MO.isRegister() && MO.getReg()) {
732 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000733 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000734 if (RegMap.getRegClass(Reg)->getSize() == 10)
735 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000736 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000737 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000738 // If we haven't found an FP register use or def in this basic block, check
739 // to see if any of our successors has an FP PHI node, which will cause a
740 // copy to be inserted into this block.
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000741 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
742 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
743 MachineBasicBlock *SBB = MBBMap[*SI];
744 for (MachineBasicBlock::iterator I = SBB->begin();
745 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
746 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
747 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000748 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000749 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000750 continue;
751 UsesFPReg:
752 // Okay, this block uses an FP register. If the block has successors (ie,
753 // it's not an unwind/return), insert the FP_REG_KILL instruction.
754 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
755 RequiresFPRegKill(BB->getBasicBlock())) {
Chris Lattneree352852004-02-29 07:22:16 +0000756 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000757 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000758 }
759 }
760}
761
762
Chris Lattner307ecba2004-03-30 22:39:09 +0000763// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
764// it into the conditional branch or select instruction which is the only user
765// of the cc instruction. This is the case if the conditional branch is the
766// only user of the setcc, and if the setcc is in the same basic block as the
767// conditional branch. We also don't handle long arguments below, so we reject
768// them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000769//
Chris Lattner307ecba2004-03-30 22:39:09 +0000770static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000771 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000772 if (SCI->hasOneUse()) {
773 Instruction *User = cast<Instruction>(SCI->use_back());
774 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
775 SCI->getParent() == User->getParent() &&
Chris Lattner48c937e2004-04-06 17:34:50 +0000776 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
777 SCI->getOpcode() == Instruction::SetEQ ||
778 SCI->getOpcode() == Instruction::SetNE))
Chris Lattner6d40c192003-01-16 16:43:00 +0000779 return SCI;
780 }
781 return 0;
782}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000783
Chris Lattner6d40c192003-01-16 16:43:00 +0000784// Return a fixed numbering for setcc instructions which does not depend on the
785// order of the opcodes.
786//
787static unsigned getSetCCNumber(unsigned Opcode) {
788 switch(Opcode) {
789 default: assert(0 && "Unknown setcc instruction!");
790 case Instruction::SetEQ: return 0;
791 case Instruction::SetNE: return 1;
792 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000793 case Instruction::SetGE: return 3;
794 case Instruction::SetGT: return 4;
795 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000796 }
797}
Chris Lattner06925362002-11-17 21:56:38 +0000798
Chris Lattner6d40c192003-01-16 16:43:00 +0000799// LLVM -> X86 signed X86 unsigned
800// ----- ---------- ------------
801// seteq -> sete sete
802// setne -> setne setne
803// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000804// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000805// setgt -> setg seta
806// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000807// ----
808// sets // Used by comparison with 0 optimization
809// setns
810static const unsigned SetCCOpcodeTab[2][8] = {
811 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
812 0, 0 },
813 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
814 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000815};
816
Chris Lattnerb2acc512003-10-19 21:09:10 +0000817// EmitComparison - This function emits a comparison of the two operands,
818// returning the extended setcc code to use.
819unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
820 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000821 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000822 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000823 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000824 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000825 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000826
827 // Special case handling of: cmp R, i
Chris Lattnere80e6372004-04-06 16:02:27 +0000828 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
829 if (Class == cByte || Class == cShort || Class == cInt) {
830 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000831
Chris Lattner333864d2003-06-05 19:30:30 +0000832 // Mask off any upper bits of the constant, if there are any...
833 Op1v &= (1ULL << (8 << Class)) - 1;
834
Chris Lattnerb2acc512003-10-19 21:09:10 +0000835 // If this is a comparison against zero, emit more efficient code. We
836 // can't handle unsigned comparisons against zero unless they are == or
837 // !=. These should have been strength reduced already anyway.
838 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
839 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000840 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000841 };
Chris Lattneree352852004-02-29 07:22:16 +0000842 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000843
844 if (OpNum == 2) return 6; // Map jl -> js
845 if (OpNum == 3) return 7; // Map jg -> jns
846 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000847 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000848
849 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000850 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000851 };
852
Chris Lattneree352852004-02-29 07:22:16 +0000853 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000854 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000855 } else {
856 assert(Class == cLong && "Unknown integer class!");
857 unsigned LowCst = CI->getRawValue();
858 unsigned HiCst = CI->getRawValue() >> 32;
859 if (OpNum < 2) { // seteq, setne
860 unsigned LoTmp = Op0r;
861 if (LowCst != 0) {
862 LoTmp = makeAnotherReg(Type::IntTy);
863 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
864 }
865 unsigned HiTmp = Op0r+1;
866 if (HiCst != 0) {
867 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +0000868 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +0000869 }
870 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
871 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
872 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +0000873 } else {
874 // Emit a sequence of code which compares the high and low parts once
875 // each, then uses a conditional move to handle the overflow case. For
876 // example, a setlt for long would generate code like this:
877 //
878 // AL = lo(op1) < lo(op2) // Signedness depends on operands
879 // BL = hi(op1) < hi(op2) // Always unsigned comparison
880 // dest = hi(op1) == hi(op2) ? AL : BL;
881 //
882
883 // FIXME: This would be much better if we had hierarchical register
884 // classes! Until then, hardcode registers so that we can deal with
885 // their aliases (because we don't have conditional byte moves).
886 //
887 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
888 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
889 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
890 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
891 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
892 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
893 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
894 .addReg(X86::AX);
895 // NOTE: visitSetCondInst knows that the value is dumped into the BL
896 // register at this point for long values...
897 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000898 }
Chris Lattner333864d2003-06-05 19:30:30 +0000899 }
Chris Lattnere80e6372004-04-06 16:02:27 +0000900 }
Chris Lattner333864d2003-06-05 19:30:30 +0000901
Chris Lattner9f08a922004-02-03 18:54:04 +0000902 // Special case handling of comparison against +/- 0.0
903 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
904 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000905 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000906 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000907 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000908 return OpNum;
909 }
910
Chris Lattner58c41fe2003-08-24 19:19:47 +0000911 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000912 switch (Class) {
913 default: assert(0 && "Unknown type class!");
914 // Emit: cmp <var1>, <var2> (do the comparison). We can
915 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
916 // 32-bit.
917 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000918 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000919 break;
920 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000921 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000922 break;
923 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000924 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000925 break;
926 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +0000927 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000928 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000929 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +0000930 break;
931
932 case cLong:
933 if (OpNum < 2) { // seteq, setne
934 unsigned LoTmp = makeAnotherReg(Type::IntTy);
935 unsigned HiTmp = makeAnotherReg(Type::IntTy);
936 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000937 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
938 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
939 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +0000940 break; // Allow the sete or setne to be generated from flags set by OR
941 } else {
942 // Emit a sequence of code which compares the high and low parts once
943 // each, then uses a conditional move to handle the overflow case. For
944 // example, a setlt for long would generate code like this:
945 //
946 // AL = lo(op1) < lo(op2) // Signedness depends on operands
947 // BL = hi(op1) < hi(op2) // Always unsigned comparison
948 // dest = hi(op1) == hi(op2) ? AL : BL;
949 //
950
Chris Lattner6d40c192003-01-16 16:43:00 +0000951 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000952 // classes! Until then, hardcode registers so that we can deal with their
953 // aliases (because we don't have conditional byte moves).
954 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000955 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +0000956 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000957 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +0000958 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
959 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
960 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000961 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +0000962 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000963 // NOTE: visitSetCondInst knows that the value is dumped into the BL
964 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +0000965 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +0000966 }
967 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000968 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +0000969}
Chris Lattner3e130a22003-01-13 00:32:26 +0000970
Chris Lattner6d40c192003-01-16 16:43:00 +0000971/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
972/// register, then move it to wherever the result should be.
973///
974void ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +0000975 if (canFoldSetCCIntoBranchOrSelect(&I))
976 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +0000977
Chris Lattner6d40c192003-01-16 16:43:00 +0000978 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000979 MachineBasicBlock::iterator MII = BB->end();
980 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
981 DestReg);
982}
Chris Lattner6d40c192003-01-16 16:43:00 +0000983
Chris Lattner58c41fe2003-08-24 19:19:47 +0000984/// emitSetCCOperation - Common code shared between visitSetCondInst and
985/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000986///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000987void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000988 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000989 Value *Op0, Value *Op1, unsigned Opcode,
990 unsigned TargetReg) {
991 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000992 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000993
Chris Lattnerb2acc512003-10-19 21:09:10 +0000994 const Type *CompTy = Op0->getType();
995 unsigned CompClass = getClassB(CompTy);
996 bool isSigned = CompTy->isSigned() && CompClass != cFP;
997
998 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000999 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +00001000 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +00001001 } else {
1002 // Handle long comparisons by copying the value which is already in BL into
1003 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001004 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +00001005 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001006}
Chris Lattner51b49a92002-11-02 19:45:49 +00001007
Chris Lattner12d96a02004-03-30 21:22:00 +00001008void ISel::visitSelectInst(SelectInst &SI) {
1009 unsigned DestReg = getReg(SI);
1010 MachineBasicBlock::iterator MII = BB->end();
1011 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1012 SI.getFalseValue(), DestReg);
1013}
1014
1015/// emitSelect - Common code shared between visitSelectInst and the constant
1016/// expression support.
1017void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1018 MachineBasicBlock::iterator IP,
1019 Value *Cond, Value *TrueVal, Value *FalseVal,
1020 unsigned DestReg) {
1021 unsigned SelectClass = getClassB(TrueVal->getType());
1022
1023 // We don't support 8-bit conditional moves. If we have incoming constants,
1024 // transform them into 16-bit constants to avoid having a run-time conversion.
1025 if (SelectClass == cByte) {
1026 if (Constant *T = dyn_cast<Constant>(TrueVal))
1027 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1028 if (Constant *F = dyn_cast<Constant>(FalseVal))
1029 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1030 }
1031
Chris Lattner307ecba2004-03-30 22:39:09 +00001032
1033 unsigned Opcode;
1034 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1035 // We successfully folded the setcc into the select instruction.
1036
1037 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1038 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1039 IP);
1040
1041 const Type *CompTy = SCI->getOperand(0)->getType();
1042 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1043
1044 // LLVM -> X86 signed X86 unsigned
1045 // ----- ---------- ------------
1046 // seteq -> cmovNE cmovNE
1047 // setne -> cmovE cmovE
1048 // setlt -> cmovGE cmovAE
1049 // setge -> cmovL cmovB
1050 // setgt -> cmovLE cmovBE
1051 // setle -> cmovG cmovA
1052 // ----
1053 // cmovNS // Used by comparison with 0 optimization
1054 // cmovS
1055
1056 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001057 default: assert(0 && "Unknown value class!");
1058 case cFP: {
1059 // Annoyingly, we don't have a full set of floating point conditional
1060 // moves. :(
1061 static const unsigned OpcodeTab[2][8] = {
1062 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1063 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1064 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1065 };
1066 Opcode = OpcodeTab[isSigned][OpNum];
1067
1068 // If opcode == 0, we hit a case that we don't support. Output a setcc
1069 // and compare the result against zero.
1070 if (Opcode == 0) {
1071 unsigned CompClass = getClassB(CompTy);
1072 unsigned CondReg;
1073 if (CompClass != cLong || OpNum < 2) {
1074 CondReg = makeAnotherReg(Type::BoolTy);
1075 // Handle normal comparisons with a setcc instruction...
1076 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1077 } else {
1078 // Long comparisons end up in the BL register.
1079 CondReg = X86::BL;
1080 }
1081
Chris Lattner68626c22004-03-31 22:22:36 +00001082 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001083 Opcode = X86::FCMOVE;
1084 }
1085 break;
1086 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001087 case cByte:
1088 case cShort: {
1089 static const unsigned OpcodeTab[2][8] = {
1090 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1091 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1092 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1093 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1094 };
1095 Opcode = OpcodeTab[isSigned][OpNum];
1096 break;
1097 }
1098 case cInt:
1099 case cLong: {
1100 static const unsigned OpcodeTab[2][8] = {
1101 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1102 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1103 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1104 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1105 };
1106 Opcode = OpcodeTab[isSigned][OpNum];
1107 break;
1108 }
1109 }
1110 } else {
1111 // Get the value being branched on, and use it to set the condition codes.
1112 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001113 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001114 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001115 default: assert(0 && "Unknown value class!");
1116 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001117 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001118 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001119 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001120 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001121 }
1122 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001123
1124 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1125 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1126 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001127
Chris Lattner12d96a02004-03-30 21:22:00 +00001128
1129 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1130 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1131 // cmove, then truncate the result.
1132 if (SelectClass == cByte) {
1133 DestReg = makeAnotherReg(Type::ShortTy);
1134 if (getClassB(TrueVal->getType()) == cByte) {
1135 // Promote the true value, by storing it into AL, and reading from AX.
1136 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1137 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1138 TrueReg = makeAnotherReg(Type::ShortTy);
1139 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1140 }
1141 if (getClassB(FalseVal->getType()) == cByte) {
1142 // Promote the true value, by storing it into CL, and reading from CX.
1143 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1144 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1145 FalseReg = makeAnotherReg(Type::ShortTy);
1146 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1147 }
1148 }
1149
1150 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1151
1152 switch (SelectClass) {
1153 case cByte:
1154 // We did the computation with 16-bit registers. Truncate back to our
1155 // result by copying into AX then copying out AL.
1156 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1157 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1158 break;
1159 case cLong:
1160 // Move the upper half of the value as well.
1161 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1162 break;
1163 }
1164}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001165
1166
1167
Brian Gaekec2505982002-11-30 11:57:28 +00001168/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1169/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001170///
Chris Lattner3e130a22003-01-13 00:32:26 +00001171void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1172 bool isUnsigned = VR.Ty->isUnsigned();
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001173
Chris Lattner29bf0622004-04-06 01:21:00 +00001174 Value *Val = VR.Val;
1175 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001176 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001177 if (Constant *C = dyn_cast<Constant>(Val)) {
1178 Val = ConstantExpr::getCast(C, Type::IntTy);
1179 Ty = Type::IntTy;
1180 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001181
Chris Lattner502e36c2004-04-06 01:25:33 +00001182 // If this is a simple constant, just emit a MOVri directly to avoid the
1183 // copy.
1184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1185 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1186 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1187 return;
1188 }
1189 }
1190
Chris Lattner29bf0622004-04-06 01:21:00 +00001191 // Make sure we have the register number for this value...
1192 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1193
1194 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001195 case cByte:
1196 // Extend value into target register (8->32)
1197 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001198 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001199 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001200 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001201 break;
1202 case cShort:
1203 // Extend value into target register (16->32)
1204 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001205 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001206 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001207 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001208 break;
1209 case cInt:
1210 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001211 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001212 break;
1213 default:
1214 assert(0 && "Unpromotable operand class in promote32");
1215 }
Brian Gaekec2505982002-11-30 11:57:28 +00001216}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001217
Chris Lattner72614082002-10-25 22:55:53 +00001218/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1219/// we have the following possibilities:
1220///
1221/// ret void: No return value, simply emit a 'ret' instruction
1222/// ret sbyte, ubyte : Extend value into EAX and return
1223/// ret short, ushort: Extend value into EAX and return
1224/// ret int, uint : Move value into EAX and return
1225/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001226/// ret long, ulong : Move value into EAX/EDX and return
1227/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001228///
Chris Lattner3e130a22003-01-13 00:32:26 +00001229void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001230 if (I.getNumOperands() == 0) {
1231 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1232 return;
1233 }
1234
1235 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001236 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001237 case cByte: // integral return values: extend or move into EAX and return
1238 case cShort:
1239 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001240 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001241 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001242 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001243 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001244 case cFP: { // Floats & Doubles: Return in ST(0)
1245 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001246 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001247 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001248 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001249 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001250 }
1251 case cLong: {
1252 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001253 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1254 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001255 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001256 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1257 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001258 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001259 }
Chris Lattner94af4142002-12-25 05:13:53 +00001260 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001261 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001262 }
Chris Lattner43189d12002-11-17 20:07:45 +00001263 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001264 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001265}
1266
Chris Lattner55f6fab2003-01-16 18:07:23 +00001267// getBlockAfter - Return the basic block which occurs lexically after the
1268// specified one.
1269static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1270 Function::iterator I = BB; ++I; // Get iterator to next block
1271 return I != BB->getParent()->end() ? &*I : 0;
1272}
1273
Chris Lattner51b49a92002-11-02 19:45:49 +00001274/// visitBranchInst - Handle conditional and unconditional branches here. Note
1275/// that since code layout is frozen at this point, that if we are trying to
1276/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001277/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001278///
Chris Lattner94af4142002-12-25 05:13:53 +00001279void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +00001280 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1281
1282 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001283 if (BI.getSuccessor(0) != NextBB)
Chris Lattner55f6fab2003-01-16 18:07:23 +00001284 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +00001285 return;
1286 }
1287
1288 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001289 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001290 if (SCI == 0) {
1291 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1292 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001293 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001294 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001295 if (BI.getSuccessor(1) == NextBB) {
1296 if (BI.getSuccessor(0) != NextBB)
1297 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1298 } else {
1299 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1300
1301 if (BI.getSuccessor(0) != NextBB)
1302 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1303 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001304 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001305 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001306
1307 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001308 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001309 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001310
1311 const Type *CompTy = SCI->getOperand(0)->getType();
1312 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001313
Chris Lattnerb2acc512003-10-19 21:09:10 +00001314
Chris Lattner6d40c192003-01-16 16:43:00 +00001315 // LLVM -> X86 signed X86 unsigned
1316 // ----- ---------- ------------
1317 // seteq -> je je
1318 // setne -> jne jne
1319 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001320 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001321 // setgt -> jg ja
1322 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001323 // ----
1324 // js // Used by comparison with 0 optimization
1325 // jns
1326
1327 static const unsigned OpcodeTab[2][8] = {
1328 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1329 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1330 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001331 };
1332
Chris Lattner55f6fab2003-01-16 18:07:23 +00001333 if (BI.getSuccessor(0) != NextBB) {
1334 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1335 if (BI.getSuccessor(1) != NextBB)
1336 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1337 } else {
1338 // Change to the inverse condition...
1339 if (BI.getSuccessor(1) != NextBB) {
1340 OpNum ^= 1;
1341 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1342 }
1343 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001344}
1345
Chris Lattner3e130a22003-01-13 00:32:26 +00001346
1347/// doCall - This emits an abstract call instruction, setting up the arguments
1348/// and the return value as appropriate. For the actual function call itself,
1349/// it inserts the specified CallMI instruction into the stream.
1350///
1351void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001352 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001353
Chris Lattner065faeb2002-12-28 20:24:02 +00001354 // Count how many bytes are to be pushed on the stack...
1355 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001356
Chris Lattner3e130a22003-01-13 00:32:26 +00001357 if (!Args.empty()) {
1358 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1359 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001360 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001361 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001362 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001363 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001364 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001365 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1366 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001367 default: assert(0 && "Unknown class!");
1368 }
1369
1370 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001371 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001372
1373 // Arguments go on the stack in reverse order, as specified by the ABI.
1374 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001375 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001376 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001377 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001378 case cByte:
Chris Lattner21585222004-03-01 02:42:43 +00001379 case cShort:
1380 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1381 // Zero/Sign extend constant, then stuff into memory.
1382 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1383 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1384 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1385 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1386 } else {
1387 // Promote arg to 32 bits wide into a temporary register...
1388 ArgReg = makeAnotherReg(Type::UIntTy);
1389 promote32(ArgReg, Args[i]);
1390 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1391 X86::ESP, ArgOffset).addReg(ArgReg);
1392 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001393 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001394 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001395 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1396 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1397 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1398 X86::ESP, ArgOffset).addImm(Val);
1399 } else {
1400 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1401 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1402 X86::ESP, ArgOffset).addReg(ArgReg);
1403 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001404 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001405 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001406 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1407 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1408 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1409 X86::ESP, ArgOffset).addImm(Val & ~0U);
1410 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1411 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1412 } else {
1413 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1414 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1415 X86::ESP, ArgOffset).addReg(ArgReg);
1416 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1417 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1418 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001419 ArgOffset += 4; // 8 byte entry, not 4.
1420 break;
1421
Chris Lattner065faeb2002-12-28 20:24:02 +00001422 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001423 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001424 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001425 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001426 X86::ESP, ArgOffset).addReg(ArgReg);
1427 } else {
1428 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001429 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001430 X86::ESP, ArgOffset).addReg(ArgReg);
1431 ArgOffset += 4; // 8 byte entry, not 4.
1432 }
1433 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001434
Chris Lattner3e130a22003-01-13 00:32:26 +00001435 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001436 }
1437 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001438 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001439 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001440 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001441 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001442
Chris Lattner3e130a22003-01-13 00:32:26 +00001443 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001444
Chris Lattneree352852004-02-29 07:22:16 +00001445 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001446
1447 // If there is a return value, scavenge the result from the location the call
1448 // leaves it in...
1449 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001450 if (Ret.Ty != Type::VoidTy) {
1451 unsigned DestClass = getClassB(Ret.Ty);
1452 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001453 case cByte:
1454 case cShort:
1455 case cInt: {
1456 // Integral results are in %eax, or the appropriate portion
1457 // thereof.
1458 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001459 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001460 };
1461 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001462 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001463 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001464 }
Chris Lattner94af4142002-12-25 05:13:53 +00001465 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001466 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001467 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001468 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001469 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1470 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001471 break;
1472 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001473 }
Chris Lattnera3243642002-12-04 23:45:28 +00001474 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001475}
Chris Lattner2df035b2002-11-02 19:27:56 +00001476
Chris Lattner3e130a22003-01-13 00:32:26 +00001477
1478/// visitCallInst - Push args on stack and do a procedure call instruction.
1479void ISel::visitCallInst(CallInst &CI) {
1480 MachineInstr *TheCall;
1481 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001482 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001483 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001484 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1485 return;
1486 }
1487
Chris Lattner3e130a22003-01-13 00:32:26 +00001488 // Emit a CALL instruction with PC-relative displacement.
1489 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1490 } else { // Emit an indirect call...
1491 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001492 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001493 }
1494
1495 std::vector<ValueRecord> Args;
1496 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001497 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001498
1499 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1500 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001501}
Chris Lattner3e130a22003-01-13 00:32:26 +00001502
Chris Lattneraeb54b82003-08-28 21:23:43 +00001503
Chris Lattner44827152003-12-28 09:47:19 +00001504/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1505/// function, lowering any calls to unknown intrinsic functions into the
1506/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001507///
Chris Lattner44827152003-12-28 09:47:19 +00001508void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1509 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1510 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1511 if (CallInst *CI = dyn_cast<CallInst>(I++))
1512 if (Function *F = CI->getCalledFunction())
1513 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001514 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001515 case Intrinsic::vastart:
1516 case Intrinsic::vacopy:
1517 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001518 case Intrinsic::returnaddress:
1519 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001520 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001521 case Intrinsic::memset:
John Criswell4ffff9e2004-04-08 20:31:47 +00001522 case Intrinsic::readport:
1523 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001524 // We directly implement these intrinsics
1525 break;
1526 default:
1527 // All other intrinsic calls we must lower.
1528 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001529 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001530 if (Before) { // Move iterator to instruction after call
1531 I = Before; ++I;
1532 } else {
1533 I = BB->begin();
1534 }
1535 }
1536
1537}
1538
Brian Gaeked0fde302003-11-11 22:41:34 +00001539void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001540 unsigned TmpReg1, TmpReg2;
1541 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001542 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001543 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001544 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001545 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001546 return;
1547
Chris Lattner5634b9f2004-03-13 00:24:52 +00001548 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001549 TmpReg1 = getReg(CI);
1550 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001551 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001552 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001553 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001554
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001555 case Intrinsic::returnaddress:
1556 case Intrinsic::frameaddress:
1557 TmpReg1 = getReg(CI);
1558 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1559 if (ID == Intrinsic::returnaddress) {
1560 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001561 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001562 ReturnAddressIndex);
1563 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001564 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001565 ReturnAddressIndex, -4);
1566 }
1567 } else {
1568 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001569 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001570 }
1571 return;
1572
Chris Lattner915e5e52004-02-12 17:53:22 +00001573 case Intrinsic::memcpy: {
1574 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1575 unsigned Align = 1;
1576 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1577 Align = AlignC->getRawValue();
1578 if (Align == 0) Align = 1;
1579 }
1580
1581 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001582 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001583 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001584 switch (Align & 3) {
1585 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001586 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1587 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1588 } else {
1589 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001590 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001591 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001592 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001593 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001594 break;
1595 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001596 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1597 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1598 } else {
1599 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001600 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001601 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001602 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001603 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001604 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001605 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001606 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001607 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001608 break;
1609 }
1610
1611 // No matter what the alignment is, we put the source in ESI, the
1612 // destination in EDI, and the count in ECX.
1613 TmpReg1 = getReg(CI.getOperand(1));
1614 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001615 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1616 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1617 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001618 BuildMI(BB, Opcode, 0);
1619 return;
1620 }
1621 case Intrinsic::memset: {
1622 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1623 unsigned Align = 1;
1624 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1625 Align = AlignC->getRawValue();
1626 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001627 }
1628
Chris Lattner2a0f2242004-02-14 04:46:05 +00001629 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001630 unsigned CountReg;
1631 unsigned Opcode;
1632 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1633 unsigned Val = ValC->getRawValue() & 255;
1634
1635 // If the value is a constant, then we can potentially use larger copies.
1636 switch (Align & 3) {
1637 case 2: // WORD aligned
1638 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001639 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001640 } else {
1641 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001642 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001643 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001644 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001645 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001646 Opcode = X86::REP_STOSW;
1647 break;
1648 case 0: // DWORD aligned
1649 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001650 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001651 } else {
1652 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001653 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001654 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001655 }
1656 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001657 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001658 Opcode = X86::REP_STOSD;
1659 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001660 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001661 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001662 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001663 Opcode = X86::REP_STOSB;
1664 break;
1665 }
1666 } else {
1667 // If it's not a constant value we are storing, just fall back. We could
1668 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1669 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001670 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001671 CountReg = getReg(CI.getOperand(3));
1672 Opcode = X86::REP_STOSB;
1673 }
1674
1675 // No matter what the alignment is, we put the source in ESI, the
1676 // destination in EDI, and the count in ECX.
1677 TmpReg1 = getReg(CI.getOperand(1));
1678 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001679 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1680 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001681 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001682 return;
1683 }
1684
John Criswell4ffff9e2004-04-08 20:31:47 +00001685 case Intrinsic::readport:
1686 //
1687 // First, determine that the size of the operand falls within the
1688 // acceptable range for this architecture.
1689 //
John Criswellca6ea0f2004-04-08 22:39:13 +00001690 if ((CI.getOperand(1)->getType()->getPrimitiveSize()) != 2) {
1691 std::cerr << "llvm.readport: Address size is not 16 bits\n";
1692 exit (1);
1693 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001694
1695 //
1696 // Now, move the I/O port address into the DX register and use the IN
1697 // instruction to get the input data.
1698 //
1699 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(getReg(CI.getOperand(1)));
1700 switch (CI.getCalledFunction()->getReturnType()->getPrimitiveSize()) {
1701 case 1:
John Criswellca6ea0f2004-04-08 22:39:13 +00001702 BuildMI(BB, X86::IN8, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001703 break;
1704 case 2:
John Criswellca6ea0f2004-04-08 22:39:13 +00001705 BuildMI(BB, X86::IN16, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001706 break;
1707 case 4:
John Criswellca6ea0f2004-04-08 22:39:13 +00001708 BuildMI(BB, X86::IN32, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001709 break;
1710 default:
John Criswellaee0cf32004-04-09 15:10:15 +00001711 std::cerr << "Cannot do input on this data type";
1712 exit (1);
John Criswell4ffff9e2004-04-08 20:31:47 +00001713 }
1714 return;
1715
1716 case Intrinsic::writeport:
1717 //
1718 // First, determine that the size of the operand falls within the
1719 // acceptable range for this architecture.
1720 //
John Criswellca6ea0f2004-04-08 22:39:13 +00001721 //
John Criswell6d804f42004-04-09 19:09:14 +00001722 if ((CI.getOperand(2)->getType()->getPrimitiveSize()) != 2) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001723 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1724 exit (1);
1725 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001726
1727 //
1728 // Now, move the I/O port address into the DX register and the value to
1729 // write into the AL/AX/EAX register.
1730 //
John Criswell6d804f42004-04-09 19:09:14 +00001731 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(getReg(CI.getOperand(2)));
1732 switch (CI.getOperand(1)->getType()->getPrimitiveSize()) {
John Criswell4ffff9e2004-04-08 20:31:47 +00001733 case 1:
John Criswell6d804f42004-04-09 19:09:14 +00001734 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(getReg(CI.getOperand(1)));
John Criswellca6ea0f2004-04-08 22:39:13 +00001735 BuildMI(BB, X86::OUT8, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001736 break;
1737 case 2:
John Criswell6d804f42004-04-09 19:09:14 +00001738 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(getReg(CI.getOperand(1)));
John Criswellca6ea0f2004-04-08 22:39:13 +00001739 BuildMI(BB, X86::OUT16, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001740 break;
1741 case 4:
John Criswell6d804f42004-04-09 19:09:14 +00001742 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(getReg(CI.getOperand(1)));
John Criswellca6ea0f2004-04-08 22:39:13 +00001743 BuildMI(BB, X86::OUT32, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001744 break;
1745 default:
John Criswellaee0cf32004-04-09 15:10:15 +00001746 std::cerr << "Cannot do output on this data type";
1747 exit (1);
John Criswell4ffff9e2004-04-08 20:31:47 +00001748 }
1749 return;
1750
Chris Lattner44827152003-12-28 09:47:19 +00001751 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001752 }
1753}
1754
Chris Lattner7dee5da2004-03-08 01:58:35 +00001755static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1756 if (LI.getParent() != User.getParent())
1757 return false;
1758 BasicBlock::iterator It = &LI;
1759 // Check all of the instructions between the load and the user. We should
1760 // really use alias analysis here, but for now we just do something simple.
1761 for (++It; It != BasicBlock::iterator(&User); ++It) {
1762 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00001763 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00001764 case Instruction::Store:
1765 case Instruction::Call:
1766 case Instruction::Invoke:
1767 return false;
1768 }
1769 }
1770 return true;
1771}
1772
Chris Lattnereca195e2003-05-08 19:44:13 +00001773
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001774/// visitSimpleBinary - Implement simple binary operators for integral types...
1775/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1776/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00001777///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001778void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1779 unsigned DestReg = getReg(B);
1780 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00001781 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1782
Chris Lattner7dee5da2004-03-08 01:58:35 +00001783 // Special case: op Reg, load [mem]
1784 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1785 if (!B.swapOperands())
1786 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1787
1788 unsigned Class = getClassB(B.getType());
1789 if (isa<LoadInst>(Op1) && Class < cFP &&
1790 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1791
1792 static const unsigned OpcodeTab[][3] = {
1793 // Arithmetic operators
1794 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1795 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1796
1797 // Bitwise operators
1798 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1799 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1800 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1801 };
1802
1803 assert(Class < cFP && "General code handles 64-bit integer types!");
1804 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1805
1806 unsigned BaseReg, Scale, IndexReg, Disp;
1807 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1808 Scale, IndexReg, Disp);
1809
1810 unsigned Op0r = getReg(Op0);
1811 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1812 BaseReg, Scale, IndexReg, Disp);
1813 return;
1814 }
1815
Chris Lattner721d2d42004-03-08 01:18:36 +00001816 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001817}
Chris Lattner3e130a22003-01-13 00:32:26 +00001818
Chris Lattnerb2acc512003-10-19 21:09:10 +00001819/// emitSimpleBinaryOperation - Implement simple binary operators for integral
1820/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1821/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00001822///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001823/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1824/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00001825///
1826void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001827 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001828 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001829 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001830 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00001831
1832 // sub 0, X -> neg X
Chris Lattner48b0c972004-04-11 20:26:20 +00001833 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1834 if (OperatorClass == 1 && CI->isNullValue()) {
1835 unsigned op1Reg = getReg(Op1, MBB, IP);
1836 static unsigned const NEGTab[] = {
1837 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
1838 };
1839 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
1840
1841 if (Class == cLong) {
1842 // We just emitted: Dl = neg Sl
1843 // Now emit : T = addc Sh, 0
1844 // : Dh = neg T
1845 unsigned T = makeAnotherReg(Type::IntTy);
1846 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
1847 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001848 }
Chris Lattner48b0c972004-04-11 20:26:20 +00001849 return;
1850 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001851
Chris Lattner48b0c972004-04-11 20:26:20 +00001852 // Special case: op Reg, <const int>
1853 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00001854 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001855
Chris Lattner721d2d42004-03-08 01:18:36 +00001856 // xor X, -1 -> not X
1857 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001858 static unsigned const NOTTab[] = {
1859 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
1860 };
Chris Lattner721d2d42004-03-08 01:18:36 +00001861 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001862 if (Class == cLong) // Invert the top part too
1863 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00001864 return;
1865 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001866
Chris Lattner721d2d42004-03-08 01:18:36 +00001867 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00001868 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
1869 // Note that we can't use dec for 64-bit decrements, because it does not
1870 // set the carry flag!
1871 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00001872 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1873 return;
1874 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001875
Chris Lattner721d2d42004-03-08 01:18:36 +00001876 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00001877 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
1878 // Note that we can't use inc for 64-bit increments, because it does not
1879 // set the carry flag!
1880 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00001881 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00001882 return;
1883 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001884
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001885 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00001886 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001887 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
1888 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00001889
Chris Lattner721d2d42004-03-08 01:18:36 +00001890 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001891 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
1892 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
1893 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00001894 };
1895
Chris Lattner721d2d42004-03-08 01:18:36 +00001896 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00001897 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00001898
Chris Lattner33f7fa32004-04-06 03:15:53 +00001899 if (Class != cLong) {
1900 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
1901 return;
1902 } else {
1903 // If this is a long value and the high or low bits have a special
1904 // property, emit some special cases.
1905 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001906
Chris Lattner33f7fa32004-04-06 03:15:53 +00001907 // If the constant is zero in the low 32-bits, just copy the low part
1908 // across and apply the normal 32-bit operation to the high parts. There
1909 // will be no carry or borrow into the top.
1910 if (Op1l == 0) {
1911 if (OperatorClass != 2) // All but and...
1912 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
1913 else
1914 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
1915 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
1916 .addReg(Op0r+1).addImm(Op1h);
1917 return;
1918 }
1919
1920 // If this is a logical operation and the top 32-bits are zero, just
1921 // operate on the lower 32.
1922 if (Op1h == 0 && OperatorClass > 1) {
1923 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
1924 .addReg(Op0r).addImm(Op1l);
1925 if (OperatorClass != 2) // All but and
1926 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
1927 else
1928 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
1929 return;
1930 }
1931
1932 // TODO: We could handle lots of other special cases here, such as AND'ing
1933 // with 0xFFFFFFFF00000000 -> noop, etc.
1934
1935 // Otherwise, code generate the full operation with a constant.
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001936 static const unsigned TopTab[] = {
1937 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
1938 };
Chris Lattner33f7fa32004-04-06 03:15:53 +00001939
1940 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001941 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
Chris Lattner33f7fa32004-04-06 03:15:53 +00001942 .addReg(Op0r+1).addImm(Op1h);
1943 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001944 }
Chris Lattner721d2d42004-03-08 01:18:36 +00001945 }
1946
Chris Lattner48b0c972004-04-11 20:26:20 +00001947 // Special case: op Reg, <const fp>
1948 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
1949 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
1950 assert(OperatorClass < 2 && "FP operations only support add/sub!");
1951
1952 // Create a constant pool entry for this constant.
1953 MachineConstantPool *CP = F->getConstantPool();
1954 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1955 const Type *Ty = Op1->getType();
1956
1957 static const unsigned OpcodeTab[][2] = {
1958 { X86::FADD32m, X86::FSUB32m }, // Float
1959 { X86::FADD64m, X86::FSUB64m }, // Double
1960 };
1961
1962 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1963 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1964 unsigned Op0r = getReg(Op0, MBB, IP);
1965 addConstantPoolReference(BuildMI(*MBB, IP, Opcode, 5,
1966 DestReg).addReg(Op0r), CPI);
1967 return;
1968 }
1969
1970 // Special case: R1 = sub <const fp>, R2
1971 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1972 if (OperatorClass == 1) { // sub only
1973 if (CFP->isExactlyValue(-0.0)) {
1974 // -0.0 - X === -X
1975 unsigned op1Reg = getReg(Op1, MBB, IP);
1976 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1977 return;
1978 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
1979 // R1 = sub CST, R2 --> R1 = subr R2, CST
1980
1981 // Create a constant pool entry for this constant.
1982 MachineConstantPool *CP = F->getConstantPool();
1983 unsigned CPI = CP->getConstantPoolIndex(CFP);
1984 const Type *Ty = CFP->getType();
1985
1986 static const unsigned OpcodeTab[2] = { X86::FSUBR32m, X86::FSUBR64m };
1987
1988 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
1989 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy];
1990 unsigned Op1r = getReg(Op1, MBB, IP);
1991 addConstantPoolReference(BuildMI(*MBB, IP, Opcode, 5,
1992 DestReg).addReg(Op1r), CPI);
1993 return;
1994 }
1995 }
1996
Chris Lattner721d2d42004-03-08 01:18:36 +00001997 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00001998 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00001999 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002000 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD, X86::ADD32rr },// ADD
2001 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB, X86::SUB32rr },// SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002002
Chris Lattnerb2acc512003-10-19 21:09:10 +00002003 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002004 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2005 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2006 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002007 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002008
Chris Lattnerb2acc512003-10-19 21:09:10 +00002009 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002010 assert(Opcode && "Floating point arguments to logical inst?");
2011 unsigned Op0r = getReg(Op0, MBB, IP);
2012 unsigned Op1r = getReg(Op1, MBB, IP);
2013 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2014
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002015 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002016 static const unsigned TopTab[] = {
2017 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2018 };
2019 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2020 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2021 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002022}
2023
Chris Lattner3e130a22003-01-13 00:32:26 +00002024/// doMultiply - Emit appropriate instructions to multiply together the
2025/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2026/// result should be given as DestTy.
2027///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002028void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00002029 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00002030 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002031 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002032 switch (Class) {
2033 case cFP: // Floating point multiply
Chris Lattneree352852004-02-29 07:22:16 +00002034 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00002035 return;
Chris Lattner0f1c4612003-06-21 17:16:58 +00002036 case cInt:
2037 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002038 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002039 .addReg(op0Reg).addReg(op1Reg);
2040 return;
2041 case cByte:
2042 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002043 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2044 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2045 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002046 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002047 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002048 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002049 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002050}
2051
Chris Lattnerb2acc512003-10-19 21:09:10 +00002052// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2053// returns zero when the input is not exactly a power of two.
2054static unsigned ExactLog2(unsigned Val) {
2055 if (Val == 0) return 0;
2056 unsigned Count = 0;
2057 while (Val != 1) {
2058 if (Val & 1) return 0;
2059 Val >>= 1;
2060 ++Count;
2061 }
2062 return Count+1;
2063}
2064
2065void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002066 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002067 unsigned DestReg, const Type *DestTy,
2068 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002069 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2070 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2071
Chris Lattnerb2acc512003-10-19 21:09:10 +00002072 unsigned Class = getClass(DestTy);
2073
Chris Lattner6ab06d52004-04-06 04:55:43 +00002074 if (ConstRHS == 0) {
2075 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2076 return;
2077 } else if (ConstRHS == 1) {
2078 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2079 return;
2080 }
2081
Chris Lattnerb2acc512003-10-19 21:09:10 +00002082 // If the element size is exactly a power of 2, use a shift to get it.
2083 if (unsigned Shift = ExactLog2(ConstRHS)) {
2084 switch (Class) {
2085 default: assert(0 && "Unknown class for this function!");
2086 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002087 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002088 return;
2089 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002090 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002091 return;
2092 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002093 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002094 return;
2095 }
2096 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002097
2098 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002099 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002100 return;
2101 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002102 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002103 return;
2104 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002105
2106 // Most general case, emit a normal multiply...
Chris Lattnerb2acc512003-10-19 21:09:10 +00002107 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002108 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002109
2110 // Emit a MUL to multiply the register holding the index by
2111 // elementSize, putting the result in OffsetReg.
2112 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2113}
2114
Chris Lattnerca9671d2002-11-02 20:28:58 +00002115/// visitMul - Multiplies are not simple binary operators because they must deal
2116/// with the EAX register explicitly.
2117///
2118void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00002119 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00002120 unsigned DestReg = getReg(I);
2121
2122 // Simple scalar multiply?
Chris Lattner028adc42004-04-06 04:29:36 +00002123 if (getClass(I.getType()) != cLong) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002124 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
2125 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
2126 MachineBasicBlock::iterator MBBI = BB->end();
2127 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
2128 } else {
2129 unsigned Op1Reg = getReg(I.getOperand(1));
2130 MachineBasicBlock::iterator MBBI = BB->end();
2131 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
2132 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002133 } else {
2134 // Long value. We have to do things the hard way...
Chris Lattner028adc42004-04-06 04:29:36 +00002135 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
2136 unsigned CLow = CI->getRawValue();
2137 unsigned CHi = CI->getRawValue() >> 32;
Chris Lattner3e130a22003-01-13 00:32:26 +00002138
Chris Lattner6ab06d52004-04-06 04:55:43 +00002139 if (CLow == 0) {
2140 // If the low part of the constant is all zeros, things are simple.
2141 BuildMI(BB, X86::MOV32ri, 1, DestReg).addImm(0);
2142 doMultiplyConst(BB, BB->end(), DestReg+1, Type::UIntTy, Op0Reg, CHi);
2143 return;
2144 }
2145
Chris Lattner028adc42004-04-06 04:29:36 +00002146 // Multiply the two low parts... capturing carry into EDX
Chris Lattner6ab06d52004-04-06 04:55:43 +00002147 unsigned OverflowReg = 0;
2148 if (CLow == 1) {
2149 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2150 } else {
2151 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2152 OverflowReg = makeAnotherReg(Type::UIntTy);
2153 BuildMI(BB, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2154 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2155 BuildMI(BB, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002156
Chris Lattner6ab06d52004-04-06 04:55:43 +00002157 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2158 BuildMI(BB, X86::MOV32rr, 1,OverflowReg).addReg(X86::EDX);// AL*BL >> 32
2159 }
Chris Lattner028adc42004-04-06 04:29:36 +00002160
2161 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
Chris Lattner6ab06d52004-04-06 04:55:43 +00002162 doMultiplyConst(BB, BB->end(), AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
Chris Lattner028adc42004-04-06 04:29:36 +00002163
Chris Lattner6ab06d52004-04-06 04:55:43 +00002164 unsigned AHBLplusOverflowReg;
2165 if (OverflowReg) {
2166 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2167 BuildMI(BB, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2168 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2169 } else {
2170 AHBLplusOverflowReg = AHBLReg;
2171 }
Chris Lattner028adc42004-04-06 04:29:36 +00002172
Chris Lattner6ab06d52004-04-06 04:55:43 +00002173 if (CHi == 0) {
2174 BuildMI(BB, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2175 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002176 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner6ab06d52004-04-06 04:55:43 +00002177 doMultiplyConst(BB, BB->end(), ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002178
2179 BuildMI(BB, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2180 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattner028adc42004-04-06 04:29:36 +00002181 }
2182 } else {
2183 unsigned Op1Reg = getReg(I.getOperand(1));
2184 // Multiply the two low parts... capturing carry into EDX
2185 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2186 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2187
2188 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2189 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2190 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2191
2192 MachineBasicBlock::iterator MBBI = BB->end();
2193 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2194 BuildMI(*BB, MBBI, X86::IMUL32rr, 2,
2195 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2196
2197 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2198 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2199 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2200
2201 MBBI = BB->end();
2202 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2203 BuildMI(*BB, MBBI, X86::IMUL32rr, 2,
2204 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2205
2206 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2207 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2208 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002209 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002210}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002211
Chris Lattner06925362002-11-17 21:56:38 +00002212
Chris Lattnerf01729e2002-11-02 20:54:46 +00002213/// visitDivRem - Handle division and remainder instructions... these
2214/// instruction both require the same instructions to be generated, they just
2215/// select the result from a different register. Note that both of these
2216/// instructions work differently for signed and unsigned operands.
2217///
2218void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002219 unsigned Op0Reg = getReg(I.getOperand(0));
2220 unsigned Op1Reg = getReg(I.getOperand(1));
2221 unsigned ResultReg = getReg(I);
Chris Lattner94af4142002-12-25 05:13:53 +00002222
Chris Lattnercadff442003-10-23 17:21:43 +00002223 MachineBasicBlock::iterator IP = BB->end();
2224 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
2225 I.getType(), ResultReg);
2226}
2227
2228void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002229 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +00002230 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
2231 const Type *Ty, unsigned ResultReg) {
2232 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002233 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002234 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002235 if (isDiv) {
Chris Lattneree352852004-02-29 07:22:16 +00002236 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002237 } else { // Floating point remainder...
Chris Lattner3e130a22003-01-13 00:32:26 +00002238 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002239 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002240 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002241 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2242 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002243 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2244 }
Chris Lattner94af4142002-12-25 05:13:53 +00002245 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002246 case cLong: {
2247 static const char *FnName[] =
2248 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2249
Chris Lattnercadff442003-10-23 17:21:43 +00002250 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002251 MachineInstr *TheCall =
2252 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2253
2254 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002255 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2256 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002257 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2258 return;
2259 }
2260 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002261 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002262 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002263 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002264
2265 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002266 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2267 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2268 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002269 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2270
2271 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002272 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2273 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002274 };
2275
Chris Lattnercadff442003-10-23 17:21:43 +00002276 bool isSigned = Ty->isSigned();
Chris Lattnerf01729e2002-11-02 20:54:46 +00002277 unsigned Reg = Regs[Class];
2278 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002279
2280 // Put the first operand into one of the A registers...
Chris Lattneree352852004-02-29 07:22:16 +00002281 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002282
2283 if (isSigned) {
2284 // Emit a sign extension instruction...
Chris Lattnercadff442003-10-23 17:21:43 +00002285 unsigned ShiftResult = makeAnotherReg(Ty);
Chris Lattneree352852004-02-29 07:22:16 +00002286 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2287 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002288 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002289 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002290 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002291 }
2292
Chris Lattner06925362002-11-17 21:56:38 +00002293 // Emit the appropriate divide or remainder instruction...
Chris Lattneree352852004-02-29 07:22:16 +00002294 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00002295
Chris Lattnerf01729e2002-11-02 20:54:46 +00002296 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002297 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002298
Chris Lattnerf01729e2002-11-02 20:54:46 +00002299 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002300 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002301}
Chris Lattnere2954c82002-11-02 20:04:26 +00002302
Chris Lattner06925362002-11-17 21:56:38 +00002303
Brian Gaekea1719c92002-10-31 23:03:59 +00002304/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2305/// for constant immediate shift values, and for constant immediate
2306/// shift values equal to 1. Even the general case is sort of special,
2307/// because the shift amount has to be in CL, not just any old register.
2308///
Chris Lattner3e130a22003-01-13 00:32:26 +00002309void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002310 MachineBasicBlock::iterator IP = BB->end ();
2311 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2312 I.getOpcode () == Instruction::Shl, I.getType (),
2313 getReg (I));
2314}
2315
2316/// emitShiftOperation - Common code shared between visitShiftInst and
2317/// constant expression support.
2318void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002319 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002320 Value *Op, Value *ShiftAmount, bool isLeftShift,
2321 const Type *ResultTy, unsigned DestReg) {
2322 unsigned SrcReg = getReg (Op, MBB, IP);
2323 bool isSigned = ResultTy->isSigned ();
2324 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002325
2326 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002327 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2328 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2329 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2330 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002331 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002332
Chris Lattner3e130a22003-01-13 00:32:26 +00002333 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002334 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2335 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2336 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2337 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002338 };
Chris Lattner796df732002-11-02 00:44:25 +00002339
Chris Lattner3e130a22003-01-13 00:32:26 +00002340 // Longs, as usual, are handled specially...
2341 if (Class == cLong) {
2342 // If we have a constant shift, we can generate much more efficient code
2343 // than otherwise...
2344 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002345 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002346 unsigned Amount = CUI->getValue();
2347 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002348 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2349 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00002350 BuildMI(*MBB, IP, Opc[3], 3,
2351 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2352 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002353 } else {
Chris Lattneree352852004-02-29 07:22:16 +00002354 BuildMI(*MBB, IP, Opc[3], 3,
2355 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2356 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002357 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002358 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002359 Amount -= 32;
2360 if (isLeftShift) {
Chris Lattner722070e2004-04-06 03:42:38 +00002361 if (Amount != 0) {
2362 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2363 DestReg + 1).addReg(SrcReg).addImm(Amount);
2364 } else {
2365 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2366 }
2367 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002368 } else {
Chris Lattner722070e2004-04-06 03:42:38 +00002369 if (Amount != 0) {
2370 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2371 DestReg).addReg(SrcReg+1).addImm(Amount);
2372 } else {
2373 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2374 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002375 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002376 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002377 }
2378 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00002379 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2380
2381 if (!isLeftShift && isSigned) {
2382 // If this is a SHR of a Long, then we need to do funny sign extension
2383 // stuff. TmpReg gets the value to use as the high-part if we are
2384 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002385 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00002386 } else {
2387 // Other shifts use a fixed zero value if the shift is more than 32
2388 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002389 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00002390 }
2391
2392 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002393 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002394 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002395
2396 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2397 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2398 if (isLeftShift) {
2399 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002400 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00002401 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002402 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002403 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002404
2405 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002406 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002407
2408 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002409 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002410 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2411 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002412 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002413 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002414 } else {
2415 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002416 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00002417 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00002418 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002419 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00002420 .addReg(SrcReg+1);
2421
2422 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002423 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002424
2425 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002426 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002427 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2428
2429 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002430 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002431 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2432 }
Brian Gaekea1719c92002-10-31 23:03:59 +00002433 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002434 return;
2435 }
Chris Lattnere9913f22002-11-02 01:41:55 +00002436
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002437 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002438 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2439 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002440
Chris Lattner3e130a22003-01-13 00:32:26 +00002441 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002442 BuildMI(*MBB, IP, Opc[Class], 2,
2443 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00002444 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002445 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002446 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002447
Chris Lattner3e130a22003-01-13 00:32:26 +00002448 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002449 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002450 }
2451}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002452
Chris Lattner3e130a22003-01-13 00:32:26 +00002453
Chris Lattner721d2d42004-03-08 01:18:36 +00002454void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2455 unsigned &IndexReg, unsigned &Disp) {
2456 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2457 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2458 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2459 BaseReg, Scale, IndexReg, Disp))
2460 return;
2461 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2462 if (CE->getOpcode() == Instruction::GetElementPtr)
2463 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2464 BaseReg, Scale, IndexReg, Disp))
2465 return;
2466 }
2467
2468 // If it's not foldable, reset addr mode.
2469 BaseReg = getReg(Addr);
2470 Scale = 1; IndexReg = 0; Disp = 0;
2471}
2472
2473
Chris Lattner6fc3c522002-11-17 21:11:55 +00002474/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00002475/// instruction. The load and store instructions are the only place where we
2476/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00002477///
2478void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002479 // Check to see if this load instruction is going to be folded into a binary
2480 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2481 // pattern matching instruction selector be nice?
2482 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
2483 Instruction *User = cast<Instruction>(I.use_back());
2484 switch (User->getOpcode()) {
2485 default: User = 0; break;
2486 case Instruction::Add:
2487 case Instruction::Sub:
2488 case Instruction::And:
2489 case Instruction::Or:
2490 case Instruction::Xor:
2491 break;
2492 }
2493
2494 if (User) {
2495 // Okay, we found a user. If the load is the first operand and there is
2496 // no second operand load, reverse the operand ordering. Note that this
2497 // can fail for a subtract (ie, no change will be made).
2498 if (!isa<LoadInst>(User->getOperand(1)))
2499 cast<BinaryOperator>(User)->swapOperands();
2500
2501 // Okay, now that everything is set up, if this load is used by the second
2502 // operand, and if there are no instructions that invalidate the load
2503 // before the binary operator, eliminate the load.
2504 if (User->getOperand(1) == &I &&
2505 isSafeToFoldLoadIntoInstruction(I, *User))
2506 return; // Eliminate the load!
2507 }
2508 }
2509
Chris Lattner94af4142002-12-25 05:13:53 +00002510 unsigned DestReg = getReg(I);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002511 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
Chris Lattner721d2d42004-03-08 01:18:36 +00002512 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
Chris Lattnere8f0d922002-12-24 00:03:11 +00002513
Brian Gaekebfedb912003-07-17 21:30:06 +00002514 unsigned Class = getClassB(I.getType());
Chris Lattner6ac1d712003-10-20 04:48:06 +00002515 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002516 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002517 BaseReg, Scale, IndexReg, Disp);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002518 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002519 BaseReg, Scale, IndexReg, Disp+4);
Chris Lattner94af4142002-12-25 05:13:53 +00002520 return;
2521 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002522
Chris Lattner6ac1d712003-10-20 04:48:06 +00002523 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002524 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
Chris Lattner3e130a22003-01-13 00:32:26 +00002525 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00002526 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002527 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002528 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2529 BaseReg, Scale, IndexReg, Disp);
Chris Lattner3e130a22003-01-13 00:32:26 +00002530}
2531
Chris Lattner6fc3c522002-11-17 21:11:55 +00002532/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2533/// instruction.
2534///
2535void ISel::visitStoreInst(StoreInst &I) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002536 unsigned BaseReg, Scale, IndexReg, Disp;
2537 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002538
Chris Lattner6c09db22003-10-20 04:11:23 +00002539 const Type *ValTy = I.getOperand(0)->getType();
2540 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00002541
Chris Lattner5a830962004-02-25 02:56:58 +00002542 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2543 uint64_t Val = CI->getRawValue();
2544 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002545 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002546 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002547 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002548 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00002549 } else {
2550 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002551 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00002552 };
2553 unsigned Opcode = Opcodes[Class];
Chris Lattnerb6bac512004-02-25 06:13:04 +00002554 addFullAddress(BuildMI(BB, Opcode, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002555 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00002556 }
2557 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002558 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002559 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattner5a830962004-02-25 02:56:58 +00002560 } else {
2561 if (Class == cLong) {
2562 unsigned ValReg = getReg(I.getOperand(0));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002563 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002564 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002565 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002566 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
Chris Lattner5a830962004-02-25 02:56:58 +00002567 } else {
2568 unsigned ValReg = getReg(I.getOperand(0));
2569 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002570 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
Chris Lattner5a830962004-02-25 02:56:58 +00002571 };
2572 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002573 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002574 addFullAddress(BuildMI(BB, Opcode, 1+4),
2575 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner5a830962004-02-25 02:56:58 +00002576 }
Chris Lattner94af4142002-12-25 05:13:53 +00002577 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002578}
2579
2580
Misha Brukman538607f2004-03-01 23:53:11 +00002581/// visitCastInst - Here we have various kinds of copying with or without sign
2582/// extension going on.
2583///
Chris Lattner3e130a22003-01-13 00:32:26 +00002584void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002585 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00002586
2587 // Noop casts are not even emitted.
2588 if (getClassB(CI.getType()) == getClassB(Op->getType()))
2589 return;
2590
Chris Lattnerf5854472003-06-21 16:01:24 +00002591 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2592 // of the case are GEP instructions, then the cast does not need to be
2593 // generated explicitly, it will be folded into the GEP.
2594 if (CI.getType() == Type::LongTy &&
2595 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2596 bool AllUsesAreGEPs = true;
2597 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2598 if (!isa<GetElementPtrInst>(*I)) {
2599 AllUsesAreGEPs = false;
2600 break;
2601 }
2602
2603 // No need to codegen this cast if all users are getelementptr instrs...
2604 if (AllUsesAreGEPs) return;
2605 }
2606
Chris Lattner548f61d2003-04-23 17:22:12 +00002607 unsigned DestReg = getReg(CI);
2608 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00002609 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00002610}
2611
Misha Brukman538607f2004-03-01 23:53:11 +00002612/// emitCastOperation - Common code shared between visitCastInst and constant
2613/// expression cast support.
2614///
Chris Lattner548f61d2003-04-23 17:22:12 +00002615void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002616 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00002617 Value *Src, const Type *DestTy,
2618 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00002619 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002620 const Type *SrcTy = Src->getType();
2621 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002622 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00002623
Chris Lattner3e130a22003-01-13 00:32:26 +00002624 // Implement casts to bool by using compare on the operand followed by set if
2625 // not zero on the result.
2626 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00002627 switch (SrcClass) {
2628 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002629 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002630 break;
2631 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002632 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002633 break;
2634 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002635 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002636 break;
2637 case cLong: {
2638 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002639 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00002640 break;
2641 }
2642 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00002643 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002644 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00002645 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00002646 break;
Chris Lattner20772542003-06-01 03:38:24 +00002647 }
2648
2649 // If the zero flag is not set, then the value is true, set the byte to
2650 // true.
Chris Lattneree352852004-02-29 07:22:16 +00002651 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00002652 return;
2653 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002654
2655 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002656 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00002657 };
2658
2659 // Implement casts between values of the same type class (as determined by
2660 // getClass) by using a register-to-register move.
2661 if (SrcClass == DestClass) {
2662 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00002663 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002664 } else if (SrcClass == cFP) {
2665 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002666 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00002667 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002668 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002669 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2670 "Unknown cFP member!");
2671 // Truncate from double to float by storing to memory as short, then
2672 // reading it back.
2673 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00002674 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002675 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2676 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002677 }
2678 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002679 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2680 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002681 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00002682 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002683 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00002684 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002685 return;
2686 }
2687
2688 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2689 // or zero extension, depending on whether the source type was signed.
2690 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2691 SrcClass < DestClass) {
2692 bool isLong = DestClass == cLong;
2693 if (isLong) DestClass = cInt;
2694
2695 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002696 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2697 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00002698 };
2699
2700 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattneree352852004-02-29 07:22:16 +00002701 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00002702 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002703
2704 if (isLong) { // Handle upper 32 bits as appropriate...
2705 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002706 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00002707 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002708 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00002709 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002710 return;
2711 }
2712
2713 // Special case long -> int ...
2714 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002715 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002716 return;
2717 }
2718
2719 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2720 // move out of AX or AL.
2721 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2722 && SrcClass > DestClass) {
2723 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00002724 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2725 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00002726 return;
2727 }
2728
2729 // Handle casts from integer to floating point now...
2730 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002731 // Promote the integer to a type supported by FLD. We do this because there
2732 // are no unsigned FLD instructions, so we must promote an unsigned value to
2733 // a larger signed value, then use FLD on the larger value.
2734 //
2735 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00002736 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002737 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002738 switch (SrcTy->getPrimitiveID()) {
2739 case Type::BoolTyID:
2740 case Type::SByteTyID:
2741 // We don't have the facilities for directly loading byte sized data from
2742 // memory (even signed). Promote it to 16 bits.
2743 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002744 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002745 break;
2746 case Type::UByteTyID:
2747 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002748 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002749 break;
2750 case Type::UShortTyID:
2751 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002752 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002753 break;
2754 case Type::UIntTyID: {
2755 // Make a 64 bit temporary... and zero out the top of it...
2756 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002757 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2758 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002759 SrcTy = Type::LongTy;
2760 SrcClass = cLong;
2761 SrcReg = TmpReg;
2762 break;
2763 }
2764 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002765 // Don't fild into the read destination.
2766 DestReg = makeAnotherReg(Type::DoubleTy);
2767 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002768 default: // No promotion needed...
2769 break;
2770 }
2771
2772 if (PromoteType) {
2773 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00002774 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002775 SrcTy = PromoteType;
2776 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00002777 SrcReg = TmpReg;
2778 }
2779
2780 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002781 int FrameIdx =
2782 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00002783
2784 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002785 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002786 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002787 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002788 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002789 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002790 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00002791 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2792 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002793 }
2794
2795 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002796 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00002797 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002798
2799 // We need special handling for unsigned 64-bit integer sources. If the
2800 // input number has the "sign bit" set, then we loaded it incorrectly as a
2801 // negative 64-bit number. In this case, add an offset value.
2802 if (SrcTy == Type::ULongTy) {
2803 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002804 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002805
Chris Lattnerb6bac512004-02-25 06:13:04 +00002806 // If the sign bit is set, get a pointer to an offset, otherwise get a
2807 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002808 MachineConstantPool *CP = F->getConstantPool();
2809 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002810 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002811 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002812 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002813 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002814 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2815
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002816 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002817 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002818 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002819 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002820
2821 // Load the constant for an add. FIXME: this could make an 'fadd' that
2822 // reads directly from memory, but we don't support these yet.
2823 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002824 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002825
Chris Lattneree352852004-02-29 07:22:16 +00002826 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2827 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002828 }
2829
Chris Lattner3e130a22003-01-13 00:32:26 +00002830 return;
2831 }
2832
2833 // Handle casts from floating point to integer now...
2834 if (SrcClass == cFP) {
2835 // Change the floating point control register to use "round towards zero"
2836 // mode when truncating to an integer value.
2837 //
2838 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002839 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002840
2841 // Load the old value of the high byte of the control word...
2842 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002843 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00002844 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002845
2846 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002847 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002848 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00002849
2850 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002851 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002852
2853 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002854 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002855 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00002856
2857 // We don't have the facilities for directly storing byte sized data to
2858 // memory. Promote it to 16 bits. We also must promote unsigned values to
2859 // larger classes because we only have signed FP stores.
2860 unsigned StoreClass = DestClass;
2861 const Type *StoreTy = DestTy;
2862 if (StoreClass == cByte || DestTy->isUnsigned())
2863 switch (StoreClass) {
2864 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2865 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2866 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00002867 // The following treatment of cLong may not be perfectly right,
2868 // but it survives chains of casts of the form
2869 // double->ulong->double.
2870 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00002871 default: assert(0 && "Unknown store class!");
2872 }
2873
2874 // Spill the integer to memory and reload it from there...
2875 int FrameIdx =
2876 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2877
2878 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002879 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00002880 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2881 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002882
2883 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002884 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2885 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00002886 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00002887 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002888 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00002889 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002890 }
2891
2892 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002893 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002894 return;
2895 }
2896
Brian Gaeked474e9c2002-12-06 10:49:33 +00002897 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00002898 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002899 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00002900}
Brian Gaekea1719c92002-10-31 23:03:59 +00002901
Chris Lattner73815062003-10-18 05:56:40 +00002902/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00002903///
Chris Lattner73815062003-10-18 05:56:40 +00002904void ISel::visitVANextInst(VANextInst &I) {
2905 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00002906 unsigned DestReg = getReg(I);
2907
Chris Lattnereca195e2003-05-08 19:44:13 +00002908 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00002909 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00002910 default:
2911 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00002912 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002913 return;
2914 case Type::PointerTyID:
2915 case Type::UIntTyID:
2916 case Type::IntTyID:
2917 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00002918 break;
2919 case Type::ULongTyID:
2920 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00002921 case Type::DoubleTyID:
2922 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00002923 break;
2924 }
2925
2926 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002927 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00002928}
Chris Lattnereca195e2003-05-08 19:44:13 +00002929
Chris Lattner73815062003-10-18 05:56:40 +00002930void ISel::visitVAArgInst(VAArgInst &I) {
2931 unsigned VAList = getReg(I.getOperand(0));
2932 unsigned DestReg = getReg(I);
2933
2934 switch (I.getType()->getPrimitiveID()) {
2935 default:
2936 std::cerr << I;
2937 assert(0 && "Error: bad type for va_next instruction!");
2938 return;
2939 case Type::PointerTyID:
2940 case Type::UIntTyID:
2941 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002942 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002943 break;
2944 case Type::ULongTyID:
2945 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002946 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2947 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00002948 break;
2949 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002950 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002951 break;
2952 }
Chris Lattnereca195e2003-05-08 19:44:13 +00002953}
2954
Misha Brukman538607f2004-03-01 23:53:11 +00002955/// visitGetElementPtrInst - instruction-select GEP instructions
2956///
Chris Lattner3e130a22003-01-13 00:32:26 +00002957void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00002958 // If this GEP instruction will be folded into all of its users, we don't need
2959 // to explicitly calculate it!
2960 unsigned A, B, C, D;
2961 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2962 // Check all of the users of the instruction to see if they are loads and
2963 // stores.
2964 bool AllWillFold = true;
2965 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2966 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2967 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2968 cast<Instruction>(*UI)->getOperand(0) == &I) {
2969 AllWillFold = false;
2970 break;
2971 }
2972
2973 // If the instruction is foldable, and will be folded into all users, don't
2974 // emit it!
2975 if (AllWillFold) return;
2976 }
2977
Chris Lattner3e130a22003-01-13 00:32:26 +00002978 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00002979 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00002980 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00002981}
2982
Chris Lattner985fe3d2004-02-25 03:45:50 +00002983/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2984/// GEPTypes (the derived types being stepped through at each level). On return
2985/// from this function, if some indexes of the instruction are representable as
2986/// an X86 lea instruction, the machine operands are put into the Ops
2987/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2988/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2989/// addressing mode that only partially consumes the input, the BaseReg input of
2990/// the addressing mode must be left free.
2991///
2992/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2993///
Chris Lattnerb6bac512004-02-25 06:13:04 +00002994void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2995 std::vector<Value*> &GEPOps,
2996 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2997 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2998 const TargetData &TD = TM.getTargetData();
2999
Chris Lattner985fe3d2004-02-25 03:45:50 +00003000 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003001 BaseReg = 0; // No base register
3002 Scale = 1; // Unit scale
3003 IndexReg = 0; // No index register
3004 Disp = 0; // No displacement
3005
Chris Lattner985fe3d2004-02-25 03:45:50 +00003006 // While there are GEP indexes that can be folded into the current address,
3007 // keep processing them.
3008 while (!GEPTypes.empty()) {
3009 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3010 // It's a struct access. CUI is the index into the structure,
3011 // which names the field. This index must have unsigned type.
3012 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3013
3014 // Use the TargetData structure to pick out what the layout of the
3015 // structure is in memory. Since the structure index must be constant, we
3016 // can get its value and use it to find the right byte offset from the
3017 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003018 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003019 GEPOps.pop_back(); // Consume a GEP operand
3020 GEPTypes.pop_back();
3021 } else {
3022 // It's an array or pointer access: [ArraySize x ElementType].
3023 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3024 Value *idx = GEPOps.back();
3025
3026 // idx is the index into the array. Unlike with structure
3027 // indices, we may not know its actual value at code-generation
3028 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003029
3030 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003031 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003032 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003033 Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003034 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3035 Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003036 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003037 // If the index reg is already taken, we can't handle this index.
3038 if (IndexReg) return;
3039
3040 // If this is a size that we can handle, then add the index as
3041 switch (TypeSize) {
3042 case 1: case 2: case 4: case 8:
3043 // These are all acceptable scales on X86.
3044 Scale = TypeSize;
3045 break;
3046 default:
3047 // Otherwise, we can't handle this scale
3048 return;
3049 }
3050
3051 if (CastInst *CI = dyn_cast<CastInst>(idx))
3052 if (CI->getOperand(0)->getType() == Type::IntTy ||
3053 CI->getOperand(0)->getType() == Type::UIntTy)
3054 idx = CI->getOperand(0);
3055
3056 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003057 }
3058
3059 GEPOps.pop_back(); // Consume a GEP operand
3060 GEPTypes.pop_back();
3061 }
3062 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003063
3064 // GEPTypes is empty, which means we have a single operand left. See if we
3065 // can set it as the base register.
3066 //
3067 // FIXME: When addressing modes are more powerful/correct, we could load
3068 // global addresses directly as 32-bit immediates.
3069 assert(BaseReg == 0);
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003070 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003071 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003072}
3073
3074
Chris Lattnerb6bac512004-02-25 06:13:04 +00003075/// isGEPFoldable - Return true if the specified GEP can be completely
3076/// folded into the addressing mode of a load/store or lea instruction.
3077bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3078 Value *Src, User::op_iterator IdxBegin,
3079 User::op_iterator IdxEnd, unsigned &BaseReg,
3080 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003081 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3082 Src = CPR->getValue();
3083
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003084 std::vector<Value*> GEPOps;
3085 GEPOps.resize(IdxEnd-IdxBegin+1);
3086 GEPOps[0] = Src;
3087 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3088
3089 std::vector<const Type*> GEPTypes;
3090 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3091 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3092
Chris Lattnerb6bac512004-02-25 06:13:04 +00003093 MachineBasicBlock::iterator IP;
3094 if (MBB) IP = MBB->end();
3095 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3096
3097 // We can fold it away iff the getGEPIndex call eliminated all operands.
3098 return GEPOps.empty();
3099}
3100
3101void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3102 MachineBasicBlock::iterator IP,
3103 Value *Src, User::op_iterator IdxBegin,
3104 User::op_iterator IdxEnd, unsigned TargetReg) {
3105 const TargetData &TD = TM.getTargetData();
3106 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3107 Src = CPR->getValue();
3108
3109 std::vector<Value*> GEPOps;
3110 GEPOps.resize(IdxEnd-IdxBegin+1);
3111 GEPOps[0] = Src;
3112 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3113
3114 std::vector<const Type*> GEPTypes;
3115 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3116 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003117
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003118 // Keep emitting instructions until we consume the entire GEP instruction.
3119 while (!GEPOps.empty()) {
3120 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003121 unsigned BaseReg, Scale, IndexReg, Disp;
3122 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003123
Chris Lattner985fe3d2004-02-25 03:45:50 +00003124 if (GEPOps.size() != OldSize) {
3125 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003126 unsigned NextTarget = 0;
3127 if (!GEPOps.empty()) {
3128 assert(BaseReg == 0 &&
3129 "getGEPIndex should have left the base register open for chaining!");
3130 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003131 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003132
3133 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003134 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003135 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003136 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003137 BaseReg, Scale, IndexReg, Disp);
3138 --IP;
3139 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003140 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003141 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3142 // all operands are consumed but the base pointer. If so, just load it
3143 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003144 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003145 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003146 } else {
3147 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003148 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003149 }
3150 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003151
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003152 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003153 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003154 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3155 Value *idx = GEPOps.back();
3156 GEPOps.pop_back(); // Consume a GEP operand
3157 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003158
Chris Lattner28977af2004-04-05 01:30:19 +00003159 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003160 // operand on X86. Handle this case directly now...
3161 if (CastInst *CI = dyn_cast<CastInst>(idx))
3162 if (CI->getOperand(0)->getType() == Type::IntTy ||
3163 CI->getOperand(0)->getType() == Type::UIntTy)
3164 idx = CI->getOperand(0);
3165
Chris Lattner3e130a22003-01-13 00:32:26 +00003166 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003167 // must find the size of the pointed-to type (Not coincidentally, the next
3168 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003169 const Type *ElTy = SqTy->getElementType();
3170 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003171
3172 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003173 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003174 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003175 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003176 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003177 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003178 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003179 --IP; // Insert the next instruction before this one.
3180 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003181 }
3182 } else if (elementSize == 1) {
3183 // If the element size is 1, we don't have to multiply, just add
3184 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003185 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003186 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003187 --IP; // Insert the next instruction before this one.
3188 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003189 } else {
3190 unsigned idxReg = getReg(idx, MBB, IP);
3191 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003192
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003193 // Make sure we can back the iterator up to point to the first
3194 // instruction emitted.
3195 MachineBasicBlock::iterator BeforeIt = IP;
3196 if (IP == MBB->begin())
3197 BeforeIt = MBB->end();
3198 else
3199 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00003200 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3201
Chris Lattner8a307e82002-12-16 19:32:50 +00003202 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003203 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003204 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003205 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003206
3207 // Step to the first instruction of the multiply.
3208 if (BeforeIt == MBB->end())
3209 IP = MBB->begin();
3210 else
3211 IP = ++BeforeIt;
3212
3213 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003214 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003215 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003216 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003217}
3218
3219
Chris Lattner065faeb2002-12-28 20:24:02 +00003220/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3221/// frame manager, otherwise do it the hard way.
3222///
3223void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00003224 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00003225 const Type *Ty = I.getAllocatedType();
3226 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3227
3228 // If this is a fixed size alloca in the entry block for the function,
3229 // statically stack allocate the space.
3230 //
3231 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
3232 if (I.getParent() == I.getParent()->getParent()->begin()) {
3233 TySize *= CUI->getValue(); // Get total allocated size...
3234 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
3235
3236 // Create a new stack object using the frame manager...
3237 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003238 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
Chris Lattner065faeb2002-12-28 20:24:02 +00003239 return;
3240 }
3241 }
3242
3243 // Create a register to hold the temporary result of multiplying the type size
3244 // constant by the variable amount.
3245 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3246 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00003247
3248 // TotalSizeReg = mul <numelements>, <TypeSize>
3249 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003250 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003251
3252 // AddedSize = add <TotalSizeReg>, 15
3253 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003254 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003255
3256 // AlignedSize = and <AddedSize>, ~15
3257 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003258 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003259
Brian Gaekee48ec012002-12-13 06:46:31 +00003260 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003261 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003262
Brian Gaekee48ec012002-12-13 06:46:31 +00003263 // Put a pointer to the space into the result register, by copying
3264 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003265 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00003266
Misha Brukman48196b32003-05-03 02:18:17 +00003267 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00003268 // object.
3269 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00003270}
Chris Lattner3e130a22003-01-13 00:32:26 +00003271
3272/// visitMallocInst - Malloc instructions are code generated into direct calls
3273/// to the library malloc.
3274///
3275void ISel::visitMallocInst(MallocInst &I) {
3276 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3277 unsigned Arg;
3278
3279 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3280 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3281 } else {
3282 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003283 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00003284 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003285 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00003286 }
3287
3288 std::vector<ValueRecord> Args;
3289 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3290 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003291 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003292 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3293}
3294
3295
3296/// visitFreeInst - Free instructions are code gen'd to call the free libc
3297/// function.
3298///
3299void ISel::visitFreeInst(FreeInst &I) {
3300 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00003301 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00003302 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003303 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003304 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3305}
3306
Chris Lattnerd281de22003-07-26 23:49:58 +00003307/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00003308/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00003309/// generated code sucks but the implementation is nice and simple.
3310///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00003311FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3312 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00003313}