blob: 8286cd05a035a59442c686007504a1938b4d9e01 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a DAG pattern matching instruction selector for X86,
11// converting from a legalized dag to a X86 dag.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86.h"
17#include "X86InstrBuilder.h"
18#include "X86ISelLowering.h"
Evan Cheng0729ccf2008-01-05 00:41:47 +000019#include "X86MachineFunctionInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "X86RegisterInfo.h"
21#include "X86Subtarget.h"
22#include "X86TargetMachine.h"
23#include "llvm/GlobalValue.h"
24#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/Support/CFG.h"
27#include "llvm/Type.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner1b989192007-12-31 04:13:23 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/CodeGen/SelectionDAGISel.h"
34#include "llvm/Target/TargetMachine.h"
Evan Chengd5bf2ca2008-02-19 23:36:51 +000035#include "llvm/Support/CommandLine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/MathExtras.h"
Evan Cheng656269e2008-04-25 08:22:20 +000039#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/Statistic.h"
41#include <queue>
42#include <set>
43using namespace llvm;
44
45STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
46STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
47
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048//===----------------------------------------------------------------------===//
49// Pattern Matcher Implementation
50//===----------------------------------------------------------------------===//
51
52namespace {
53 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
54 /// SDOperand's instead of register numbers for the leaves of the matched
55 /// tree.
56 struct X86ISelAddressMode {
57 enum {
58 RegBase,
59 FrameIndexBase
60 } BaseType;
61
62 struct { // This is really a union, discriminated by BaseType!
63 SDOperand Reg;
64 int FrameIndex;
65 } Base;
66
Evan Cheng3b5a1272008-02-07 08:53:49 +000067 bool isRIPRel; // RIP as base?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 unsigned Scale;
69 SDOperand IndexReg;
70 unsigned Disp;
71 GlobalValue *GV;
72 Constant *CP;
73 const char *ES;
74 int JT;
75 unsigned Align; // CP alignment.
76
77 X86ISelAddressMode()
78 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
79 GV(0), CP(0), ES(0), JT(-1), Align(0) {
80 }
81 };
82}
83
84namespace {
85 //===--------------------------------------------------------------------===//
86 /// ISel - X86 specific code to select X86 machine instructions for
87 /// SelectionDAG operations.
88 ///
89 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
90 /// ContainsFPCode - Every instruction we select that uses or defines a FP
91 /// register should set this to true.
92 bool ContainsFPCode;
93
94 /// FastISel - Enable fast(er) instruction selection.
95 ///
96 bool FastISel;
97
98 /// TM - Keep a reference to X86TargetMachine.
99 ///
100 X86TargetMachine &TM;
101
102 /// X86Lowering - This object fully describes how to lower LLVM code to an
103 /// X86-specific SelectionDAG.
104 X86TargetLowering X86Lowering;
105
106 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
107 /// make the right decision when generating code for different targets.
108 const X86Subtarget *Subtarget;
109
110 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
111 /// base register.
112 unsigned GlobalBaseReg;
113
114 public:
115 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
116 : SelectionDAGISel(X86Lowering),
117 ContainsFPCode(false), FastISel(fast), TM(tm),
118 X86Lowering(*TM.getTargetLowering()),
119 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
120
121 virtual bool runOnFunction(Function &Fn) {
122 // Make sure we re-emit a set of the global base reg if necessary
123 GlobalBaseReg = 0;
124 return SelectionDAGISel::runOnFunction(Fn);
125 }
126
127 virtual const char *getPassName() const {
128 return "X86 DAG->DAG Instruction Selection";
129 }
130
131 /// InstructionSelectBasicBlock - This callback is invoked by
132 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
133 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
134
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000135 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
136
Dan Gohmand6098272007-07-24 23:00:27 +0000137 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138
139// Include the pieces autogenerated from the target description.
140#include "X86GenDAGISel.inc"
141
142 private:
143 SDNode *Select(SDOperand N);
144
145 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
146 bool isRoot = true, unsigned Depth = 0);
Dan Gohmana60c1b32007-08-13 20:03:06 +0000147 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
148 bool isRoot, unsigned Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
150 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
151 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
152 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
153 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
154 SDOperand N, SDOperand &Base, SDOperand &Scale,
155 SDOperand &Index, SDOperand &Disp,
156 SDOperand &InChain, SDOperand &OutChain);
157 bool TryFoldLoad(SDOperand P, SDOperand N,
158 SDOperand &Base, SDOperand &Scale,
159 SDOperand &Index, SDOperand &Disp);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000160 void PreprocessForRMW(SelectionDAG &DAG);
161 void PreprocessForFPConvert(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162
163 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
164 /// inline asm expressions.
165 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
166 char ConstraintCode,
167 std::vector<SDOperand> &OutOps,
168 SelectionDAG &DAG);
169
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000170 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
171
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
173 SDOperand &Scale, SDOperand &Index,
174 SDOperand &Disp) {
175 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
176 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
177 AM.Base.Reg;
178 Scale = getI8Imm(AM.Scale);
179 Index = AM.IndexReg;
180 // These are 32-bit even in 64-bit mode since RIP relative offset
181 // is 32-bit.
182 if (AM.GV)
183 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
184 else if (AM.CP)
185 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
186 else if (AM.ES)
187 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
188 else if (AM.JT != -1)
189 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
190 else
191 Disp = getI32Imm(AM.Disp);
192 }
193
194 /// getI8Imm - Return a target constant with the specified value, of type
195 /// i8.
196 inline SDOperand getI8Imm(unsigned Imm) {
197 return CurDAG->getTargetConstant(Imm, MVT::i8);
198 }
199
200 /// getI16Imm - Return a target constant with the specified value, of type
201 /// i16.
202 inline SDOperand getI16Imm(unsigned Imm) {
203 return CurDAG->getTargetConstant(Imm, MVT::i16);
204 }
205
206 /// getI32Imm - Return a target constant with the specified value, of type
207 /// i32.
208 inline SDOperand getI32Imm(unsigned Imm) {
209 return CurDAG->getTargetConstant(Imm, MVT::i32);
210 }
211
212 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
213 /// base register. Return the virtual register that holds this value.
214 SDNode *getGlobalBaseReg();
215
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000216 /// getTruncate - return an SDNode that implements a subreg based truncate
217 /// of the specified operand to the the specified value type.
218 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
219
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220#ifndef NDEBUG
221 unsigned Indent;
222#endif
223 };
224}
225
Evan Cheng656269e2008-04-25 08:22:20 +0000226/// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
227///
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228static SDNode *findFlagUse(SDNode *N) {
229 unsigned FlagResNo = N->getNumValues()-1;
230 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +0000231 SDNode *User = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
233 SDOperand Op = User->getOperand(i);
234 if (Op.Val == N && Op.ResNo == FlagResNo)
235 return User;
236 }
237 }
238 return NULL;
239}
240
Evan Cheng656269e2008-04-25 08:22:20 +0000241/// findNonImmUse - Return true by reference in "found" if "Use" is an
242/// non-immediate use of "Def". This function recursively traversing
243/// up the operand chain ignoring certain nodes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
245 SDNode *Root, SDNode *Skip, bool &found,
Evan Cheng656269e2008-04-25 08:22:20 +0000246 SmallPtrSet<SDNode*, 16> &Visited) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 if (found ||
248 Use->getNodeId() > Def->getNodeId() ||
Evan Cheng656269e2008-04-25 08:22:20 +0000249 !Visited.insert(Use))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 return;
Evan Cheng656269e2008-04-25 08:22:20 +0000251
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
253 SDNode *N = Use->getOperand(i).Val;
254 if (N == Skip)
255 continue;
256 if (N == Def) {
257 if (Use == ImmedUse)
Evan Cheng9ea310c2008-04-25 08:55:28 +0000258 continue; // We are not looking for immediate use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 if (Use == Root) {
Evan Cheng9ea310c2008-04-25 08:55:28 +0000260 // Must be a chain reading node where it is possible to reach its own
261 // chain operand through a path started from another operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 assert(Use->getOpcode() == ISD::STORE ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000263 Use->getOpcode() == X86ISD::CMP ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000264 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
265 Use->getOpcode() == ISD::INTRINSIC_VOID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 continue;
267 }
268 found = true;
269 break;
270 }
Evan Cheng656269e2008-04-25 08:22:20 +0000271
272 // Traverse up the operand chain.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
274 }
275}
276
277/// isNonImmUse - Start searching from Root up the DAG to check is Def can
278/// be reached. Return true if that's the case. However, ignore direct uses
279/// by ImmedUse (which would be U in the example illustrated in
280/// CanBeFoldedBy) and by Root (which can happen in the store case).
281/// FIXME: to be really generic, we should allow direct use by any node
282/// that is being folded. But realisticly since we only fold loads which
283/// have one non-chain use, we only need to watch out for load/op/store
284/// and load/op/cmp case where the root (store / cmp) may reach the load via
285/// its chain operand.
286static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
287 SDNode *Skip = NULL) {
Evan Cheng656269e2008-04-25 08:22:20 +0000288 SmallPtrSet<SDNode*, 16> Visited;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 bool found = false;
290 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
291 return found;
292}
293
294
Dan Gohmand6098272007-07-24 23:00:27 +0000295bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 if (FastISel) return false;
297
298 // If U use can somehow reach N through another path then U can't fold N or
299 // it will create a cycle. e.g. In the following diagram, U can reach N
300 // through X. If N is folded into into U, then X is both a predecessor and
301 // a successor of U.
302 //
303 // [ N ]
304 // ^ ^
305 // | |
306 // / \---
307 // / [X]
308 // | ^
309 // [U]--------|
310
311 if (isNonImmUse(Root, N, U))
312 return false;
313
314 // If U produces a flag, then it gets (even more) interesting. Since it
315 // would have been "glued" together with its flag use, we need to check if
316 // it might reach N:
317 //
318 // [ N ]
319 // ^ ^
320 // | |
321 // [U] \--
322 // ^ [TF]
323 // | ^
324 // | |
325 // \ /
326 // [FU]
327 //
328 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
329 // NU), then TF is a predecessor of FU and a successor of NU. But since
330 // NU and FU are flagged together, this effectively creates a cycle.
331 bool HasFlagUse = false;
332 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
333 while ((VT == MVT::Flag && !Root->use_empty())) {
334 SDNode *FU = findFlagUse(Root);
335 if (FU == NULL)
336 break;
337 else {
338 Root = FU;
339 HasFlagUse = true;
340 }
341 VT = Root->getValueType(Root->getNumValues()-1);
342 }
343
344 if (HasFlagUse)
345 return !isNonImmUse(Root, N, Root, U);
346 return true;
347}
348
349/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
350/// and move load below the TokenFactor. Replace store's chain operand with
351/// load's chain result.
352static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
353 SDOperand Store, SDOperand TF) {
354 std::vector<SDOperand> Ops;
355 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
356 if (Load.Val == TF.Val->getOperand(i).Val)
357 Ops.push_back(Load.Val->getOperand(0));
358 else
359 Ops.push_back(TF.Val->getOperand(i));
360 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
361 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
362 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
363 Store.getOperand(2), Store.getOperand(3));
364}
365
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000366/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
367/// This is only run if not in -fast mode (aka -O0).
368/// This allows the instruction selector to pick more read-modify-write
369/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370///
371/// [Load chain]
372/// ^
373/// |
374/// [Load]
375/// ^ ^
376/// | |
377/// / \-
378/// / |
379/// [TokenFactor] [Op]
380/// ^ ^
381/// | |
382/// \ /
383/// \ /
384/// [Store]
385///
386/// The fact the store's chain operand != load's chain will prevent the
387/// (store (op (load))) instruction from being selected. We can transform it to:
388///
389/// [Load chain]
390/// ^
391/// |
392/// [TokenFactor]
393/// ^
394/// |
395/// [Load]
396/// ^ ^
397/// | |
398/// | \-
399/// | |
400/// | [Op]
401/// | ^
402/// | |
403/// \ /
404/// \ /
405/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000406void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
408 E = DAG.allnodes_end(); I != E; ++I) {
409 if (!ISD::isNON_TRUNCStore(I))
410 continue;
411 SDOperand Chain = I->getOperand(0);
412 if (Chain.Val->getOpcode() != ISD::TokenFactor)
413 continue;
414
415 SDOperand N1 = I->getOperand(1);
416 SDOperand N2 = I->getOperand(2);
417 if (MVT::isFloatingPoint(N1.getValueType()) ||
418 MVT::isVector(N1.getValueType()) ||
419 !N1.hasOneUse())
420 continue;
421
422 bool RModW = false;
423 SDOperand Load;
424 unsigned Opcode = N1.Val->getOpcode();
425 switch (Opcode) {
426 case ISD::ADD:
427 case ISD::MUL:
428 case ISD::AND:
429 case ISD::OR:
430 case ISD::XOR:
431 case ISD::ADDC:
432 case ISD::ADDE: {
433 SDOperand N10 = N1.getOperand(0);
434 SDOperand N11 = N1.getOperand(1);
435 if (ISD::isNON_EXTLoad(N10.Val))
436 RModW = true;
437 else if (ISD::isNON_EXTLoad(N11.Val)) {
438 RModW = true;
439 std::swap(N10, N11);
440 }
Evan Cheng9123cfa2008-03-04 00:40:35 +0000441 RModW = RModW && N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 (N10.getOperand(1) == N2) &&
443 (N10.Val->getValueType(0) == N1.getValueType());
444 if (RModW)
445 Load = N10;
446 break;
447 }
448 case ISD::SUB:
449 case ISD::SHL:
450 case ISD::SRA:
451 case ISD::SRL:
452 case ISD::ROTL:
453 case ISD::ROTR:
454 case ISD::SUBC:
455 case ISD::SUBE:
456 case X86ISD::SHLD:
457 case X86ISD::SHRD: {
458 SDOperand N10 = N1.getOperand(0);
459 if (ISD::isNON_EXTLoad(N10.Val))
Evan Cheng9123cfa2008-03-04 00:40:35 +0000460 RModW = N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 (N10.getOperand(1) == N2) &&
462 (N10.Val->getValueType(0) == N1.getValueType());
463 if (RModW)
464 Load = N10;
465 break;
466 }
467 }
468
469 if (RModW) {
470 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
471 ++NumLoadMoved;
472 }
473 }
474}
475
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000476
477/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
478/// nodes that target the FP stack to be store and load to the stack. This is a
479/// gross hack. We would like to simply mark these as being illegal, but when
480/// we do that, legalize produces these when it expands calls, then expands
481/// these in the same legalize pass. We would like dag combine to be able to
482/// hack on these between the call expansion and the node legalization. As such
483/// this pass basically does "really late" legalization of these inline with the
484/// X86 isel pass.
485void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
486 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
487 E = DAG.allnodes_end(); I != E; ) {
488 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
489 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
490 continue;
491
492 // If the source and destination are SSE registers, then this is a legal
493 // conversion that should not be lowered.
494 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
495 MVT::ValueType DstVT = N->getValueType(0);
496 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
497 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
498 if (SrcIsSSE && DstIsSSE)
499 continue;
500
Chris Lattner5d294e52008-03-09 07:05:32 +0000501 if (!SrcIsSSE && !DstIsSSE) {
502 // If this is an FPStack extension, it is a noop.
503 if (N->getOpcode() == ISD::FP_EXTEND)
504 continue;
505 // If this is a value-preserving FPStack truncation, it is a noop.
506 if (N->getConstantOperandVal(1))
507 continue;
508 }
509
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000510 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
511 // FPStack has extload and truncstore. SSE can fold direct loads into other
512 // operations. Based on this, decide what we want to do.
513 MVT::ValueType MemVT;
514 if (N->getOpcode() == ISD::FP_ROUND)
515 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
516 else
517 MemVT = SrcIsSSE ? SrcVT : DstVT;
518
519 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
520
521 // FIXME: optimize the case where the src/dest is a load or store?
522 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
523 MemTmp, NULL, 0, MemVT);
524 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
525 NULL, 0, MemVT);
526
527 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
528 // extload we created. This will cause general havok on the dag because
529 // anything below the conversion could be folded into other existing nodes.
530 // To avoid invalidating 'I', back it up to the convert node.
531 --I;
532 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
533
534 // Now that we did that, the node is dead. Increment the iterator to the
535 // next node to process, then delete N.
536 ++I;
537 DAG.DeleteNode(N);
538 }
539}
540
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
542/// when it has created a SelectionDAG for us to codegen.
543void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
544 DEBUG(BB->dump());
545 MachineFunction::iterator FirstMBB = BB;
546
547 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000548 PreprocessForRMW(DAG);
549
550 // FIXME: This should only happen when not -fast.
551 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552
553 // Codegen the basic block.
554#ifndef NDEBUG
555 DOUT << "===== Instruction selection begins:\n";
556 Indent = 0;
557#endif
558 DAG.setRoot(SelectRoot(DAG.getRoot()));
559#ifndef NDEBUG
560 DOUT << "===== Instruction selection ends:\n";
561#endif
562
563 DAG.RemoveDeadNodes();
564
Chris Lattner04d64b22008-03-10 23:34:12 +0000565 // Emit machine code to BB. This can change 'BB' to the last block being
566 // inserted into.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 ScheduleAndEmitDAG(DAG);
568
569 // If we are emitting FP stack code, scan the basic block to determine if this
570 // block defines any FP values. If so, put an FP_REG_KILL instruction before
571 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000572
Dale Johannesen684887e2007-09-24 22:52:39 +0000573 // Note that FP stack instructions are used in all modes for long double,
574 // so we always need to do this check.
575 // Also note that it's possible for an FP stack register to be live across
576 // an instruction that produces multiple basic blocks (SSE CMOV) so we
577 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000578
579 // Scan all of the machine instructions in these MBBs, checking for FP
580 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
581 MachineFunction::iterator MBBI = FirstMBB;
Chris Lattner04d64b22008-03-10 23:34:12 +0000582 MachineFunction::iterator EndMBB = BB; ++EndMBB;
583 for (; MBBI != EndMBB; ++MBBI) {
584 MachineBasicBlock *MBB = MBBI;
585
586 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
587 // before the return.
588 if (!MBB->empty()) {
589 MachineBasicBlock::iterator EndI = MBB->end();
590 --EndI;
591 if (EndI->getDesc().isReturn())
592 continue;
593 }
594
Dale Johannesen684887e2007-09-24 22:52:39 +0000595 bool ContainsFPCode = false;
Chris Lattner04d64b22008-03-10 23:34:12 +0000596 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000597 !ContainsFPCode && I != E; ++I) {
598 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
599 const TargetRegisterClass *clas;
600 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
601 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Chris Lattner04d64b22008-03-10 23:34:12 +0000602 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000603 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000604 X86::RFP32RegisterClass ||
605 clas == X86::RFP64RegisterClass ||
606 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 ContainsFPCode = true;
608 break;
609 }
610 }
611 }
612 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000613 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
614 // a copy of the input value in this block. In SSE mode, we only care about
615 // 80-bit values.
616 if (!ContainsFPCode) {
617 // Final check, check LLVM BB's that are successors to the LLVM BB
618 // corresponding to BB for FP PHI nodes.
619 const BasicBlock *LLVMBB = BB->getBasicBlock();
620 const PHINode *PN;
621 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
622 !ContainsFPCode && SI != E; ++SI) {
623 for (BasicBlock::const_iterator II = SI->begin();
624 (PN = dyn_cast<PHINode>(II)); ++II) {
625 if (PN->getType()==Type::X86_FP80Ty ||
626 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
627 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
628 ContainsFPCode = true;
629 break;
630 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000631 }
632 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000634 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
635 if (ContainsFPCode) {
Chris Lattner04d64b22008-03-10 23:34:12 +0000636 BuildMI(*MBB, MBBI->getFirstTerminator(),
Dale Johannesen684887e2007-09-24 22:52:39 +0000637 TM.getInstrInfo()->get(X86::FP_REG_KILL));
638 ++NumFPKill;
639 }
Chris Lattner04d64b22008-03-10 23:34:12 +0000640 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641}
642
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000643/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
644/// the main function.
645void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
646 MachineFrameInfo *MFI) {
647 const TargetInstrInfo *TII = TM.getInstrInfo();
648 if (Subtarget->isTargetCygMing())
649 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
650}
651
652void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
653 // If this is main, emit special code for main.
654 MachineBasicBlock *BB = MF.begin();
655 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
656 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
657}
658
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659/// MatchAddress - Add the specified node to the specified addressing mode,
660/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000661/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
663 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000664 // Limit recursion.
665 if (Depth > 5)
666 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667
668 // RIP relative addressing: %rip + 32-bit displacement!
669 if (AM.isRIPRel) {
670 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
671 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
672 if (isInt32(AM.Disp + Val)) {
673 AM.Disp += Val;
674 return false;
675 }
676 }
677 return true;
678 }
679
680 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000681 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682
683 switch (N.getOpcode()) {
684 default: break;
685 case ISD::Constant: {
686 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
687 if (isInt32(AM.Disp + Val)) {
688 AM.Disp += Val;
689 return false;
690 }
691 break;
692 }
693
694 case X86ISD::Wrapper: {
695 bool is64Bit = Subtarget->is64Bit();
696 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000697 // Also, base and index reg must be 0 in order to use rip as base.
698 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
699 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 break;
701 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
702 break;
703 // If value is available in a register both base and index components have
704 // been picked, we can't fit the result available in the register in the
705 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000706 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 SDOperand N0 = N.getOperand(0);
708 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
709 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000710 AM.GV = GV;
711 AM.Disp += G->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000712 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
713 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000714 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000716 AM.CP = CP->getConstVal();
717 AM.Align = CP->getAlignment();
718 AM.Disp += CP->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000719 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
720 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000721 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000723 AM.ES = S->getSymbol();
Evan Chenga54e14f2008-02-12 19:20:46 +0000724 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
725 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000726 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000728 AM.JT = J->getIndex();
Evan Chenga54e14f2008-02-12 19:20:46 +0000729 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
730 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000731 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 }
733 }
734 break;
735 }
736
737 case ISD::FrameIndex:
738 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
739 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
740 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
741 return false;
742 }
743 break;
744
745 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000746 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000747 break;
748
749 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
750 unsigned Val = CN->getValue();
751 if (Val == 1 || Val == 2 || Val == 3) {
752 AM.Scale = 1 << Val;
753 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754
Chris Lattner7f06edd2007-12-08 07:22:58 +0000755 // Okay, we know that we have a scale by now. However, if the scaled
756 // value is an add of something and a constant, we can fold the
757 // constant into the disp field here.
758 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
759 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
760 AM.IndexReg = ShVal.Val->getOperand(0);
761 ConstantSDNode *AddVal =
762 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
763 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
764 if (isInt32(Disp))
765 AM.Disp = Disp;
766 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000768 } else {
769 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000771 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 }
773 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000774 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775
Dan Gohman35b99222007-10-22 20:22:24 +0000776 case ISD::SMUL_LOHI:
777 case ISD::UMUL_LOHI:
778 // A mul_lohi where we need the low part can be folded as a plain multiply.
779 if (N.ResNo != 0) break;
780 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 case ISD::MUL:
782 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000783 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 AM.BaseType == X86ISelAddressMode::RegBase &&
785 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000786 AM.IndexReg.Val == 0 &&
787 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
789 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
790 AM.Scale = unsigned(CN->getValue())-1;
791
792 SDOperand MulVal = N.Val->getOperand(0);
793 SDOperand Reg;
794
795 // Okay, we know that we have a scale by now. However, if the scaled
796 // value is an add of something and a constant, we can fold the
797 // constant into the disp field here.
798 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
799 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
800 Reg = MulVal.Val->getOperand(0);
801 ConstantSDNode *AddVal =
802 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
803 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
804 if (isInt32(Disp))
805 AM.Disp = Disp;
806 else
807 Reg = N.Val->getOperand(0);
808 } else {
809 Reg = N.Val->getOperand(0);
810 }
811
812 AM.IndexReg = AM.Base.Reg = Reg;
813 return false;
814 }
815 }
816 break;
817
818 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000819 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 X86ISelAddressMode Backup = AM;
821 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
822 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
823 return false;
824 AM = Backup;
825 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
826 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
827 return false;
828 AM = Backup;
829 }
830 break;
831
832 case ISD::OR:
833 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000834 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000835
836 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
837 X86ISelAddressMode Backup = AM;
838 // Start with the LHS as an addr mode.
839 if (!MatchAddress(N.getOperand(0), AM, false) &&
840 // Address could not have picked a GV address for the displacement.
841 AM.GV == NULL &&
842 // On x86-64, the resultant disp must fit in 32-bits.
843 isInt32(AM.Disp + CN->getSignExtended()) &&
844 // Check to see if the LHS & C is zero.
Dan Gohman07961cd2008-02-25 21:11:39 +0000845 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
Chris Lattner7f06edd2007-12-08 07:22:58 +0000846 AM.Disp += CN->getValue();
847 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000849 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 }
851 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000852
853 case ISD::AND: {
854 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
855 // allows us to fold the shift into this addressing mode.
856 if (AlreadySelected) break;
857 SDOperand Shift = N.getOperand(0);
858 if (Shift.getOpcode() != ISD::SHL) break;
859
860 // Scale must not be used already.
861 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000862
863 // Not when RIP is used as the base.
864 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000865
866 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
867 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
868 if (!C1 || !C2) break;
869
870 // Not likely to be profitable if either the AND or SHIFT node has more
871 // than one use (unless all uses are for address computation). Besides,
872 // isel mechanism requires their node ids to be reused.
873 if (!N.hasOneUse() || !Shift.hasOneUse())
874 break;
875
876 // Verify that the shift amount is something we can fold.
877 unsigned ShiftCst = C1->getValue();
878 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
879 break;
880
881 // Get the new AND mask, this folds to a constant.
882 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
883 SDOperand(C2, 0), SDOperand(C1, 0));
884 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
885 Shift.getOperand(0), NewANDMask);
886 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
887 NewAND.Val->setNodeId(N.Val->getNodeId());
888
889 AM.Scale = 1 << ShiftCst;
890 AM.IndexReg = NewAND;
891 return false;
892 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 }
894
Dan Gohmana60c1b32007-08-13 20:03:06 +0000895 return MatchAddressBase(N, AM, isRoot, Depth);
896}
897
898/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
899/// specified addressing mode without any further recursion.
900bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
901 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 // Is the base register already occupied?
903 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
904 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000905 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 AM.IndexReg = N;
907 AM.Scale = 1;
908 return false;
909 }
910
911 // Otherwise, we cannot select it.
912 return true;
913 }
914
915 // Default, generate it as a register.
916 AM.BaseType = X86ISelAddressMode::RegBase;
917 AM.Base.Reg = N;
918 return false;
919}
920
921/// SelectAddr - returns true if it is able pattern match an addressing mode.
922/// It returns the operands which make up the maximal addressing mode it can
923/// match by reference.
924bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
925 SDOperand &Scale, SDOperand &Index,
926 SDOperand &Disp) {
927 X86ISelAddressMode AM;
928 if (MatchAddress(N, AM))
929 return false;
930
931 MVT::ValueType VT = N.getValueType();
932 if (AM.BaseType == X86ISelAddressMode::RegBase) {
933 if (!AM.Base.Reg.Val)
934 AM.Base.Reg = CurDAG->getRegister(0, VT);
935 }
936
937 if (!AM.IndexReg.Val)
938 AM.IndexReg = CurDAG->getRegister(0, VT);
939
940 getAddressOperands(AM, Base, Scale, Index, Disp);
941 return true;
942}
943
944/// isZeroNode - Returns true if Elt is a constant zero or a floating point
945/// constant +0.0.
946static inline bool isZeroNode(SDOperand Elt) {
947 return ((isa<ConstantSDNode>(Elt) &&
948 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
949 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000950 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951}
952
953
954/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
955/// match a load whose top elements are either undef or zeros. The load flavor
956/// is derived from the type of N, which is either v4f32 or v2f64.
957bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
958 SDOperand N, SDOperand &Base,
959 SDOperand &Scale, SDOperand &Index,
960 SDOperand &Disp, SDOperand &InChain,
961 SDOperand &OutChain) {
962 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
963 InChain = N.getOperand(0).getValue(1);
964 if (ISD::isNON_EXTLoad(InChain.Val) &&
965 InChain.getValue(0).hasOneUse() &&
966 N.hasOneUse() &&
967 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
968 LoadSDNode *LD = cast<LoadSDNode>(InChain);
969 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
970 return false;
971 OutChain = LD->getChain();
972 return true;
973 }
974 }
975
976 // Also handle the case where we explicitly require zeros in the top
977 // elements. This is a vector shuffle from the zero vector.
978 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000979 // Check to see if the top elements are all zeros (or bitcast of zeros).
980 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
982 N.getOperand(1).Val->hasOneUse() &&
983 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
984 N.getOperand(1).getOperand(0).hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
986 // from the LHS.
Chris Lattnere6aa3862007-11-25 00:24:49 +0000987 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 SDOperand ShufMask = N.getOperand(2);
989 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
990 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
991 if (C->getValue() == VecWidth) {
992 for (unsigned i = 1; i != VecWidth; ++i) {
993 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
994 // ok.
995 } else {
996 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
997 if (C->getValue() >= VecWidth) return false;
998 }
999 }
1000 }
1001
1002 // Okay, this is a zero extending load. Fold it.
1003 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
1004 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1005 return false;
1006 OutChain = LD->getChain();
1007 InChain = SDOperand(LD, 1);
1008 return true;
1009 }
1010 }
1011 return false;
1012}
1013
1014
1015/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1016/// mode it matches can be cost effectively emitted as an LEA instruction.
1017bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1018 SDOperand &Base, SDOperand &Scale,
1019 SDOperand &Index, SDOperand &Disp) {
1020 X86ISelAddressMode AM;
1021 if (MatchAddress(N, AM))
1022 return false;
1023
1024 MVT::ValueType VT = N.getValueType();
1025 unsigned Complexity = 0;
1026 if (AM.BaseType == X86ISelAddressMode::RegBase)
1027 if (AM.Base.Reg.Val)
1028 Complexity = 1;
1029 else
1030 AM.Base.Reg = CurDAG->getRegister(0, VT);
1031 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1032 Complexity = 4;
1033
1034 if (AM.IndexReg.Val)
1035 Complexity++;
1036 else
1037 AM.IndexReg = CurDAG->getRegister(0, VT);
1038
1039 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1040 // a simple shift.
1041 if (AM.Scale > 1)
1042 Complexity++;
1043
1044 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1045 // to a LEA. This is determined with some expermentation but is by no means
1046 // optimal (especially for code size consideration). LEA is nice because of
1047 // its three-address nature. Tweak the cost function again when we can run
1048 // convertToThreeAddress() at register allocation time.
1049 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1050 // For X86-64, we should always use lea to materialize RIP relative
1051 // addresses.
1052 if (Subtarget->is64Bit())
1053 Complexity = 4;
1054 else
1055 Complexity += 2;
1056 }
1057
1058 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1059 Complexity++;
1060
1061 if (Complexity > 2) {
1062 getAddressOperands(AM, Base, Scale, Index, Disp);
1063 return true;
1064 }
1065 return false;
1066}
1067
1068bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1069 SDOperand &Base, SDOperand &Scale,
1070 SDOperand &Index, SDOperand &Disp) {
1071 if (ISD::isNON_EXTLoad(N.Val) &&
1072 N.hasOneUse() &&
1073 CanBeFoldedBy(N.Val, P.Val, P.Val))
1074 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1075 return false;
1076}
1077
1078/// getGlobalBaseReg - Output the instructions required to put the
1079/// base address to use for accessing globals into a register.
1080///
1081SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1082 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1083 if (!GlobalBaseReg) {
1084 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001085 MachineFunction *MF = BB->getParent();
1086 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001088 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001089 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001092 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1093 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001094 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095
1096 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1097 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1098 if (TM.getRelocationModel() == Reloc::PIC_ &&
1099 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001100 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001101 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1102 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 } else {
1104 GlobalBaseReg = PC;
1105 }
1106
1107 }
1108 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1109}
1110
1111static SDNode *FindCallStartFromCall(SDNode *Node) {
1112 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1113 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1114 "Node doesn't have a token chain argument!");
1115 return FindCallStartFromCall(Node->getOperand(0).Val);
1116}
1117
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001118SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1119 SDOperand SRIdx;
1120 switch (VT) {
1121 case MVT::i8:
1122 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1123 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1124 if (!Subtarget->is64Bit()) {
1125 unsigned Opc;
1126 MVT::ValueType VT;
1127 switch (N0.getValueType()) {
1128 default: assert(0 && "Unknown truncate!");
1129 case MVT::i16:
1130 Opc = X86::MOV16to16_;
1131 VT = MVT::i16;
1132 break;
1133 case MVT::i32:
1134 Opc = X86::MOV32to32_;
1135 VT = MVT::i32;
1136 break;
1137 }
Evan Chenge1f39552007-10-12 07:55:53 +00001138 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1139 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1140 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001141 }
1142 break;
1143 case MVT::i16:
1144 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1145 break;
1146 case MVT::i32:
1147 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1148 break;
Evan Chenge1f39552007-10-12 07:55:53 +00001149 default: assert(0 && "Unknown truncate!"); break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001150 }
Evan Chenge1f39552007-10-12 07:55:53 +00001151 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001152}
1153
1154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1156 SDNode *Node = N.Val;
1157 MVT::ValueType NVT = Node->getValueType(0);
1158 unsigned Opc, MOpc;
1159 unsigned Opcode = Node->getOpcode();
1160
1161#ifndef NDEBUG
1162 DOUT << std::string(Indent, ' ') << "Selecting: ";
1163 DEBUG(Node->dump(CurDAG));
1164 DOUT << "\n";
1165 Indent += 2;
1166#endif
1167
1168 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1169#ifndef NDEBUG
1170 DOUT << std::string(Indent-2, ' ') << "== ";
1171 DEBUG(Node->dump(CurDAG));
1172 DOUT << "\n";
1173 Indent -= 2;
1174#endif
1175 return NULL; // Already selected.
1176 }
1177
1178 switch (Opcode) {
1179 default: break;
1180 case X86ISD::GlobalBaseReg:
1181 return getGlobalBaseReg();
1182
Chris Lattnerb56cc342008-03-11 03:23:40 +00001183 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1184 case X86ISD::RET_FLAG:
1185 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1186 if (Amt->getSignExtended() != 0) break;
1187
1188 // Match (X86retflag 0).
1189 SDOperand Chain = N.getOperand(0);
1190 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1191 == MVT::Flag;
1192 SmallVector<SDOperand, 8> Ops0;
1193 AddToISelQueue(Chain);
1194 SDOperand InFlag(0, 0);
1195 if (HasInFlag) {
1196 InFlag = N.getOperand(N.getNumOperands()-1);
1197 AddToISelQueue(InFlag);
1198 }
1199 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1200 ++i) {
1201 AddToISelQueue(N.getOperand(i));
1202 Ops0.push_back(N.getOperand(i));
1203 }
1204 Ops0.push_back(Chain);
1205 if (HasInFlag)
1206 Ops0.push_back(InFlag);
1207 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1208 &Ops0[0], Ops0.size());
1209 }
1210 break;
1211
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212 case ISD::ADD: {
1213 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1214 // code and is matched first so to prevent it from being turned into
1215 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001216 // In 64-bit small code size mode, use LEA to take advantage of
1217 // RIP-relative addressing.
1218 if (TM.getCodeModel() != CodeModel::Small)
1219 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 MVT::ValueType PtrVT = TLI.getPointerTy();
1221 SDOperand N0 = N.getOperand(0);
1222 SDOperand N1 = N.getOperand(1);
1223 if (N.Val->getValueType(0) == PtrVT &&
1224 N0.getOpcode() == X86ISD::Wrapper &&
1225 N1.getOpcode() == ISD::Constant) {
1226 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1227 SDOperand C(0, 0);
1228 // TODO: handle ExternalSymbolSDNode.
1229 if (GlobalAddressSDNode *G =
1230 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1231 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1232 G->getOffset() + Offset);
1233 } else if (ConstantPoolSDNode *CP =
1234 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1235 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1236 CP->getAlignment(),
1237 CP->getOffset()+Offset);
1238 }
1239
1240 if (C.Val) {
1241 if (Subtarget->is64Bit()) {
1242 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1243 CurDAG->getRegister(0, PtrVT), C };
1244 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1245 } else
1246 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1247 }
1248 }
1249
1250 // Other cases are handled by auto-generated code.
1251 break;
1252 }
1253
Dan Gohman5a199552007-10-08 18:33:35 +00001254 case ISD::SMUL_LOHI:
1255 case ISD::UMUL_LOHI: {
1256 SDOperand N0 = Node->getOperand(0);
1257 SDOperand N1 = Node->getOperand(1);
1258
Dan Gohman5a199552007-10-08 18:33:35 +00001259 bool isSigned = Opcode == ISD::SMUL_LOHI;
1260 if (!isSigned)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001261 switch (NVT) {
1262 default: assert(0 && "Unsupported VT!");
1263 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1264 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1265 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1266 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1267 }
1268 else
1269 switch (NVT) {
1270 default: assert(0 && "Unsupported VT!");
1271 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1272 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1273 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1274 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1275 }
1276
1277 unsigned LoReg, HiReg;
1278 switch (NVT) {
1279 default: assert(0 && "Unsupported VT!");
1280 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1281 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1282 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1283 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1284 }
1285
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001287 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001288 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 if (!foldedLoad) {
1290 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001291 if (foldedLoad)
1292 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 }
1294
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001296 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1297 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298
1299 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001300 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 AddToISelQueue(Tmp0);
1302 AddToISelQueue(Tmp1);
1303 AddToISelQueue(Tmp2);
1304 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001305 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 SDNode *CNode =
1307 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001309 // Update the chain.
1310 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 } else {
1312 AddToISelQueue(N1);
1313 InFlag =
1314 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1315 }
1316
Dan Gohman5a199552007-10-08 18:33:35 +00001317 // Copy the low half of the result, if it is needed.
1318 if (!N.getValue(0).use_empty()) {
1319 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1320 LoReg, NVT, InFlag);
1321 InFlag = Result.getValue(2);
1322 ReplaceUses(N.getValue(0), Result);
1323#ifndef NDEBUG
1324 DOUT << std::string(Indent-2, ' ') << "=> ";
1325 DEBUG(Result.Val->dump(CurDAG));
1326 DOUT << "\n";
1327#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001328 }
Dan Gohman5a199552007-10-08 18:33:35 +00001329 // Copy the high half of the result, if it is needed.
1330 if (!N.getValue(1).use_empty()) {
1331 SDOperand Result;
1332 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1333 // Prevent use of AH in a REX instruction by referencing AX instead.
1334 // Shift it down 8 bits.
1335 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1336 X86::AX, MVT::i16, InFlag);
1337 InFlag = Result.getValue(2);
1338 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1339 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1340 // Then truncate it down to i8.
1341 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1342 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1343 MVT::i8, Result, SRIdx), 0);
1344 } else {
1345 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1346 HiReg, NVT, InFlag);
1347 InFlag = Result.getValue(2);
1348 }
1349 ReplaceUses(N.getValue(1), Result);
1350#ifndef NDEBUG
1351 DOUT << std::string(Indent-2, ' ') << "=> ";
1352 DEBUG(Result.Val->dump(CurDAG));
1353 DOUT << "\n";
1354#endif
1355 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356
1357#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 Indent -= 2;
1359#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001360
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 return NULL;
1362 }
1363
Dan Gohman5a199552007-10-08 18:33:35 +00001364 case ISD::SDIVREM:
1365 case ISD::UDIVREM: {
1366 SDOperand N0 = Node->getOperand(0);
1367 SDOperand N1 = Node->getOperand(1);
1368
1369 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 if (!isSigned)
1371 switch (NVT) {
1372 default: assert(0 && "Unsupported VT!");
1373 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1374 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1375 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1376 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1377 }
1378 else
1379 switch (NVT) {
1380 default: assert(0 && "Unsupported VT!");
1381 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1382 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1383 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1384 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1385 }
1386
1387 unsigned LoReg, HiReg;
1388 unsigned ClrOpcode, SExtOpcode;
1389 switch (NVT) {
1390 default: assert(0 && "Unsupported VT!");
1391 case MVT::i8:
1392 LoReg = X86::AL; HiReg = X86::AH;
1393 ClrOpcode = 0;
1394 SExtOpcode = X86::CBW;
1395 break;
1396 case MVT::i16:
1397 LoReg = X86::AX; HiReg = X86::DX;
1398 ClrOpcode = X86::MOV16r0;
1399 SExtOpcode = X86::CWD;
1400 break;
1401 case MVT::i32:
1402 LoReg = X86::EAX; HiReg = X86::EDX;
1403 ClrOpcode = X86::MOV32r0;
1404 SExtOpcode = X86::CDQ;
1405 break;
1406 case MVT::i64:
1407 LoReg = X86::RAX; HiReg = X86::RDX;
1408 ClrOpcode = X86::MOV64r0;
1409 SExtOpcode = X86::CQO;
1410 break;
1411 }
1412
Dan Gohman5a199552007-10-08 18:33:35 +00001413 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1414 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1415
1416 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 if (NVT == MVT::i8 && !isSigned) {
1418 // Special case for div8, just use a move with zero extension to AX to
1419 // clear the upper 8 bits (AH).
1420 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1421 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1422 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1423 AddToISelQueue(N0.getOperand(0));
1424 AddToISelQueue(Tmp0);
1425 AddToISelQueue(Tmp1);
1426 AddToISelQueue(Tmp2);
1427 AddToISelQueue(Tmp3);
1428 Move =
1429 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1430 Ops, 5), 0);
1431 Chain = Move.getValue(1);
1432 ReplaceUses(N0.getValue(1), Chain);
1433 } else {
1434 AddToISelQueue(N0);
1435 Move =
1436 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1437 Chain = CurDAG->getEntryNode();
1438 }
Dan Gohman5a199552007-10-08 18:33:35 +00001439 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 InFlag = Chain.getValue(1);
1441 } else {
1442 AddToISelQueue(N0);
1443 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001444 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1445 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 if (isSigned) {
1447 // Sign extend the low part into the high part.
1448 InFlag =
1449 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1450 } else {
1451 // Zero out the high part, effectively zero extending the input.
1452 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001453 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1454 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 }
1456 }
1457
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 if (foldedLoad) {
1459 AddToISelQueue(N1.getOperand(0));
1460 AddToISelQueue(Tmp0);
1461 AddToISelQueue(Tmp1);
1462 AddToISelQueue(Tmp2);
1463 AddToISelQueue(Tmp3);
1464 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1465 SDNode *CNode =
1466 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001468 // Update the chain.
1469 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 } else {
1471 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 InFlag =
1473 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1474 }
1475
Dan Gohman242a5ba2007-09-25 18:23:27 +00001476 // Copy the division (low) result, if it is needed.
1477 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001478 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1479 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001480 InFlag = Result.getValue(2);
1481 ReplaceUses(N.getValue(0), Result);
1482#ifndef NDEBUG
1483 DOUT << std::string(Indent-2, ' ') << "=> ";
1484 DEBUG(Result.Val->dump(CurDAG));
1485 DOUT << "\n";
1486#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001487 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001488 // Copy the remainder (high) result, if it is needed.
1489 if (!N.getValue(1).use_empty()) {
1490 SDOperand Result;
1491 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1492 // Prevent use of AH in a REX instruction by referencing AX instead.
1493 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001494 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1495 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001496 InFlag = Result.getValue(2);
1497 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1498 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1499 // Then truncate it down to i8.
1500 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1501 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1502 MVT::i8, Result, SRIdx), 0);
1503 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001504 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1505 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001506 InFlag = Result.getValue(2);
1507 }
1508 ReplaceUses(N.getValue(1), Result);
1509#ifndef NDEBUG
1510 DOUT << std::string(Indent-2, ' ') << "=> ";
1511 DEBUG(Result.Val->dump(CurDAG));
1512 DOUT << "\n";
1513#endif
1514 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515
1516#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 Indent -= 2;
1518#endif
1519
1520 return NULL;
1521 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001522
1523 case ISD::ANY_EXTEND: {
Christopher Lamb76d72da2008-03-16 03:12:01 +00001524 // Check if the type extended to supports subregs.
1525 if (NVT == MVT::i8)
1526 break;
1527
Christopher Lamb422213d2007-08-10 22:22:41 +00001528 SDOperand N0 = Node->getOperand(0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001529 // Get the subregsiter index for the type to extend.
1530 MVT::ValueType N0VT = N0.getValueType();
1531 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1532 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1533 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1534
1535 // If we don't have a subreg Idx, let generated ISel have a try.
1536 if (Idx == 0)
1537 break;
1538
1539 // If we have an index, generate an insert_subreg into undef.
Christopher Lamb422213d2007-08-10 22:22:41 +00001540 AddToISelQueue(N0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001541 SDOperand Undef =
Evan Cheng55a2dd02008-04-03 07:45:18 +00001542 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001543 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1544 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
Evan Cheng55a2dd02008-04-03 07:45:18 +00001545 NVT, Undef, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001546
1547#ifndef NDEBUG
Christopher Lamb76d72da2008-03-16 03:12:01 +00001548 DOUT << std::string(Indent-2, ' ') << "=> ";
1549 DEBUG(ResNode->dump(CurDAG));
1550 DOUT << "\n";
1551 Indent -= 2;
Christopher Lamb422213d2007-08-10 22:22:41 +00001552#endif
Christopher Lamb76d72da2008-03-16 03:12:01 +00001553 return ResNode;
Christopher Lamb422213d2007-08-10 22:22:41 +00001554 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001555
1556 case ISD::SIGN_EXTEND_INREG: {
1557 SDOperand N0 = Node->getOperand(0);
1558 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001560 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1561 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001562 unsigned Opc = 0;
Christopher Lamb444336c2007-07-29 01:24:57 +00001563 switch (NVT) {
Christopher Lamb444336c2007-07-29 01:24:57 +00001564 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001565 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1566 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001567 break;
1568 case MVT::i32:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001569 switch (SVT) {
1570 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1571 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1572 default: assert(0 && "Unknown sign_extend_inreg!");
1573 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001574 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001575 case MVT::i64:
1576 switch (SVT) {
1577 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1578 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1579 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1580 default: assert(0 && "Unknown sign_extend_inreg!");
1581 }
1582 break;
1583 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001584 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001585
1586 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1587
1588#ifndef NDEBUG
1589 DOUT << std::string(Indent-2, ' ') << "=> ";
1590 DEBUG(TruncOp.Val->dump(CurDAG));
1591 DOUT << "\n";
1592 DOUT << std::string(Indent-2, ' ') << "=> ";
1593 DEBUG(ResNode->dump(CurDAG));
1594 DOUT << "\n";
1595 Indent -= 2;
1596#endif
1597 return ResNode;
1598 break;
1599 }
1600
1601 case ISD::TRUNCATE: {
1602 SDOperand Input = Node->getOperand(0);
1603 AddToISelQueue(Node->getOperand(0));
1604 SDNode *ResNode = getTruncate(Input, NVT);
1605
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606#ifndef NDEBUG
1607 DOUT << std::string(Indent-2, ' ') << "=> ";
1608 DEBUG(ResNode->dump(CurDAG));
1609 DOUT << "\n";
1610 Indent -= 2;
1611#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001612 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001613 break;
1614 }
1615 }
1616
1617 SDNode *ResNode = SelectCode(N);
1618
1619#ifndef NDEBUG
1620 DOUT << std::string(Indent-2, ' ') << "=> ";
1621 if (ResNode == NULL || ResNode == N.Val)
1622 DEBUG(N.Val->dump(CurDAG));
1623 else
1624 DEBUG(ResNode->dump(CurDAG));
1625 DOUT << "\n";
1626 Indent -= 2;
1627#endif
1628
1629 return ResNode;
1630}
1631
1632bool X86DAGToDAGISel::
1633SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1634 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1635 SDOperand Op0, Op1, Op2, Op3;
1636 switch (ConstraintCode) {
1637 case 'o': // offsetable ??
1638 case 'v': // not offsetable ??
1639 default: return true;
1640 case 'm': // memory
1641 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1642 return true;
1643 break;
1644 }
1645
1646 OutOps.push_back(Op0);
1647 OutOps.push_back(Op1);
1648 OutOps.push_back(Op2);
1649 OutOps.push_back(Op3);
1650 AddToISelQueue(Op0);
1651 AddToISelQueue(Op1);
1652 AddToISelQueue(Op2);
1653 AddToISelQueue(Op3);
1654 return false;
1655}
1656
1657/// createX86ISelDag - This pass converts a legalized DAG into a
1658/// X86-specific DAG, ready for instruction scheduling.
1659///
1660FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1661 return new X86DAGToDAGISel(TM, Fast);
1662}