blob: 48546aa54f0083e8f15312f3defd243b00d44f10 [file] [log] [blame]
Misha Brukman91b5ca82004-07-26 18:45:48 +00001//===-- X86ISelSimple.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"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000021#include "llvm/Pass.h"
Chris Lattner30483732004-06-20 07:49:54 +000022#include "llvm/CodeGen/IntrinsicLowering.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000023#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"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner986618e2004-02-22 19:47:26 +000034namespace {
35 Statistic<>
36 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
Chris Lattner427aeb42004-04-11 19:21:59 +000037
38 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
39 /// Representation.
40 ///
41 enum TypeClass {
42 cByte, cShort, cInt, cFP, cLong
43 };
44}
45
46/// getClass - Turn a primitive type into a "class" number which is based on the
47/// size of the type, and whether or not it is floating point.
48///
49static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000050 switch (Ty->getTypeID()) {
Chris Lattner427aeb42004-04-11 19:21:59 +000051 case Type::SByteTyID:
52 case Type::UByteTyID: return cByte; // Byte operands are class #0
53 case Type::ShortTyID:
54 case Type::UShortTyID: return cShort; // Short operands are class #1
55 case Type::IntTyID:
56 case Type::UIntTyID:
57 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
58
59 case Type::FloatTyID:
60 case Type::DoubleTyID: return cFP; // Floating Point is #3
61
62 case Type::LongTyID:
63 case Type::ULongTyID: return cLong; // Longs are class #4
64 default:
65 assert(0 && "Invalid type to getClass!");
66 return cByte; // not reached
67 }
68}
69
70// getClassB - Just like getClass, but treat boolean values as bytes.
71static inline TypeClass getClassB(const Type *Ty) {
72 if (Ty == Type::BoolTy) return cByte;
73 return getClass(Ty);
Chris Lattner986618e2004-02-22 19:47:26 +000074}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000075
Chris Lattner72614082002-10-25 22:55:53 +000076namespace {
Misha Brukmaneae1bf12004-09-21 18:21:21 +000077 struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000078 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000079 MachineFunction *F; // The function we are compiling into
80 MachineBasicBlock *BB; // The current MBB we are compiling
81 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000082 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000083
Chris Lattner72614082002-10-25 22:55:53 +000084 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
85
Chris Lattner333b2fa2002-12-13 10:09:43 +000086 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
Chris Lattnercb2fd552004-05-13 07:40:27 +000089 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
92
Misha Brukmaneae1bf12004-09-21 18:21:21 +000093 X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000094
95 /// runOnFunction - Top level implementation of instruction selection for
96 /// the entire function.
97 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000098 bool runOnFunction(Function &Fn) {
Chris Lattner11cf7aa2004-12-17 00:07:46 +000099 // Lazily create a stack slot for the return address if needed.
Chris Lattner8cdbc352004-12-17 00:46:51 +0000100 ReturnAddressIndex = 0;
Chris Lattner11cf7aa2004-12-17 00:07:46 +0000101
Chris Lattner44827152003-12-28 09:47:19 +0000102 // First pass over the function, lower any unknown intrinsic functions
103 // with the IntrinsicLowering class.
104 LowerUnknownIntrinsicFunctionCalls(Fn);
105
Chris Lattner36b36032002-10-29 23:40:58 +0000106 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000107
Chris Lattner065faeb2002-12-28 20:24:02 +0000108 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +0000109 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
110 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
111
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000112 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +0000113
Chris Lattnerdbd73722003-05-06 21:32:22 +0000114 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000115 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000116
Chris Lattnerc0354c92004-12-13 17:23:11 +0000117 // If this is main, emit special code.
118 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
119 EmitSpecialCodeForMain();
120
Chris Lattner333b2fa2002-12-13 10:09:43 +0000121 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000122 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000123
124 // Select the PHI nodes
125 SelectPHINodes();
126
Chris Lattner986618e2004-02-22 19:47:26 +0000127 // Insert the FP_REG_KILL instructions into blocks that need them.
128 InsertFPRegKills();
129
Chris Lattner72614082002-10-25 22:55:53 +0000130 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000131 MBBMap.clear();
Chris Lattnercb2fd552004-05-13 07:40:27 +0000132 AllocaMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000133 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +0000134 // We always build a machine code representation for the function
135 return true;
Chris Lattner72614082002-10-25 22:55:53 +0000136 }
137
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000138 virtual const char *getPassName() const {
139 return "X86 Simple Instruction Selection";
140 }
141
Chris Lattnerc0354c92004-12-13 17:23:11 +0000142 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
143 /// the main function.
144 void EmitSpecialCodeForMain();
145
Chris Lattner72614082002-10-25 22:55:53 +0000146 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000147 /// block. This simply creates a new MachineBasicBlock to emit code into
148 /// and adds it to the current MachineFunction. Subsequent visit* for
149 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000150 ///
151 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000152 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000153 }
154
Chris Lattner44827152003-12-28 09:47:19 +0000155 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
156 /// function, lowering any calls to unknown intrinsic functions into the
157 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000158 ///
Chris Lattner44827152003-12-28 09:47:19 +0000159 void LowerUnknownIntrinsicFunctionCalls(Function &F);
160
Chris Lattner065faeb2002-12-28 20:24:02 +0000161 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
162 /// from the stack into virtual registers.
163 ///
164 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000165
166 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
167 /// because we have to generate our sources into the source basic blocks,
168 /// not the current one.
169 ///
170 void SelectPHINodes();
171
Chris Lattner986618e2004-02-22 19:47:26 +0000172 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
173 /// that need them. This only occurs due to the floating point stackifier
174 /// not being aggressive enough to handle arbitrary global stackification.
175 ///
176 void InsertFPRegKills();
177
Chris Lattner72614082002-10-25 22:55:53 +0000178 // Visitation methods for various instructions. These methods simply emit
179 // fixed X86 code for each instruction.
180 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000181
182 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000183 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000184 void visitBranchInst(BranchInst &BI);
Chris Lattner30483b02004-10-16 18:13:05 +0000185 void visitUnreachableInst(UnreachableInst &UI) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000186
187 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000188 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000189 unsigned Reg;
190 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000191 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
192 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000193 };
194 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000195 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000196 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000197 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000198
199 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000200 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000201 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
202 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerca9671d2002-11-02 20:28:58 +0000203 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000204
Chris Lattnerf01729e2002-11-02 20:54:46 +0000205 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
206 void visitRem(BinaryOperator &B) { visitDivRem(B); }
207 void visitDivRem(BinaryOperator &B);
208
Chris Lattnere2954c82002-11-02 20:04:26 +0000209 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000210 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
211 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
212 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000213
Chris Lattner6d40c192003-01-16 16:43:00 +0000214 // Comparison operators...
215 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000216 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
217 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000218 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000219 void visitSelectInst(SelectInst &SI);
220
Chris Lattnerb2acc512003-10-19 21:09:10 +0000221
Chris Lattner6fc3c522002-11-17 21:11:55 +0000222 // Memory Instructions
223 void visitLoadInst(LoadInst &I);
224 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000225 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000226 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000227 void visitMallocInst(MallocInst &I);
228 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000229
Chris Lattnere2954c82002-11-02 20:04:26 +0000230 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000231 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000232 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000233 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000234 void visitVANextInst(VANextInst &I);
235 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000236
237 void visitInstruction(Instruction &I) {
238 std::cerr << "Cannot instruction select: " << I;
239 abort();
240 }
241
Brian Gaeke95780cc2002-12-13 07:56:18 +0000242 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000243 ///
244 void promote32(unsigned targetReg, const ValueRecord &VR);
245
Chris Lattner721d2d42004-03-08 01:18:36 +0000246 /// getAddressingMode - Get the addressing mode to use to address the
247 /// specified value. The returned value should be used with addFullAddress.
Reid Spencerfc989e12004-08-30 00:13:26 +0000248 void getAddressingMode(Value *Addr, X86AddressMode &AM);
Chris Lattner721d2d42004-03-08 01:18:36 +0000249
250
251 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
252 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000253 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
254 std::vector<Value*> &GEPOps,
Reid Spencerfc989e12004-08-30 00:13:26 +0000255 std::vector<const Type*> &GEPTypes,
256 X86AddressMode &AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +0000257
258 /// isGEPFoldable - Return true if the specified GEP can be completely
259 /// folded into the addressing mode of a load/store or lea instruction.
260 bool isGEPFoldable(MachineBasicBlock *MBB,
261 Value *Src, User::op_iterator IdxBegin,
Reid Spencerfc989e12004-08-30 00:13:26 +0000262 User::op_iterator IdxEnd, X86AddressMode &AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +0000263
Chris Lattner3e130a22003-01-13 00:32:26 +0000264 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
265 /// constant expression GEP support.
266 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000267 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000268 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000269 User::op_iterator IdxEnd, unsigned TargetReg);
270
Chris Lattner548f61d2003-04-23 17:22:12 +0000271 /// emitCastOperation - Common code shared between visitCastInst and
272 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000273 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000274 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000275 Value *Src, const Type *DestTy, unsigned TargetReg);
276
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000277 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
278 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000279 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000280 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000281 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000282 Value *Op0, Value *Op1,
283 unsigned OperatorClass, unsigned TargetReg);
284
Chris Lattner6621ed92004-04-11 21:23:56 +0000285 /// emitBinaryFPOperation - This method handles emission of floating point
286 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
287 void emitBinaryFPOperation(MachineBasicBlock *BB,
288 MachineBasicBlock::iterator IP,
289 Value *Op0, Value *Op1,
290 unsigned OperatorClass, unsigned TargetReg);
291
Chris Lattner462fa822004-04-11 20:56:28 +0000292 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
293 Value *Op0, Value *Op1, unsigned TargetReg);
294
295 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
296 unsigned DestReg, const Type *DestTy,
297 unsigned Op0Reg, unsigned Op1Reg);
298 void doMultiplyConst(MachineBasicBlock *MBB,
299 MachineBasicBlock::iterator MBBI,
300 unsigned DestReg, const Type *DestTy,
301 unsigned Op0Reg, unsigned Op1Val);
302
Chris Lattnercadff442003-10-23 17:21:43 +0000303 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000304 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +0000305 Value *Op0, Value *Op1, bool isDiv,
306 unsigned TargetReg);
Chris Lattnercadff442003-10-23 17:21:43 +0000307
Chris Lattner58c41fe2003-08-24 19:19:47 +0000308 /// emitSetCCOperation - Common code shared between visitSetCondInst and
309 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000310 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000311 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000312 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000313 Value *Op0, Value *Op1, unsigned Opcode,
314 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000315
316 /// emitShiftOperation - Common code shared between visitShiftInst and
317 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000318 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000319 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000320 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000321 Value *Op, Value *ShiftAmount, bool isLeftShift,
322 const Type *ResultTy, unsigned DestReg);
Chris Lattnerce7cafa2004-11-13 20:48:57 +0000323
324 // Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
325 // constant.
326 void doSHLDConst(MachineBasicBlock *MBB,
327 MachineBasicBlock::iterator MBBI,
328 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
329 unsigned Op1Val);
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000330
Chris Lattner12d96a02004-03-30 21:22:00 +0000331 /// emitSelectOperation - Common code shared between visitSelectInst and the
332 /// constant expression support.
333 void emitSelectOperation(MachineBasicBlock *MBB,
334 MachineBasicBlock::iterator IP,
335 Value *Cond, Value *TrueVal, Value *FalseVal,
336 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000337
Chris Lattnerc5291f52002-10-27 21:16:59 +0000338 /// copyConstantToRegister - Output the instructions required to put the
339 /// specified constant into the specified register.
340 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000341 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000342 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000343 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000344
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000345 void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
346 unsigned LHS, unsigned RHS);
347
Chris Lattner3e130a22003-01-13 00:32:26 +0000348 /// makeAnotherReg - This method returns the next register number we haven't
349 /// yet used.
350 ///
351 /// Long values are handled somewhat specially. They are always allocated
352 /// as pairs of 32 bit integer values. The register number returned is the
353 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
354 /// of the long value.
355 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000356 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000357 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
358 "Current target doesn't have X86 reg info??");
359 const X86RegisterInfo *MRI =
360 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000361 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000362 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
363 // Create the lower part
364 F->getSSARegMap()->createVirtualRegister(RC);
365 // Create the upper part.
366 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000367 }
368
Chris Lattnerc0812d82002-12-13 06:56:29 +0000369 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000370 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000371 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000372 }
373
Chris Lattnercb2fd552004-05-13 07:40:27 +0000374 /// getReg - This method turns an LLVM value into a register number.
Chris Lattner72614082002-10-25 22:55:53 +0000375 ///
376 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000377 unsigned getReg(Value *V) {
378 // Just append to the end of the current bb.
379 MachineBasicBlock::iterator It = BB->end();
380 return getReg(V, BB, It);
381 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000382 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnercb2fd552004-05-13 07:40:27 +0000383 MachineBasicBlock::iterator IPt);
Chris Lattner427aeb42004-04-11 19:21:59 +0000384
Chris Lattnercb2fd552004-05-13 07:40:27 +0000385 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
386 /// that is to be statically allocated with the initial stack frame
387 /// adjustment.
388 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
Chris Lattner72614082002-10-25 22:55:53 +0000389 };
390}
391
Chris Lattnercb2fd552004-05-13 07:40:27 +0000392/// dyn_castFixedAlloca - If the specified value is a fixed size alloca
393/// instruction in the entry block, return it. Otherwise, return a null
394/// pointer.
395static AllocaInst *dyn_castFixedAlloca(Value *V) {
396 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
397 BasicBlock *BB = AI->getParent();
398 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
399 return AI;
400 }
401 return 0;
402}
403
404/// getReg - This method turns an LLVM value into a register number.
405///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000406unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
407 MachineBasicBlock::iterator IPt) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000408 // If this operand is a constant, emit the code to copy the constant into
409 // the register here...
Chris Lattnercb2fd552004-05-13 07:40:27 +0000410 if (Constant *C = dyn_cast<Constant>(V)) {
411 unsigned Reg = makeAnotherReg(V->getType());
412 copyConstantToRegister(MBB, IPt, C, Reg);
413 return Reg;
Chris Lattnercb2fd552004-05-13 07:40:27 +0000414 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Chris Lattner8b486a12004-06-29 00:14:38 +0000415 // Do not emit noop casts at all, unless it's a double -> float cast.
416 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
417 (CI->getType() != Type::FloatTy ||
418 CI->getOperand(0)->getType() != Type::DoubleTy))
Chris Lattnercb2fd552004-05-13 07:40:27 +0000419 return getReg(CI->getOperand(0), MBB, IPt);
420 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
421 // If the alloca address couldn't be folded into the instruction addressing,
422 // emit an explicit LEA as appropriate.
423 unsigned Reg = makeAnotherReg(V->getType());
424 unsigned FI = getFixedSizedAllocaFI(AI);
425 addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
426 return Reg;
427 }
428
429 unsigned &Reg = RegMap[V];
430 if (Reg == 0) {
431 Reg = makeAnotherReg(V->getType());
432 RegMap[V] = Reg;
433 }
434
435 return Reg;
436}
437
438/// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
439/// that is to be statically allocated with the initial stack frame
440/// adjustment.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000441unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000442 // Already computed this?
443 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
444 if (I != AllocaMap.end() && I->first == AI) return I->second;
445
446 const Type *Ty = AI->getAllocatedType();
447 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
448 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
449 TySize *= CUI->getValue(); // Get total allocated size...
450 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
451
452 // Create a new stack object using the frame manager...
453 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
454 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
455 return FrameIdx;
456}
457
458
Chris Lattnerc5291f52002-10-27 21:16:59 +0000459/// copyConstantToRegister - Output the instructions required to put the
460/// specified constant into the specified register.
461///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000462void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
463 MachineBasicBlock::iterator IP,
464 Constant *C, unsigned R) {
Chris Lattner30483b02004-10-16 18:13:05 +0000465 if (isa<UndefValue>(C)) {
466 switch (getClassB(C->getType())) {
467 case cFP:
468 // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
469 BuildMI(*MBB, IP, X86::FLD0, 0, R);
470 return;
471 case cLong:
472 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R+1);
473 // FALL THROUGH
474 default:
475 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R);
476 return;
477 }
478 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000479 unsigned Class = 0;
480 switch (CE->getOpcode()) {
481 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000482 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000483 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000484 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000485 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000486 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000487 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000488
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000489 case Instruction::Xor: ++Class; // FALL THROUGH
490 case Instruction::Or: ++Class; // FALL THROUGH
491 case Instruction::And: ++Class; // FALL THROUGH
492 case Instruction::Sub: ++Class; // FALL THROUGH
493 case Instruction::Add:
494 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
495 Class, R);
496 return;
497
Chris Lattner462fa822004-04-11 20:56:28 +0000498 case Instruction::Mul:
499 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
Chris Lattnercadff442003-10-23 17:21:43 +0000500 return;
Chris Lattner462fa822004-04-11 20:56:28 +0000501
Chris Lattnercadff442003-10-23 17:21:43 +0000502 case Instruction::Div:
Chris Lattner462fa822004-04-11 20:56:28 +0000503 case Instruction::Rem:
504 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
505 CE->getOpcode() == Instruction::Div, R);
Chris Lattnercadff442003-10-23 17:21:43 +0000506 return;
Chris Lattnercadff442003-10-23 17:21:43 +0000507
Chris Lattner58c41fe2003-08-24 19:19:47 +0000508 case Instruction::SetNE:
509 case Instruction::SetEQ:
510 case Instruction::SetLT:
511 case Instruction::SetGT:
512 case Instruction::SetLE:
513 case Instruction::SetGE:
514 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
515 CE->getOpcode(), R);
516 return;
517
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000518 case Instruction::Shl:
519 case Instruction::Shr:
520 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000521 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
522 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000523
Chris Lattner12d96a02004-03-30 21:22:00 +0000524 case Instruction::Select:
525 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
526 CE->getOperand(2), R);
527 return;
528
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000529 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000530 std::cerr << "Offending expr: " << *C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000531 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000532 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000533 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000534
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000535 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000536 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000537
538 if (Class == cLong) {
539 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000540 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000541 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
542 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000543 return;
544 }
545
Chris Lattner94af4142002-12-25 05:13:53 +0000546 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000547
548 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000549 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000550 };
551
Chris Lattner6b993cc2002-12-15 08:02:15 +0000552 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000553 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000554 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000555 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000556 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000557 }
Chris Lattner94af4142002-12-25 05:13:53 +0000558 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000559 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000560 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000561 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000562 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner6ac95f92005-01-06 21:19:16 +0000563 else if (CFP->isExactlyValue(-0.0)) {
564 unsigned Tmp = makeAnotherReg(Type::DoubleTy);
565 BuildMI(*MBB, IP, X86::FLD0, 0, Tmp);
566 BuildMI(*MBB, IP, X86::FCHS, 1, R).addReg(Tmp);
567 } else if (CFP->isExactlyValue(-1.0)) {
568 unsigned Tmp = makeAnotherReg(Type::DoubleTy);
569 BuildMI(*MBB, IP, X86::FLD1, 0, Tmp);
570 BuildMI(*MBB, IP, X86::FCHS, 1, R).addReg(Tmp);
571 } else { // FIXME: PI, other native values
Chris Lattner5384b382005-01-05 16:30:14 +0000572 // FIXME: 2*PI -> LDPI + FADD
573
574 // Otherwise we need to spill the constant to memory.
Chris Lattner3e130a22003-01-13 00:32:26 +0000575 MachineConstantPool *CP = F->getConstantPool();
Chris Lattner5384b382005-01-05 16:30:14 +0000576
Chris Lattner6c09db22003-10-20 04:11:23 +0000577 const Type *Ty = CFP->getType();
578
Chris Lattner5384b382005-01-05 16:30:14 +0000579 // If a FP immediate is precise when represented as a float, we put it
580 // into the constant pool as a float, even if it's is statically typed as
581 // a double.
582 if (Ty == Type::DoubleTy)
583 if (CFP->isExactlyValue((float)CFP->getValue())) {
584 Ty = Type::FloatTy;
585 CFP = cast<ConstantFP>(ConstantExpr::getCast(CFP, Ty));
586 }
587
588 unsigned CPI = CP->getConstantPoolIndex(CFP);
589
Chris Lattner6c09db22003-10-20 04:11:23 +0000590 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000591 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000592 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000593 }
594
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000595 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000596 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000597 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Reid Spencer8863f182004-07-18 00:38:32 +0000598 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
599 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000600 } else {
Chris Lattner76e2df22004-07-15 02:14:30 +0000601 std::cerr << "Offending constant: " << *C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000602 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000603 }
604}
605
Chris Lattner065faeb2002-12-28 20:24:02 +0000606/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
607/// the stack into virtual registers.
608///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000609void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000610 // Emit instructions to load the arguments... On entry to a function on the
611 // X86, the stack frame looks like this:
612 //
613 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000614 // [ESP + 4] -- first argument (leftmost lexically)
615 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000616 // ...
617 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000618 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000619 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000620
Chris Lattnere4d5c442005-03-15 04:54:21 +0000621 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000622 bool ArgLive = !I->use_empty();
623 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000624 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000625
Chris Lattner065faeb2002-12-28 20:24:02 +0000626 switch (getClassB(I->getType())) {
627 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000628 if (ArgLive) {
629 FI = MFI->CreateFixedObject(1, ArgOffset);
630 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
631 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000632 break;
633 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000634 if (ArgLive) {
635 FI = MFI->CreateFixedObject(2, ArgOffset);
636 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
637 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000638 break;
639 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000640 if (ArgLive) {
641 FI = MFI->CreateFixedObject(4, ArgOffset);
642 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
643 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000644 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000645 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000646 if (ArgLive) {
647 FI = MFI->CreateFixedObject(8, ArgOffset);
648 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
649 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
650 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000651 ArgOffset += 4; // longs require 4 additional bytes
652 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000653 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000654 if (ArgLive) {
655 unsigned Opcode;
656 if (I->getType() == Type::FloatTy) {
657 Opcode = X86::FLD32m;
658 FI = MFI->CreateFixedObject(4, ArgOffset);
659 } else {
660 Opcode = X86::FLD64m;
661 FI = MFI->CreateFixedObject(8, ArgOffset);
662 }
663 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000664 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000665 if (I->getType() == Type::DoubleTy)
666 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000667 break;
668 default:
669 assert(0 && "Unhandled argument type!");
670 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000671 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000672 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000673
674 // If the function takes variable number of arguments, add a frame offset for
675 // the start of the first vararg value... this is used to expand
676 // llvm.va_start.
677 if (Fn.getFunctionType()->isVarArg())
678 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000679}
680
Chris Lattnerc0354c92004-12-13 17:23:11 +0000681/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
682/// the main function.
683void X86ISel::EmitSpecialCodeForMain() {
684 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
685 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
686 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
687
688 // Set the high part to be 64-bit precision.
689 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
690 CWFrameIdx, 1).addImm(2);
691
692 // Reload the modified control word now.
693 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
694}
Chris Lattner065faeb2002-12-28 20:24:02 +0000695
Chris Lattner333b2fa2002-12-13 10:09:43 +0000696/// SelectPHINodes - Insert machine code to generate phis. This is tricky
697/// because we have to generate our sources into the source basic blocks, not
698/// the current one.
699///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000700void X86ISel::SelectPHINodes() {
Chris Lattnerd029cd22004-06-02 05:55:25 +0000701 const TargetInstrInfo &TII = *TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000702 const Function &LF = *F->getFunction(); // The LLVM function...
703 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
704 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000705 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000706
707 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000708 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000709 for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
710 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
Chris Lattner3e130a22003-01-13 00:32:26 +0000711
Chris Lattner333b2fa2002-12-13 10:09:43 +0000712 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000713 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000714 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
715 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000716
717 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000718 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
719 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
720 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000721
Chris Lattnera6e73f12003-05-12 14:22:21 +0000722 // PHIValues - Map of blocks to incoming virtual registers. We use this
723 // so that we only initialize one incoming value for a particular block,
724 // even if the block has multiple entries in the PHI node.
725 //
726 std::map<MachineBasicBlock*, unsigned> PHIValues;
727
Chris Lattner333b2fa2002-12-13 10:09:43 +0000728 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
729 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000730 unsigned ValReg;
731 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
732 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000733
Chris Lattnera6e73f12003-05-12 14:22:21 +0000734 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
735 // We already inserted an initialization of the register for this
736 // predecessor. Recycle it.
737 ValReg = EntryIt->second;
738
739 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000740 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000741 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000742 Value *Val = PN->getIncomingValue(i);
743
744 // If this is a constant or GlobalValue, we may have to insert code
745 // into the basic block to compute it into a virtual register.
Reid Spencer8863f182004-07-18 00:38:32 +0000746 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000747 // Simple constants get emitted at the end of the basic block,
748 // before any terminator instructions. We "know" that the code to
749 // move a constant into a register will never clobber any flags.
750 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
Chris Lattnera81fc682003-10-19 00:26:11 +0000751 } else {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000752 // Because we don't want to clobber any values which might be in
753 // physical registers with the computation of this constant (which
754 // might be arbitrarily complex if it is a constant expression),
755 // just insert the computation at the top of the basic block.
756 MachineBasicBlock::iterator PI = PredMBB->begin();
757
758 // Skip over any PHI nodes though!
759 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
760 ++PI;
761
762 ValReg = getReg(Val, PredMBB, PI);
Chris Lattnera81fc682003-10-19 00:26:11 +0000763 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000764
765 // Remember that we inserted a value for this PHI for this predecessor
766 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
767 }
768
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000769 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000770 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000771 if (LongPhiMI) {
772 LongPhiMI->addRegOperand(ValReg+1);
773 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
774 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000775 }
Chris Lattner168aa902004-02-29 07:10:16 +0000776
777 // Now that we emitted all of the incoming values for the PHI node, make
778 // sure to reposition the InsertPoint after the PHI that we just added.
779 // This is needed because we might have inserted a constant into this
780 // block, right after the PHI's which is before the old insert point!
781 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
782 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000783 }
784 }
785}
786
Chris Lattner986618e2004-02-22 19:47:26 +0000787/// RequiresFPRegKill - The floating point stackifier pass cannot insert
788/// compensation code on critical edges. As such, it requires that we kill all
789/// FP registers on the exit from any blocks that either ARE critical edges, or
790/// branch to a block that has incoming critical edges.
791///
792/// Note that this kill instruction will eventually be eliminated when
793/// restrictions in the stackifier are relaxed.
794///
Brian Gaeke1afe7732004-04-28 04:45:55 +0000795static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000796#if 0
Brian Gaeke1afe7732004-04-28 04:45:55 +0000797 const BasicBlock *BB = MBB->getBasicBlock ();
Chris Lattner986618e2004-02-22 19:47:26 +0000798 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
799 const BasicBlock *Succ = *SI;
800 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
801 ++PI; // Block have at least one predecessory
802 if (PI != PE) { // If it has exactly one, this isn't crit edge
803 // If this block has more than one predecessor, check all of the
804 // predecessors to see if they have multiple successors. If so, then the
805 // block we are analyzing needs an FPRegKill.
806 for (PI = pred_begin(Succ); PI != PE; ++PI) {
807 const BasicBlock *Pred = *PI;
808 succ_const_iterator SI2 = succ_begin(Pred);
809 ++SI2; // There must be at least one successor of this block.
810 if (SI2 != succ_end(Pred))
811 return true; // Yes, we must insert the kill on this edge.
812 }
813 }
814 }
815 // If we got this far, there is no need to insert the kill instruction.
816 return false;
817#else
818 return true;
819#endif
820}
821
822// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
823// need them. This only occurs due to the floating point stackifier not being
824// aggressive enough to handle arbitrary global stackification.
825//
826// Currently we insert an FP_REG_KILL instruction into each block that uses or
827// defines a floating point virtual register.
828//
829// When the global register allocators (like linear scan) finally update live
830// variable analysis, we can keep floating point values in registers across
831// portions of the CFG that do not involve critical edges. This will be a big
832// win, but we are waiting on the global allocators before we can do this.
833//
834// With a bit of work, the floating point stackifier pass can be enhanced to
835// break critical edges as needed (to make a place to put compensation code),
836// but this will require some infrastructure improvements as well.
837//
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000838void X86ISel::InsertFPRegKills() {
Chris Lattner986618e2004-02-22 19:47:26 +0000839 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000840
841 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000842 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000843 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
844 MachineOperand& MO = I->getOperand(i);
845 if (MO.isRegister() && MO.getReg()) {
846 unsigned Reg = MO.getReg();
Chris Lattner223d4c42004-12-03 05:13:15 +0000847 if (MRegisterInfo::isVirtualRegister(Reg)) {
848 unsigned RegSize = RegMap.getRegClass(Reg)->getSize();
849 if (RegSize == 10 || RegSize == 8)
Chris Lattner65cf42d2004-02-23 07:29:45 +0000850 goto UsesFPReg;
Chris Lattner223d4c42004-12-03 05:13:15 +0000851 }
Chris Lattner986618e2004-02-22 19:47:26 +0000852 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000853 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000854 // If we haven't found an FP register use or def in this basic block, check
855 // to see if any of our successors has an FP PHI node, which will cause a
856 // copy to be inserted into this block.
Brian Gaeke235aa5e2004-04-28 04:34:16 +0000857 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
858 SE = BB->succ_end(); SI != SE; ++SI) {
859 MachineBasicBlock *SBB = *SI;
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000860 for (MachineBasicBlock::iterator I = SBB->begin();
861 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
Chris Lattner39869242004-12-02 17:57:21 +0000862 const TargetRegisterClass *RC =
863 RegMap.getRegClass(I->getOperand(0).getReg());
864 if (RC->getSize() == 10 || RC->getSize() == 8)
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000865 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000866 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000867 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000868 continue;
869 UsesFPReg:
870 // Okay, this block uses an FP register. If the block has successors (ie,
871 // it's not an unwind/return), insert the FP_REG_KILL instruction.
Chris Lattner5384b382005-01-05 16:30:14 +0000872 if (BB->succ_size() && RequiresFPRegKill(BB)) {
Chris Lattneree352852004-02-29 07:22:16 +0000873 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000874 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000875 }
876 }
877}
878
879
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000880void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
Reid Spencerfc989e12004-08-30 00:13:26 +0000881 AM.BaseType = X86AddressMode::RegBase;
882 AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000883 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
884 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
Reid Spencerfc989e12004-08-30 00:13:26 +0000885 AM))
Chris Lattner9f1b5312004-05-13 15:12:43 +0000886 return;
887 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
888 if (CE->getOpcode() == Instruction::GetElementPtr)
889 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
Reid Spencerfc989e12004-08-30 00:13:26 +0000890 AM))
Chris Lattner9f1b5312004-05-13 15:12:43 +0000891 return;
Reid Spencerfc989e12004-08-30 00:13:26 +0000892 } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
893 AM.BaseType = X86AddressMode::FrameIndexBase;
894 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
895 return;
Chris Lattner358a9022004-10-15 05:05:29 +0000896 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
897 AM.GV = GV;
898 return;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000899 }
900
901 // If it's not foldable, reset addr mode.
Reid Spencerfc989e12004-08-30 00:13:26 +0000902 AM.BaseType = X86AddressMode::RegBase;
903 AM.Base.Reg = getReg(Addr);
904 AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000905}
906
Chris Lattner307ecba2004-03-30 22:39:09 +0000907// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
908// it into the conditional branch or select instruction which is the only user
909// of the cc instruction. This is the case if the conditional branch is the
Chris Lattnera6f9fe62004-06-18 00:29:22 +0000910// only user of the setcc. We also don't handle long arguments below, so we
911// reject them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000912//
Chris Lattner307ecba2004-03-30 22:39:09 +0000913static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000914 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000915 if (SCI->hasOneUse()) {
916 Instruction *User = cast<Instruction>(SCI->use_back());
Tanya Lattner9855b842004-12-01 18:27:03 +0000917 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
918 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
919 SCI->getOpcode() == Instruction::SetEQ ||
920 SCI->getOpcode() == Instruction::SetNE) &&
921 (isa<BranchInst>(User) || User->getOperand(0) == V))
Chris Lattner6d40c192003-01-16 16:43:00 +0000922 return SCI;
923 }
924 return 0;
925}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000926
Chris Lattner6d40c192003-01-16 16:43:00 +0000927// Return a fixed numbering for setcc instructions which does not depend on the
928// order of the opcodes.
929//
930static unsigned getSetCCNumber(unsigned Opcode) {
931 switch(Opcode) {
932 default: assert(0 && "Unknown setcc instruction!");
933 case Instruction::SetEQ: return 0;
934 case Instruction::SetNE: return 1;
935 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000936 case Instruction::SetGE: return 3;
937 case Instruction::SetGT: return 4;
938 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000939 }
940}
Chris Lattner06925362002-11-17 21:56:38 +0000941
Chris Lattner6d40c192003-01-16 16:43:00 +0000942// LLVM -> X86 signed X86 unsigned
943// ----- ---------- ------------
944// seteq -> sete sete
945// setne -> setne setne
946// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000947// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000948// setgt -> setg seta
949// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000950// ----
951// sets // Used by comparison with 0 optimization
952// setns
953static const unsigned SetCCOpcodeTab[2][8] = {
954 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
955 0, 0 },
956 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
957 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000958};
959
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000960/// emitUCOMr - In the future when we support processors before the P6, this
961/// wraps the logic for emitting an FUCOMr vs FUCOMIr.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000962void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
963 unsigned LHS, unsigned RHS) {
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000964 if (0) { // for processors prior to the P6
965 BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
966 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
967 BuildMI(*MBB, IP, X86::SAHF, 1);
968 } else {
969 BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
970 }
971}
972
Chris Lattnerb2acc512003-10-19 21:09:10 +0000973// EmitComparison - This function emits a comparison of the two operands,
974// returning the extended setcc code to use.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000975unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
976 MachineBasicBlock *MBB,
977 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000978 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000979 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000980 unsigned Class = getClassB(CompTy);
Chris Lattner333864d2003-06-05 19:30:30 +0000981
982 // Special case handling of: cmp R, i
Chris Lattner260195d2004-05-07 19:55:55 +0000983 if (isa<ConstantPointerNull>(Op1)) {
Chris Lattnerde95c9e2004-10-17 06:10:40 +0000984 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner260195d2004-05-07 19:55:55 +0000985 if (OpNum < 2) // seteq/setne -> test
986 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
987 else
988 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
989 return OpNum;
990
991 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere80e6372004-04-06 16:02:27 +0000992 if (Class == cByte || Class == cShort || Class == cInt) {
993 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000994
Chris Lattner333864d2003-06-05 19:30:30 +0000995 // Mask off any upper bits of the constant, if there are any...
996 Op1v &= (1ULL << (8 << Class)) - 1;
997
Chris Lattnerb2acc512003-10-19 21:09:10 +0000998 // If this is a comparison against zero, emit more efficient code. We
999 // can't handle unsigned comparisons against zero unless they are == or
1000 // !=. These should have been strength reduced already anyway.
1001 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001002
1003 // If this is a comparison against zero and the LHS is an and of a
1004 // register with a constant, use the test to do the and.
1005 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1006 if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
1007 isa<ConstantInt>(Op0I->getOperand(1))) {
1008 static const unsigned TESTTab[] = {
1009 X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
1010 };
1011
1012 // Emit test X, i
1013 unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
1014 unsigned Imm =
1015 cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
1016 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
1017
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001018 if (OpNum == 2) return 6; // Map jl -> js
1019 if (OpNum == 3) return 7; // Map jg -> jns
1020 return OpNum;
1021 }
1022
1023 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001024 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001025 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +00001026 };
Chris Lattneree352852004-02-29 07:22:16 +00001027 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001028
1029 if (OpNum == 2) return 6; // Map jl -> js
1030 if (OpNum == 3) return 7; // Map jg -> jns
1031 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +00001032 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001033
1034 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001035 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +00001036 };
1037
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001038 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001039 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001040 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +00001041 } else {
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001042 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnere80e6372004-04-06 16:02:27 +00001043 assert(Class == cLong && "Unknown integer class!");
1044 unsigned LowCst = CI->getRawValue();
1045 unsigned HiCst = CI->getRawValue() >> 32;
1046 if (OpNum < 2) { // seteq, setne
1047 unsigned LoTmp = Op0r;
1048 if (LowCst != 0) {
1049 LoTmp = makeAnotherReg(Type::IntTy);
1050 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
1051 }
1052 unsigned HiTmp = Op0r+1;
1053 if (HiCst != 0) {
1054 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +00001055 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +00001056 }
1057 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1058 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1059 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +00001060 } else {
Tanya Lattner9855b842004-12-01 18:27:03 +00001061 // Emit a sequence of code which compares the high and low parts once
1062 // each, then uses a conditional move to handle the overflow case. For
1063 // example, a setlt for long would generate code like this:
1064 //
1065 // AL = lo(op1) < lo(op2) // Always unsigned comparison
1066 // BL = hi(op1) < hi(op2) // Signedness depends on operands
1067 // dest = hi(op1) == hi(op2) ? BL : AL;
1068 //
1069
1070 // FIXME: This would be much better if we had hierarchical register
1071 // classes! Until then, hardcode registers so that we can deal with
1072 // their aliases (because we don't have conditional byte moves).
1073 //
1074 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
1075 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1076 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
1077 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
1078 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1079 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1080 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1081 .addReg(X86::AX);
1082 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1083 // register at this point for long values...
Chris Lattner48c937e2004-04-06 17:34:50 +00001084 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +00001085 }
Chris Lattner333864d2003-06-05 19:30:30 +00001086 }
Chris Lattnere80e6372004-04-06 16:02:27 +00001087 }
Chris Lattner333864d2003-06-05 19:30:30 +00001088
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001089 unsigned Op0r = getReg(Op0, MBB, IP);
1090
Chris Lattner9f08a922004-02-03 18:54:04 +00001091 // Special case handling of comparison against +/- 0.0
1092 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
1093 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +00001094 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001095 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00001096 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +00001097 return OpNum;
1098 }
1099
Chris Lattner58c41fe2003-08-24 19:19:47 +00001100 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001101 switch (Class) {
1102 default: assert(0 && "Unknown type class!");
1103 // Emit: cmp <var1>, <var2> (do the comparison). We can
1104 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1105 // 32-bit.
1106 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001107 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001108 break;
1109 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001110 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001111 break;
1112 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001113 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001114 break;
1115 case cFP:
Chris Lattner01cdb1b2004-06-11 05:33:49 +00001116 emitUCOMr(MBB, IP, Op0r, Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001117 break;
1118
1119 case cLong:
1120 if (OpNum < 2) { // seteq, setne
1121 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1122 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1123 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001124 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1125 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1126 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +00001127 break; // Allow the sete or setne to be generated from flags set by OR
1128 } else {
1129 // Emit a sequence of code which compares the high and low parts once
1130 // each, then uses a conditional move to handle the overflow case. For
1131 // example, a setlt for long would generate code like this:
1132 //
1133 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1134 // BL = hi(op1) < hi(op2) // Always unsigned comparison
Chris Lattner9984fd02004-05-09 23:16:33 +00001135 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner3e130a22003-01-13 00:32:26 +00001136 //
1137
Chris Lattner6d40c192003-01-16 16:43:00 +00001138 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +00001139 // classes! Until then, hardcode registers so that we can deal with their
1140 // aliases (because we don't have conditional byte moves).
1141 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001142 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +00001143 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001144 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +00001145 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1146 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1147 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001148 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +00001149 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +00001150 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1151 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +00001152 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +00001153 }
1154 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001155 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +00001156}
Chris Lattner3e130a22003-01-13 00:32:26 +00001157
Chris Lattner6d40c192003-01-16 16:43:00 +00001158/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1159/// register, then move it to wherever the result should be.
1160///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001161void X86ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +00001162 if (canFoldSetCCIntoBranchOrSelect(&I))
1163 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +00001164
Chris Lattner6d40c192003-01-16 16:43:00 +00001165 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001166 MachineBasicBlock::iterator MII = BB->end();
1167 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1168 DestReg);
1169}
Chris Lattner6d40c192003-01-16 16:43:00 +00001170
Chris Lattner58c41fe2003-08-24 19:19:47 +00001171/// emitSetCCOperation - Common code shared between visitSetCondInst and
1172/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +00001173///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001174void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1175 MachineBasicBlock::iterator IP,
1176 Value *Op0, Value *Op1, unsigned Opcode,
1177 unsigned TargetReg) {
Chris Lattner58c41fe2003-08-24 19:19:47 +00001178 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001179 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001180
Chris Lattnerb2acc512003-10-19 21:09:10 +00001181 const Type *CompTy = Op0->getType();
1182 unsigned CompClass = getClassB(CompTy);
1183 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1184
Tanya Lattner9855b842004-12-01 18:27:03 +00001185 if (CompClass != cLong || OpNum < 2) {
1186 // Handle normal comparisons with a setcc instruction...
1187 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1188 } else {
1189 // Handle long comparisons by copying the value which is already in BL into
1190 // the register we want...
1191 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1192 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001193}
Chris Lattner51b49a92002-11-02 19:45:49 +00001194
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001195void X86ISel::visitSelectInst(SelectInst &SI) {
Chris Lattner12d96a02004-03-30 21:22:00 +00001196 unsigned DestReg = getReg(SI);
1197 MachineBasicBlock::iterator MII = BB->end();
1198 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1199 SI.getFalseValue(), DestReg);
1200}
1201
1202/// emitSelect - Common code shared between visitSelectInst and the constant
1203/// expression support.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001204void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1205 MachineBasicBlock::iterator IP,
1206 Value *Cond, Value *TrueVal, Value *FalseVal,
1207 unsigned DestReg) {
Chris Lattner12d96a02004-03-30 21:22:00 +00001208 unsigned SelectClass = getClassB(TrueVal->getType());
1209
1210 // We don't support 8-bit conditional moves. If we have incoming constants,
1211 // transform them into 16-bit constants to avoid having a run-time conversion.
1212 if (SelectClass == cByte) {
1213 if (Constant *T = dyn_cast<Constant>(TrueVal))
1214 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1215 if (Constant *F = dyn_cast<Constant>(FalseVal))
1216 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1217 }
1218
Chris Lattner82c5a992004-04-13 21:56:09 +00001219 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1220 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1221 if (TrueReg == FalseReg) {
1222 static const unsigned Opcode[] = {
1223 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1224 };
1225 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1226 if (SelectClass == cLong)
1227 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1228 return;
1229 }
1230
Chris Lattner307ecba2004-03-30 22:39:09 +00001231 unsigned Opcode;
1232 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1233 // We successfully folded the setcc into the select instruction.
1234
1235 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1236 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1237 IP);
1238
1239 const Type *CompTy = SCI->getOperand(0)->getType();
1240 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1241
1242 // LLVM -> X86 signed X86 unsigned
1243 // ----- ---------- ------------
1244 // seteq -> cmovNE cmovNE
1245 // setne -> cmovE cmovE
1246 // setlt -> cmovGE cmovAE
1247 // setge -> cmovL cmovB
1248 // setgt -> cmovLE cmovBE
1249 // setle -> cmovG cmovA
1250 // ----
1251 // cmovNS // Used by comparison with 0 optimization
1252 // cmovS
1253
1254 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001255 default: assert(0 && "Unknown value class!");
1256 case cFP: {
1257 // Annoyingly, we don't have a full set of floating point conditional
1258 // moves. :(
1259 static const unsigned OpcodeTab[2][8] = {
1260 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1261 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1262 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1263 };
1264 Opcode = OpcodeTab[isSigned][OpNum];
1265
1266 // If opcode == 0, we hit a case that we don't support. Output a setcc
1267 // and compare the result against zero.
1268 if (Opcode == 0) {
1269 unsigned CompClass = getClassB(CompTy);
1270 unsigned CondReg;
1271 if (CompClass != cLong || OpNum < 2) {
1272 CondReg = makeAnotherReg(Type::BoolTy);
1273 // Handle normal comparisons with a setcc instruction...
1274 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1275 } else {
1276 // Long comparisons end up in the BL register.
1277 CondReg = X86::BL;
1278 }
1279
Chris Lattner68626c22004-03-31 22:22:36 +00001280 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001281 Opcode = X86::FCMOVE;
1282 }
1283 break;
1284 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001285 case cByte:
1286 case cShort: {
1287 static const unsigned OpcodeTab[2][8] = {
1288 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1289 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1290 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1291 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1292 };
1293 Opcode = OpcodeTab[isSigned][OpNum];
1294 break;
1295 }
1296 case cInt:
1297 case cLong: {
1298 static const unsigned OpcodeTab[2][8] = {
1299 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1300 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1301 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1302 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1303 };
1304 Opcode = OpcodeTab[isSigned][OpNum];
1305 break;
1306 }
1307 }
1308 } else {
1309 // Get the value being branched on, and use it to set the condition codes.
1310 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001311 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001312 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001313 default: assert(0 && "Unknown value class!");
1314 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001315 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001316 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001317 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001318 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001319 }
1320 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001321
Chris Lattner12d96a02004-03-30 21:22:00 +00001322 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001323
Chris Lattner12d96a02004-03-30 21:22:00 +00001324
1325 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1326 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1327 // cmove, then truncate the result.
1328 if (SelectClass == cByte) {
1329 DestReg = makeAnotherReg(Type::ShortTy);
1330 if (getClassB(TrueVal->getType()) == cByte) {
1331 // Promote the true value, by storing it into AL, and reading from AX.
1332 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1333 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1334 TrueReg = makeAnotherReg(Type::ShortTy);
1335 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1336 }
1337 if (getClassB(FalseVal->getType()) == cByte) {
1338 // Promote the true value, by storing it into CL, and reading from CX.
1339 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1340 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1341 FalseReg = makeAnotherReg(Type::ShortTy);
1342 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1343 }
1344 }
1345
1346 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1347
1348 switch (SelectClass) {
1349 case cByte:
1350 // We did the computation with 16-bit registers. Truncate back to our
1351 // result by copying into AX then copying out AL.
1352 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1353 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1354 break;
1355 case cLong:
1356 // Move the upper half of the value as well.
1357 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1358 break;
1359 }
1360}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001361
1362
1363
Brian Gaekec2505982002-11-30 11:57:28 +00001364/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1365/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001366///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001367void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
Chris Lattner9984fd02004-05-09 23:16:33 +00001368 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001369
Chris Lattner29bf0622004-04-06 01:21:00 +00001370 Value *Val = VR.Val;
1371 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001372 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001373 if (Constant *C = dyn_cast<Constant>(Val)) {
1374 Val = ConstantExpr::getCast(C, Type::IntTy);
1375 Ty = Type::IntTy;
1376 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001377
Chris Lattner502e36c2004-04-06 01:25:33 +00001378 // If this is a simple constant, just emit a MOVri directly to avoid the
1379 // copy.
1380 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1381 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
Chris Lattner2b10b082004-05-12 16:35:04 +00001382 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
Chris Lattner502e36c2004-04-06 01:25:33 +00001383 return;
1384 }
1385 }
1386
Chris Lattner29bf0622004-04-06 01:21:00 +00001387 // Make sure we have the register number for this value...
1388 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1389
1390 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001391 case cByte:
1392 // Extend value into target register (8->32)
1393 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001394 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001395 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001396 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001397 break;
1398 case cShort:
1399 // Extend value into target register (16->32)
1400 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001401 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001402 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001403 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001404 break;
1405 case cInt:
1406 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001407 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001408 break;
1409 default:
1410 assert(0 && "Unpromotable operand class in promote32");
1411 }
Brian Gaekec2505982002-11-30 11:57:28 +00001412}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001413
Chris Lattner72614082002-10-25 22:55:53 +00001414/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1415/// we have the following possibilities:
1416///
1417/// ret void: No return value, simply emit a 'ret' instruction
1418/// ret sbyte, ubyte : Extend value into EAX and return
1419/// ret short, ushort: Extend value into EAX and return
1420/// ret int, uint : Move value into EAX and return
1421/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001422/// ret long, ulong : Move value into EAX/EDX and return
1423/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001424///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001425void X86ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001426 if (I.getNumOperands() == 0) {
1427 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1428 return;
1429 }
1430
1431 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001432 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001433 case cByte: // integral return values: extend or move into EAX and return
1434 case cShort:
1435 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001436 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001437 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001438 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001439 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001440 case cFP: { // Floats & Doubles: Return in ST(0)
1441 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001442 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001443 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001444 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001445 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001446 }
1447 case cLong: {
1448 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001449 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1450 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001451 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001452 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1453 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001454 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001455 }
Chris Lattner94af4142002-12-25 05:13:53 +00001456 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001457 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001458 }
Chris Lattner43189d12002-11-17 20:07:45 +00001459 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001460 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001461}
1462
Chris Lattner55f6fab2003-01-16 18:07:23 +00001463// getBlockAfter - Return the basic block which occurs lexically after the
1464// specified one.
1465static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1466 Function::iterator I = BB; ++I; // Get iterator to next block
1467 return I != BB->getParent()->end() ? &*I : 0;
1468}
1469
Chris Lattner51b49a92002-11-02 19:45:49 +00001470/// visitBranchInst - Handle conditional and unconditional branches here. Note
1471/// that since code layout is frozen at this point, that if we are trying to
1472/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001473/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001474///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001475void X86ISel::visitBranchInst(BranchInst &BI) {
Brian Gaekeea9ca672004-04-28 04:19:37 +00001476 // Update machine-CFG edges
1477 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1478 if (BI.isConditional())
1479 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1480
Chris Lattner55f6fab2003-01-16 18:07:23 +00001481 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1482
1483 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001484 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001485 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner6d40c192003-01-16 16:43:00 +00001486 return;
1487 }
1488
1489 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001490 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001491 if (SCI == 0) {
1492 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1493 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001494 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001495 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001496 if (BI.getSuccessor(1) == NextBB) {
1497 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001498 BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001499 } else {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001500 BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001501
1502 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001503 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001504 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001505 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001506 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001507
1508 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001509 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001510 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001511
1512 const Type *CompTy = SCI->getOperand(0)->getType();
1513 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001514
Chris Lattnerb2acc512003-10-19 21:09:10 +00001515
Chris Lattner6d40c192003-01-16 16:43:00 +00001516 // LLVM -> X86 signed X86 unsigned
1517 // ----- ---------- ------------
1518 // seteq -> je je
1519 // setne -> jne jne
1520 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001521 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001522 // setgt -> jg ja
1523 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001524 // ----
1525 // js // Used by comparison with 0 optimization
1526 // jns
1527
1528 static const unsigned OpcodeTab[2][8] = {
1529 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1530 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1531 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001532 };
1533
Chris Lattner55f6fab2003-01-16 18:07:23 +00001534 if (BI.getSuccessor(0) != NextBB) {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001535 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1536 .addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001537 if (BI.getSuccessor(1) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001538 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001539 } else {
1540 // Change to the inverse condition...
1541 if (BI.getSuccessor(1) != NextBB) {
1542 OpNum ^= 1;
Brian Gaeke9f088e42004-05-14 06:54:56 +00001543 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1544 .addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001545 }
1546 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001547}
1548
Chris Lattner3e130a22003-01-13 00:32:26 +00001549
1550/// doCall - This emits an abstract call instruction, setting up the arguments
1551/// and the return value as appropriate. For the actual function call itself,
1552/// it inserts the specified CallMI instruction into the stream.
1553///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001554void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1555 const std::vector<ValueRecord> &Args) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001556 // Count how many bytes are to be pushed on the stack...
1557 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001558
Chris Lattner3e130a22003-01-13 00:32:26 +00001559 if (!Args.empty()) {
1560 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1561 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001562 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001563 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001564 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001565 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001566 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001567 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1568 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001569 default: assert(0 && "Unknown class!");
1570 }
1571
1572 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001573 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001574
1575 // Arguments go on the stack in reverse order, as specified by the ABI.
1576 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001577 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001578 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001579 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001580 case cByte:
Chris Lattner2b10b082004-05-12 16:35:04 +00001581 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1582 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1583 .addImm(Args[i].Val == ConstantBool::True);
1584 break;
1585 }
1586 // FALL THROUGH
Chris Lattner21585222004-03-01 02:42:43 +00001587 case cShort:
1588 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1589 // Zero/Sign extend constant, then stuff into memory.
1590 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1591 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1592 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1593 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1594 } else {
1595 // Promote arg to 32 bits wide into a temporary register...
1596 ArgReg = makeAnotherReg(Type::UIntTy);
1597 promote32(ArgReg, Args[i]);
1598 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1599 X86::ESP, ArgOffset).addReg(ArgReg);
1600 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001601 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001602 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001603 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1604 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1605 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1606 X86::ESP, ArgOffset).addImm(Val);
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00001607 } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1608 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1609 X86::ESP, ArgOffset).addImm(0);
Chris Lattner21585222004-03-01 02:42:43 +00001610 } else {
1611 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1612 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1613 X86::ESP, ArgOffset).addReg(ArgReg);
1614 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001615 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001616 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001617 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1618 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1619 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1620 X86::ESP, ArgOffset).addImm(Val & ~0U);
1621 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1622 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1623 } else {
1624 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1625 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1626 X86::ESP, ArgOffset).addReg(ArgReg);
1627 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1628 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1629 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001630 ArgOffset += 4; // 8 byte entry, not 4.
1631 break;
1632
Chris Lattner065faeb2002-12-28 20:24:02 +00001633 case cFP:
Chris Lattner7ab65932005-01-08 05:45:24 +00001634 if (ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(Args[i].Val)) {
Chris Lattner8c926282005-01-08 06:59:50 +00001635 // Store constant FP values with integer instructions to avoid having
1636 // to load the constants from the constant pool then do a store.
Chris Lattner7ab65932005-01-08 05:45:24 +00001637 if (CFP->getType() == Type::FloatTy) {
1638 union {
1639 unsigned I;
1640 float F;
1641 } V;
1642 V.F = CFP->getValue();
1643 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1644 X86::ESP, ArgOffset).addImm(V.I);
1645 } else {
1646 union {
1647 uint64_t I;
1648 double F;
1649 } V;
1650 V.F = CFP->getValue();
1651 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1652 X86::ESP, ArgOffset).addImm((unsigned)V.I);
1653 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1654 X86::ESP, ArgOffset+4).addImm(unsigned(V.I >> 32));
1655 ArgOffset += 4; // 8 byte entry, not 4.
1656 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001657 } else {
Chris Lattner7ab65932005-01-08 05:45:24 +00001658 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1659 if (Args[i].Ty == Type::FloatTy) {
1660 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1661 X86::ESP, ArgOffset).addReg(ArgReg);
1662 } else {
1663 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1664 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1665 X86::ESP, ArgOffset).addReg(ArgReg);
1666 ArgOffset += 4; // 8 byte entry, not 4.
1667 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001668 }
1669 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001670
Chris Lattner3e130a22003-01-13 00:32:26 +00001671 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001672 }
1673 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001674 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001675 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001676 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001677 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001678
Chris Lattner3e130a22003-01-13 00:32:26 +00001679 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001680
Chris Lattneree352852004-02-29 07:22:16 +00001681 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001682
1683 // If there is a return value, scavenge the result from the location the call
1684 // leaves it in...
1685 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001686 if (Ret.Ty != Type::VoidTy) {
1687 unsigned DestClass = getClassB(Ret.Ty);
1688 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001689 case cByte:
1690 case cShort:
1691 case cInt: {
1692 // Integral results are in %eax, or the appropriate portion
1693 // thereof.
1694 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001695 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001696 };
1697 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001698 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001699 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001700 }
Chris Lattner94af4142002-12-25 05:13:53 +00001701 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001702 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001703 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001704 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001705 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1706 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001707 break;
1708 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001709 }
Chris Lattnera3243642002-12-04 23:45:28 +00001710 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001711}
Chris Lattner2df035b2002-11-02 19:27:56 +00001712
Chris Lattner3e130a22003-01-13 00:32:26 +00001713
1714/// visitCallInst - Push args on stack and do a procedure call instruction.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001715void X86ISel::visitCallInst(CallInst &CI) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001716 MachineInstr *TheCall;
1717 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001718 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001719 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001720 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1721 return;
1722 }
1723
Chris Lattner3e130a22003-01-13 00:32:26 +00001724 // Emit a CALL instruction with PC-relative displacement.
1725 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1726 } else { // Emit an indirect call...
1727 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001728 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001729 }
1730
1731 std::vector<ValueRecord> Args;
1732 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001733 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001734
1735 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1736 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001737}
Chris Lattner3e130a22003-01-13 00:32:26 +00001738
Chris Lattner44827152003-12-28 09:47:19 +00001739/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1740/// function, lowering any calls to unknown intrinsic functions into the
1741/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001742///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001743void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
Chris Lattner44827152003-12-28 09:47:19 +00001744 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1745 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1746 if (CallInst *CI = dyn_cast<CallInst>(I++))
1747 if (Function *F = CI->getCalledFunction())
1748 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001749 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001750 case Intrinsic::vastart:
1751 case Intrinsic::vacopy:
1752 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001753 case Intrinsic::returnaddress:
1754 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001755 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001756 case Intrinsic::memset:
Chris Lattnerdc572442004-06-15 21:36:44 +00001757 case Intrinsic::isunordered:
John Criswell4ffff9e2004-04-08 20:31:47 +00001758 case Intrinsic::readport:
1759 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001760 // We directly implement these intrinsics
1761 break;
John Criswelle5a4c152004-04-13 22:13:14 +00001762 case Intrinsic::readio: {
1763 // On X86, memory operations are in-order. Lower this intrinsic
1764 // into a volatile load.
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001765 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1766 CI->replaceAllUsesWith(LI);
1767 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001768 break;
1769 }
1770 case Intrinsic::writeio: {
1771 // On X86, memory operations are in-order. Lower this intrinsic
1772 // into a volatile store.
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001773 StoreInst *LI = new StoreInst(CI->getOperand(1),
1774 CI->getOperand(2), true, CI);
1775 CI->replaceAllUsesWith(LI);
1776 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001777 break;
1778 }
Chris Lattner44827152003-12-28 09:47:19 +00001779 default:
1780 // All other intrinsic calls we must lower.
1781 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001782 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001783 if (Before) { // Move iterator to instruction after call
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001784 I = Before; ++I;
Chris Lattner44827152003-12-28 09:47:19 +00001785 } else {
1786 I = BB->begin();
1787 }
1788 }
Chris Lattner44827152003-12-28 09:47:19 +00001789}
1790
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001791void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001792 unsigned TmpReg1, TmpReg2;
1793 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001794 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001795 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001796 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001797 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001798 return;
1799
Chris Lattner5634b9f2004-03-13 00:24:52 +00001800 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001801 TmpReg1 = getReg(CI);
1802 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001803 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001804 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001805 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001806
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001807 case Intrinsic::returnaddress:
1808 case Intrinsic::frameaddress:
1809 TmpReg1 = getReg(CI);
1810 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
Chris Lattner8cdbc352004-12-17 00:46:51 +00001811 if (ReturnAddressIndex == 0) {
Chris Lattner11cf7aa2004-12-17 00:07:46 +00001812 // Set up a frame object for the return address.
1813 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
1814 }
1815
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001816 if (ID == Intrinsic::returnaddress) {
1817 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001818 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001819 ReturnAddressIndex);
1820 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001821 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001822 ReturnAddressIndex, -4);
1823 }
1824 } else {
1825 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001826 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001827 }
1828 return;
1829
Chris Lattnerdc572442004-06-15 21:36:44 +00001830 case Intrinsic::isunordered:
1831 TmpReg1 = getReg(CI.getOperand(1));
1832 TmpReg2 = getReg(CI.getOperand(2));
1833 emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1834 TmpReg2 = getReg(CI);
1835 BuildMI(BB, X86::SETPr, 0, TmpReg2);
1836 return;
1837
Chris Lattner915e5e52004-02-12 17:53:22 +00001838 case Intrinsic::memcpy: {
1839 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1840 unsigned Align = 1;
1841 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1842 Align = AlignC->getRawValue();
1843 if (Align == 0) Align = 1;
1844 }
1845
1846 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001847 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001848 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001849 switch (Align & 3) {
1850 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001851 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1852 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1853 } else {
1854 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001855 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001856 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001857 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001858 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001859 break;
1860 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001861 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1862 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1863 } else {
1864 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001865 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001866 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001867 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001868 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001869 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001870 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001871 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001872 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001873 break;
1874 }
1875
1876 // No matter what the alignment is, we put the source in ESI, the
1877 // destination in EDI, and the count in ECX.
1878 TmpReg1 = getReg(CI.getOperand(1));
1879 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001880 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1881 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1882 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001883 BuildMI(BB, Opcode, 0);
1884 return;
1885 }
1886 case Intrinsic::memset: {
1887 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1888 unsigned Align = 1;
1889 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1890 Align = AlignC->getRawValue();
1891 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001892 }
1893
Chris Lattner2a0f2242004-02-14 04:46:05 +00001894 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001895 unsigned CountReg;
1896 unsigned Opcode;
1897 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1898 unsigned Val = ValC->getRawValue() & 255;
1899
1900 // If the value is a constant, then we can potentially use larger copies.
1901 switch (Align & 3) {
1902 case 2: // WORD aligned
1903 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001904 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001905 } else {
1906 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001907 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001908 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001909 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001910 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001911 Opcode = X86::REP_STOSW;
1912 break;
1913 case 0: // DWORD aligned
1914 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001915 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001916 } else {
1917 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001918 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001919 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001920 }
1921 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001922 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001923 Opcode = X86::REP_STOSD;
1924 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001925 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001926 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001927 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001928 Opcode = X86::REP_STOSB;
1929 break;
1930 }
1931 } else {
1932 // If it's not a constant value we are storing, just fall back. We could
1933 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1934 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001935 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001936 CountReg = getReg(CI.getOperand(3));
1937 Opcode = X86::REP_STOSB;
1938 }
1939
1940 // No matter what the alignment is, we put the source in ESI, the
1941 // destination in EDI, and the count in ECX.
1942 TmpReg1 = getReg(CI.getOperand(1));
1943 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001944 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1945 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001946 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001947 return;
1948 }
1949
Chris Lattner87e18de2004-04-13 17:20:37 +00001950 case Intrinsic::readport: {
1951 // First, determine that the size of the operand falls within the acceptable
1952 // range for this architecture.
John Criswell4ffff9e2004-04-08 20:31:47 +00001953 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001954 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001955 std::cerr << "llvm.readport: Address size is not 16 bits\n";
Chris Lattner87e18de2004-04-13 17:20:37 +00001956 exit(1);
John Criswellca6ea0f2004-04-08 22:39:13 +00001957 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001958
John Criswell4ffff9e2004-04-08 20:31:47 +00001959 // Now, move the I/O port address into the DX register and use the IN
1960 // instruction to get the input data.
1961 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001962 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1963 unsigned DestReg = getReg(CI);
John Criswell4ffff9e2004-04-08 20:31:47 +00001964
Chris Lattner87e18de2004-04-13 17:20:37 +00001965 // If the port is a single-byte constant, use the immediate form.
1966 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1967 if ((C->getRawValue() & 255) == C->getRawValue()) {
1968 switch (Class) {
1969 case cByte:
1970 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1971 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1972 return;
1973 case cShort:
1974 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1975 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1976 return;
1977 case cInt:
1978 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1979 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1980 return;
1981 }
1982 }
1983
1984 unsigned Reg = getReg(CI.getOperand(1));
1985 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1986 switch (Class) {
1987 case cByte:
1988 BuildMI(BB, X86::IN8rr, 0);
1989 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1990 break;
1991 case cShort:
1992 BuildMI(BB, X86::IN16rr, 0);
1993 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1994 break;
1995 case cInt:
1996 BuildMI(BB, X86::IN32rr, 0);
1997 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1998 break;
1999 default:
2000 std::cerr << "Cannot do input on this data type";
John Criswellca6ea0f2004-04-08 22:39:13 +00002001 exit (1);
2002 }
John Criswell4ffff9e2004-04-08 20:31:47 +00002003 return;
Chris Lattner87e18de2004-04-13 17:20:37 +00002004 }
John Criswell4ffff9e2004-04-08 20:31:47 +00002005
Chris Lattner87e18de2004-04-13 17:20:37 +00002006 case Intrinsic::writeport: {
2007 // First, determine that the size of the operand falls within the
2008 // acceptable range for this architecture.
2009 if (getClass(CI.getOperand(2)->getType()) != cShort) {
2010 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
2011 exit(1);
2012 }
2013
2014 unsigned Class = getClassB(CI.getOperand(1)->getType());
2015 unsigned ValReg = getReg(CI.getOperand(1));
2016 switch (Class) {
2017 case cByte:
2018 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
2019 break;
2020 case cShort:
2021 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
2022 break;
2023 case cInt:
2024 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
2025 break;
2026 default:
2027 std::cerr << "llvm.writeport: invalid data type for X86 target";
2028 exit(1);
2029 }
2030
2031
2032 // If the port is a single-byte constant, use the immediate form.
2033 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
2034 if ((C->getRawValue() & 255) == C->getRawValue()) {
2035 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
2036 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
2037 return;
2038 }
2039
2040 // Otherwise, move the I/O port address into the DX register and the value
2041 // to write into the AL/AX/EAX register.
2042 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
2043 unsigned Reg = getReg(CI.getOperand(2));
2044 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
2045 BuildMI(BB, Opc[Class], 0);
2046 return;
2047 }
2048
Chris Lattner44827152003-12-28 09:47:19 +00002049 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002050 }
2051}
2052
Chris Lattner7dee5da2004-03-08 01:58:35 +00002053static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
2054 if (LI.getParent() != User.getParent())
2055 return false;
2056 BasicBlock::iterator It = &LI;
2057 // Check all of the instructions between the load and the user. We should
2058 // really use alias analysis here, but for now we just do something simple.
2059 for (++It; It != BasicBlock::iterator(&User); ++It) {
2060 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00002061 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00002062 case Instruction::Store:
2063 case Instruction::Call:
2064 case Instruction::Invoke:
2065 return false;
Chris Lattner133dbb12004-04-12 03:02:48 +00002066 case Instruction::Load:
2067 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
2068 return false;
2069 break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002070 }
2071 }
2072 return true;
2073}
2074
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002075/// visitSimpleBinary - Implement simple binary operators for integral types...
2076/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2077/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00002078///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002079void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002080 unsigned DestReg = getReg(B);
2081 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00002082 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002083 unsigned Class = getClassB(B.getType());
Chris Lattner721d2d42004-03-08 01:18:36 +00002084
Chris Lattnerde95c9e2004-10-17 06:10:40 +00002085 // If this is AND X, C, and it is only used by a setcc instruction, it will
2086 // be folded. There is no need to emit this instruction.
2087 if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
2088 if (Class == cByte || Class == cShort || Class == cInt) {
2089 Instruction *Use = cast<Instruction>(B.use_back());
2090 if (isa<SetCondInst>(Use) &&
2091 Use->getOperand(1) == Constant::getNullValue(B.getType())) {
2092 switch (getSetCCNumber(Use->getOpcode())) {
2093 case 0:
2094 case 1:
2095 return;
2096 default:
2097 if (B.getType()->isSigned()) return;
2098 }
2099 }
2100 }
2101
Chris Lattner7dee5da2004-03-08 01:58:35 +00002102 // Special case: op Reg, load [mem]
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002103 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
Chris Lattnerccd97962004-06-17 22:15:25 +00002104 Op0->hasOneUse() &&
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002105 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
Chris Lattner7dee5da2004-03-08 01:58:35 +00002106 if (!B.swapOperands())
2107 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2108
Chris Lattnerccd97962004-06-17 22:15:25 +00002109 if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
Chris Lattner7dee5da2004-03-08 01:58:35 +00002110 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
2111
Chris Lattner95157f72004-04-11 22:05:45 +00002112 unsigned Opcode;
2113 if (Class != cFP) {
2114 static const unsigned OpcodeTab[][3] = {
2115 // Arithmetic operators
2116 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
2117 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
2118
2119 // Bitwise operators
2120 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
2121 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
2122 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
2123 };
2124 Opcode = OpcodeTab[OperatorClass][Class];
2125 } else {
2126 static const unsigned OpcodeTab[][2] = {
2127 { X86::FADD32m, X86::FADD64m }, // ADD
2128 { X86::FSUB32m, X86::FSUB64m }, // SUB
2129 };
2130 const Type *Ty = Op0->getType();
2131 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2132 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
2133 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002134
Chris Lattner7dee5da2004-03-08 01:58:35 +00002135 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002136 if (AllocaInst *AI =
2137 dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
2138 unsigned FI = getFixedSizedAllocaFI(AI);
2139 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2140
2141 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002142 X86AddressMode AM;
2143 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002144
Reid Spencerfc989e12004-08-30 00:13:26 +00002145 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002146 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002147 return;
2148 }
2149
Chris Lattner95157f72004-04-11 22:05:45 +00002150 // If this is a floating point subtract, check to see if we can fold the first
2151 // operand in.
2152 if (Class == cFP && OperatorClass == 1 &&
2153 isa<LoadInst>(Op0) &&
2154 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2155 const Type *Ty = Op0->getType();
2156 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2157 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2158
Chris Lattner95157f72004-04-11 22:05:45 +00002159 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002160 if (AllocaInst *AI =
2161 dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2162 unsigned FI = getFixedSizedAllocaFI(AI);
2163 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2164 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002165 X86AddressMode AM;
2166 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002167
Reid Spencerfc989e12004-08-30 00:13:26 +00002168 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002169 }
Chris Lattner95157f72004-04-11 22:05:45 +00002170 return;
2171 }
2172
Chris Lattner721d2d42004-03-08 01:18:36 +00002173 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002174}
Chris Lattner3e130a22003-01-13 00:32:26 +00002175
Chris Lattner6621ed92004-04-11 21:23:56 +00002176
2177/// emitBinaryFPOperation - This method handles emission of floating point
2178/// Add (0), Sub (1), Mul (2), and Div (3) operations.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002179void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2180 MachineBasicBlock::iterator IP,
2181 Value *Op0, Value *Op1,
2182 unsigned OperatorClass, unsigned DestReg) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002183 // Special case: op Reg, <const fp>
2184 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2185 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2186 // Create a constant pool entry for this constant.
2187 MachineConstantPool *CP = F->getConstantPool();
2188 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2189 const Type *Ty = Op1->getType();
2190
2191 static const unsigned OpcodeTab[][4] = {
2192 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2193 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2194 };
2195
2196 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2197 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2198 unsigned Op0r = getReg(Op0, BB, IP);
2199 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2200 DestReg).addReg(Op0r), CPI);
2201 return;
2202 }
2203
Chris Lattner13c07fe2004-04-12 00:12:04 +00002204 // Special case: R1 = op <const fp>, R2
Chris Lattner6621ed92004-04-11 21:23:56 +00002205 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2206 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2207 // -0.0 - X === -X
2208 unsigned op1Reg = getReg(Op1, BB, IP);
2209 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2210 return;
2211 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
Chris Lattner13c07fe2004-04-12 00:12:04 +00002212 // R1 = op CST, R2 --> R1 = opr R2, CST
Chris Lattner6621ed92004-04-11 21:23:56 +00002213
2214 // Create a constant pool entry for this constant.
2215 MachineConstantPool *CP = F->getConstantPool();
2216 unsigned CPI = CP->getConstantPoolIndex(CFP);
2217 const Type *Ty = CFP->getType();
2218
2219 static const unsigned OpcodeTab[][4] = {
2220 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2221 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2222 };
2223
2224 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2225 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2226 unsigned Op1r = getReg(Op1, BB, IP);
2227 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2228 DestReg).addReg(Op1r), CPI);
2229 return;
2230 }
2231
2232 // General case.
2233 static const unsigned OpcodeTab[4] = {
2234 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2235 };
2236
2237 unsigned Opcode = OpcodeTab[OperatorClass];
2238 unsigned Op0r = getReg(Op0, BB, IP);
2239 unsigned Op1r = getReg(Op1, BB, IP);
2240 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2241}
2242
Chris Lattnerb2acc512003-10-19 21:09:10 +00002243/// emitSimpleBinaryOperation - Implement simple binary operators for integral
2244/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2245/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00002246///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002247/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2248/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002249///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002250void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2251 MachineBasicBlock::iterator IP,
2252 Value *Op0, Value *Op1,
2253 unsigned OperatorClass,
2254 unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002255 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00002256
Chris Lattner6621ed92004-04-11 21:23:56 +00002257 if (Class == cFP) {
2258 assert(OperatorClass < 2 && "No logical ops for FP!");
2259 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2260 return;
2261 }
2262
Chris Lattner48b0c972004-04-11 20:26:20 +00002263 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
Chris Lattner667ea022004-06-18 00:50:37 +00002264 if (OperatorClass == 1) {
Chris Lattner48b0c972004-04-11 20:26:20 +00002265 static unsigned const NEGTab[] = {
2266 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2267 };
Chris Lattner667ea022004-06-18 00:50:37 +00002268
2269 // sub 0, X -> neg X
2270 if (CI->isNullValue()) {
2271 unsigned op1Reg = getReg(Op1, MBB, IP);
2272 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
Chris Lattner48b0c972004-04-11 20:26:20 +00002273
Chris Lattner667ea022004-06-18 00:50:37 +00002274 if (Class == cLong) {
2275 // We just emitted: Dl = neg Sl
2276 // Now emit : T = addc Sh, 0
2277 // : Dh = neg T
2278 unsigned T = makeAnotherReg(Type::IntTy);
2279 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2280 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2281 }
2282 return;
2283 } else if (Op1->hasOneUse() && Class != cLong) {
2284 // sub C, X -> tmp = neg X; DestReg = add tmp, C. This is better
2285 // than copying C into a temporary register, because of register
2286 // pressure (tmp and destreg can share a register.
2287 static unsigned const ADDRITab[] = {
2288 X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2289 };
2290 unsigned op1Reg = getReg(Op1, MBB, IP);
2291 unsigned Tmp = makeAnotherReg(Op0->getType());
2292 BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
Chris Lattner30483732004-06-20 07:49:54 +00002293 BuildMI(*MBB, IP, ADDRITab[Class], 2,
2294 DestReg).addReg(Tmp).addImm(CI->getRawValue());
Chris Lattner667ea022004-06-18 00:50:37 +00002295 return;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002296 }
Chris Lattner48b0c972004-04-11 20:26:20 +00002297 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002298
Chris Lattner48b0c972004-04-11 20:26:20 +00002299 // Special case: op Reg, <const int>
2300 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002301 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002302
Chris Lattner721d2d42004-03-08 01:18:36 +00002303 // xor X, -1 -> not X
2304 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002305 static unsigned const NOTTab[] = {
2306 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2307 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002308 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002309 if (Class == cLong) // Invert the top part too
2310 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00002311 return;
2312 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002313
Chris Lattner721d2d42004-03-08 01:18:36 +00002314 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00002315 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2316 // Note that we can't use dec for 64-bit decrements, because it does not
2317 // set the carry flag!
2318 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00002319 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2320 return;
2321 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002322
Chris Lattner721d2d42004-03-08 01:18:36 +00002323 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00002324 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2325 // Note that we can't use inc for 64-bit increments, because it does not
2326 // set the carry flag!
2327 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00002328 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00002329 return;
2330 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002331
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002332 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002333 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002334 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2335 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00002336
Chris Lattner721d2d42004-03-08 01:18:36 +00002337 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002338 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2339 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2340 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00002341 };
2342
Chris Lattner721d2d42004-03-08 01:18:36 +00002343 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00002344 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00002345
Chris Lattner33f7fa32004-04-06 03:15:53 +00002346 if (Class != cLong) {
2347 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2348 return;
Chris Lattner6621ed92004-04-11 21:23:56 +00002349 }
2350
2351 // If this is a long value and the high or low bits have a special
2352 // property, emit some special cases.
2353 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2354
2355 // If the constant is zero in the low 32-bits, just copy the low part
2356 // across and apply the normal 32-bit operation to the high parts. There
2357 // will be no carry or borrow into the top.
2358 if (Op1l == 0) {
2359 if (OperatorClass != 2) // All but and...
2360 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2361 else
2362 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2363 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2364 .addReg(Op0r+1).addImm(Op1h);
Chris Lattner33f7fa32004-04-06 03:15:53 +00002365 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002366 }
Chris Lattner6621ed92004-04-11 21:23:56 +00002367
2368 // If this is a logical operation and the top 32-bits are zero, just
2369 // operate on the lower 32.
2370 if (Op1h == 0 && OperatorClass > 1) {
2371 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2372 .addReg(Op0r).addImm(Op1l);
2373 if (OperatorClass != 2) // All but and
2374 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2375 else
2376 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2377 return;
2378 }
2379
2380 // TODO: We could handle lots of other special cases here, such as AND'ing
2381 // with 0xFFFFFFFF00000000 -> noop, etc.
2382
2383 // Otherwise, code generate the full operation with a constant.
2384 static const unsigned TopTab[] = {
2385 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2386 };
2387
2388 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2389 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2390 .addReg(Op0r+1).addImm(Op1h);
2391 return;
Chris Lattner721d2d42004-03-08 01:18:36 +00002392 }
2393
2394 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00002395 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002396 // Arithmetic operators
Chris Lattner6621ed92004-04-11 21:23:56 +00002397 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2398 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002399
Chris Lattnerb2acc512003-10-19 21:09:10 +00002400 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002401 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2402 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2403 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002404 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002405
Chris Lattnerb2acc512003-10-19 21:09:10 +00002406 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002407 unsigned Op0r = getReg(Op0, MBB, IP);
2408 unsigned Op1r = getReg(Op1, MBB, IP);
2409 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2410
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002411 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002412 static const unsigned TopTab[] = {
2413 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2414 };
2415 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2416 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2417 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002418}
2419
Chris Lattner3e130a22003-01-13 00:32:26 +00002420/// doMultiply - Emit appropriate instructions to multiply together the
2421/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2422/// result should be given as DestTy.
2423///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002424void X86ISel::doMultiply(MachineBasicBlock *MBB,
2425 MachineBasicBlock::iterator MBBI,
2426 unsigned DestReg, const Type *DestTy,
2427 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002428 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002429 switch (Class) {
Chris Lattner0f1c4612003-06-21 17:16:58 +00002430 case cInt:
2431 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002432 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002433 .addReg(op0Reg).addReg(op1Reg);
2434 return;
2435 case cByte:
2436 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002437 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2438 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2439 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002440 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002441 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002442 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002443 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002444}
2445
Chris Lattnerb2acc512003-10-19 21:09:10 +00002446// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2447// returns zero when the input is not exactly a power of two.
2448static unsigned ExactLog2(unsigned Val) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002449 if (Val == 0 || (Val & (Val-1))) return 0;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002450 unsigned Count = 0;
2451 while (Val != 1) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002452 Val >>= 1;
2453 ++Count;
2454 }
2455 return Count+1;
2456}
2457
Chris Lattner462fa822004-04-11 20:56:28 +00002458
2459/// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2460/// 16, or 32-bit integer multiply by a constant.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002461void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2462 MachineBasicBlock::iterator IP,
2463 unsigned DestReg, const Type *DestTy,
2464 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002465 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2466 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002467 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
Chris Lattner596b97f2004-07-19 23:47:21 +00002468 static const unsigned NEGrTab[] = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
Chris Lattner6ab06d52004-04-06 04:55:43 +00002469
Chris Lattnerb2acc512003-10-19 21:09:10 +00002470 unsigned Class = getClass(DestTy);
Chris Lattner596b97f2004-07-19 23:47:21 +00002471 unsigned TmpReg;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002472
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002473 // Handle special cases here.
2474 switch (ConstRHS) {
Chris Lattner596b97f2004-07-19 23:47:21 +00002475 case -2:
2476 TmpReg = makeAnotherReg(DestTy);
2477 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2478 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2479 return;
2480 case -1:
2481 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2482 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002483 case 0:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002484 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2485 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002486 case 1:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002487 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2488 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002489 case 2:
2490 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2491 return;
2492 case 3:
2493 case 5:
2494 case 9:
2495 if (Class == cInt) {
Reid Spencerfc989e12004-08-30 00:13:26 +00002496 X86AddressMode AM;
2497 AM.BaseType = X86AddressMode::RegBase;
2498 AM.Base.Reg = op0Reg;
2499 AM.Scale = ConstRHS-1;
2500 AM.IndexReg = op0Reg;
2501 AM.Disp = 0;
2502 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002503 return;
2504 }
Chris Lattner596b97f2004-07-19 23:47:21 +00002505 case -3:
2506 case -5:
2507 case -9:
2508 if (Class == cInt) {
2509 TmpReg = makeAnotherReg(DestTy);
Reid Spencerfc989e12004-08-30 00:13:26 +00002510 X86AddressMode AM;
2511 AM.BaseType = X86AddressMode::RegBase;
2512 AM.Base.Reg = op0Reg;
2513 AM.Scale = -ConstRHS-1;
2514 AM.IndexReg = op0Reg;
2515 AM.Disp = 0;
2516 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
Chris Lattner596b97f2004-07-19 23:47:21 +00002517 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2518 return;
2519 }
Chris Lattner6ab06d52004-04-06 04:55:43 +00002520 }
2521
Chris Lattnerb2acc512003-10-19 21:09:10 +00002522 // If the element size is exactly a power of 2, use a shift to get it.
2523 if (unsigned Shift = ExactLog2(ConstRHS)) {
2524 switch (Class) {
2525 default: assert(0 && "Unknown class for this function!");
2526 case cByte:
Chris Lattner596b97f2004-07-19 23:47:21 +00002527 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002528 return;
2529 case cShort:
Chris Lattner596b97f2004-07-19 23:47:21 +00002530 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002531 return;
2532 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002533 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002534 return;
2535 }
2536 }
Chris Lattner596b97f2004-07-19 23:47:21 +00002537
2538 // If the element size is a negative power of 2, use a shift/neg to get it.
2539 if (unsigned Shift = ExactLog2(-ConstRHS)) {
2540 TmpReg = makeAnotherReg(DestTy);
2541 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2542 switch (Class) {
2543 default: assert(0 && "Unknown class for this function!");
2544 case cByte:
2545 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2546 return;
2547 case cShort:
2548 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2549 return;
2550 case cInt:
2551 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2552 return;
2553 }
2554 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002555
2556 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002557 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002558 return;
2559 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002560 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002561 return;
2562 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002563
2564 // Most general case, emit a normal multiply...
Chris Lattner596b97f2004-07-19 23:47:21 +00002565 TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002566 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002567
2568 // Emit a MUL to multiply the register holding the index by
2569 // elementSize, putting the result in OffsetReg.
2570 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2571}
2572
Chris Lattnerca9671d2002-11-02 20:28:58 +00002573/// visitMul - Multiplies are not simple binary operators because they must deal
2574/// with the EAX register explicitly.
2575///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002576void X86ISel::visitMul(BinaryOperator &I) {
Chris Lattner462fa822004-04-11 20:56:28 +00002577 unsigned ResultReg = getReg(I);
2578
Chris Lattner95157f72004-04-11 22:05:45 +00002579 Value *Op0 = I.getOperand(0);
2580 Value *Op1 = I.getOperand(1);
2581
2582 // Fold loads into floating point multiplies.
2583 if (getClass(Op0->getType()) == cFP) {
2584 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2585 if (!I.swapOperands())
2586 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2587 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2588 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2589 const Type *Ty = Op0->getType();
2590 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2591 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2592
Chris Lattner95157f72004-04-11 22:05:45 +00002593 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002594 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2595 unsigned FI = getFixedSizedAllocaFI(AI);
2596 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2597 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002598 X86AddressMode AM;
2599 getAddressingMode(LI->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002600
Reid Spencerfc989e12004-08-30 00:13:26 +00002601 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002602 }
Chris Lattner95157f72004-04-11 22:05:45 +00002603 return;
2604 }
2605 }
2606
Chris Lattner462fa822004-04-11 20:56:28 +00002607 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002608 emitMultiply(BB, IP, Op0, Op1, ResultReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002609}
2610
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002611void X86ISel::emitMultiply(MachineBasicBlock *MBB,
2612 MachineBasicBlock::iterator IP,
2613 Value *Op0, Value *Op1, unsigned DestReg) {
Chris Lattner462fa822004-04-11 20:56:28 +00002614 MachineBasicBlock &BB = *MBB;
2615 TypeClass Class = getClass(Op0->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +00002616
2617 // Simple scalar multiply?
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002618 unsigned Op0Reg = getReg(Op0, &BB, IP);
Chris Lattner462fa822004-04-11 20:56:28 +00002619 switch (Class) {
2620 case cByte:
2621 case cShort:
2622 case cInt:
2623 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner462fa822004-04-11 20:56:28 +00002624 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2625 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002626 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002627 unsigned Op1Reg = getReg(Op1, &BB, IP);
2628 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002629 }
Chris Lattner462fa822004-04-11 20:56:28 +00002630 return;
2631 case cFP:
Chris Lattner6621ed92004-04-11 21:23:56 +00002632 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2633 return;
Chris Lattner462fa822004-04-11 20:56:28 +00002634 case cLong:
2635 break;
2636 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002637
Chris Lattner462fa822004-04-11 20:56:28 +00002638 // Long value. We have to do things the hard way...
2639 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2640 unsigned CLow = CI->getRawValue();
2641 unsigned CHi = CI->getRawValue() >> 32;
2642
2643 if (CLow == 0) {
2644 // If the low part of the constant is all zeros, things are simple.
2645 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2646 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2647 return;
2648 }
2649
2650 // Multiply the two low parts... capturing carry into EDX
2651 unsigned OverflowReg = 0;
2652 if (CLow == 1) {
2653 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
Chris Lattner028adc42004-04-06 04:29:36 +00002654 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002655 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2656 OverflowReg = makeAnotherReg(Type::UIntTy);
2657 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2658 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2659 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002660
Chris Lattner462fa822004-04-11 20:56:28 +00002661 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2662 BuildMI(BB, IP, X86::MOV32rr, 1,
2663 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2664 }
2665
2666 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2667 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2668
2669 unsigned AHBLplusOverflowReg;
2670 if (OverflowReg) {
2671 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2672 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002673 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002674 } else {
2675 AHBLplusOverflowReg = AHBLReg;
2676 }
2677
2678 if (CHi == 0) {
2679 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2680 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002681 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner462fa822004-04-11 20:56:28 +00002682 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002683
Chris Lattner462fa822004-04-11 20:56:28 +00002684 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002685 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2686 }
Chris Lattner462fa822004-04-11 20:56:28 +00002687 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002688 }
Chris Lattner462fa822004-04-11 20:56:28 +00002689
2690 // General 64x64 multiply
2691
2692 unsigned Op1Reg = getReg(Op1, &BB, IP);
2693 // Multiply the two low parts... capturing carry into EDX
2694 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2695 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2696
2697 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2698 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2699 BuildMI(BB, IP, X86::MOV32rr, 1,
2700 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2701
2702 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2703 BuildMI(BB, IP, X86::IMUL32rr, 2,
2704 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2705
2706 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2707 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2708 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2709
2710 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2711 BuildMI(BB, IP, X86::IMUL32rr, 2,
2712 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2713
2714 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2715 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002716}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002717
Chris Lattner06925362002-11-17 21:56:38 +00002718
Chris Lattnerf01729e2002-11-02 20:54:46 +00002719/// visitDivRem - Handle division and remainder instructions... these
2720/// instruction both require the same instructions to be generated, they just
2721/// select the result from a different register. Note that both of these
2722/// instructions work differently for signed and unsigned operands.
2723///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002724void X86ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002725 unsigned ResultReg = getReg(I);
Chris Lattner95157f72004-04-11 22:05:45 +00002726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2727
2728 // Fold loads into floating point divides.
2729 if (getClass(Op0->getType()) == cFP) {
2730 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2731 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2732 const Type *Ty = Op0->getType();
2733 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2734 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2735
Chris Lattner95157f72004-04-11 22:05:45 +00002736 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002737 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2738 unsigned FI = getFixedSizedAllocaFI(AI);
2739 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2740 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002741 X86AddressMode AM;
2742 getAddressingMode(LI->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002743
Reid Spencerfc989e12004-08-30 00:13:26 +00002744 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002745 }
Chris Lattner95157f72004-04-11 22:05:45 +00002746 return;
2747 }
2748
2749 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2750 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2751 const Type *Ty = Op0->getType();
2752 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2753 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2754
Chris Lattner95157f72004-04-11 22:05:45 +00002755 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002756 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2757 unsigned FI = getFixedSizedAllocaFI(AI);
2758 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2759 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002760 X86AddressMode AM;
2761 getAddressingMode(LI->getOperand(0), AM);
2762 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002763 }
Chris Lattner95157f72004-04-11 22:05:45 +00002764 return;
2765 }
2766 }
2767
Chris Lattner94af4142002-12-25 05:13:53 +00002768
Chris Lattnercadff442003-10-23 17:21:43 +00002769 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002770 emitDivRemOperation(BB, IP, Op0, Op1,
Chris Lattner462fa822004-04-11 20:56:28 +00002771 I.getOpcode() == Instruction::Div, ResultReg);
Chris Lattnercadff442003-10-23 17:21:43 +00002772}
2773
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002774void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2775 MachineBasicBlock::iterator IP,
2776 Value *Op0, Value *Op1, bool isDiv,
2777 unsigned ResultReg) {
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002778 const Type *Ty = Op0->getType();
2779 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002780 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002781 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002782 if (isDiv) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002783 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2784 return;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002785 } else { // Floating point remainder...
Chris Lattner462fa822004-04-11 20:56:28 +00002786 unsigned Op0Reg = getReg(Op0, BB, IP);
2787 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002788 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002789 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002790 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002791 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2792 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002793 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2794 }
Chris Lattner94af4142002-12-25 05:13:53 +00002795 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002796 case cLong: {
2797 static const char *FnName[] =
2798 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
Chris Lattner462fa822004-04-11 20:56:28 +00002799 unsigned Op0Reg = getReg(Op0, BB, IP);
2800 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002801 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002802 MachineInstr *TheCall =
2803 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2804
2805 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002806 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2807 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002808 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2809 return;
2810 }
2811 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002812 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002813 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002814 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002815
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002816 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
Chris Lattner2483f672004-10-06 05:01:07 +00002817 static const unsigned NEGOpcode[]={ X86::NEG8r, X86::NEG16r, X86::NEG32r };
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002818 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2819 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2820 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2821
2822 // Special case signed division by power of 2.
Chris Lattner2483f672004-10-06 05:01:07 +00002823 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2824 if (isDiv) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002825 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2826 int V = CI->getValue();
2827
2828 if (V == 1) { // X /s 1 => X
2829 unsigned Op0Reg = getReg(Op0, BB, IP);
2830 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2831 return;
2832 }
2833
2834 if (V == -1) { // X /s -1 => -X
2835 unsigned Op0Reg = getReg(Op0, BB, IP);
2836 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2837 return;
2838 }
2839
Chris Lattner610f1e22004-10-06 04:02:39 +00002840 if (V == 2 || V == -2) { // X /s 2
2841 static const unsigned CMPOpcode[] = {
2842 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2843 };
2844 static const unsigned SBBOpcode[] = {
2845 X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2846 };
2847 unsigned Op0Reg = getReg(Op0, BB, IP);
2848 unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2849 BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2850
2851 unsigned TmpReg = makeAnotherReg(Op0->getType());
2852 BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2853
2854 unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2855 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2856 if (V == -2) {
2857 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2858 }
2859 return;
2860 }
2861
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002862 bool isNeg = false;
2863 if (V < 0) { // Not a positive power of 2?
2864 V = -V;
2865 isNeg = true; // Maybe it's a negative power of 2.
2866 }
2867 if (unsigned Log = ExactLog2(V)) {
2868 --Log;
2869 unsigned Op0Reg = getReg(Op0, BB, IP);
2870 unsigned TmpReg = makeAnotherReg(Op0->getType());
Chris Lattner3ffdff62004-10-06 04:19:43 +00002871 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2872 .addReg(Op0Reg).addImm(Log-1);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002873 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2874 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2875 .addReg(TmpReg).addImm(32-Log);
2876 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2877 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2878 .addReg(Op0Reg).addReg(TmpReg2);
2879
2880 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2881 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
Chris Lattner3ffdff62004-10-06 04:19:43 +00002882 .addReg(TmpReg3).addImm(Log);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002883 if (isNeg)
2884 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2885 return;
2886 }
Chris Lattner2483f672004-10-06 05:01:07 +00002887 } else { // X % C
2888 assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2889 int V = CI->getValue();
2890
2891 if (V == 2 || V == -2) { // X % 2, X % -2
Chris Lattner2483f672004-10-06 05:01:07 +00002892 static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2893 static const unsigned BaseReg[] = { X86::AL , X86::AX , X86::EAX };
2894 static const unsigned SExtReg[] = { X86::AH , X86::DX , X86::EDX };
2895 static const unsigned ANDOpcode[] = {
2896 X86::AND8ri, X86::AND16ri, X86::AND32ri
2897 };
2898 static const unsigned XOROpcode[] = {
2899 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2900 };
2901 static const unsigned SUBOpcode[] = {
2902 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2903 };
2904
2905 // Sign extend result into reg of -1 or 0.
2906 unsigned Op0Reg = getReg(Op0, BB, IP);
2907 BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2908 BuildMI(*BB, IP, SExtOpcode[Class], 0);
2909 unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2910 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2911
2912 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2913 BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2914
2915 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2916 BuildMI(*BB, IP, XOROpcode[Class], 2,
2917 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2918 BuildMI(*BB, IP, SUBOpcode[Class], 2,
2919 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2920 return;
2921 }
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002922 }
2923
2924 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002925 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002926 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
Chris Lattner5384b382005-01-05 16:30:14 +00002927 static const unsigned SExOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002928
2929 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002930 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2931 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002932 };
2933
Chris Lattnerf01729e2002-11-02 20:54:46 +00002934 unsigned Reg = Regs[Class];
2935 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002936
2937 // Put the first operand into one of the A registers...
Chris Lattner462fa822004-04-11 20:56:28 +00002938 unsigned Op0Reg = getReg(Op0, BB, IP);
2939 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00002940 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002941
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002942 if (Ty->isSigned()) {
Chris Lattner5384b382005-01-05 16:30:14 +00002943 // Emit a sign extension instruction.
2944 BuildMI(*BB, IP, SExOpcode[Class], 0);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002945
2946 // Emit the appropriate divide or remainder instruction...
2947 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002948 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002949 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002950 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002951
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002952 // Emit the appropriate divide or remainder instruction...
2953 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2954 }
Chris Lattner06925362002-11-17 21:56:38 +00002955
Chris Lattnerf01729e2002-11-02 20:54:46 +00002956 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002957 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002958
Chris Lattnerf01729e2002-11-02 20:54:46 +00002959 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002960 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002961}
Chris Lattnere2954c82002-11-02 20:04:26 +00002962
Chris Lattner06925362002-11-17 21:56:38 +00002963
Brian Gaekea1719c92002-10-31 23:03:59 +00002964/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2965/// for constant immediate shift values, and for constant immediate
2966/// shift values equal to 1. Even the general case is sort of special,
2967/// because the shift amount has to be in CL, not just any old register.
2968///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002969void X86ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002970 MachineBasicBlock::iterator IP = BB->end ();
2971 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2972 I.getOpcode () == Instruction::Shl, I.getType (),
2973 getReg (I));
2974}
2975
Chris Lattnerce7cafa2004-11-13 20:48:57 +00002976/// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
2977/// constant.
2978void X86ISel::doSHLDConst(MachineBasicBlock *MBB,
2979 MachineBasicBlock::iterator IP,
2980 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
2981 unsigned Amt) {
2982 // SHLD is a very inefficient operation on every processor, try to do
2983 // somethign simpler for common values of 'Amt'.
2984 if (Amt == 0) {
2985 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2986 } else if (Amt == 1) {
2987 unsigned Tmp = makeAnotherReg(Type::UIntTy);
2988 BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
2989 BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2990 } else if (Amt == 2 || Amt == 3) {
2991 // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
2992 // shift/lea pair. NOTE: This should not be done on the P6 family!
2993 unsigned Tmp = makeAnotherReg(Type::UIntTy);
2994 BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
2995 X86AddressMode AM;
2996 AM.BaseType = X86AddressMode::RegBase;
2997 AM.Base.Reg = Tmp;
2998 AM.Scale = 1 << Amt;
2999 AM.IndexReg = Op0Reg;
3000 AM.Disp = 0;
3001 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
3002 } else {
3003 // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
3004 // than it is to emit a real SHLD.
3005
3006 BuildMI(*MBB, IP, X86::SHLD32rri8, 3,
3007 DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
3008 }
3009}
3010
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003011/// emitShiftOperation - Common code shared between visitShiftInst and
3012/// constant expression support.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003013void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
3014 MachineBasicBlock::iterator IP,
3015 Value *Op, Value *ShiftAmount,
3016 bool isLeftShift, const Type *ResultTy,
3017 unsigned DestReg) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003018 unsigned SrcReg = getReg (Op, MBB, IP);
3019 bool isSigned = ResultTy->isSigned ();
3020 unsigned Class = getClass (ResultTy);
Chris Lattnerde95c9e2004-10-17 06:10:40 +00003021
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003022 static const unsigned ConstantOperand[][3] = {
3023 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri }, // SHR
3024 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri }, // SAR
3025 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SHL
3026 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00003027 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003028
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003029 static const unsigned NonConstantOperand[][3] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003030 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
3031 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
3032 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
3033 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00003034 };
Chris Lattner796df732002-11-02 00:44:25 +00003035
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003036 // Longs, as usual, are handled specially.
Chris Lattner3e130a22003-01-13 00:32:26 +00003037 if (Class == cLong) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003038 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003039 unsigned Amount = CUI->getValue();
Chris Lattner62f5a942004-11-13 20:04:38 +00003040 if (Amount == 1 && isLeftShift) { // X << 1 == X+X
Chris Lattner44205ca2004-11-13 20:03:48 +00003041 BuildMI(*MBB, IP, X86::ADD32rr, 2,
3042 DestReg).addReg(SrcReg).addReg(SrcReg);
3043 BuildMI(*MBB, IP, X86::ADC32rr, 2,
3044 DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
3045 } else if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003046 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3047 if (isLeftShift) {
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003048 doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
Chris Lattneree352852004-02-29 07:22:16 +00003049 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003050 } else {
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003051 BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
3052 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
Chris Lattneree352852004-02-29 07:22:16 +00003053 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003054 }
Chris Lattner36c625d2004-11-15 23:16:34 +00003055 } else if (Amount == 32) {
3056 if (isLeftShift) {
3057 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
3058 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3059 } else {
Chris Lattner39a83dc2004-11-16 18:40:52 +00003060 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
Chris Lattner36c625d2004-11-15 23:16:34 +00003061 if (!isSigned) {
3062 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3063 } else {
3064 BuildMI(*MBB, IP, X86::SAR32ri, 2,
3065 DestReg+1).addReg(SrcReg).addImm(31);
3066 }
3067 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003068 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003069 Amount -= 32;
3070 if (isLeftShift) {
Chris Lattner36c625d2004-11-15 23:16:34 +00003071 BuildMI(*MBB, IP, X86::SHL32ri, 2,
3072 DestReg + 1).addReg(SrcReg).addImm(Amount);
Chris Lattner722070e2004-04-06 03:42:38 +00003073 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003074 } else {
Chris Lattner36c625d2004-11-15 23:16:34 +00003075 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
3076 DestReg).addReg(SrcReg+1).addImm(Amount);
Chris Lattner6d027f22005-04-06 20:59:35 +00003077 if (isSigned)
3078 BuildMI(*MBB, IP, X86::SAR32ri, 2,
3079 DestReg+1).addReg(SrcReg+1).addImm(31);
3080 else
3081 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003082 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003083 }
3084 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00003085 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Chris Lattner9171ef52003-06-01 01:56:54 +00003086 if (!isLeftShift && isSigned) {
3087 // If this is a SHR of a Long, then we need to do funny sign extension
3088 // stuff. TmpReg gets the value to use as the high-part if we are
3089 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003090 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00003091 } else {
3092 // Other shifts use a fixed zero value if the shift is more than 32
3093 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003094 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00003095 }
3096
3097 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003098 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003099 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003100
3101 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
3102 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3103 if (isLeftShift) {
3104 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003105 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00003106 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003107 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003108 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003109
3110 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003111 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00003112
3113 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003114 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003115 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
3116 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003117 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003118 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003119 } else {
3120 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003121 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00003122 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00003123 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003124 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00003125 .addReg(SrcReg+1);
3126
3127 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003128 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00003129
3130 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003131 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003132 DestReg).addReg(TmpReg2).addReg(TmpReg3);
3133
3134 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003135 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003136 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
3137 }
Brian Gaekea1719c92002-10-31 23:03:59 +00003138 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003139 return;
3140 }
Chris Lattnere9913f22002-11-02 01:41:55 +00003141
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003142 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003143 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
3144 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003145
Chris Lattner44205ca2004-11-13 20:03:48 +00003146 if (CUI->getValue() == 1 && isLeftShift) { // X << 1 -> X+X
3147 static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
3148 BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
3149 } else {
3150 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3151 BuildMI(*MBB, IP, Opc[Class], 2,
3152 DestReg).addReg(SrcReg).addImm(CUI->getValue());
3153 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003154 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003155 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003156 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003157
Chris Lattner3e130a22003-01-13 00:32:26 +00003158 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00003159 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003160 }
3161}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003162
Chris Lattner3e130a22003-01-13 00:32:26 +00003163
Chris Lattner6fc3c522002-11-17 21:11:55 +00003164/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00003165/// instruction. The load and store instructions are the only place where we
3166/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00003167///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003168void X86ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00003169 // Check to see if this load instruction is going to be folded into a binary
3170 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
3171 // pattern matching instruction selector be nice?
Chris Lattner95157f72004-04-11 22:05:45 +00003172 unsigned Class = getClassB(I.getType());
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003173 if (I.hasOneUse()) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00003174 Instruction *User = cast<Instruction>(I.use_back());
3175 switch (User->getOpcode()) {
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003176 case Instruction::Cast:
3177 // If this is a cast from a signed-integer type to a floating point type,
3178 // fold the cast here.
John Criswell6b5bd582004-06-09 15:18:51 +00003179 if (getClassB(User->getType()) == cFP &&
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003180 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
3181 I.getType() == Type::LongTy)) {
3182 unsigned DestReg = getReg(User);
3183 static const unsigned Opcode[] = {
3184 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
3185 };
Chris Lattner9f1b5312004-05-13 15:12:43 +00003186
3187 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3188 unsigned FI = getFixedSizedAllocaFI(AI);
3189 addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3190 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003191 X86AddressMode AM;
3192 getAddressingMode(I.getOperand(0), AM);
3193 addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003194 }
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003195 return;
3196 } else {
3197 User = 0;
3198 }
3199 break;
Chris Lattner13c07fe2004-04-12 00:12:04 +00003200
Chris Lattner7dee5da2004-03-08 01:58:35 +00003201 case Instruction::Add:
3202 case Instruction::Sub:
3203 case Instruction::And:
3204 case Instruction::Or:
3205 case Instruction::Xor:
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003206 if (Class == cLong) User = 0;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003207 break;
Chris Lattner95157f72004-04-11 22:05:45 +00003208 case Instruction::Mul:
3209 case Instruction::Div:
Chris Lattner13c07fe2004-04-12 00:12:04 +00003210 if (Class != cFP) User = 0;
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003211 break; // Folding only implemented for floating point.
Chris Lattner95157f72004-04-11 22:05:45 +00003212 default: User = 0; break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003213 }
3214
3215 if (User) {
3216 // Okay, we found a user. If the load is the first operand and there is
3217 // no second operand load, reverse the operand ordering. Note that this
3218 // can fail for a subtract (ie, no change will be made).
Chris Lattner3dbb5042004-07-21 21:28:26 +00003219 bool Swapped = false;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003220 if (!isa<LoadInst>(User->getOperand(1)))
Chris Lattner3dbb5042004-07-21 21:28:26 +00003221 Swapped = !cast<BinaryOperator>(User)->swapOperands();
Chris Lattner7dee5da2004-03-08 01:58:35 +00003222
3223 // Okay, now that everything is set up, if this load is used by the second
3224 // operand, and if there are no instructions that invalidate the load
3225 // before the binary operator, eliminate the load.
3226 if (User->getOperand(1) == &I &&
3227 isSafeToFoldLoadIntoInstruction(I, *User))
3228 return; // Eliminate the load!
Chris Lattner95157f72004-04-11 22:05:45 +00003229
3230 // If this is a floating point sub or div, we won't be able to swap the
3231 // operands, but we will still be able to eliminate the load.
3232 if (Class == cFP && User->getOperand(0) == &I &&
3233 !isa<LoadInst>(User->getOperand(1)) &&
3234 (User->getOpcode() == Instruction::Sub ||
3235 User->getOpcode() == Instruction::Div) &&
3236 isSafeToFoldLoadIntoInstruction(I, *User))
3237 return; // Eliminate the load!
Chris Lattner3dbb5042004-07-21 21:28:26 +00003238
3239 // If we swapped the operands to the instruction, but couldn't fold the
3240 // load anyway, swap them back. We don't want to break add X, int
3241 // folding.
3242 if (Swapped) cast<BinaryOperator>(User)->swapOperands();
Chris Lattner7dee5da2004-03-08 01:58:35 +00003243 }
3244 }
3245
Chris Lattner6ac1d712003-10-20 04:48:06 +00003246 static const unsigned Opcodes[] = {
Chris Lattner9f1b5312004-05-13 15:12:43 +00003247 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
Chris Lattner3e130a22003-01-13 00:32:26 +00003248 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00003249 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003250 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003251
3252 unsigned DestReg = getReg(I);
3253
3254 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3255 unsigned FI = getFixedSizedAllocaFI(AI);
3256 if (Class == cLong) {
3257 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3258 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3259 } else {
3260 addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3261 }
3262 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003263 X86AddressMode AM;
3264 getAddressingMode(I.getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003265
3266 if (Class == cLong) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003267 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3268 AM.Disp += 4;
3269 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003270 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003271 addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003272 }
3273 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003274}
3275
Chris Lattner6fc3c522002-11-17 21:11:55 +00003276/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3277/// instruction.
3278///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003279void X86ISel::visitStoreInst(StoreInst &I) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003280 X86AddressMode AM;
3281 getAddressingMode(I.getOperand(1), AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003282
Chris Lattner6c09db22003-10-20 04:11:23 +00003283 const Type *ValTy = I.getOperand(0)->getType();
3284 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00003285
Chris Lattner5a830962004-02-25 02:56:58 +00003286 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3287 uint64_t Val = CI->getRawValue();
3288 if (Class == cLong) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003289 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3290 AM.Disp += 4;
3291 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00003292 } else {
3293 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003294 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00003295 };
3296 unsigned Opcode = Opcodes[Class];
Reid Spencerfc989e12004-08-30 00:13:26 +00003297 addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00003298 }
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00003299 } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
Chris Lattner358a9022004-10-15 05:05:29 +00003300 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
Chris Lattner5a830962004-02-25 02:56:58 +00003301 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003302 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
Chris Lattnere7a31c92004-05-07 21:18:15 +00003303 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3304 // Store constant FP values with integer instructions to avoid having to
3305 // load the constants from the constant pool then do a store.
3306 if (CFP->getType() == Type::FloatTy) {
3307 union {
3308 unsigned I;
3309 float F;
3310 } V;
3311 V.F = CFP->getValue();
Reid Spencerfc989e12004-08-30 00:13:26 +00003312 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
Chris Lattner5a830962004-02-25 02:56:58 +00003313 } else {
Chris Lattnere7a31c92004-05-07 21:18:15 +00003314 union {
3315 uint64_t I;
3316 double F;
3317 } V;
3318 V.F = CFP->getValue();
Reid Spencerfc989e12004-08-30 00:13:26 +00003319 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3320 AM.Disp += 4;
3321 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
Chris Lattnere7a31c92004-05-07 21:18:15 +00003322 unsigned(V.I >> 32));
Chris Lattner5a830962004-02-25 02:56:58 +00003323 }
Chris Lattnere7a31c92004-05-07 21:18:15 +00003324
3325 } else if (Class == cLong) {
3326 unsigned ValReg = getReg(I.getOperand(0));
Reid Spencerfc989e12004-08-30 00:13:26 +00003327 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3328 AM.Disp += 4;
3329 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
Chris Lattnere7a31c92004-05-07 21:18:15 +00003330 } else {
Chris Lattner358a9022004-10-15 05:05:29 +00003331 // FIXME: stop emitting these two instructions:
3332 // movl $global,%eax
3333 // movl %eax,(%ebx)
3334 // when one instruction will suffice. That includes when the global
3335 // has an offset applied to it.
Chris Lattnere7a31c92004-05-07 21:18:15 +00003336 unsigned ValReg = getReg(I.getOperand(0));
3337 static const unsigned Opcodes[] = {
3338 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3339 };
3340 unsigned Opcode = Opcodes[Class];
3341 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003342
Reid Spencerfc989e12004-08-30 00:13:26 +00003343 addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003344 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00003345}
3346
3347
Misha Brukman538607f2004-03-01 23:53:11 +00003348/// visitCastInst - Here we have various kinds of copying with or without sign
3349/// extension going on.
3350///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003351void X86ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003352 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00003353
Chris Lattner99382862004-04-12 00:23:04 +00003354 unsigned SrcClass = getClassB(Op->getType());
3355 unsigned DestClass = getClassB(CI.getType());
3356 // Noop casts are not emitted: getReg will return the source operand as the
3357 // register to use for any uses of the noop cast.
Chris Lattner8b486a12004-06-29 00:14:38 +00003358 if (DestClass == SrcClass) {
3359 // The only detail in this plan is that casts from double -> float are
3360 // truncating operations that we have to codegen through memory (despite
3361 // the fact that the source/dest registers are the same class).
3362 if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3363 return;
3364 }
Chris Lattner427aeb42004-04-11 19:21:59 +00003365
Chris Lattnerf5854472003-06-21 16:01:24 +00003366 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3367 // of the case are GEP instructions, then the cast does not need to be
3368 // generated explicitly, it will be folded into the GEP.
Chris Lattner99382862004-04-12 00:23:04 +00003369 if (DestClass == cLong && SrcClass == cInt) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003370 bool AllUsesAreGEPs = true;
3371 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3372 if (!isa<GetElementPtrInst>(*I)) {
3373 AllUsesAreGEPs = false;
3374 break;
3375 }
3376
3377 // No need to codegen this cast if all users are getelementptr instrs...
3378 if (AllUsesAreGEPs) return;
3379 }
3380
Chris Lattner99382862004-04-12 00:23:04 +00003381 // If this cast converts a load from a short,int, or long integer to a FP
3382 // value, we will have folded this cast away.
3383 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3384 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3385 Op->getType() == Type::LongTy))
3386 return;
3387
3388
Chris Lattner548f61d2003-04-23 17:22:12 +00003389 unsigned DestReg = getReg(CI);
3390 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00003391 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00003392}
3393
Misha Brukman538607f2004-03-01 23:53:11 +00003394/// emitCastOperation - Common code shared between visitCastInst and constant
3395/// expression cast support.
3396///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003397void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3398 MachineBasicBlock::iterator IP,
3399 Value *Src, const Type *DestTy,
3400 unsigned DestReg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003401 const Type *SrcTy = Src->getType();
3402 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00003403 unsigned DestClass = getClassB(DestTy);
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003404 unsigned SrcReg = getReg(Src, BB, IP);
3405
Chris Lattner3e130a22003-01-13 00:32:26 +00003406 // Implement casts to bool by using compare on the operand followed by set if
3407 // not zero on the result.
3408 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00003409 switch (SrcClass) {
3410 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003411 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003412 break;
3413 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003414 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003415 break;
3416 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003417 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003418 break;
3419 case cLong: {
3420 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003421 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00003422 break;
3423 }
3424 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00003425 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003426 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00003427 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00003428 break;
Chris Lattner20772542003-06-01 03:38:24 +00003429 }
3430
3431 // If the zero flag is not set, then the value is true, set the byte to
3432 // true.
Chris Lattneree352852004-02-29 07:22:16 +00003433 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003434 return;
3435 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003436
3437 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003438 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00003439 };
3440
3441 // Implement casts between values of the same type class (as determined by
3442 // getClass) by using a register-to-register move.
3443 if (SrcClass == DestClass) {
3444 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00003445 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003446 } else if (SrcClass == cFP) {
3447 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003448 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00003449 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003450 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003451 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3452 "Unknown cFP member!");
3453 // Truncate from double to float by storing to memory as short, then
3454 // reading it back.
3455 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00003456 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Chris Lattner5384b382005-01-05 16:30:14 +00003457 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5),
3458 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003459 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003460 }
3461 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003462 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3463 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003464 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00003465 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003466 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00003467 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003468 return;
3469 }
3470
3471 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3472 // or zero extension, depending on whether the source type was signed.
3473 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3474 SrcClass < DestClass) {
3475 bool isLong = DestClass == cLong;
3476 if (isLong) DestClass = cInt;
3477
3478 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003479 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3480 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00003481 };
3482
Chris Lattner96e3b422004-05-09 22:28:45 +00003483 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
Chris Lattneree352852004-02-29 07:22:16 +00003484 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00003485 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003486
3487 if (isLong) { // Handle upper 32 bits as appropriate...
3488 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003489 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00003490 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003491 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00003492 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003493 return;
3494 }
3495
3496 // Special case long -> int ...
3497 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003498 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003499 return;
3500 }
3501
3502 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3503 // move out of AX or AL.
3504 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3505 && SrcClass > DestClass) {
3506 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00003507 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3508 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00003509 return;
3510 }
3511
3512 // Handle casts from integer to floating point now...
3513 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003514 // Promote the integer to a type supported by FLD. We do this because there
3515 // are no unsigned FLD instructions, so we must promote an unsigned value to
3516 // a larger signed value, then use FLD on the larger value.
3517 //
3518 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00003519 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003520 unsigned RealDestReg = DestReg;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003521 switch (SrcTy->getTypeID()) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003522 case Type::BoolTyID:
3523 case Type::SByteTyID:
3524 // We don't have the facilities for directly loading byte sized data from
3525 // memory (even signed). Promote it to 16 bits.
3526 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003527 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003528 break;
3529 case Type::UByteTyID:
3530 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003531 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003532 break;
3533 case Type::UShortTyID:
3534 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003535 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003536 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003537 case Type::ULongTyID:
Chris Lattner56a31c62004-10-17 08:01:28 +00003538 case Type::UIntTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003539 // Don't fild into the read destination.
3540 DestReg = makeAnotherReg(Type::DoubleTy);
3541 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003542 default: // No promotion needed...
3543 break;
3544 }
3545
3546 if (PromoteType) {
3547 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00003548 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003549 SrcTy = PromoteType;
3550 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00003551 SrcReg = TmpReg;
3552 }
3553
3554 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003555 int FrameIdx =
3556 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00003557
3558 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003559 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003560 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003561 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003562 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003563 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003564 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00003565 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3566 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003567 }
3568
3569 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003570 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00003571 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003572
Chris Lattner56a31c62004-10-17 08:01:28 +00003573 if (SrcTy == Type::UIntTy) {
3574 // If this is a cast from uint -> double, we need to be careful about if
3575 // the "sign" bit is set. If so, we don't want to make a negative number,
3576 // we want to make a positive number. Emit code to add an offset if the
3577 // sign bit is set.
3578
3579 // Compute whether the sign bit is set by shifting the reg right 31 bits.
3580 unsigned IsNeg = makeAnotherReg(Type::IntTy);
Chris Lattner6e7c47c2005-01-09 01:49:29 +00003581 BuildMI(*BB, IP, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
Chris Lattner56a31c62004-10-17 08:01:28 +00003582
3583 // Create a CP value that has the offset in one word and 0 in the other.
3584 static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
3585 0x4f80000000000000ULL);
3586 unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
Chris Lattner6e7c47c2005-01-09 01:49:29 +00003587 BuildMI(*BB, IP, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
Chris Lattner56a31c62004-10-17 08:01:28 +00003588 .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
3589
3590 } else if (SrcTy == Type::ULongTy) {
3591 // We need special handling for unsigned 64-bit integer sources. If the
3592 // input number has the "sign bit" set, then we loaded it incorrectly as a
3593 // negative 64-bit number. In this case, add an offset value.
3594
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003595 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003596 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003597
Chris Lattnerb6bac512004-02-25 06:13:04 +00003598 // If the sign bit is set, get a pointer to an offset, otherwise get a
3599 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003600 MachineConstantPool *CP = F->getConstantPool();
3601 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003602 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003603 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003604 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003605 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003606 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3607
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003608 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003609 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003610 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003611 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003612
3613 // Load the constant for an add. FIXME: this could make an 'fadd' that
3614 // reads directly from memory, but we don't support these yet.
3615 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003616 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003617
Chris Lattneree352852004-02-29 07:22:16 +00003618 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3619 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003620 }
3621
Chris Lattner3e130a22003-01-13 00:32:26 +00003622 return;
3623 }
3624
3625 // Handle casts from floating point to integer now...
3626 if (SrcClass == cFP) {
3627 // Change the floating point control register to use "round towards zero"
3628 // mode when truncating to an integer value.
3629 //
3630 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003631 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003632
3633 // Load the old value of the high byte of the control word...
3634 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003635 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00003636 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003637
3638 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003639 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003640 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00003641
3642 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003643 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003644
3645 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003646 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003647 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00003648
3649 // We don't have the facilities for directly storing byte sized data to
3650 // memory. Promote it to 16 bits. We also must promote unsigned values to
3651 // larger classes because we only have signed FP stores.
3652 unsigned StoreClass = DestClass;
3653 const Type *StoreTy = DestTy;
3654 if (StoreClass == cByte || DestTy->isUnsigned())
3655 switch (StoreClass) {
3656 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3657 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3658 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00003659 // The following treatment of cLong may not be perfectly right,
3660 // but it survives chains of casts of the form
3661 // double->ulong->double.
3662 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00003663 default: assert(0 && "Unknown store class!");
3664 }
3665
3666 // Spill the integer to memory and reload it from there...
3667 int FrameIdx =
3668 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3669
3670 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003671 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00003672 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3673 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003674
3675 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003676 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3677 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00003678 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00003679 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003680 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00003681 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003682 }
3683
3684 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003685 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003686 return;
3687 }
3688
Brian Gaeked474e9c2002-12-06 10:49:33 +00003689 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00003690 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003691 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00003692}
Brian Gaekea1719c92002-10-31 23:03:59 +00003693
Chris Lattner73815062003-10-18 05:56:40 +00003694/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00003695///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003696void X86ISel::visitVANextInst(VANextInst &I) {
Chris Lattner73815062003-10-18 05:56:40 +00003697 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00003698 unsigned DestReg = getReg(I);
3699
Chris Lattnereca195e2003-05-08 19:44:13 +00003700 unsigned Size;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003701 switch (I.getArgType()->getTypeID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00003702 default:
3703 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00003704 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00003705 return;
3706 case Type::PointerTyID:
3707 case Type::UIntTyID:
3708 case Type::IntTyID:
3709 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00003710 break;
3711 case Type::ULongTyID:
3712 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00003713 case Type::DoubleTyID:
3714 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00003715 break;
3716 }
3717
3718 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003719 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00003720}
Chris Lattnereca195e2003-05-08 19:44:13 +00003721
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003722void X86ISel::visitVAArgInst(VAArgInst &I) {
Chris Lattner73815062003-10-18 05:56:40 +00003723 unsigned VAList = getReg(I.getOperand(0));
3724 unsigned DestReg = getReg(I);
3725
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003726 switch (I.getType()->getTypeID()) {
Chris Lattner73815062003-10-18 05:56:40 +00003727 default:
3728 std::cerr << I;
3729 assert(0 && "Error: bad type for va_next instruction!");
3730 return;
3731 case Type::PointerTyID:
3732 case Type::UIntTyID:
3733 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003734 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003735 break;
3736 case Type::ULongTyID:
3737 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003738 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3739 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00003740 break;
3741 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003742 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003743 break;
3744 }
Chris Lattnereca195e2003-05-08 19:44:13 +00003745}
3746
Misha Brukman538607f2004-03-01 23:53:11 +00003747/// visitGetElementPtrInst - instruction-select GEP instructions
3748///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003749void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003750 // If this GEP instruction will be folded into all of its users, we don't need
3751 // to explicitly calculate it!
Reid Spencerfc989e12004-08-30 00:13:26 +00003752 X86AddressMode AM;
3753 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003754 // Check all of the users of the instruction to see if they are loads and
3755 // stores.
3756 bool AllWillFold = true;
3757 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3758 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3759 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3760 cast<Instruction>(*UI)->getOperand(0) == &I) {
3761 AllWillFold = false;
3762 break;
3763 }
3764
3765 // If the instruction is foldable, and will be folded into all users, don't
3766 // emit it!
3767 if (AllWillFold) return;
3768 }
3769
Chris Lattner3e130a22003-01-13 00:32:26 +00003770 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00003771 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00003772 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00003773}
3774
Chris Lattner985fe3d2004-02-25 03:45:50 +00003775/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3776/// GEPTypes (the derived types being stepped through at each level). On return
3777/// from this function, if some indexes of the instruction are representable as
3778/// an X86 lea instruction, the machine operands are put into the Ops
3779/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3780/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3781/// addressing mode that only partially consumes the input, the BaseReg input of
3782/// the addressing mode must be left free.
3783///
3784/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3785///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003786void X86ISel::getGEPIndex(MachineBasicBlock *MBB,
3787 MachineBasicBlock::iterator IP,
3788 std::vector<Value*> &GEPOps,
3789 std::vector<const Type*> &GEPTypes,
3790 X86AddressMode &AM) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003791 const TargetData &TD = TM.getTargetData();
3792
Chris Lattner985fe3d2004-02-25 03:45:50 +00003793 // Clear out the state we are working with...
Reid Spencerfc989e12004-08-30 00:13:26 +00003794 AM.BaseType = X86AddressMode::RegBase;
3795 AM.Base.Reg = 0; // No base register
3796 AM.Scale = 1; // Unit scale
3797 AM.IndexReg = 0; // No index register
3798 AM.Disp = 0; // No displacement
Chris Lattnerb6bac512004-02-25 06:13:04 +00003799
Chris Lattner985fe3d2004-02-25 03:45:50 +00003800 // While there are GEP indexes that can be folded into the current address,
3801 // keep processing them.
3802 while (!GEPTypes.empty()) {
3803 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3804 // It's a struct access. CUI is the index into the structure,
3805 // which names the field. This index must have unsigned type.
3806 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3807
3808 // Use the TargetData structure to pick out what the layout of the
3809 // structure is in memory. Since the structure index must be constant, we
3810 // can get its value and use it to find the right byte offset from the
3811 // StructLayout class's list of structure member offsets.
Reid Spencerfc989e12004-08-30 00:13:26 +00003812 AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003813 GEPOps.pop_back(); // Consume a GEP operand
3814 GEPTypes.pop_back();
3815 } else {
3816 // It's an array or pointer access: [ArraySize x ElementType].
3817 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3818 Value *idx = GEPOps.back();
3819
3820 // idx is the index into the array. Unlike with structure
3821 // indices, we may not know its actual value at code-generation
3822 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003823
3824 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003825 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003826 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003827 AM.Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003828 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003829 AM.Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003830 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003831 // If the index reg is already taken, we can't handle this index.
Reid Spencerfc989e12004-08-30 00:13:26 +00003832 if (AM.IndexReg) return;
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003833
3834 // If this is a size that we can handle, then add the index as
3835 switch (TypeSize) {
3836 case 1: case 2: case 4: case 8:
3837 // These are all acceptable scales on X86.
Reid Spencerfc989e12004-08-30 00:13:26 +00003838 AM.Scale = TypeSize;
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003839 break;
3840 default:
3841 // Otherwise, we can't handle this scale
3842 return;
3843 }
3844
3845 if (CastInst *CI = dyn_cast<CastInst>(idx))
3846 if (CI->getOperand(0)->getType() == Type::IntTy ||
3847 CI->getOperand(0)->getType() == Type::UIntTy)
3848 idx = CI->getOperand(0);
3849
Reid Spencerfc989e12004-08-30 00:13:26 +00003850 AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003851 }
3852
3853 GEPOps.pop_back(); // Consume a GEP operand
3854 GEPTypes.pop_back();
3855 }
3856 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003857
Chris Lattnerdf040972004-05-23 21:23:12 +00003858 // GEPTypes is empty, which means we have a single operand left. Set it as
3859 // the base register.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003860 //
Reid Spencerfc989e12004-08-30 00:13:26 +00003861 assert(AM.Base.Reg == 0);
Chris Lattnerdf040972004-05-23 21:23:12 +00003862
Reid Spencerfc989e12004-08-30 00:13:26 +00003863 if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3864 AM.BaseType = X86AddressMode::FrameIndexBase;
3865 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
Chris Lattnerdf040972004-05-23 21:23:12 +00003866 GEPOps.pop_back();
3867 return;
Reid Spencerfc989e12004-08-30 00:13:26 +00003868 }
3869
Chris Lattner358a9022004-10-15 05:05:29 +00003870 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
3871 AM.GV = GV;
3872 GEPOps.pop_back();
3873 return;
Chris Lattnerdf040972004-05-23 21:23:12 +00003874 }
Chris Lattnerdf040972004-05-23 21:23:12 +00003875
Reid Spencerfc989e12004-08-30 00:13:26 +00003876 AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003877 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003878}
3879
3880
Chris Lattnerb6bac512004-02-25 06:13:04 +00003881/// isGEPFoldable - Return true if the specified GEP can be completely
3882/// folded into the addressing mode of a load/store or lea instruction.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003883bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3884 Value *Src, User::op_iterator IdxBegin,
3885 User::op_iterator IdxEnd, X86AddressMode &AM) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003886
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003887 std::vector<Value*> GEPOps;
3888 GEPOps.resize(IdxEnd-IdxBegin+1);
3889 GEPOps[0] = Src;
3890 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3891
Chris Lattnerdf040972004-05-23 21:23:12 +00003892 std::vector<const Type*>
3893 GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3894 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003895
Chris Lattnerb6bac512004-02-25 06:13:04 +00003896 MachineBasicBlock::iterator IP;
3897 if (MBB) IP = MBB->end();
Reid Spencerfc989e12004-08-30 00:13:26 +00003898 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003899
3900 // We can fold it away iff the getGEPIndex call eliminated all operands.
3901 return GEPOps.empty();
3902}
3903
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003904void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3905 MachineBasicBlock::iterator IP,
3906 Value *Src, User::op_iterator IdxBegin,
3907 User::op_iterator IdxEnd, unsigned TargetReg) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003908 const TargetData &TD = TM.getTargetData();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003909
Chris Lattnerd2995df2004-07-15 00:58:53 +00003910 // If this is a getelementptr null, with all constant integer indices, just
3911 // replace it with TargetReg = 42.
3912 if (isa<ConstantPointerNull>(Src)) {
3913 User::op_iterator I = IdxBegin;
3914 for (; I != IdxEnd; ++I)
3915 if (!isa<ConstantInt>(*I))
3916 break;
3917 if (I == IdxEnd) { // All constant indices
3918 unsigned Offset = TD.getIndexedOffset(Src->getType(),
3919 std::vector<Value*>(IdxBegin, IdxEnd));
3920 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3921 return;
3922 }
3923 }
3924
Chris Lattnerb6bac512004-02-25 06:13:04 +00003925 std::vector<Value*> GEPOps;
3926 GEPOps.resize(IdxEnd-IdxBegin+1);
3927 GEPOps[0] = Src;
3928 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3929
3930 std::vector<const Type*> GEPTypes;
3931 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3932 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003933
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003934 // Keep emitting instructions until we consume the entire GEP instruction.
3935 while (!GEPOps.empty()) {
3936 unsigned OldSize = GEPOps.size();
Reid Spencerfc989e12004-08-30 00:13:26 +00003937 X86AddressMode AM;
3938 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003939
Chris Lattner985fe3d2004-02-25 03:45:50 +00003940 if (GEPOps.size() != OldSize) {
3941 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003942 unsigned NextTarget = 0;
3943 if (!GEPOps.empty()) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003944 assert(AM.Base.Reg == 0 &&
Chris Lattnerb6bac512004-02-25 06:13:04 +00003945 "getGEPIndex should have left the base register open for chaining!");
Reid Spencerfc989e12004-08-30 00:13:26 +00003946 NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003947 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003948
Reid Spencerfc989e12004-08-30 00:13:26 +00003949 if (AM.BaseType == X86AddressMode::RegBase &&
Chris Lattner358a9022004-10-15 05:05:29 +00003950 AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
Reid Spencerfc989e12004-08-30 00:13:26 +00003951 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
Chris Lattner358a9022004-10-15 05:05:29 +00003952 else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
3953 AM.IndexReg == 0 && AM.Disp == 0)
3954 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003955 else
Reid Spencerfc989e12004-08-30 00:13:26 +00003956 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003957 --IP;
3958 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003959 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003960 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3961 // all operands are consumed but the base pointer. If so, just load it
3962 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003963 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003964 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003965 } else {
3966 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003967 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003968 }
3969 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003970
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003971 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003972 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003973 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3974 Value *idx = GEPOps.back();
3975 GEPOps.pop_back(); // Consume a GEP operand
3976 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003977
Chris Lattner28977af2004-04-05 01:30:19 +00003978 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003979 // operand on X86. Handle this case directly now...
3980 if (CastInst *CI = dyn_cast<CastInst>(idx))
3981 if (CI->getOperand(0)->getType() == Type::IntTy ||
3982 CI->getOperand(0)->getType() == Type::UIntTy)
3983 idx = CI->getOperand(0);
3984
Chris Lattner3e130a22003-01-13 00:32:26 +00003985 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003986 // must find the size of the pointed-to type (Not coincidentally, the next
3987 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003988 const Type *ElTy = SqTy->getElementType();
3989 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003990
3991 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003992 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003993 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003994 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003995 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003996 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003997 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003998 --IP; // Insert the next instruction before this one.
3999 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00004000 }
4001 } else if (elementSize == 1) {
4002 // If the element size is 1, we don't have to multiply, just add
4003 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004004 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004005 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004006 --IP; // Insert the next instruction before this one.
4007 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00004008 } else {
4009 unsigned idxReg = getReg(idx, MBB, IP);
4010 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00004011
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004012 // Make sure we can back the iterator up to point to the first
4013 // instruction emitted.
4014 MachineBasicBlock::iterator BeforeIt = IP;
4015 if (IP == MBB->begin())
4016 BeforeIt = MBB->end();
4017 else
4018 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00004019 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
4020
Chris Lattner8a307e82002-12-16 19:32:50 +00004021 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004022 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004023 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00004024 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004025
4026 // Step to the first instruction of the multiply.
4027 if (BeforeIt == MBB->end())
4028 IP = MBB->begin();
4029 else
4030 IP = ++BeforeIt;
4031
4032 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00004033 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004034 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004035 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004036}
4037
Chris Lattner065faeb2002-12-28 20:24:02 +00004038/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
4039/// frame manager, otherwise do it the hard way.
4040///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004041void X86ISel::visitAllocaInst(AllocaInst &I) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00004042 // If this is a fixed size alloca in the entry block for the function, we
4043 // statically stack allocate the space, so we don't need to do anything here.
4044 //
Chris Lattnercb2fd552004-05-13 07:40:27 +00004045 if (dyn_castFixedAlloca(&I)) return;
Chris Lattner9f1b5312004-05-13 15:12:43 +00004046
Brian Gaekee48ec012002-12-13 06:46:31 +00004047 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00004048 const Type *Ty = I.getAllocatedType();
4049 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
4050
Chris Lattner065faeb2002-12-28 20:24:02 +00004051 // Create a register to hold the temporary result of multiplying the type size
4052 // constant by the variable amount.
4053 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
4054 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00004055
4056 // TotalSizeReg = mul <numelements>, <TypeSize>
4057 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00004058 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00004059
4060 // AddedSize = add <TotalSizeReg>, 15
4061 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004062 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00004063
4064 // AlignedSize = and <AddedSize>, ~15
4065 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004066 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00004067
Brian Gaekee48ec012002-12-13 06:46:31 +00004068 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004069 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00004070
Brian Gaekee48ec012002-12-13 06:46:31 +00004071 // Put a pointer to the space into the result register, by copying
4072 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004073 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00004074
Misha Brukman48196b32003-05-03 02:18:17 +00004075 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00004076 // object.
4077 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00004078}
Chris Lattner3e130a22003-01-13 00:32:26 +00004079
4080/// visitMallocInst - Malloc instructions are code generated into direct calls
4081/// to the library malloc.
4082///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004083void X86ISel::visitMallocInst(MallocInst &I) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004084 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
4085 unsigned Arg;
4086
4087 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
4088 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
4089 } else {
4090 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00004091 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00004092 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00004093 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00004094 }
4095
4096 std::vector<ValueRecord> Args;
4097 Args.push_back(ValueRecord(Arg, Type::UIntTy));
4098 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00004099 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00004100 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
4101}
4102
4103
4104/// visitFreeInst - Free instructions are code gen'd to call the free libc
4105/// function.
4106///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004107void X86ISel::visitFreeInst(FreeInst &I) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004108 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00004109 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00004110 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00004111 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00004112 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
4113}
4114
Chris Lattnerd281de22003-07-26 23:49:58 +00004115/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00004116/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00004117/// generated code sucks but the implementation is nice and simple.
4118///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00004119FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004120 return new X86ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00004121}