blob: 6c37b7095f84d83975f45a85cbe95be63dc38ce9 [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 Lattner4c52f0e2005-04-09 15:23:56 +0000621 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
622 I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000623 bool ArgLive = !I->use_empty();
624 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000625 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000626
Chris Lattner065faeb2002-12-28 20:24:02 +0000627 switch (getClassB(I->getType())) {
628 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000629 if (ArgLive) {
630 FI = MFI->CreateFixedObject(1, ArgOffset);
631 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
632 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000633 break;
634 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000635 if (ArgLive) {
636 FI = MFI->CreateFixedObject(2, ArgOffset);
637 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
638 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000639 break;
640 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000641 if (ArgLive) {
642 FI = MFI->CreateFixedObject(4, ArgOffset);
643 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
644 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000645 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000646 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000647 if (ArgLive) {
648 FI = MFI->CreateFixedObject(8, ArgOffset);
649 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
650 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
651 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000652 ArgOffset += 4; // longs require 4 additional bytes
653 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000654 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000655 if (ArgLive) {
656 unsigned Opcode;
657 if (I->getType() == Type::FloatTy) {
658 Opcode = X86::FLD32m;
659 FI = MFI->CreateFixedObject(4, ArgOffset);
660 } else {
661 Opcode = X86::FLD64m;
662 FI = MFI->CreateFixedObject(8, ArgOffset);
663 }
664 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000665 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000666 if (I->getType() == Type::DoubleTy)
667 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000668 break;
669 default:
670 assert(0 && "Unhandled argument type!");
671 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000672 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000673 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000674
675 // If the function takes variable number of arguments, add a frame offset for
676 // the start of the first vararg value... this is used to expand
677 // llvm.va_start.
678 if (Fn.getFunctionType()->isVarArg())
679 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner4c52f0e2005-04-09 15:23:56 +0000680
681 // Finally, inform the compiler what our live-outs will be, aka, what we will
682 // be returning in registers.
683 if (Fn.getReturnType() != Type::VoidTy)
684 switch (getClassB(Fn.getReturnType())) {
685 default: assert(0 && "Unknown type!");
686 case cByte:
687 case cShort:
688 case cInt:
689 F->addLiveOut(X86::EAX);
690 break;
691 case cLong:
692 F->addLiveOut(X86::EAX);
693 F->addLiveOut(X86::EDX);
694 break;
695 case cFP:
696 F->addLiveOut(X86::ST0);
697 break;
698 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000699}
700
Chris Lattnerc0354c92004-12-13 17:23:11 +0000701/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
702/// the main function.
703void X86ISel::EmitSpecialCodeForMain() {
704 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
705 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
706 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
707
708 // Set the high part to be 64-bit precision.
709 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
710 CWFrameIdx, 1).addImm(2);
711
712 // Reload the modified control word now.
713 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
714}
Chris Lattner065faeb2002-12-28 20:24:02 +0000715
Chris Lattner333b2fa2002-12-13 10:09:43 +0000716/// SelectPHINodes - Insert machine code to generate phis. This is tricky
717/// because we have to generate our sources into the source basic blocks, not
718/// the current one.
719///
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000720void X86ISel::SelectPHINodes() {
Chris Lattnerd029cd22004-06-02 05:55:25 +0000721 const TargetInstrInfo &TII = *TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000722 const Function &LF = *F->getFunction(); // The LLVM function...
723 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
724 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000725 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000726
727 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000728 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000729 for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
730 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
Chris Lattner3e130a22003-01-13 00:32:26 +0000731
Chris Lattner333b2fa2002-12-13 10:09:43 +0000732 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000733 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000734 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
735 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000736
737 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000738 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
739 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
740 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000741
Chris Lattnera6e73f12003-05-12 14:22:21 +0000742 // PHIValues - Map of blocks to incoming virtual registers. We use this
743 // so that we only initialize one incoming value for a particular block,
744 // even if the block has multiple entries in the PHI node.
745 //
746 std::map<MachineBasicBlock*, unsigned> PHIValues;
747
Chris Lattner333b2fa2002-12-13 10:09:43 +0000748 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
749 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000750 unsigned ValReg;
751 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
752 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000753
Chris Lattnera6e73f12003-05-12 14:22:21 +0000754 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
755 // We already inserted an initialization of the register for this
756 // predecessor. Recycle it.
757 ValReg = EntryIt->second;
758
759 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000760 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000761 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000762 Value *Val = PN->getIncomingValue(i);
763
764 // If this is a constant or GlobalValue, we may have to insert code
765 // into the basic block to compute it into a virtual register.
Reid Spencer8863f182004-07-18 00:38:32 +0000766 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000767 // Simple constants get emitted at the end of the basic block,
768 // before any terminator instructions. We "know" that the code to
769 // move a constant into a register will never clobber any flags.
770 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
Chris Lattnera81fc682003-10-19 00:26:11 +0000771 } else {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000772 // Because we don't want to clobber any values which might be in
773 // physical registers with the computation of this constant (which
774 // might be arbitrarily complex if it is a constant expression),
775 // just insert the computation at the top of the basic block.
776 MachineBasicBlock::iterator PI = PredMBB->begin();
777
778 // Skip over any PHI nodes though!
779 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
780 ++PI;
781
782 ValReg = getReg(Val, PredMBB, PI);
Chris Lattnera81fc682003-10-19 00:26:11 +0000783 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000784
785 // Remember that we inserted a value for this PHI for this predecessor
786 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
787 }
788
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000789 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000790 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000791 if (LongPhiMI) {
792 LongPhiMI->addRegOperand(ValReg+1);
793 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
794 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000795 }
Chris Lattner168aa902004-02-29 07:10:16 +0000796
797 // Now that we emitted all of the incoming values for the PHI node, make
798 // sure to reposition the InsertPoint after the PHI that we just added.
799 // This is needed because we might have inserted a constant into this
800 // block, right after the PHI's which is before the old insert point!
801 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
802 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000803 }
804 }
805}
806
Chris Lattner986618e2004-02-22 19:47:26 +0000807/// RequiresFPRegKill - The floating point stackifier pass cannot insert
808/// compensation code on critical edges. As such, it requires that we kill all
809/// FP registers on the exit from any blocks that either ARE critical edges, or
810/// branch to a block that has incoming critical edges.
811///
812/// Note that this kill instruction will eventually be eliminated when
813/// restrictions in the stackifier are relaxed.
814///
Brian Gaeke1afe7732004-04-28 04:45:55 +0000815static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000816#if 0
Brian Gaeke1afe7732004-04-28 04:45:55 +0000817 const BasicBlock *BB = MBB->getBasicBlock ();
Chris Lattner986618e2004-02-22 19:47:26 +0000818 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
819 const BasicBlock *Succ = *SI;
820 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
821 ++PI; // Block have at least one predecessory
822 if (PI != PE) { // If it has exactly one, this isn't crit edge
823 // If this block has more than one predecessor, check all of the
824 // predecessors to see if they have multiple successors. If so, then the
825 // block we are analyzing needs an FPRegKill.
826 for (PI = pred_begin(Succ); PI != PE; ++PI) {
827 const BasicBlock *Pred = *PI;
828 succ_const_iterator SI2 = succ_begin(Pred);
829 ++SI2; // There must be at least one successor of this block.
830 if (SI2 != succ_end(Pred))
831 return true; // Yes, we must insert the kill on this edge.
832 }
833 }
834 }
835 // If we got this far, there is no need to insert the kill instruction.
836 return false;
837#else
838 return true;
839#endif
840}
841
842// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
843// need them. This only occurs due to the floating point stackifier not being
844// aggressive enough to handle arbitrary global stackification.
845//
846// Currently we insert an FP_REG_KILL instruction into each block that uses or
847// defines a floating point virtual register.
848//
849// When the global register allocators (like linear scan) finally update live
850// variable analysis, we can keep floating point values in registers across
851// portions of the CFG that do not involve critical edges. This will be a big
852// win, but we are waiting on the global allocators before we can do this.
853//
854// With a bit of work, the floating point stackifier pass can be enhanced to
855// break critical edges as needed (to make a place to put compensation code),
856// but this will require some infrastructure improvements as well.
857//
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000858void X86ISel::InsertFPRegKills() {
Chris Lattner986618e2004-02-22 19:47:26 +0000859 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000860
861 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000862 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000863 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
864 MachineOperand& MO = I->getOperand(i);
865 if (MO.isRegister() && MO.getReg()) {
866 unsigned Reg = MO.getReg();
Chris Lattner223d4c42004-12-03 05:13:15 +0000867 if (MRegisterInfo::isVirtualRegister(Reg)) {
868 unsigned RegSize = RegMap.getRegClass(Reg)->getSize();
869 if (RegSize == 10 || RegSize == 8)
Chris Lattner65cf42d2004-02-23 07:29:45 +0000870 goto UsesFPReg;
Chris Lattner223d4c42004-12-03 05:13:15 +0000871 }
Chris Lattner986618e2004-02-22 19:47:26 +0000872 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000873 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000874 // If we haven't found an FP register use or def in this basic block, check
875 // to see if any of our successors has an FP PHI node, which will cause a
876 // copy to be inserted into this block.
Brian Gaeke235aa5e2004-04-28 04:34:16 +0000877 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
878 SE = BB->succ_end(); SI != SE; ++SI) {
879 MachineBasicBlock *SBB = *SI;
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000880 for (MachineBasicBlock::iterator I = SBB->begin();
881 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
Chris Lattner39869242004-12-02 17:57:21 +0000882 const TargetRegisterClass *RC =
883 RegMap.getRegClass(I->getOperand(0).getReg());
884 if (RC->getSize() == 10 || RC->getSize() == 8)
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000885 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000886 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000887 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000888 continue;
889 UsesFPReg:
890 // Okay, this block uses an FP register. If the block has successors (ie,
891 // it's not an unwind/return), insert the FP_REG_KILL instruction.
Chris Lattner5384b382005-01-05 16:30:14 +0000892 if (BB->succ_size() && RequiresFPRegKill(BB)) {
Chris Lattneree352852004-02-29 07:22:16 +0000893 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000894 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000895 }
896 }
897}
898
899
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000900void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
Reid Spencerfc989e12004-08-30 00:13:26 +0000901 AM.BaseType = X86AddressMode::RegBase;
902 AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000903 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
904 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
Reid Spencerfc989e12004-08-30 00:13:26 +0000905 AM))
Chris Lattner9f1b5312004-05-13 15:12:43 +0000906 return;
907 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
908 if (CE->getOpcode() == Instruction::GetElementPtr)
909 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
Reid Spencerfc989e12004-08-30 00:13:26 +0000910 AM))
Chris Lattner9f1b5312004-05-13 15:12:43 +0000911 return;
Reid Spencerfc989e12004-08-30 00:13:26 +0000912 } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
913 AM.BaseType = X86AddressMode::FrameIndexBase;
914 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
915 return;
Chris Lattner358a9022004-10-15 05:05:29 +0000916 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
917 AM.GV = GV;
918 return;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000919 }
920
921 // If it's not foldable, reset addr mode.
Reid Spencerfc989e12004-08-30 00:13:26 +0000922 AM.BaseType = X86AddressMode::RegBase;
923 AM.Base.Reg = getReg(Addr);
924 AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
Chris Lattner9f1b5312004-05-13 15:12:43 +0000925}
926
Chris Lattner307ecba2004-03-30 22:39:09 +0000927// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
928// it into the conditional branch or select instruction which is the only user
929// of the cc instruction. This is the case if the conditional branch is the
Chris Lattnera6f9fe62004-06-18 00:29:22 +0000930// only user of the setcc. We also don't handle long arguments below, so we
931// reject them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000932//
Chris Lattner307ecba2004-03-30 22:39:09 +0000933static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000934 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000935 if (SCI->hasOneUse()) {
936 Instruction *User = cast<Instruction>(SCI->use_back());
Tanya Lattner9855b842004-12-01 18:27:03 +0000937 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
938 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
939 SCI->getOpcode() == Instruction::SetEQ ||
940 SCI->getOpcode() == Instruction::SetNE) &&
941 (isa<BranchInst>(User) || User->getOperand(0) == V))
Chris Lattner6d40c192003-01-16 16:43:00 +0000942 return SCI;
943 }
944 return 0;
945}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000946
Chris Lattner6d40c192003-01-16 16:43:00 +0000947// Return a fixed numbering for setcc instructions which does not depend on the
948// order of the opcodes.
949//
950static unsigned getSetCCNumber(unsigned Opcode) {
951 switch(Opcode) {
952 default: assert(0 && "Unknown setcc instruction!");
953 case Instruction::SetEQ: return 0;
954 case Instruction::SetNE: return 1;
955 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000956 case Instruction::SetGE: return 3;
957 case Instruction::SetGT: return 4;
958 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000959 }
960}
Chris Lattner06925362002-11-17 21:56:38 +0000961
Chris Lattner6d40c192003-01-16 16:43:00 +0000962// LLVM -> X86 signed X86 unsigned
963// ----- ---------- ------------
964// seteq -> sete sete
965// setne -> setne setne
966// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000967// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000968// setgt -> setg seta
969// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000970// ----
971// sets // Used by comparison with 0 optimization
972// setns
973static const unsigned SetCCOpcodeTab[2][8] = {
974 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
975 0, 0 },
976 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
977 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000978};
979
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000980/// emitUCOMr - In the future when we support processors before the P6, this
981/// wraps the logic for emitting an FUCOMr vs FUCOMIr.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000982void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
983 unsigned LHS, unsigned RHS) {
Chris Lattner01cdb1b2004-06-11 05:33:49 +0000984 if (0) { // for processors prior to the P6
985 BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
986 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
987 BuildMI(*MBB, IP, X86::SAHF, 1);
988 } else {
989 BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
990 }
991}
992
Chris Lattnerb2acc512003-10-19 21:09:10 +0000993// EmitComparison - This function emits a comparison of the two operands,
994// returning the extended setcc code to use.
Misha Brukmaneae1bf12004-09-21 18:21:21 +0000995unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
996 MachineBasicBlock *MBB,
997 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000998 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000999 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +00001000 unsigned Class = getClassB(CompTy);
Chris Lattner333864d2003-06-05 19:30:30 +00001001
1002 // Special case handling of: cmp R, i
Chris Lattner260195d2004-05-07 19:55:55 +00001003 if (isa<ConstantPointerNull>(Op1)) {
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001004 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner260195d2004-05-07 19:55:55 +00001005 if (OpNum < 2) // seteq/setne -> test
1006 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
1007 else
1008 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
1009 return OpNum;
1010
1011 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere80e6372004-04-06 16:02:27 +00001012 if (Class == cByte || Class == cShort || Class == cInt) {
1013 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +00001014
Chris Lattner333864d2003-06-05 19:30:30 +00001015 // Mask off any upper bits of the constant, if there are any...
1016 Op1v &= (1ULL << (8 << Class)) - 1;
1017
Chris Lattnerb2acc512003-10-19 21:09:10 +00001018 // If this is a comparison against zero, emit more efficient code. We
1019 // can't handle unsigned comparisons against zero unless they are == or
1020 // !=. These should have been strength reduced already anyway.
1021 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001022
1023 // If this is a comparison against zero and the LHS is an and of a
1024 // register with a constant, use the test to do the and.
1025 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1026 if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
1027 isa<ConstantInt>(Op0I->getOperand(1))) {
1028 static const unsigned TESTTab[] = {
1029 X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
1030 };
1031
1032 // Emit test X, i
1033 unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
1034 unsigned Imm =
1035 cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
1036 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
1037
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001038 if (OpNum == 2) return 6; // Map jl -> js
1039 if (OpNum == 3) return 7; // Map jg -> jns
1040 return OpNum;
1041 }
1042
1043 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001044 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001045 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +00001046 };
Chris Lattneree352852004-02-29 07:22:16 +00001047 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001048
1049 if (OpNum == 2) return 6; // Map jl -> js
1050 if (OpNum == 3) return 7; // Map jg -> jns
1051 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +00001052 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001053
1054 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001055 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +00001056 };
1057
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001058 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001059 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001060 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +00001061 } else {
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001062 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnere80e6372004-04-06 16:02:27 +00001063 assert(Class == cLong && "Unknown integer class!");
1064 unsigned LowCst = CI->getRawValue();
1065 unsigned HiCst = CI->getRawValue() >> 32;
1066 if (OpNum < 2) { // seteq, setne
1067 unsigned LoTmp = Op0r;
1068 if (LowCst != 0) {
1069 LoTmp = makeAnotherReg(Type::IntTy);
1070 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
1071 }
1072 unsigned HiTmp = Op0r+1;
1073 if (HiCst != 0) {
1074 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +00001075 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +00001076 }
1077 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1078 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1079 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +00001080 } else {
Tanya Lattner9855b842004-12-01 18:27:03 +00001081 // Emit a sequence of code which compares the high and low parts once
1082 // each, then uses a conditional move to handle the overflow case. For
1083 // example, a setlt for long would generate code like this:
1084 //
1085 // AL = lo(op1) < lo(op2) // Always unsigned comparison
1086 // BL = hi(op1) < hi(op2) // Signedness depends on operands
1087 // dest = hi(op1) == hi(op2) ? BL : AL;
1088 //
1089
1090 // FIXME: This would be much better if we had hierarchical register
1091 // classes! Until then, hardcode registers so that we can deal with
1092 // their aliases (because we don't have conditional byte moves).
1093 //
1094 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
1095 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1096 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
1097 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
1098 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1099 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1100 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1101 .addReg(X86::AX);
1102 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1103 // register at this point for long values...
Chris Lattner48c937e2004-04-06 17:34:50 +00001104 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +00001105 }
Chris Lattner333864d2003-06-05 19:30:30 +00001106 }
Chris Lattnere80e6372004-04-06 16:02:27 +00001107 }
Chris Lattner333864d2003-06-05 19:30:30 +00001108
Chris Lattnerde95c9e2004-10-17 06:10:40 +00001109 unsigned Op0r = getReg(Op0, MBB, IP);
1110
Chris Lattner9f08a922004-02-03 18:54:04 +00001111 // Special case handling of comparison against +/- 0.0
1112 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
1113 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +00001114 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001115 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00001116 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +00001117 return OpNum;
1118 }
1119
Chris Lattner58c41fe2003-08-24 19:19:47 +00001120 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001121 switch (Class) {
1122 default: assert(0 && "Unknown type class!");
1123 // Emit: cmp <var1>, <var2> (do the comparison). We can
1124 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1125 // 32-bit.
1126 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001127 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001128 break;
1129 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001130 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001131 break;
1132 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001133 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001134 break;
1135 case cFP:
Chris Lattner01cdb1b2004-06-11 05:33:49 +00001136 emitUCOMr(MBB, IP, Op0r, Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +00001137 break;
1138
1139 case cLong:
1140 if (OpNum < 2) { // seteq, setne
1141 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1142 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1143 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001144 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1145 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1146 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +00001147 break; // Allow the sete or setne to be generated from flags set by OR
1148 } else {
1149 // Emit a sequence of code which compares the high and low parts once
1150 // each, then uses a conditional move to handle the overflow case. For
1151 // example, a setlt for long would generate code like this:
1152 //
1153 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1154 // BL = hi(op1) < hi(op2) // Always unsigned comparison
Chris Lattner9984fd02004-05-09 23:16:33 +00001155 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner3e130a22003-01-13 00:32:26 +00001156 //
1157
Chris Lattner6d40c192003-01-16 16:43:00 +00001158 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +00001159 // classes! Until then, hardcode registers so that we can deal with their
1160 // aliases (because we don't have conditional byte moves).
1161 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001162 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +00001163 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001164 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +00001165 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1166 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1167 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001168 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +00001169 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +00001170 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1171 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +00001172 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +00001173 }
1174 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001175 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +00001176}
Chris Lattner3e130a22003-01-13 00:32:26 +00001177
Chris Lattner6d40c192003-01-16 16:43:00 +00001178/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1179/// register, then move it to wherever the result should be.
1180///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001181void X86ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +00001182 if (canFoldSetCCIntoBranchOrSelect(&I))
1183 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +00001184
Chris Lattner6d40c192003-01-16 16:43:00 +00001185 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001186 MachineBasicBlock::iterator MII = BB->end();
1187 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1188 DestReg);
1189}
Chris Lattner6d40c192003-01-16 16:43:00 +00001190
Chris Lattner58c41fe2003-08-24 19:19:47 +00001191/// emitSetCCOperation - Common code shared between visitSetCondInst and
1192/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +00001193///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001194void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1195 MachineBasicBlock::iterator IP,
1196 Value *Op0, Value *Op1, unsigned Opcode,
1197 unsigned TargetReg) {
Chris Lattner58c41fe2003-08-24 19:19:47 +00001198 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001199 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001200
Chris Lattnerb2acc512003-10-19 21:09:10 +00001201 const Type *CompTy = Op0->getType();
1202 unsigned CompClass = getClassB(CompTy);
1203 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1204
Tanya Lattner9855b842004-12-01 18:27:03 +00001205 if (CompClass != cLong || OpNum < 2) {
1206 // Handle normal comparisons with a setcc instruction...
1207 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1208 } else {
1209 // Handle long comparisons by copying the value which is already in BL into
1210 // the register we want...
1211 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1212 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001213}
Chris Lattner51b49a92002-11-02 19:45:49 +00001214
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001215void X86ISel::visitSelectInst(SelectInst &SI) {
Chris Lattner12d96a02004-03-30 21:22:00 +00001216 unsigned DestReg = getReg(SI);
1217 MachineBasicBlock::iterator MII = BB->end();
1218 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1219 SI.getFalseValue(), DestReg);
1220}
1221
1222/// emitSelect - Common code shared between visitSelectInst and the constant
1223/// expression support.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001224void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1225 MachineBasicBlock::iterator IP,
1226 Value *Cond, Value *TrueVal, Value *FalseVal,
1227 unsigned DestReg) {
Chris Lattner12d96a02004-03-30 21:22:00 +00001228 unsigned SelectClass = getClassB(TrueVal->getType());
1229
1230 // We don't support 8-bit conditional moves. If we have incoming constants,
1231 // transform them into 16-bit constants to avoid having a run-time conversion.
1232 if (SelectClass == cByte) {
1233 if (Constant *T = dyn_cast<Constant>(TrueVal))
1234 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1235 if (Constant *F = dyn_cast<Constant>(FalseVal))
1236 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1237 }
1238
Chris Lattner82c5a992004-04-13 21:56:09 +00001239 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1240 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1241 if (TrueReg == FalseReg) {
1242 static const unsigned Opcode[] = {
1243 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1244 };
1245 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1246 if (SelectClass == cLong)
1247 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1248 return;
1249 }
1250
Chris Lattner307ecba2004-03-30 22:39:09 +00001251 unsigned Opcode;
1252 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1253 // We successfully folded the setcc into the select instruction.
1254
1255 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1256 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1257 IP);
1258
1259 const Type *CompTy = SCI->getOperand(0)->getType();
1260 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1261
1262 // LLVM -> X86 signed X86 unsigned
1263 // ----- ---------- ------------
1264 // seteq -> cmovNE cmovNE
1265 // setne -> cmovE cmovE
1266 // setlt -> cmovGE cmovAE
1267 // setge -> cmovL cmovB
1268 // setgt -> cmovLE cmovBE
1269 // setle -> cmovG cmovA
1270 // ----
1271 // cmovNS // Used by comparison with 0 optimization
1272 // cmovS
1273
1274 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001275 default: assert(0 && "Unknown value class!");
1276 case cFP: {
1277 // Annoyingly, we don't have a full set of floating point conditional
1278 // moves. :(
1279 static const unsigned OpcodeTab[2][8] = {
1280 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1281 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1282 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1283 };
1284 Opcode = OpcodeTab[isSigned][OpNum];
1285
1286 // If opcode == 0, we hit a case that we don't support. Output a setcc
1287 // and compare the result against zero.
1288 if (Opcode == 0) {
1289 unsigned CompClass = getClassB(CompTy);
1290 unsigned CondReg;
1291 if (CompClass != cLong || OpNum < 2) {
1292 CondReg = makeAnotherReg(Type::BoolTy);
1293 // Handle normal comparisons with a setcc instruction...
1294 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1295 } else {
1296 // Long comparisons end up in the BL register.
1297 CondReg = X86::BL;
1298 }
1299
Chris Lattner68626c22004-03-31 22:22:36 +00001300 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001301 Opcode = X86::FCMOVE;
1302 }
1303 break;
1304 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001305 case cByte:
1306 case cShort: {
1307 static const unsigned OpcodeTab[2][8] = {
1308 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1309 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1310 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1311 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1312 };
1313 Opcode = OpcodeTab[isSigned][OpNum];
1314 break;
1315 }
1316 case cInt:
1317 case cLong: {
1318 static const unsigned OpcodeTab[2][8] = {
1319 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1320 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1321 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1322 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1323 };
1324 Opcode = OpcodeTab[isSigned][OpNum];
1325 break;
1326 }
1327 }
1328 } else {
1329 // Get the value being branched on, and use it to set the condition codes.
1330 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001331 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001332 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001333 default: assert(0 && "Unknown value class!");
1334 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001335 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001336 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001337 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001338 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001339 }
1340 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001341
Chris Lattner12d96a02004-03-30 21:22:00 +00001342 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001343
Chris Lattner12d96a02004-03-30 21:22:00 +00001344
1345 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1346 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1347 // cmove, then truncate the result.
1348 if (SelectClass == cByte) {
1349 DestReg = makeAnotherReg(Type::ShortTy);
1350 if (getClassB(TrueVal->getType()) == cByte) {
1351 // Promote the true value, by storing it into AL, and reading from AX.
1352 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1353 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1354 TrueReg = makeAnotherReg(Type::ShortTy);
1355 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1356 }
1357 if (getClassB(FalseVal->getType()) == cByte) {
1358 // Promote the true value, by storing it into CL, and reading from CX.
1359 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1360 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1361 FalseReg = makeAnotherReg(Type::ShortTy);
1362 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1363 }
1364 }
1365
1366 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1367
1368 switch (SelectClass) {
1369 case cByte:
1370 // We did the computation with 16-bit registers. Truncate back to our
1371 // result by copying into AX then copying out AL.
1372 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1373 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1374 break;
1375 case cLong:
1376 // Move the upper half of the value as well.
1377 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1378 break;
1379 }
1380}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001381
1382
1383
Brian Gaekec2505982002-11-30 11:57:28 +00001384/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1385/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001386///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001387void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
Chris Lattner9984fd02004-05-09 23:16:33 +00001388 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001389
Chris Lattner29bf0622004-04-06 01:21:00 +00001390 Value *Val = VR.Val;
1391 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001392 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001393 if (Constant *C = dyn_cast<Constant>(Val)) {
1394 Val = ConstantExpr::getCast(C, Type::IntTy);
1395 Ty = Type::IntTy;
1396 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001397
Chris Lattner502e36c2004-04-06 01:25:33 +00001398 // If this is a simple constant, just emit a MOVri directly to avoid the
1399 // copy.
1400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1401 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
Chris Lattner2b10b082004-05-12 16:35:04 +00001402 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
Chris Lattner502e36c2004-04-06 01:25:33 +00001403 return;
1404 }
1405 }
1406
Chris Lattner29bf0622004-04-06 01:21:00 +00001407 // Make sure we have the register number for this value...
1408 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1409
1410 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001411 case cByte:
1412 // Extend value into target register (8->32)
1413 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001414 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001415 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001416 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001417 break;
1418 case cShort:
1419 // Extend value into target register (16->32)
1420 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001421 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001422 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001423 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001424 break;
1425 case cInt:
1426 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001427 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001428 break;
1429 default:
1430 assert(0 && "Unpromotable operand class in promote32");
1431 }
Brian Gaekec2505982002-11-30 11:57:28 +00001432}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001433
Chris Lattner72614082002-10-25 22:55:53 +00001434/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1435/// we have the following possibilities:
1436///
1437/// ret void: No return value, simply emit a 'ret' instruction
1438/// ret sbyte, ubyte : Extend value into EAX and return
1439/// ret short, ushort: Extend value into EAX and return
1440/// ret int, uint : Move value into EAX and return
1441/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001442/// ret long, ulong : Move value into EAX/EDX and return
1443/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001444///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001445void X86ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001446 if (I.getNumOperands() == 0) {
1447 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1448 return;
1449 }
1450
1451 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001452 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001453 case cByte: // integral return values: extend or move into EAX and return
1454 case cShort:
1455 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001456 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattner94af4142002-12-25 05:13:53 +00001457 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001458 case cFP: { // Floats & Doubles: Return in ST(0)
1459 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001460 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001461 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001462 }
1463 case cLong: {
1464 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001465 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1466 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001467 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001468 }
Chris Lattner94af4142002-12-25 05:13:53 +00001469 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001470 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001471 }
Chris Lattner43189d12002-11-17 20:07:45 +00001472 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001473 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001474}
1475
Chris Lattner55f6fab2003-01-16 18:07:23 +00001476// getBlockAfter - Return the basic block which occurs lexically after the
1477// specified one.
1478static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1479 Function::iterator I = BB; ++I; // Get iterator to next block
1480 return I != BB->getParent()->end() ? &*I : 0;
1481}
1482
Chris Lattner51b49a92002-11-02 19:45:49 +00001483/// visitBranchInst - Handle conditional and unconditional branches here. Note
1484/// that since code layout is frozen at this point, that if we are trying to
1485/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001486/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001487///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001488void X86ISel::visitBranchInst(BranchInst &BI) {
Brian Gaekeea9ca672004-04-28 04:19:37 +00001489 // Update machine-CFG edges
1490 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1491 if (BI.isConditional())
1492 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1493
Chris Lattner55f6fab2003-01-16 18:07:23 +00001494 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1495
1496 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001497 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001498 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner6d40c192003-01-16 16:43:00 +00001499 return;
1500 }
1501
1502 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001503 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001504 if (SCI == 0) {
1505 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1506 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001507 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001508 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001509 if (BI.getSuccessor(1) == NextBB) {
1510 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001511 BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001512 } else {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001513 BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001514
1515 if (BI.getSuccessor(0) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001516 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001517 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001518 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001519 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001520
1521 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001522 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001523 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001524
1525 const Type *CompTy = SCI->getOperand(0)->getType();
1526 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001527
Chris Lattnerb2acc512003-10-19 21:09:10 +00001528
Chris Lattner6d40c192003-01-16 16:43:00 +00001529 // LLVM -> X86 signed X86 unsigned
1530 // ----- ---------- ------------
1531 // seteq -> je je
1532 // setne -> jne jne
1533 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001534 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001535 // setgt -> jg ja
1536 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001537 // ----
1538 // js // Used by comparison with 0 optimization
1539 // jns
1540
1541 static const unsigned OpcodeTab[2][8] = {
1542 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1543 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1544 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001545 };
1546
Chris Lattner55f6fab2003-01-16 18:07:23 +00001547 if (BI.getSuccessor(0) != NextBB) {
Brian Gaeke9f088e42004-05-14 06:54:56 +00001548 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1549 .addMBB(MBBMap[BI.getSuccessor(0)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001550 if (BI.getSuccessor(1) != NextBB)
Brian Gaeke9f088e42004-05-14 06:54:56 +00001551 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001552 } else {
1553 // Change to the inverse condition...
1554 if (BI.getSuccessor(1) != NextBB) {
1555 OpNum ^= 1;
Brian Gaeke9f088e42004-05-14 06:54:56 +00001556 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1557 .addMBB(MBBMap[BI.getSuccessor(1)]);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001558 }
1559 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001560}
1561
Chris Lattner3e130a22003-01-13 00:32:26 +00001562
1563/// doCall - This emits an abstract call instruction, setting up the arguments
1564/// and the return value as appropriate. For the actual function call itself,
1565/// it inserts the specified CallMI instruction into the stream.
1566///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001567void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1568 const std::vector<ValueRecord> &Args) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001569 // Count how many bytes are to be pushed on the stack...
1570 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001571
Chris Lattner3e130a22003-01-13 00:32:26 +00001572 if (!Args.empty()) {
1573 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1574 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001575 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001576 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001577 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001578 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001579 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001580 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1581 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001582 default: assert(0 && "Unknown class!");
1583 }
1584
1585 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001586 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001587
1588 // Arguments go on the stack in reverse order, as specified by the ABI.
1589 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001590 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001591 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001592 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001593 case cByte:
Chris Lattner2b10b082004-05-12 16:35:04 +00001594 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1595 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1596 .addImm(Args[i].Val == ConstantBool::True);
1597 break;
1598 }
1599 // FALL THROUGH
Chris Lattner21585222004-03-01 02:42:43 +00001600 case cShort:
1601 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1602 // Zero/Sign extend constant, then stuff into memory.
1603 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1604 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1605 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1606 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1607 } else {
1608 // Promote arg to 32 bits wide into a temporary register...
1609 ArgReg = makeAnotherReg(Type::UIntTy);
1610 promote32(ArgReg, Args[i]);
1611 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1612 X86::ESP, ArgOffset).addReg(ArgReg);
1613 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001614 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001615 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001616 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1617 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1618 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1619 X86::ESP, ArgOffset).addImm(Val);
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00001620 } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1621 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1622 X86::ESP, ArgOffset).addImm(0);
Chris Lattner21585222004-03-01 02:42:43 +00001623 } 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 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001628 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001629 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001630 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1631 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1632 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1633 X86::ESP, ArgOffset).addImm(Val & ~0U);
1634 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1635 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1636 } else {
1637 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1638 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1639 X86::ESP, ArgOffset).addReg(ArgReg);
1640 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1641 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1642 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001643 ArgOffset += 4; // 8 byte entry, not 4.
1644 break;
1645
Chris Lattner065faeb2002-12-28 20:24:02 +00001646 case cFP:
Chris Lattner7ab65932005-01-08 05:45:24 +00001647 if (ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(Args[i].Val)) {
Chris Lattner8c926282005-01-08 06:59:50 +00001648 // Store constant FP values with integer instructions to avoid having
1649 // to load the constants from the constant pool then do a store.
Chris Lattner7ab65932005-01-08 05:45:24 +00001650 if (CFP->getType() == Type::FloatTy) {
1651 union {
1652 unsigned I;
1653 float F;
1654 } V;
1655 V.F = CFP->getValue();
1656 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1657 X86::ESP, ArgOffset).addImm(V.I);
1658 } else {
1659 union {
1660 uint64_t I;
1661 double F;
1662 } V;
1663 V.F = CFP->getValue();
1664 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1665 X86::ESP, ArgOffset).addImm((unsigned)V.I);
1666 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1667 X86::ESP, ArgOffset+4).addImm(unsigned(V.I >> 32));
1668 ArgOffset += 4; // 8 byte entry, not 4.
1669 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001670 } else {
Chris Lattner7ab65932005-01-08 05:45:24 +00001671 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1672 if (Args[i].Ty == Type::FloatTy) {
1673 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1674 X86::ESP, ArgOffset).addReg(ArgReg);
1675 } else {
1676 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1677 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1678 X86::ESP, ArgOffset).addReg(ArgReg);
1679 ArgOffset += 4; // 8 byte entry, not 4.
1680 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001681 }
1682 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001683
Chris Lattner3e130a22003-01-13 00:32:26 +00001684 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001685 }
1686 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001687 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001688 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001689 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001690 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001691
Chris Lattner3e130a22003-01-13 00:32:26 +00001692 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001693
Chris Lattneree352852004-02-29 07:22:16 +00001694 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001695
1696 // If there is a return value, scavenge the result from the location the call
1697 // leaves it in...
1698 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001699 if (Ret.Ty != Type::VoidTy) {
1700 unsigned DestClass = getClassB(Ret.Ty);
1701 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001702 case cByte:
1703 case cShort:
1704 case cInt: {
1705 // Integral results are in %eax, or the appropriate portion
1706 // thereof.
1707 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001708 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001709 };
1710 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001711 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001712 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001713 }
Chris Lattner94af4142002-12-25 05:13:53 +00001714 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001715 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001716 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001717 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001718 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1719 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001720 break;
1721 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001722 }
Chris Lattnera3243642002-12-04 23:45:28 +00001723 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001724}
Chris Lattner2df035b2002-11-02 19:27:56 +00001725
Chris Lattner3e130a22003-01-13 00:32:26 +00001726
1727/// visitCallInst - Push args on stack and do a procedure call instruction.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001728void X86ISel::visitCallInst(CallInst &CI) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001729 MachineInstr *TheCall;
1730 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001731 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001732 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001733 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1734 return;
1735 }
1736
Chris Lattner3e130a22003-01-13 00:32:26 +00001737 // Emit a CALL instruction with PC-relative displacement.
1738 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1739 } else { // Emit an indirect call...
1740 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001741 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001742 }
1743
1744 std::vector<ValueRecord> Args;
1745 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001746 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001747
1748 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1749 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001750}
Chris Lattner3e130a22003-01-13 00:32:26 +00001751
Chris Lattner44827152003-12-28 09:47:19 +00001752/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1753/// function, lowering any calls to unknown intrinsic functions into the
1754/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001755///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001756void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
Chris Lattner44827152003-12-28 09:47:19 +00001757 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1758 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1759 if (CallInst *CI = dyn_cast<CallInst>(I++))
1760 if (Function *F = CI->getCalledFunction())
1761 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001762 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001763 case Intrinsic::vastart:
1764 case Intrinsic::vacopy:
1765 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001766 case Intrinsic::returnaddress:
1767 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001768 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001769 case Intrinsic::memset:
Chris Lattnerdc572442004-06-15 21:36:44 +00001770 case Intrinsic::isunordered:
John Criswell4ffff9e2004-04-08 20:31:47 +00001771 case Intrinsic::readport:
1772 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001773 // We directly implement these intrinsics
1774 break;
John Criswelle5a4c152004-04-13 22:13:14 +00001775 case Intrinsic::readio: {
1776 // On X86, memory operations are in-order. Lower this intrinsic
1777 // into a volatile load.
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001778 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1779 CI->replaceAllUsesWith(LI);
1780 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001781 break;
1782 }
1783 case Intrinsic::writeio: {
1784 // On X86, memory operations are in-order. Lower this intrinsic
1785 // into a volatile store.
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001786 StoreInst *LI = new StoreInst(CI->getOperand(1),
1787 CI->getOperand(2), true, CI);
1788 CI->replaceAllUsesWith(LI);
1789 BB->getInstList().erase(CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001790 break;
1791 }
Chris Lattner44827152003-12-28 09:47:19 +00001792 default:
1793 // All other intrinsic calls we must lower.
1794 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001795 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001796 if (Before) { // Move iterator to instruction after call
Chris Lattnerb4fe76c2004-06-11 04:31:10 +00001797 I = Before; ++I;
Chris Lattner44827152003-12-28 09:47:19 +00001798 } else {
1799 I = BB->begin();
1800 }
1801 }
Chris Lattner44827152003-12-28 09:47:19 +00001802}
1803
Misha Brukmaneae1bf12004-09-21 18:21:21 +00001804void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001805 unsigned TmpReg1, TmpReg2;
1806 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001807 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001808 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001809 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001810 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001811 return;
1812
Chris Lattner5634b9f2004-03-13 00:24:52 +00001813 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001814 TmpReg1 = getReg(CI);
1815 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001816 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001817 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001818 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001819
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001820 case Intrinsic::returnaddress:
1821 case Intrinsic::frameaddress:
1822 TmpReg1 = getReg(CI);
1823 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
Chris Lattner8cdbc352004-12-17 00:46:51 +00001824 if (ReturnAddressIndex == 0) {
Chris Lattner11cf7aa2004-12-17 00:07:46 +00001825 // Set up a frame object for the return address.
1826 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
1827 }
1828
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001829 if (ID == Intrinsic::returnaddress) {
1830 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001831 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001832 ReturnAddressIndex);
1833 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001834 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001835 ReturnAddressIndex, -4);
1836 }
1837 } else {
1838 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001839 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001840 }
1841 return;
1842
Chris Lattnerdc572442004-06-15 21:36:44 +00001843 case Intrinsic::isunordered:
1844 TmpReg1 = getReg(CI.getOperand(1));
1845 TmpReg2 = getReg(CI.getOperand(2));
1846 emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1847 TmpReg2 = getReg(CI);
1848 BuildMI(BB, X86::SETPr, 0, TmpReg2);
1849 return;
1850
Chris Lattner915e5e52004-02-12 17:53:22 +00001851 case Intrinsic::memcpy: {
1852 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1853 unsigned Align = 1;
1854 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1855 Align = AlignC->getRawValue();
1856 if (Align == 0) Align = 1;
1857 }
1858
1859 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001860 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001861 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001862 switch (Align & 3) {
1863 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001864 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1865 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1866 } else {
1867 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001868 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001869 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001870 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001871 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001872 break;
1873 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001874 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1875 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1876 } else {
1877 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001878 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001879 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001880 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001881 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001882 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001883 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001884 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001885 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001886 break;
1887 }
1888
1889 // No matter what the alignment is, we put the source in ESI, the
1890 // destination in EDI, and the count in ECX.
1891 TmpReg1 = getReg(CI.getOperand(1));
1892 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001893 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1894 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1895 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001896 BuildMI(BB, Opcode, 0);
1897 return;
1898 }
1899 case Intrinsic::memset: {
1900 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1901 unsigned Align = 1;
1902 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1903 Align = AlignC->getRawValue();
1904 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001905 }
1906
Chris Lattner2a0f2242004-02-14 04:46:05 +00001907 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001908 unsigned CountReg;
1909 unsigned Opcode;
1910 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1911 unsigned Val = ValC->getRawValue() & 255;
1912
1913 // If the value is a constant, then we can potentially use larger copies.
1914 switch (Align & 3) {
1915 case 2: // WORD aligned
1916 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001917 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001918 } else {
1919 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001920 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001921 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001922 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001923 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001924 Opcode = X86::REP_STOSW;
1925 break;
1926 case 0: // DWORD aligned
1927 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001928 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001929 } else {
1930 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001931 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001932 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001933 }
1934 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001935 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001936 Opcode = X86::REP_STOSD;
1937 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001938 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001939 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001940 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001941 Opcode = X86::REP_STOSB;
1942 break;
1943 }
1944 } else {
1945 // If it's not a constant value we are storing, just fall back. We could
1946 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1947 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001948 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001949 CountReg = getReg(CI.getOperand(3));
1950 Opcode = X86::REP_STOSB;
1951 }
1952
1953 // No matter what the alignment is, we put the source in ESI, the
1954 // destination in EDI, and the count in ECX.
1955 TmpReg1 = getReg(CI.getOperand(1));
1956 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001957 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1958 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001959 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001960 return;
1961 }
1962
Chris Lattner87e18de2004-04-13 17:20:37 +00001963 case Intrinsic::readport: {
1964 // First, determine that the size of the operand falls within the acceptable
1965 // range for this architecture.
John Criswell4ffff9e2004-04-08 20:31:47 +00001966 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001967 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001968 std::cerr << "llvm.readport: Address size is not 16 bits\n";
Chris Lattner87e18de2004-04-13 17:20:37 +00001969 exit(1);
John Criswellca6ea0f2004-04-08 22:39:13 +00001970 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001971
John Criswell4ffff9e2004-04-08 20:31:47 +00001972 // Now, move the I/O port address into the DX register and use the IN
1973 // instruction to get the input data.
1974 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001975 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1976 unsigned DestReg = getReg(CI);
John Criswell4ffff9e2004-04-08 20:31:47 +00001977
Chris Lattner87e18de2004-04-13 17:20:37 +00001978 // If the port is a single-byte constant, use the immediate form.
1979 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1980 if ((C->getRawValue() & 255) == C->getRawValue()) {
1981 switch (Class) {
1982 case cByte:
1983 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1984 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1985 return;
1986 case cShort:
1987 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1988 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1989 return;
1990 case cInt:
1991 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1992 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1993 return;
1994 }
1995 }
1996
1997 unsigned Reg = getReg(CI.getOperand(1));
1998 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1999 switch (Class) {
2000 case cByte:
2001 BuildMI(BB, X86::IN8rr, 0);
2002 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2003 break;
2004 case cShort:
2005 BuildMI(BB, X86::IN16rr, 0);
2006 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
2007 break;
2008 case cInt:
2009 BuildMI(BB, X86::IN32rr, 0);
2010 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
2011 break;
2012 default:
2013 std::cerr << "Cannot do input on this data type";
John Criswellca6ea0f2004-04-08 22:39:13 +00002014 exit (1);
2015 }
John Criswell4ffff9e2004-04-08 20:31:47 +00002016 return;
Chris Lattner87e18de2004-04-13 17:20:37 +00002017 }
John Criswell4ffff9e2004-04-08 20:31:47 +00002018
Chris Lattner87e18de2004-04-13 17:20:37 +00002019 case Intrinsic::writeport: {
2020 // First, determine that the size of the operand falls within the
2021 // acceptable range for this architecture.
2022 if (getClass(CI.getOperand(2)->getType()) != cShort) {
2023 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
2024 exit(1);
2025 }
2026
2027 unsigned Class = getClassB(CI.getOperand(1)->getType());
2028 unsigned ValReg = getReg(CI.getOperand(1));
2029 switch (Class) {
2030 case cByte:
2031 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
2032 break;
2033 case cShort:
2034 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
2035 break;
2036 case cInt:
2037 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
2038 break;
2039 default:
2040 std::cerr << "llvm.writeport: invalid data type for X86 target";
2041 exit(1);
2042 }
2043
2044
2045 // If the port is a single-byte constant, use the immediate form.
2046 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
2047 if ((C->getRawValue() & 255) == C->getRawValue()) {
2048 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
2049 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
2050 return;
2051 }
2052
2053 // Otherwise, move the I/O port address into the DX register and the value
2054 // to write into the AL/AX/EAX register.
2055 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
2056 unsigned Reg = getReg(CI.getOperand(2));
2057 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
2058 BuildMI(BB, Opc[Class], 0);
2059 return;
2060 }
2061
Chris Lattner44827152003-12-28 09:47:19 +00002062 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002063 }
2064}
2065
Chris Lattner7dee5da2004-03-08 01:58:35 +00002066static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
2067 if (LI.getParent() != User.getParent())
2068 return false;
2069 BasicBlock::iterator It = &LI;
2070 // Check all of the instructions between the load and the user. We should
2071 // really use alias analysis here, but for now we just do something simple.
2072 for (++It; It != BasicBlock::iterator(&User); ++It) {
2073 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00002074 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00002075 case Instruction::Store:
2076 case Instruction::Call:
2077 case Instruction::Invoke:
2078 return false;
Chris Lattner133dbb12004-04-12 03:02:48 +00002079 case Instruction::Load:
2080 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
2081 return false;
2082 break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002083 }
2084 }
2085 return true;
2086}
2087
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002088/// visitSimpleBinary - Implement simple binary operators for integral types...
2089/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2090/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00002091///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002092void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002093 unsigned DestReg = getReg(B);
2094 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00002095 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002096 unsigned Class = getClassB(B.getType());
Chris Lattner721d2d42004-03-08 01:18:36 +00002097
Chris Lattnerde95c9e2004-10-17 06:10:40 +00002098 // If this is AND X, C, and it is only used by a setcc instruction, it will
2099 // be folded. There is no need to emit this instruction.
2100 if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
2101 if (Class == cByte || Class == cShort || Class == cInt) {
2102 Instruction *Use = cast<Instruction>(B.use_back());
2103 if (isa<SetCondInst>(Use) &&
2104 Use->getOperand(1) == Constant::getNullValue(B.getType())) {
2105 switch (getSetCCNumber(Use->getOpcode())) {
2106 case 0:
2107 case 1:
2108 return;
2109 default:
2110 if (B.getType()->isSigned()) return;
2111 }
2112 }
2113 }
2114
Chris Lattner7dee5da2004-03-08 01:58:35 +00002115 // Special case: op Reg, load [mem]
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002116 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
Chris Lattnerccd97962004-06-17 22:15:25 +00002117 Op0->hasOneUse() &&
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00002118 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
Chris Lattner7dee5da2004-03-08 01:58:35 +00002119 if (!B.swapOperands())
2120 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2121
Chris Lattnerccd97962004-06-17 22:15:25 +00002122 if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
Chris Lattner7dee5da2004-03-08 01:58:35 +00002123 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
2124
Chris Lattner95157f72004-04-11 22:05:45 +00002125 unsigned Opcode;
2126 if (Class != cFP) {
2127 static const unsigned OpcodeTab[][3] = {
2128 // Arithmetic operators
2129 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
2130 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
2131
2132 // Bitwise operators
2133 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
2134 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
2135 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
2136 };
2137 Opcode = OpcodeTab[OperatorClass][Class];
2138 } else {
2139 static const unsigned OpcodeTab[][2] = {
2140 { X86::FADD32m, X86::FADD64m }, // ADD
2141 { X86::FSUB32m, X86::FSUB64m }, // SUB
2142 };
2143 const Type *Ty = Op0->getType();
2144 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2145 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
2146 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002147
Chris Lattner7dee5da2004-03-08 01:58:35 +00002148 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002149 if (AllocaInst *AI =
2150 dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
2151 unsigned FI = getFixedSizedAllocaFI(AI);
2152 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2153
2154 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002155 X86AddressMode AM;
2156 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002157
Reid Spencerfc989e12004-08-30 00:13:26 +00002158 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002159 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00002160 return;
2161 }
2162
Chris Lattner95157f72004-04-11 22:05:45 +00002163 // If this is a floating point subtract, check to see if we can fold the first
2164 // operand in.
2165 if (Class == cFP && OperatorClass == 1 &&
2166 isa<LoadInst>(Op0) &&
2167 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2168 const Type *Ty = Op0->getType();
2169 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2170 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2171
Chris Lattner95157f72004-04-11 22:05:45 +00002172 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002173 if (AllocaInst *AI =
2174 dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2175 unsigned FI = getFixedSizedAllocaFI(AI);
2176 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2177 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002178 X86AddressMode AM;
2179 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002180
Reid Spencerfc989e12004-08-30 00:13:26 +00002181 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002182 }
Chris Lattner95157f72004-04-11 22:05:45 +00002183 return;
2184 }
2185
Chris Lattner721d2d42004-03-08 01:18:36 +00002186 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002187}
Chris Lattner3e130a22003-01-13 00:32:26 +00002188
Chris Lattner6621ed92004-04-11 21:23:56 +00002189
2190/// emitBinaryFPOperation - This method handles emission of floating point
2191/// Add (0), Sub (1), Mul (2), and Div (3) operations.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002192void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2193 MachineBasicBlock::iterator IP,
2194 Value *Op0, Value *Op1,
2195 unsigned OperatorClass, unsigned DestReg) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002196 // Special case: op Reg, <const fp>
2197 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2198 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2199 // Create a constant pool entry for this constant.
2200 MachineConstantPool *CP = F->getConstantPool();
2201 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2202 const Type *Ty = Op1->getType();
2203
2204 static const unsigned OpcodeTab[][4] = {
2205 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2206 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2207 };
2208
2209 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2210 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2211 unsigned Op0r = getReg(Op0, BB, IP);
2212 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2213 DestReg).addReg(Op0r), CPI);
2214 return;
2215 }
2216
Chris Lattner13c07fe2004-04-12 00:12:04 +00002217 // Special case: R1 = op <const fp>, R2
Chris Lattner6621ed92004-04-11 21:23:56 +00002218 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2219 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2220 // -0.0 - X === -X
2221 unsigned op1Reg = getReg(Op1, BB, IP);
2222 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2223 return;
2224 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
Chris Lattner13c07fe2004-04-12 00:12:04 +00002225 // R1 = op CST, R2 --> R1 = opr R2, CST
Chris Lattner6621ed92004-04-11 21:23:56 +00002226
2227 // Create a constant pool entry for this constant.
2228 MachineConstantPool *CP = F->getConstantPool();
2229 unsigned CPI = CP->getConstantPoolIndex(CFP);
2230 const Type *Ty = CFP->getType();
2231
2232 static const unsigned OpcodeTab[][4] = {
2233 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2234 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2235 };
2236
2237 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2238 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2239 unsigned Op1r = getReg(Op1, BB, IP);
2240 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2241 DestReg).addReg(Op1r), CPI);
2242 return;
2243 }
2244
2245 // General case.
2246 static const unsigned OpcodeTab[4] = {
2247 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2248 };
2249
2250 unsigned Opcode = OpcodeTab[OperatorClass];
2251 unsigned Op0r = getReg(Op0, BB, IP);
2252 unsigned Op1r = getReg(Op1, BB, IP);
2253 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2254}
2255
Chris Lattnerb2acc512003-10-19 21:09:10 +00002256/// emitSimpleBinaryOperation - Implement simple binary operators for integral
2257/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2258/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00002259///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002260/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2261/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002262///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002263void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2264 MachineBasicBlock::iterator IP,
2265 Value *Op0, Value *Op1,
2266 unsigned OperatorClass,
2267 unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002268 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00002269
Chris Lattner6621ed92004-04-11 21:23:56 +00002270 if (Class == cFP) {
2271 assert(OperatorClass < 2 && "No logical ops for FP!");
2272 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2273 return;
2274 }
2275
Chris Lattner48b0c972004-04-11 20:26:20 +00002276 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
Chris Lattner667ea022004-06-18 00:50:37 +00002277 if (OperatorClass == 1) {
Chris Lattner48b0c972004-04-11 20:26:20 +00002278 static unsigned const NEGTab[] = {
2279 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2280 };
Chris Lattner667ea022004-06-18 00:50:37 +00002281
2282 // sub 0, X -> neg X
2283 if (CI->isNullValue()) {
2284 unsigned op1Reg = getReg(Op1, MBB, IP);
2285 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
Chris Lattner48b0c972004-04-11 20:26:20 +00002286
Chris Lattner667ea022004-06-18 00:50:37 +00002287 if (Class == cLong) {
2288 // We just emitted: Dl = neg Sl
2289 // Now emit : T = addc Sh, 0
2290 // : Dh = neg T
2291 unsigned T = makeAnotherReg(Type::IntTy);
2292 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2293 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2294 }
2295 return;
2296 } else if (Op1->hasOneUse() && Class != cLong) {
2297 // sub C, X -> tmp = neg X; DestReg = add tmp, C. This is better
2298 // than copying C into a temporary register, because of register
2299 // pressure (tmp and destreg can share a register.
2300 static unsigned const ADDRITab[] = {
2301 X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2302 };
2303 unsigned op1Reg = getReg(Op1, MBB, IP);
2304 unsigned Tmp = makeAnotherReg(Op0->getType());
2305 BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
Chris Lattner30483732004-06-20 07:49:54 +00002306 BuildMI(*MBB, IP, ADDRITab[Class], 2,
2307 DestReg).addReg(Tmp).addImm(CI->getRawValue());
Chris Lattner667ea022004-06-18 00:50:37 +00002308 return;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002309 }
Chris Lattner48b0c972004-04-11 20:26:20 +00002310 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002311
Chris Lattner48b0c972004-04-11 20:26:20 +00002312 // Special case: op Reg, <const int>
2313 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002314 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002315
Chris Lattner721d2d42004-03-08 01:18:36 +00002316 // xor X, -1 -> not X
2317 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002318 static unsigned const NOTTab[] = {
2319 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2320 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002321 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002322 if (Class == cLong) // Invert the top part too
2323 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00002324 return;
2325 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002326
Chris Lattner721d2d42004-03-08 01:18:36 +00002327 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00002328 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2329 // Note that we can't use dec for 64-bit decrements, because it does not
2330 // set the carry flag!
2331 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00002332 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2333 return;
2334 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002335
Chris Lattner721d2d42004-03-08 01:18:36 +00002336 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00002337 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2338 // Note that we can't use inc for 64-bit increments, because it does not
2339 // set the carry flag!
2340 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00002341 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00002342 return;
2343 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002344
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002345 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002346 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002347 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2348 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00002349
Chris Lattner721d2d42004-03-08 01:18:36 +00002350 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002351 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2352 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2353 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00002354 };
2355
Chris Lattner721d2d42004-03-08 01:18:36 +00002356 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00002357 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00002358
Chris Lattner33f7fa32004-04-06 03:15:53 +00002359 if (Class != cLong) {
2360 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2361 return;
Chris Lattner6621ed92004-04-11 21:23:56 +00002362 }
2363
2364 // If this is a long value and the high or low bits have a special
2365 // property, emit some special cases.
2366 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2367
2368 // If the constant is zero in the low 32-bits, just copy the low part
2369 // across and apply the normal 32-bit operation to the high parts. There
2370 // will be no carry or borrow into the top.
2371 if (Op1l == 0) {
2372 if (OperatorClass != 2) // All but and...
2373 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2374 else
2375 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2376 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2377 .addReg(Op0r+1).addImm(Op1h);
Chris Lattner33f7fa32004-04-06 03:15:53 +00002378 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002379 }
Chris Lattner6621ed92004-04-11 21:23:56 +00002380
2381 // If this is a logical operation and the top 32-bits are zero, just
2382 // operate on the lower 32.
2383 if (Op1h == 0 && OperatorClass > 1) {
2384 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2385 .addReg(Op0r).addImm(Op1l);
2386 if (OperatorClass != 2) // All but and
2387 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2388 else
2389 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2390 return;
2391 }
2392
2393 // TODO: We could handle lots of other special cases here, such as AND'ing
2394 // with 0xFFFFFFFF00000000 -> noop, etc.
2395
2396 // Otherwise, code generate the full operation with a constant.
2397 static const unsigned TopTab[] = {
2398 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2399 };
2400
2401 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2402 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2403 .addReg(Op0r+1).addImm(Op1h);
2404 return;
Chris Lattner721d2d42004-03-08 01:18:36 +00002405 }
2406
2407 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00002408 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002409 // Arithmetic operators
Chris Lattner6621ed92004-04-11 21:23:56 +00002410 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2411 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002412
Chris Lattnerb2acc512003-10-19 21:09:10 +00002413 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002414 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2415 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2416 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002417 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002418
Chris Lattnerb2acc512003-10-19 21:09:10 +00002419 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002420 unsigned Op0r = getReg(Op0, MBB, IP);
2421 unsigned Op1r = getReg(Op1, MBB, IP);
2422 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2423
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002424 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002425 static const unsigned TopTab[] = {
2426 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2427 };
2428 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2429 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2430 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002431}
2432
Chris Lattner3e130a22003-01-13 00:32:26 +00002433/// doMultiply - Emit appropriate instructions to multiply together the
2434/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2435/// result should be given as DestTy.
2436///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002437void X86ISel::doMultiply(MachineBasicBlock *MBB,
2438 MachineBasicBlock::iterator MBBI,
2439 unsigned DestReg, const Type *DestTy,
2440 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002441 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002442 switch (Class) {
Chris Lattner0f1c4612003-06-21 17:16:58 +00002443 case cInt:
2444 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002445 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002446 .addReg(op0Reg).addReg(op1Reg);
2447 return;
2448 case cByte:
2449 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002450 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2451 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2452 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002453 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002454 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002455 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002456 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002457}
2458
Chris Lattnerb2acc512003-10-19 21:09:10 +00002459// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2460// returns zero when the input is not exactly a power of two.
2461static unsigned ExactLog2(unsigned Val) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002462 if (Val == 0 || (Val & (Val-1))) return 0;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002463 unsigned Count = 0;
2464 while (Val != 1) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002465 Val >>= 1;
2466 ++Count;
2467 }
2468 return Count+1;
2469}
2470
Chris Lattner462fa822004-04-11 20:56:28 +00002471
2472/// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2473/// 16, or 32-bit integer multiply by a constant.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002474void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2475 MachineBasicBlock::iterator IP,
2476 unsigned DestReg, const Type *DestTy,
2477 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002478 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2479 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002480 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
Chris Lattner596b97f2004-07-19 23:47:21 +00002481 static const unsigned NEGrTab[] = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
Chris Lattner6ab06d52004-04-06 04:55:43 +00002482
Chris Lattnerb2acc512003-10-19 21:09:10 +00002483 unsigned Class = getClass(DestTy);
Chris Lattner596b97f2004-07-19 23:47:21 +00002484 unsigned TmpReg;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002485
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002486 // Handle special cases here.
2487 switch (ConstRHS) {
Chris Lattner596b97f2004-07-19 23:47:21 +00002488 case -2:
2489 TmpReg = makeAnotherReg(DestTy);
2490 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2491 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2492 return;
2493 case -1:
2494 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2495 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002496 case 0:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002497 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2498 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002499 case 1:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002500 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2501 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002502 case 2:
2503 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2504 return;
2505 case 3:
2506 case 5:
2507 case 9:
2508 if (Class == cInt) {
Reid Spencerfc989e12004-08-30 00:13:26 +00002509 X86AddressMode AM;
2510 AM.BaseType = X86AddressMode::RegBase;
2511 AM.Base.Reg = op0Reg;
2512 AM.Scale = ConstRHS-1;
2513 AM.IndexReg = op0Reg;
2514 AM.Disp = 0;
2515 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002516 return;
2517 }
Chris Lattner596b97f2004-07-19 23:47:21 +00002518 case -3:
2519 case -5:
2520 case -9:
2521 if (Class == cInt) {
2522 TmpReg = makeAnotherReg(DestTy);
Reid Spencerfc989e12004-08-30 00:13:26 +00002523 X86AddressMode AM;
2524 AM.BaseType = X86AddressMode::RegBase;
2525 AM.Base.Reg = op0Reg;
2526 AM.Scale = -ConstRHS-1;
2527 AM.IndexReg = op0Reg;
2528 AM.Disp = 0;
2529 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
Chris Lattner596b97f2004-07-19 23:47:21 +00002530 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2531 return;
2532 }
Chris Lattner6ab06d52004-04-06 04:55:43 +00002533 }
2534
Chris Lattnerb2acc512003-10-19 21:09:10 +00002535 // If the element size is exactly a power of 2, use a shift to get it.
2536 if (unsigned Shift = ExactLog2(ConstRHS)) {
2537 switch (Class) {
2538 default: assert(0 && "Unknown class for this function!");
2539 case cByte:
Chris Lattner596b97f2004-07-19 23:47:21 +00002540 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002541 return;
2542 case cShort:
Chris Lattner596b97f2004-07-19 23:47:21 +00002543 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002544 return;
2545 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002546 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002547 return;
2548 }
2549 }
Chris Lattner596b97f2004-07-19 23:47:21 +00002550
2551 // If the element size is a negative power of 2, use a shift/neg to get it.
2552 if (unsigned Shift = ExactLog2(-ConstRHS)) {
2553 TmpReg = makeAnotherReg(DestTy);
2554 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2555 switch (Class) {
2556 default: assert(0 && "Unknown class for this function!");
2557 case cByte:
2558 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2559 return;
2560 case cShort:
2561 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2562 return;
2563 case cInt:
2564 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2565 return;
2566 }
2567 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002568
2569 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002570 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002571 return;
2572 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002573 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002574 return;
2575 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002576
2577 // Most general case, emit a normal multiply...
Chris Lattner596b97f2004-07-19 23:47:21 +00002578 TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002579 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002580
2581 // Emit a MUL to multiply the register holding the index by
2582 // elementSize, putting the result in OffsetReg.
2583 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2584}
2585
Chris Lattnerca9671d2002-11-02 20:28:58 +00002586/// visitMul - Multiplies are not simple binary operators because they must deal
2587/// with the EAX register explicitly.
2588///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002589void X86ISel::visitMul(BinaryOperator &I) {
Chris Lattner462fa822004-04-11 20:56:28 +00002590 unsigned ResultReg = getReg(I);
2591
Chris Lattner95157f72004-04-11 22:05:45 +00002592 Value *Op0 = I.getOperand(0);
2593 Value *Op1 = I.getOperand(1);
2594
2595 // Fold loads into floating point multiplies.
2596 if (getClass(Op0->getType()) == cFP) {
2597 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2598 if (!I.swapOperands())
2599 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2600 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2601 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2602 const Type *Ty = Op0->getType();
2603 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2604 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2605
Chris Lattner95157f72004-04-11 22:05:45 +00002606 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002607 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2608 unsigned FI = getFixedSizedAllocaFI(AI);
2609 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2610 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002611 X86AddressMode AM;
2612 getAddressingMode(LI->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002613
Reid Spencerfc989e12004-08-30 00:13:26 +00002614 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002615 }
Chris Lattner95157f72004-04-11 22:05:45 +00002616 return;
2617 }
2618 }
2619
Chris Lattner462fa822004-04-11 20:56:28 +00002620 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002621 emitMultiply(BB, IP, Op0, Op1, ResultReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002622}
2623
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002624void X86ISel::emitMultiply(MachineBasicBlock *MBB,
2625 MachineBasicBlock::iterator IP,
2626 Value *Op0, Value *Op1, unsigned DestReg) {
Chris Lattner462fa822004-04-11 20:56:28 +00002627 MachineBasicBlock &BB = *MBB;
2628 TypeClass Class = getClass(Op0->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +00002629
2630 // Simple scalar multiply?
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002631 unsigned Op0Reg = getReg(Op0, &BB, IP);
Chris Lattner462fa822004-04-11 20:56:28 +00002632 switch (Class) {
2633 case cByte:
2634 case cShort:
2635 case cInt:
2636 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner462fa822004-04-11 20:56:28 +00002637 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2638 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002639 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002640 unsigned Op1Reg = getReg(Op1, &BB, IP);
2641 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002642 }
Chris Lattner462fa822004-04-11 20:56:28 +00002643 return;
2644 case cFP:
Chris Lattner6621ed92004-04-11 21:23:56 +00002645 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2646 return;
Chris Lattner462fa822004-04-11 20:56:28 +00002647 case cLong:
2648 break;
2649 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002650
Chris Lattner462fa822004-04-11 20:56:28 +00002651 // Long value. We have to do things the hard way...
2652 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2653 unsigned CLow = CI->getRawValue();
2654 unsigned CHi = CI->getRawValue() >> 32;
2655
2656 if (CLow == 0) {
2657 // If the low part of the constant is all zeros, things are simple.
2658 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2659 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2660 return;
2661 }
2662
2663 // Multiply the two low parts... capturing carry into EDX
2664 unsigned OverflowReg = 0;
2665 if (CLow == 1) {
2666 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
Chris Lattner028adc42004-04-06 04:29:36 +00002667 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002668 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2669 OverflowReg = makeAnotherReg(Type::UIntTy);
2670 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2671 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2672 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002673
Chris Lattner462fa822004-04-11 20:56:28 +00002674 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2675 BuildMI(BB, IP, X86::MOV32rr, 1,
2676 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2677 }
2678
2679 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2680 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2681
2682 unsigned AHBLplusOverflowReg;
2683 if (OverflowReg) {
2684 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2685 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002686 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002687 } else {
2688 AHBLplusOverflowReg = AHBLReg;
2689 }
2690
2691 if (CHi == 0) {
2692 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2693 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002694 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner462fa822004-04-11 20:56:28 +00002695 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002696
Chris Lattner462fa822004-04-11 20:56:28 +00002697 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002698 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2699 }
Chris Lattner462fa822004-04-11 20:56:28 +00002700 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002701 }
Chris Lattner462fa822004-04-11 20:56:28 +00002702
2703 // General 64x64 multiply
2704
2705 unsigned Op1Reg = getReg(Op1, &BB, IP);
2706 // Multiply the two low parts... capturing carry into EDX
2707 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2708 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2709
2710 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2711 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2712 BuildMI(BB, IP, X86::MOV32rr, 1,
2713 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2714
2715 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2716 BuildMI(BB, IP, X86::IMUL32rr, 2,
2717 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2718
2719 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2720 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2721 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2722
2723 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2724 BuildMI(BB, IP, X86::IMUL32rr, 2,
2725 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2726
2727 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2728 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002729}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002730
Chris Lattner06925362002-11-17 21:56:38 +00002731
Chris Lattnerf01729e2002-11-02 20:54:46 +00002732/// visitDivRem - Handle division and remainder instructions... these
2733/// instruction both require the same instructions to be generated, they just
2734/// select the result from a different register. Note that both of these
2735/// instructions work differently for signed and unsigned operands.
2736///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002737void X86ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002738 unsigned ResultReg = getReg(I);
Chris Lattner95157f72004-04-11 22:05:45 +00002739 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2740
2741 // Fold loads into floating point divides.
2742 if (getClass(Op0->getType()) == cFP) {
2743 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2744 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2745 const Type *Ty = Op0->getType();
2746 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2747 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2748
Chris Lattner95157f72004-04-11 22:05:45 +00002749 unsigned Op0r = getReg(Op0);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002750 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2751 unsigned FI = getFixedSizedAllocaFI(AI);
2752 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2753 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002754 X86AddressMode AM;
2755 getAddressingMode(LI->getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002756
Reid Spencerfc989e12004-08-30 00:13:26 +00002757 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002758 }
Chris Lattner95157f72004-04-11 22:05:45 +00002759 return;
2760 }
2761
2762 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2763 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2764 const Type *Ty = Op0->getType();
2765 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2766 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2767
Chris Lattner95157f72004-04-11 22:05:45 +00002768 unsigned Op1r = getReg(Op1);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002769 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2770 unsigned FI = getFixedSizedAllocaFI(AI);
2771 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2772 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00002773 X86AddressMode AM;
2774 getAddressingMode(LI->getOperand(0), AM);
2775 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00002776 }
Chris Lattner95157f72004-04-11 22:05:45 +00002777 return;
2778 }
2779 }
2780
Chris Lattner94af4142002-12-25 05:13:53 +00002781
Chris Lattnercadff442003-10-23 17:21:43 +00002782 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002783 emitDivRemOperation(BB, IP, Op0, Op1,
Chris Lattner462fa822004-04-11 20:56:28 +00002784 I.getOpcode() == Instruction::Div, ResultReg);
Chris Lattnercadff442003-10-23 17:21:43 +00002785}
2786
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002787void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2788 MachineBasicBlock::iterator IP,
2789 Value *Op0, Value *Op1, bool isDiv,
2790 unsigned ResultReg) {
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002791 const Type *Ty = Op0->getType();
2792 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002793 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002794 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002795 if (isDiv) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002796 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2797 return;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002798 } else { // Floating point remainder...
Chris Lattner462fa822004-04-11 20:56:28 +00002799 unsigned Op0Reg = getReg(Op0, BB, IP);
2800 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002801 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002802 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002803 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002804 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2805 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002806 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2807 }
Chris Lattner94af4142002-12-25 05:13:53 +00002808 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002809 case cLong: {
2810 static const char *FnName[] =
2811 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
Chris Lattner462fa822004-04-11 20:56:28 +00002812 unsigned Op0Reg = getReg(Op0, BB, IP);
2813 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002814 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002815 MachineInstr *TheCall =
2816 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2817
2818 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002819 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2820 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002821 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2822 return;
2823 }
2824 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002825 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002826 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002827 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002828
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002829 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
Chris Lattner2483f672004-10-06 05:01:07 +00002830 static const unsigned NEGOpcode[]={ X86::NEG8r, X86::NEG16r, X86::NEG32r };
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002831 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2832 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2833 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2834
2835 // Special case signed division by power of 2.
Chris Lattner2483f672004-10-06 05:01:07 +00002836 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2837 if (isDiv) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002838 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2839 int V = CI->getValue();
2840
2841 if (V == 1) { // X /s 1 => X
2842 unsigned Op0Reg = getReg(Op0, BB, IP);
2843 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2844 return;
2845 }
2846
2847 if (V == -1) { // X /s -1 => -X
2848 unsigned Op0Reg = getReg(Op0, BB, IP);
2849 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2850 return;
2851 }
2852
Chris Lattner610f1e22004-10-06 04:02:39 +00002853 if (V == 2 || V == -2) { // X /s 2
2854 static const unsigned CMPOpcode[] = {
2855 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2856 };
2857 static const unsigned SBBOpcode[] = {
2858 X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2859 };
2860 unsigned Op0Reg = getReg(Op0, BB, IP);
2861 unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2862 BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2863
2864 unsigned TmpReg = makeAnotherReg(Op0->getType());
2865 BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2866
2867 unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2868 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2869 if (V == -2) {
2870 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2871 }
2872 return;
2873 }
2874
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002875 bool isNeg = false;
2876 if (V < 0) { // Not a positive power of 2?
2877 V = -V;
2878 isNeg = true; // Maybe it's a negative power of 2.
2879 }
2880 if (unsigned Log = ExactLog2(V)) {
2881 --Log;
2882 unsigned Op0Reg = getReg(Op0, BB, IP);
2883 unsigned TmpReg = makeAnotherReg(Op0->getType());
Chris Lattner3ffdff62004-10-06 04:19:43 +00002884 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2885 .addReg(Op0Reg).addImm(Log-1);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002886 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2887 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2888 .addReg(TmpReg).addImm(32-Log);
2889 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2890 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2891 .addReg(Op0Reg).addReg(TmpReg2);
2892
2893 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2894 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
Chris Lattner3ffdff62004-10-06 04:19:43 +00002895 .addReg(TmpReg3).addImm(Log);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002896 if (isNeg)
2897 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2898 return;
2899 }
Chris Lattner2483f672004-10-06 05:01:07 +00002900 } else { // X % C
2901 assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2902 int V = CI->getValue();
2903
2904 if (V == 2 || V == -2) { // X % 2, X % -2
Chris Lattner2483f672004-10-06 05:01:07 +00002905 static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2906 static const unsigned BaseReg[] = { X86::AL , X86::AX , X86::EAX };
2907 static const unsigned SExtReg[] = { X86::AH , X86::DX , X86::EDX };
2908 static const unsigned ANDOpcode[] = {
2909 X86::AND8ri, X86::AND16ri, X86::AND32ri
2910 };
2911 static const unsigned XOROpcode[] = {
2912 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2913 };
2914 static const unsigned SUBOpcode[] = {
2915 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2916 };
2917
2918 // Sign extend result into reg of -1 or 0.
2919 unsigned Op0Reg = getReg(Op0, BB, IP);
2920 BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2921 BuildMI(*BB, IP, SExtOpcode[Class], 0);
2922 unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2923 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2924
2925 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2926 BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2927
2928 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2929 BuildMI(*BB, IP, XOROpcode[Class], 2,
2930 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2931 BuildMI(*BB, IP, SUBOpcode[Class], 2,
2932 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2933 return;
2934 }
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002935 }
2936
2937 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002938 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002939 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
Chris Lattner5384b382005-01-05 16:30:14 +00002940 static const unsigned SExOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002941
2942 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002943 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2944 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002945 };
2946
Chris Lattnerf01729e2002-11-02 20:54:46 +00002947 unsigned Reg = Regs[Class];
2948 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002949
2950 // Put the first operand into one of the A registers...
Chris Lattner462fa822004-04-11 20:56:28 +00002951 unsigned Op0Reg = getReg(Op0, BB, IP);
2952 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00002953 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002954
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002955 if (Ty->isSigned()) {
Chris Lattner5384b382005-01-05 16:30:14 +00002956 // Emit a sign extension instruction.
2957 BuildMI(*BB, IP, SExOpcode[Class], 0);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002958
2959 // Emit the appropriate divide or remainder instruction...
2960 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002961 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002962 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002963 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002964
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002965 // Emit the appropriate divide or remainder instruction...
2966 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2967 }
Chris Lattner06925362002-11-17 21:56:38 +00002968
Chris Lattnerf01729e2002-11-02 20:54:46 +00002969 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002970 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002971
Chris Lattnerf01729e2002-11-02 20:54:46 +00002972 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002973 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002974}
Chris Lattnere2954c82002-11-02 20:04:26 +00002975
Chris Lattner06925362002-11-17 21:56:38 +00002976
Brian Gaekea1719c92002-10-31 23:03:59 +00002977/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2978/// for constant immediate shift values, and for constant immediate
2979/// shift values equal to 1. Even the general case is sort of special,
2980/// because the shift amount has to be in CL, not just any old register.
2981///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00002982void X86ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002983 MachineBasicBlock::iterator IP = BB->end ();
2984 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2985 I.getOpcode () == Instruction::Shl, I.getType (),
2986 getReg (I));
2987}
2988
Chris Lattnerce7cafa2004-11-13 20:48:57 +00002989/// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
2990/// constant.
2991void X86ISel::doSHLDConst(MachineBasicBlock *MBB,
2992 MachineBasicBlock::iterator IP,
2993 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
2994 unsigned Amt) {
2995 // SHLD is a very inefficient operation on every processor, try to do
2996 // somethign simpler for common values of 'Amt'.
2997 if (Amt == 0) {
2998 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2999 } else if (Amt == 1) {
3000 unsigned Tmp = makeAnotherReg(Type::UIntTy);
3001 BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
3002 BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
3003 } else if (Amt == 2 || Amt == 3) {
3004 // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
3005 // shift/lea pair. NOTE: This should not be done on the P6 family!
3006 unsigned Tmp = makeAnotherReg(Type::UIntTy);
3007 BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
3008 X86AddressMode AM;
3009 AM.BaseType = X86AddressMode::RegBase;
3010 AM.Base.Reg = Tmp;
3011 AM.Scale = 1 << Amt;
3012 AM.IndexReg = Op0Reg;
3013 AM.Disp = 0;
3014 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
3015 } else {
3016 // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
3017 // than it is to emit a real SHLD.
3018
3019 BuildMI(*MBB, IP, X86::SHLD32rri8, 3,
3020 DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
3021 }
3022}
3023
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003024/// emitShiftOperation - Common code shared between visitShiftInst and
3025/// constant expression support.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003026void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
3027 MachineBasicBlock::iterator IP,
3028 Value *Op, Value *ShiftAmount,
3029 bool isLeftShift, const Type *ResultTy,
3030 unsigned DestReg) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003031 unsigned SrcReg = getReg (Op, MBB, IP);
3032 bool isSigned = ResultTy->isSigned ();
3033 unsigned Class = getClass (ResultTy);
Chris Lattnerde95c9e2004-10-17 06:10:40 +00003034
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003035 static const unsigned ConstantOperand[][3] = {
3036 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri }, // SHR
3037 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri }, // SAR
3038 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SHL
3039 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00003040 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003041
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003042 static const unsigned NonConstantOperand[][3] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003043 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
3044 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
3045 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
3046 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00003047 };
Chris Lattner796df732002-11-02 00:44:25 +00003048
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003049 // Longs, as usual, are handled specially.
Chris Lattner3e130a22003-01-13 00:32:26 +00003050 if (Class == cLong) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003051 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003052 unsigned Amount = CUI->getValue();
Chris Lattner62f5a942004-11-13 20:04:38 +00003053 if (Amount == 1 && isLeftShift) { // X << 1 == X+X
Chris Lattner44205ca2004-11-13 20:03:48 +00003054 BuildMI(*MBB, IP, X86::ADD32rr, 2,
3055 DestReg).addReg(SrcReg).addReg(SrcReg);
3056 BuildMI(*MBB, IP, X86::ADC32rr, 2,
3057 DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
3058 } else if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003059 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3060 if (isLeftShift) {
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003061 doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
Chris Lattneree352852004-02-29 07:22:16 +00003062 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003063 } else {
Chris Lattnerce7cafa2004-11-13 20:48:57 +00003064 BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
3065 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
Chris Lattneree352852004-02-29 07:22:16 +00003066 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003067 }
Chris Lattner36c625d2004-11-15 23:16:34 +00003068 } else if (Amount == 32) {
3069 if (isLeftShift) {
3070 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
3071 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3072 } else {
Chris Lattner39a83dc2004-11-16 18:40:52 +00003073 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
Chris Lattner36c625d2004-11-15 23:16:34 +00003074 if (!isSigned) {
3075 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3076 } else {
3077 BuildMI(*MBB, IP, X86::SAR32ri, 2,
3078 DestReg+1).addReg(SrcReg).addImm(31);
3079 }
3080 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003081 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003082 Amount -= 32;
3083 if (isLeftShift) {
Chris Lattner36c625d2004-11-15 23:16:34 +00003084 BuildMI(*MBB, IP, X86::SHL32ri, 2,
3085 DestReg + 1).addReg(SrcReg).addImm(Amount);
Chris Lattner722070e2004-04-06 03:42:38 +00003086 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003087 } else {
Chris Lattner36c625d2004-11-15 23:16:34 +00003088 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
3089 DestReg).addReg(SrcReg+1).addImm(Amount);
Chris Lattner6d027f22005-04-06 20:59:35 +00003090 if (isSigned)
3091 BuildMI(*MBB, IP, X86::SAR32ri, 2,
3092 DestReg+1).addReg(SrcReg+1).addImm(31);
3093 else
3094 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003095 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003096 }
3097 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00003098 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Chris Lattner9171ef52003-06-01 01:56:54 +00003099 if (!isLeftShift && isSigned) {
3100 // If this is a SHR of a Long, then we need to do funny sign extension
3101 // stuff. TmpReg gets the value to use as the high-part if we are
3102 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003103 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00003104 } else {
3105 // Other shifts use a fixed zero value if the shift is more than 32
3106 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003107 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00003108 }
3109
3110 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003111 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003112 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003113
3114 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
3115 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3116 if (isLeftShift) {
3117 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003118 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00003119 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003120 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003121 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003122
3123 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003124 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00003125
3126 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003127 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003128 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
3129 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003130 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003131 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00003132 } else {
3133 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003134 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00003135 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00003136 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003137 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00003138 .addReg(SrcReg+1);
3139
3140 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003141 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00003142
3143 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003144 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003145 DestReg).addReg(TmpReg2).addReg(TmpReg3);
3146
3147 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003148 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00003149 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
3150 }
Brian Gaekea1719c92002-10-31 23:03:59 +00003151 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003152 return;
3153 }
Chris Lattnere9913f22002-11-02 01:41:55 +00003154
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003155 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003156 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
3157 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003158
Chris Lattner44205ca2004-11-13 20:03:48 +00003159 if (CUI->getValue() == 1 && isLeftShift) { // X << 1 -> X+X
3160 static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
3161 BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
3162 } else {
3163 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3164 BuildMI(*MBB, IP, Opc[Class], 2,
3165 DestReg).addReg(SrcReg).addImm(CUI->getValue());
3166 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003167 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00003168 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003169 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003170
Chris Lattner3e130a22003-01-13 00:32:26 +00003171 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00003172 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003173 }
3174}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00003175
Chris Lattner3e130a22003-01-13 00:32:26 +00003176
Chris Lattner6fc3c522002-11-17 21:11:55 +00003177/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00003178/// instruction. The load and store instructions are the only place where we
3179/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00003180///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003181void X86ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00003182 // Check to see if this load instruction is going to be folded into a binary
3183 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
3184 // pattern matching instruction selector be nice?
Chris Lattner95157f72004-04-11 22:05:45 +00003185 unsigned Class = getClassB(I.getType());
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003186 if (I.hasOneUse()) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00003187 Instruction *User = cast<Instruction>(I.use_back());
3188 switch (User->getOpcode()) {
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003189 case Instruction::Cast:
3190 // If this is a cast from a signed-integer type to a floating point type,
3191 // fold the cast here.
John Criswell6b5bd582004-06-09 15:18:51 +00003192 if (getClassB(User->getType()) == cFP &&
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003193 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
3194 I.getType() == Type::LongTy)) {
3195 unsigned DestReg = getReg(User);
3196 static const unsigned Opcode[] = {
3197 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
3198 };
Chris Lattner9f1b5312004-05-13 15:12:43 +00003199
3200 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3201 unsigned FI = getFixedSizedAllocaFI(AI);
3202 addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3203 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003204 X86AddressMode AM;
3205 getAddressingMode(I.getOperand(0), AM);
3206 addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003207 }
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003208 return;
3209 } else {
3210 User = 0;
3211 }
3212 break;
Chris Lattner13c07fe2004-04-12 00:12:04 +00003213
Chris Lattner7dee5da2004-03-08 01:58:35 +00003214 case Instruction::Add:
3215 case Instruction::Sub:
3216 case Instruction::And:
3217 case Instruction::Or:
3218 case Instruction::Xor:
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003219 if (Class == cLong) User = 0;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003220 break;
Chris Lattner95157f72004-04-11 22:05:45 +00003221 case Instruction::Mul:
3222 case Instruction::Div:
Chris Lattner13c07fe2004-04-12 00:12:04 +00003223 if (Class != cFP) User = 0;
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003224 break; // Folding only implemented for floating point.
Chris Lattner95157f72004-04-11 22:05:45 +00003225 default: User = 0; break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003226 }
3227
3228 if (User) {
3229 // Okay, we found a user. If the load is the first operand and there is
3230 // no second operand load, reverse the operand ordering. Note that this
3231 // can fail for a subtract (ie, no change will be made).
Chris Lattner3dbb5042004-07-21 21:28:26 +00003232 bool Swapped = false;
Chris Lattner7dee5da2004-03-08 01:58:35 +00003233 if (!isa<LoadInst>(User->getOperand(1)))
Chris Lattner3dbb5042004-07-21 21:28:26 +00003234 Swapped = !cast<BinaryOperator>(User)->swapOperands();
Chris Lattner7dee5da2004-03-08 01:58:35 +00003235
3236 // Okay, now that everything is set up, if this load is used by the second
3237 // operand, and if there are no instructions that invalidate the load
3238 // before the binary operator, eliminate the load.
3239 if (User->getOperand(1) == &I &&
3240 isSafeToFoldLoadIntoInstruction(I, *User))
3241 return; // Eliminate the load!
Chris Lattner95157f72004-04-11 22:05:45 +00003242
3243 // If this is a floating point sub or div, we won't be able to swap the
3244 // operands, but we will still be able to eliminate the load.
3245 if (Class == cFP && User->getOperand(0) == &I &&
3246 !isa<LoadInst>(User->getOperand(1)) &&
3247 (User->getOpcode() == Instruction::Sub ||
3248 User->getOpcode() == Instruction::Div) &&
3249 isSafeToFoldLoadIntoInstruction(I, *User))
3250 return; // Eliminate the load!
Chris Lattner3dbb5042004-07-21 21:28:26 +00003251
3252 // If we swapped the operands to the instruction, but couldn't fold the
3253 // load anyway, swap them back. We don't want to break add X, int
3254 // folding.
3255 if (Swapped) cast<BinaryOperator>(User)->swapOperands();
Chris Lattner7dee5da2004-03-08 01:58:35 +00003256 }
3257 }
3258
Chris Lattner6ac1d712003-10-20 04:48:06 +00003259 static const unsigned Opcodes[] = {
Chris Lattner9f1b5312004-05-13 15:12:43 +00003260 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
Chris Lattner3e130a22003-01-13 00:32:26 +00003261 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00003262 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003263 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003264
3265 unsigned DestReg = getReg(I);
3266
3267 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3268 unsigned FI = getFixedSizedAllocaFI(AI);
3269 if (Class == cLong) {
3270 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3271 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3272 } else {
3273 addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3274 }
3275 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003276 X86AddressMode AM;
3277 getAddressingMode(I.getOperand(0), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003278
3279 if (Class == cLong) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003280 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3281 AM.Disp += 4;
3282 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003283 } else {
Reid Spencerfc989e12004-08-30 00:13:26 +00003284 addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
Chris Lattner9f1b5312004-05-13 15:12:43 +00003285 }
3286 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003287}
3288
Chris Lattner6fc3c522002-11-17 21:11:55 +00003289/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3290/// instruction.
3291///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003292void X86ISel::visitStoreInst(StoreInst &I) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003293 X86AddressMode AM;
3294 getAddressingMode(I.getOperand(1), AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003295
Chris Lattner6c09db22003-10-20 04:11:23 +00003296 const Type *ValTy = I.getOperand(0)->getType();
3297 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00003298
Chris Lattner5a830962004-02-25 02:56:58 +00003299 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3300 uint64_t Val = CI->getRawValue();
3301 if (Class == cLong) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003302 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3303 AM.Disp += 4;
3304 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00003305 } else {
3306 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003307 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00003308 };
3309 unsigned Opcode = Opcodes[Class];
Reid Spencerfc989e12004-08-30 00:13:26 +00003310 addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00003311 }
Chris Lattnerb7cb9ff2004-05-13 15:26:48 +00003312 } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
Chris Lattner358a9022004-10-15 05:05:29 +00003313 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
Chris Lattner5a830962004-02-25 02:56:58 +00003314 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003315 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
Chris Lattnere7a31c92004-05-07 21:18:15 +00003316 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3317 // Store constant FP values with integer instructions to avoid having to
3318 // load the constants from the constant pool then do a store.
3319 if (CFP->getType() == Type::FloatTy) {
3320 union {
3321 unsigned I;
3322 float F;
3323 } V;
3324 V.F = CFP->getValue();
Reid Spencerfc989e12004-08-30 00:13:26 +00003325 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
Chris Lattner5a830962004-02-25 02:56:58 +00003326 } else {
Chris Lattnere7a31c92004-05-07 21:18:15 +00003327 union {
3328 uint64_t I;
3329 double F;
3330 } V;
3331 V.F = CFP->getValue();
Reid Spencerfc989e12004-08-30 00:13:26 +00003332 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3333 AM.Disp += 4;
3334 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
Chris Lattnere7a31c92004-05-07 21:18:15 +00003335 unsigned(V.I >> 32));
Chris Lattner5a830962004-02-25 02:56:58 +00003336 }
Chris Lattnere7a31c92004-05-07 21:18:15 +00003337
3338 } else if (Class == cLong) {
3339 unsigned ValReg = getReg(I.getOperand(0));
Reid Spencerfc989e12004-08-30 00:13:26 +00003340 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3341 AM.Disp += 4;
3342 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
Chris Lattnere7a31c92004-05-07 21:18:15 +00003343 } else {
Chris Lattner358a9022004-10-15 05:05:29 +00003344 // FIXME: stop emitting these two instructions:
3345 // movl $global,%eax
3346 // movl %eax,(%ebx)
3347 // when one instruction will suffice. That includes when the global
3348 // has an offset applied to it.
Chris Lattnere7a31c92004-05-07 21:18:15 +00003349 unsigned ValReg = getReg(I.getOperand(0));
3350 static const unsigned Opcodes[] = {
3351 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3352 };
3353 unsigned Opcode = Opcodes[Class];
3354 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattner9f1b5312004-05-13 15:12:43 +00003355
Reid Spencerfc989e12004-08-30 00:13:26 +00003356 addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003357 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00003358}
3359
3360
Misha Brukman538607f2004-03-01 23:53:11 +00003361/// visitCastInst - Here we have various kinds of copying with or without sign
3362/// extension going on.
3363///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003364void X86ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003365 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00003366
Chris Lattner99382862004-04-12 00:23:04 +00003367 unsigned SrcClass = getClassB(Op->getType());
3368 unsigned DestClass = getClassB(CI.getType());
3369 // Noop casts are not emitted: getReg will return the source operand as the
3370 // register to use for any uses of the noop cast.
Chris Lattner8b486a12004-06-29 00:14:38 +00003371 if (DestClass == SrcClass) {
3372 // The only detail in this plan is that casts from double -> float are
3373 // truncating operations that we have to codegen through memory (despite
3374 // the fact that the source/dest registers are the same class).
3375 if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3376 return;
3377 }
Chris Lattner427aeb42004-04-11 19:21:59 +00003378
Chris Lattnerf5854472003-06-21 16:01:24 +00003379 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3380 // of the case are GEP instructions, then the cast does not need to be
3381 // generated explicitly, it will be folded into the GEP.
Chris Lattner99382862004-04-12 00:23:04 +00003382 if (DestClass == cLong && SrcClass == cInt) {
Chris Lattnerf5854472003-06-21 16:01:24 +00003383 bool AllUsesAreGEPs = true;
3384 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3385 if (!isa<GetElementPtrInst>(*I)) {
3386 AllUsesAreGEPs = false;
3387 break;
3388 }
3389
3390 // No need to codegen this cast if all users are getelementptr instrs...
3391 if (AllUsesAreGEPs) return;
3392 }
3393
Chris Lattner99382862004-04-12 00:23:04 +00003394 // If this cast converts a load from a short,int, or long integer to a FP
3395 // value, we will have folded this cast away.
3396 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3397 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3398 Op->getType() == Type::LongTy))
3399 return;
3400
3401
Chris Lattner548f61d2003-04-23 17:22:12 +00003402 unsigned DestReg = getReg(CI);
3403 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00003404 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00003405}
3406
Misha Brukman538607f2004-03-01 23:53:11 +00003407/// emitCastOperation - Common code shared between visitCastInst and constant
3408/// expression cast support.
3409///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003410void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3411 MachineBasicBlock::iterator IP,
3412 Value *Src, const Type *DestTy,
3413 unsigned DestReg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003414 const Type *SrcTy = Src->getType();
3415 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00003416 unsigned DestClass = getClassB(DestTy);
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003417 unsigned SrcReg = getReg(Src, BB, IP);
3418
Chris Lattner3e130a22003-01-13 00:32:26 +00003419 // Implement casts to bool by using compare on the operand followed by set if
3420 // not zero on the result.
3421 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00003422 switch (SrcClass) {
3423 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003424 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003425 break;
3426 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003427 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003428 break;
3429 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003430 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003431 break;
3432 case cLong: {
3433 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003434 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00003435 break;
3436 }
3437 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00003438 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003439 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00003440 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00003441 break;
Chris Lattner20772542003-06-01 03:38:24 +00003442 }
3443
3444 // If the zero flag is not set, then the value is true, set the byte to
3445 // true.
Chris Lattneree352852004-02-29 07:22:16 +00003446 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003447 return;
3448 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003449
3450 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003451 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00003452 };
3453
3454 // Implement casts between values of the same type class (as determined by
3455 // getClass) by using a register-to-register move.
3456 if (SrcClass == DestClass) {
3457 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00003458 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003459 } else if (SrcClass == cFP) {
3460 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003461 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00003462 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003463 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003464 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3465 "Unknown cFP member!");
3466 // Truncate from double to float by storing to memory as short, then
3467 // reading it back.
3468 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00003469 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Chris Lattner5384b382005-01-05 16:30:14 +00003470 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5),
3471 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003472 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003473 }
3474 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003475 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3476 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003477 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00003478 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003479 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00003480 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003481 return;
3482 }
3483
3484 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3485 // or zero extension, depending on whether the source type was signed.
3486 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3487 SrcClass < DestClass) {
3488 bool isLong = DestClass == cLong;
3489 if (isLong) DestClass = cInt;
3490
3491 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003492 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3493 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00003494 };
3495
Chris Lattner96e3b422004-05-09 22:28:45 +00003496 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
Chris Lattneree352852004-02-29 07:22:16 +00003497 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00003498 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003499
3500 if (isLong) { // Handle upper 32 bits as appropriate...
3501 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003502 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00003503 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003504 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00003505 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003506 return;
3507 }
3508
3509 // Special case long -> int ...
3510 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003511 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003512 return;
3513 }
3514
3515 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3516 // move out of AX or AL.
3517 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3518 && SrcClass > DestClass) {
3519 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00003520 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3521 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00003522 return;
3523 }
3524
3525 // Handle casts from integer to floating point now...
3526 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003527 // Promote the integer to a type supported by FLD. We do this because there
3528 // are no unsigned FLD instructions, so we must promote an unsigned value to
3529 // a larger signed value, then use FLD on the larger value.
3530 //
3531 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00003532 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003533 unsigned RealDestReg = DestReg;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003534 switch (SrcTy->getTypeID()) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003535 case Type::BoolTyID:
3536 case Type::SByteTyID:
3537 // We don't have the facilities for directly loading byte sized data from
3538 // memory (even signed). Promote it to 16 bits.
3539 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003540 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003541 break;
3542 case Type::UByteTyID:
3543 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003544 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003545 break;
3546 case Type::UShortTyID:
3547 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003548 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003549 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003550 case Type::ULongTyID:
Chris Lattner56a31c62004-10-17 08:01:28 +00003551 case Type::UIntTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003552 // Don't fild into the read destination.
3553 DestReg = makeAnotherReg(Type::DoubleTy);
3554 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003555 default: // No promotion needed...
3556 break;
3557 }
3558
3559 if (PromoteType) {
3560 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00003561 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003562 SrcTy = PromoteType;
3563 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00003564 SrcReg = TmpReg;
3565 }
3566
3567 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003568 int FrameIdx =
3569 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00003570
3571 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003572 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003573 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003574 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003575 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003576 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003577 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00003578 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3579 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003580 }
3581
3582 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003583 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00003584 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003585
Chris Lattner56a31c62004-10-17 08:01:28 +00003586 if (SrcTy == Type::UIntTy) {
3587 // If this is a cast from uint -> double, we need to be careful about if
3588 // the "sign" bit is set. If so, we don't want to make a negative number,
3589 // we want to make a positive number. Emit code to add an offset if the
3590 // sign bit is set.
3591
3592 // Compute whether the sign bit is set by shifting the reg right 31 bits.
3593 unsigned IsNeg = makeAnotherReg(Type::IntTy);
Chris Lattner6e7c47c2005-01-09 01:49:29 +00003594 BuildMI(*BB, IP, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
Chris Lattner56a31c62004-10-17 08:01:28 +00003595
3596 // Create a CP value that has the offset in one word and 0 in the other.
3597 static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
3598 0x4f80000000000000ULL);
3599 unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
Chris Lattner6e7c47c2005-01-09 01:49:29 +00003600 BuildMI(*BB, IP, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
Chris Lattner56a31c62004-10-17 08:01:28 +00003601 .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
3602
3603 } else if (SrcTy == Type::ULongTy) {
3604 // We need special handling for unsigned 64-bit integer sources. If the
3605 // input number has the "sign bit" set, then we loaded it incorrectly as a
3606 // negative 64-bit number. In this case, add an offset value.
3607
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003608 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003609 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003610
Chris Lattnerb6bac512004-02-25 06:13:04 +00003611 // If the sign bit is set, get a pointer to an offset, otherwise get a
3612 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003613 MachineConstantPool *CP = F->getConstantPool();
3614 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003615 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003616 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003617 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003618 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003619 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3620
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003621 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003622 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003623 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003624 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003625
3626 // Load the constant for an add. FIXME: this could make an 'fadd' that
3627 // reads directly from memory, but we don't support these yet.
3628 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003629 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003630
Chris Lattneree352852004-02-29 07:22:16 +00003631 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3632 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003633 }
3634
Chris Lattner3e130a22003-01-13 00:32:26 +00003635 return;
3636 }
3637
3638 // Handle casts from floating point to integer now...
3639 if (SrcClass == cFP) {
3640 // Change the floating point control register to use "round towards zero"
3641 // mode when truncating to an integer value.
3642 //
3643 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003644 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003645
3646 // Load the old value of the high byte of the control word...
3647 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003648 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00003649 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003650
3651 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003652 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003653 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00003654
3655 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003656 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003657
3658 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003659 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003660 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00003661
3662 // We don't have the facilities for directly storing byte sized data to
3663 // memory. Promote it to 16 bits. We also must promote unsigned values to
3664 // larger classes because we only have signed FP stores.
3665 unsigned StoreClass = DestClass;
3666 const Type *StoreTy = DestTy;
3667 if (StoreClass == cByte || DestTy->isUnsigned())
3668 switch (StoreClass) {
3669 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3670 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3671 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00003672 // The following treatment of cLong may not be perfectly right,
3673 // but it survives chains of casts of the form
3674 // double->ulong->double.
3675 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00003676 default: assert(0 && "Unknown store class!");
3677 }
3678
3679 // Spill the integer to memory and reload it from there...
3680 int FrameIdx =
3681 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3682
3683 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003684 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00003685 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3686 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003687
3688 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003689 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3690 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00003691 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00003692 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003693 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00003694 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003695 }
3696
3697 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003698 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003699 return;
3700 }
3701
Brian Gaeked474e9c2002-12-06 10:49:33 +00003702 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00003703 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003704 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00003705}
Brian Gaekea1719c92002-10-31 23:03:59 +00003706
Chris Lattner73815062003-10-18 05:56:40 +00003707/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00003708///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003709void X86ISel::visitVANextInst(VANextInst &I) {
Chris Lattner73815062003-10-18 05:56:40 +00003710 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00003711 unsigned DestReg = getReg(I);
3712
Chris Lattnereca195e2003-05-08 19:44:13 +00003713 unsigned Size;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003714 switch (I.getArgType()->getTypeID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00003715 default:
3716 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00003717 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00003718 return;
3719 case Type::PointerTyID:
3720 case Type::UIntTyID:
3721 case Type::IntTyID:
3722 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00003723 break;
3724 case Type::ULongTyID:
3725 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00003726 case Type::DoubleTyID:
3727 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00003728 break;
3729 }
3730
3731 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003732 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00003733}
Chris Lattnereca195e2003-05-08 19:44:13 +00003734
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003735void X86ISel::visitVAArgInst(VAArgInst &I) {
Chris Lattner73815062003-10-18 05:56:40 +00003736 unsigned VAList = getReg(I.getOperand(0));
3737 unsigned DestReg = getReg(I);
3738
Chris Lattnerf70c22b2004-06-17 18:19:28 +00003739 switch (I.getType()->getTypeID()) {
Chris Lattner73815062003-10-18 05:56:40 +00003740 default:
3741 std::cerr << I;
3742 assert(0 && "Error: bad type for va_next instruction!");
3743 return;
3744 case Type::PointerTyID:
3745 case Type::UIntTyID:
3746 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003747 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003748 break;
3749 case Type::ULongTyID:
3750 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003751 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3752 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00003753 break;
3754 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003755 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003756 break;
3757 }
Chris Lattnereca195e2003-05-08 19:44:13 +00003758}
3759
Misha Brukman538607f2004-03-01 23:53:11 +00003760/// visitGetElementPtrInst - instruction-select GEP instructions
3761///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003762void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003763 // If this GEP instruction will be folded into all of its users, we don't need
3764 // to explicitly calculate it!
Reid Spencerfc989e12004-08-30 00:13:26 +00003765 X86AddressMode AM;
3766 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003767 // Check all of the users of the instruction to see if they are loads and
3768 // stores.
3769 bool AllWillFold = true;
3770 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3771 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3772 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3773 cast<Instruction>(*UI)->getOperand(0) == &I) {
3774 AllWillFold = false;
3775 break;
3776 }
3777
3778 // If the instruction is foldable, and will be folded into all users, don't
3779 // emit it!
3780 if (AllWillFold) return;
3781 }
3782
Chris Lattner3e130a22003-01-13 00:32:26 +00003783 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00003784 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00003785 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00003786}
3787
Chris Lattner985fe3d2004-02-25 03:45:50 +00003788/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3789/// GEPTypes (the derived types being stepped through at each level). On return
3790/// from this function, if some indexes of the instruction are representable as
3791/// an X86 lea instruction, the machine operands are put into the Ops
3792/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3793/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3794/// addressing mode that only partially consumes the input, the BaseReg input of
3795/// the addressing mode must be left free.
3796///
3797/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3798///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003799void X86ISel::getGEPIndex(MachineBasicBlock *MBB,
3800 MachineBasicBlock::iterator IP,
3801 std::vector<Value*> &GEPOps,
3802 std::vector<const Type*> &GEPTypes,
3803 X86AddressMode &AM) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003804 const TargetData &TD = TM.getTargetData();
3805
Chris Lattner985fe3d2004-02-25 03:45:50 +00003806 // Clear out the state we are working with...
Reid Spencerfc989e12004-08-30 00:13:26 +00003807 AM.BaseType = X86AddressMode::RegBase;
3808 AM.Base.Reg = 0; // No base register
3809 AM.Scale = 1; // Unit scale
3810 AM.IndexReg = 0; // No index register
3811 AM.Disp = 0; // No displacement
Chris Lattnerb6bac512004-02-25 06:13:04 +00003812
Chris Lattner985fe3d2004-02-25 03:45:50 +00003813 // While there are GEP indexes that can be folded into the current address,
3814 // keep processing them.
3815 while (!GEPTypes.empty()) {
3816 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3817 // It's a struct access. CUI is the index into the structure,
3818 // which names the field. This index must have unsigned type.
3819 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3820
3821 // Use the TargetData structure to pick out what the layout of the
3822 // structure is in memory. Since the structure index must be constant, we
3823 // can get its value and use it to find the right byte offset from the
3824 // StructLayout class's list of structure member offsets.
Reid Spencerfc989e12004-08-30 00:13:26 +00003825 AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003826 GEPOps.pop_back(); // Consume a GEP operand
3827 GEPTypes.pop_back();
3828 } else {
3829 // It's an array or pointer access: [ArraySize x ElementType].
3830 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3831 Value *idx = GEPOps.back();
3832
3833 // idx is the index into the array. Unlike with structure
3834 // indices, we may not know its actual value at code-generation
3835 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003836
3837 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003838 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003839 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003840 AM.Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003841 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003842 AM.Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003843 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003844 // If the index reg is already taken, we can't handle this index.
Reid Spencerfc989e12004-08-30 00:13:26 +00003845 if (AM.IndexReg) return;
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003846
3847 // If this is a size that we can handle, then add the index as
3848 switch (TypeSize) {
3849 case 1: case 2: case 4: case 8:
3850 // These are all acceptable scales on X86.
Reid Spencerfc989e12004-08-30 00:13:26 +00003851 AM.Scale = TypeSize;
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003852 break;
3853 default:
3854 // Otherwise, we can't handle this scale
3855 return;
3856 }
3857
3858 if (CastInst *CI = dyn_cast<CastInst>(idx))
3859 if (CI->getOperand(0)->getType() == Type::IntTy ||
3860 CI->getOperand(0)->getType() == Type::UIntTy)
3861 idx = CI->getOperand(0);
3862
Reid Spencerfc989e12004-08-30 00:13:26 +00003863 AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003864 }
3865
3866 GEPOps.pop_back(); // Consume a GEP operand
3867 GEPTypes.pop_back();
3868 }
3869 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003870
Chris Lattnerdf040972004-05-23 21:23:12 +00003871 // GEPTypes is empty, which means we have a single operand left. Set it as
3872 // the base register.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003873 //
Reid Spencerfc989e12004-08-30 00:13:26 +00003874 assert(AM.Base.Reg == 0);
Chris Lattnerdf040972004-05-23 21:23:12 +00003875
Reid Spencerfc989e12004-08-30 00:13:26 +00003876 if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3877 AM.BaseType = X86AddressMode::FrameIndexBase;
3878 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
Chris Lattnerdf040972004-05-23 21:23:12 +00003879 GEPOps.pop_back();
3880 return;
Reid Spencerfc989e12004-08-30 00:13:26 +00003881 }
3882
Chris Lattner358a9022004-10-15 05:05:29 +00003883 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
3884 AM.GV = GV;
3885 GEPOps.pop_back();
3886 return;
Chris Lattnerdf040972004-05-23 21:23:12 +00003887 }
Chris Lattnerdf040972004-05-23 21:23:12 +00003888
Reid Spencerfc989e12004-08-30 00:13:26 +00003889 AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003890 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003891}
3892
3893
Chris Lattnerb6bac512004-02-25 06:13:04 +00003894/// isGEPFoldable - Return true if the specified GEP can be completely
3895/// folded into the addressing mode of a load/store or lea instruction.
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003896bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3897 Value *Src, User::op_iterator IdxBegin,
3898 User::op_iterator IdxEnd, X86AddressMode &AM) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003899
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003900 std::vector<Value*> GEPOps;
3901 GEPOps.resize(IdxEnd-IdxBegin+1);
3902 GEPOps[0] = Src;
3903 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3904
Chris Lattnerdf040972004-05-23 21:23:12 +00003905 std::vector<const Type*>
3906 GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3907 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003908
Chris Lattnerb6bac512004-02-25 06:13:04 +00003909 MachineBasicBlock::iterator IP;
3910 if (MBB) IP = MBB->end();
Reid Spencerfc989e12004-08-30 00:13:26 +00003911 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003912
3913 // We can fold it away iff the getGEPIndex call eliminated all operands.
3914 return GEPOps.empty();
3915}
3916
Misha Brukmaneae1bf12004-09-21 18:21:21 +00003917void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3918 MachineBasicBlock::iterator IP,
3919 Value *Src, User::op_iterator IdxBegin,
3920 User::op_iterator IdxEnd, unsigned TargetReg) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003921 const TargetData &TD = TM.getTargetData();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003922
Chris Lattnerd2995df2004-07-15 00:58:53 +00003923 // If this is a getelementptr null, with all constant integer indices, just
3924 // replace it with TargetReg = 42.
3925 if (isa<ConstantPointerNull>(Src)) {
3926 User::op_iterator I = IdxBegin;
3927 for (; I != IdxEnd; ++I)
3928 if (!isa<ConstantInt>(*I))
3929 break;
3930 if (I == IdxEnd) { // All constant indices
3931 unsigned Offset = TD.getIndexedOffset(Src->getType(),
3932 std::vector<Value*>(IdxBegin, IdxEnd));
3933 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3934 return;
3935 }
3936 }
3937
Chris Lattnerb6bac512004-02-25 06:13:04 +00003938 std::vector<Value*> GEPOps;
3939 GEPOps.resize(IdxEnd-IdxBegin+1);
3940 GEPOps[0] = Src;
3941 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3942
3943 std::vector<const Type*> GEPTypes;
3944 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3945 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003946
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003947 // Keep emitting instructions until we consume the entire GEP instruction.
3948 while (!GEPOps.empty()) {
3949 unsigned OldSize = GEPOps.size();
Reid Spencerfc989e12004-08-30 00:13:26 +00003950 X86AddressMode AM;
3951 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003952
Chris Lattner985fe3d2004-02-25 03:45:50 +00003953 if (GEPOps.size() != OldSize) {
3954 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003955 unsigned NextTarget = 0;
3956 if (!GEPOps.empty()) {
Reid Spencerfc989e12004-08-30 00:13:26 +00003957 assert(AM.Base.Reg == 0 &&
Chris Lattnerb6bac512004-02-25 06:13:04 +00003958 "getGEPIndex should have left the base register open for chaining!");
Reid Spencerfc989e12004-08-30 00:13:26 +00003959 NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003960 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003961
Reid Spencerfc989e12004-08-30 00:13:26 +00003962 if (AM.BaseType == X86AddressMode::RegBase &&
Chris Lattner358a9022004-10-15 05:05:29 +00003963 AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
Reid Spencerfc989e12004-08-30 00:13:26 +00003964 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
Chris Lattner358a9022004-10-15 05:05:29 +00003965 else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
3966 AM.IndexReg == 0 && AM.Disp == 0)
3967 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003968 else
Reid Spencerfc989e12004-08-30 00:13:26 +00003969 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003970 --IP;
3971 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003972 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003973 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3974 // all operands are consumed but the base pointer. If so, just load it
3975 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003976 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003977 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003978 } else {
3979 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003980 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003981 }
3982 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003983
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003984 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003985 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003986 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3987 Value *idx = GEPOps.back();
3988 GEPOps.pop_back(); // Consume a GEP operand
3989 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003990
Chris Lattner28977af2004-04-05 01:30:19 +00003991 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003992 // operand on X86. Handle this case directly now...
3993 if (CastInst *CI = dyn_cast<CastInst>(idx))
3994 if (CI->getOperand(0)->getType() == Type::IntTy ||
3995 CI->getOperand(0)->getType() == Type::UIntTy)
3996 idx = CI->getOperand(0);
3997
Chris Lattner3e130a22003-01-13 00:32:26 +00003998 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003999 // must find the size of the pointed-to type (Not coincidentally, the next
4000 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004001 const Type *ElTy = SqTy->getElementType();
4002 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00004003
4004 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00004005 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004006 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00004007 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004008 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004009 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00004010 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004011 --IP; // Insert the next instruction before this one.
4012 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00004013 }
4014 } else if (elementSize == 1) {
4015 // If the element size is 1, we don't have to multiply, just add
4016 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004017 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004018 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004019 --IP; // Insert the next instruction before this one.
4020 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00004021 } else {
4022 unsigned idxReg = getReg(idx, MBB, IP);
4023 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00004024
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004025 // Make sure we can back the iterator up to point to the first
4026 // instruction emitted.
4027 MachineBasicBlock::iterator BeforeIt = IP;
4028 if (IP == MBB->begin())
4029 BeforeIt = MBB->end();
4030 else
4031 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00004032 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
4033
Chris Lattner8a307e82002-12-16 19:32:50 +00004034 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004035 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004036 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00004037 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00004038
4039 // Step to the first instruction of the multiply.
4040 if (BeforeIt == MBB->end())
4041 IP = MBB->begin();
4042 else
4043 IP = ++BeforeIt;
4044
4045 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00004046 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004047 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004048 }
Brian Gaeke20244b72002-12-12 15:33:40 +00004049}
4050
Chris Lattner065faeb2002-12-28 20:24:02 +00004051/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
4052/// frame manager, otherwise do it the hard way.
4053///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004054void X86ISel::visitAllocaInst(AllocaInst &I) {
Chris Lattner9f1b5312004-05-13 15:12:43 +00004055 // If this is a fixed size alloca in the entry block for the function, we
4056 // statically stack allocate the space, so we don't need to do anything here.
4057 //
Chris Lattnercb2fd552004-05-13 07:40:27 +00004058 if (dyn_castFixedAlloca(&I)) return;
Chris Lattner9f1b5312004-05-13 15:12:43 +00004059
Brian Gaekee48ec012002-12-13 06:46:31 +00004060 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00004061 const Type *Ty = I.getAllocatedType();
4062 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
4063
Chris Lattner065faeb2002-12-28 20:24:02 +00004064 // Create a register to hold the temporary result of multiplying the type size
4065 // constant by the variable amount.
4066 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
4067 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00004068
4069 // TotalSizeReg = mul <numelements>, <TypeSize>
4070 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00004071 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00004072
4073 // AddedSize = add <TotalSizeReg>, 15
4074 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004075 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00004076
4077 // AlignedSize = and <AddedSize>, ~15
4078 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004079 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00004080
Brian Gaekee48ec012002-12-13 06:46:31 +00004081 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004082 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00004083
Brian Gaekee48ec012002-12-13 06:46:31 +00004084 // Put a pointer to the space into the result register, by copying
4085 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00004086 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00004087
Misha Brukman48196b32003-05-03 02:18:17 +00004088 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00004089 // object.
4090 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00004091}
Chris Lattner3e130a22003-01-13 00:32:26 +00004092
4093/// visitMallocInst - Malloc instructions are code generated into direct calls
4094/// to the library malloc.
4095///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004096void X86ISel::visitMallocInst(MallocInst &I) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004097 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
4098 unsigned Arg;
4099
4100 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
4101 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
4102 } else {
4103 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00004104 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00004105 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00004106 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00004107 }
4108
4109 std::vector<ValueRecord> Args;
4110 Args.push_back(ValueRecord(Arg, Type::UIntTy));
4111 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00004112 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00004113 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
4114}
4115
4116
4117/// visitFreeInst - Free instructions are code gen'd to call the free libc
4118/// function.
4119///
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004120void X86ISel::visitFreeInst(FreeInst &I) {
Chris Lattner3e130a22003-01-13 00:32:26 +00004121 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00004122 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00004123 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00004124 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00004125 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
4126}
4127
Chris Lattnerd281de22003-07-26 23:49:58 +00004128/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00004129/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00004130/// generated code sucks but the implementation is nice and simple.
4131///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00004132FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
Misha Brukmaneae1bf12004-09-21 18:21:21 +00004133 return new X86ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00004134}