blob: 1ca1e311449f43fc525867bf4a9e63af911db5f7 [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 Cheng656269e2008-04-25 08:22:20 +0000258 continue; // We are not looking for immediate use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 if (Use == Root) {
260 assert(Use->getOpcode() == ISD::STORE ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000261 Use->getOpcode() == X86ISD::CMP ||
262 Use->getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
263 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
264 Use->getOpcode() == ISD::INTRINSIC_VOID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 continue;
266 }
267 found = true;
268 break;
269 }
Evan Cheng656269e2008-04-25 08:22:20 +0000270
271 // Traverse up the operand chain.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
273 }
274}
275
276/// isNonImmUse - Start searching from Root up the DAG to check is Def can
277/// be reached. Return true if that's the case. However, ignore direct uses
278/// by ImmedUse (which would be U in the example illustrated in
279/// CanBeFoldedBy) and by Root (which can happen in the store case).
280/// FIXME: to be really generic, we should allow direct use by any node
281/// that is being folded. But realisticly since we only fold loads which
282/// have one non-chain use, we only need to watch out for load/op/store
283/// and load/op/cmp case where the root (store / cmp) may reach the load via
284/// its chain operand.
285static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
286 SDNode *Skip = NULL) {
Evan Cheng656269e2008-04-25 08:22:20 +0000287 SmallPtrSet<SDNode*, 16> Visited;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 bool found = false;
289 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
290 return found;
291}
292
293
Dan Gohmand6098272007-07-24 23:00:27 +0000294bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (FastISel) return false;
296
297 // If U use can somehow reach N through another path then U can't fold N or
298 // it will create a cycle. e.g. In the following diagram, U can reach N
299 // through X. If N is folded into into U, then X is both a predecessor and
300 // a successor of U.
301 //
302 // [ N ]
303 // ^ ^
304 // | |
305 // / \---
306 // / [X]
307 // | ^
308 // [U]--------|
309
310 if (isNonImmUse(Root, N, U))
311 return false;
312
313 // If U produces a flag, then it gets (even more) interesting. Since it
314 // would have been "glued" together with its flag use, we need to check if
315 // it might reach N:
316 //
317 // [ N ]
318 // ^ ^
319 // | |
320 // [U] \--
321 // ^ [TF]
322 // | ^
323 // | |
324 // \ /
325 // [FU]
326 //
327 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
328 // NU), then TF is a predecessor of FU and a successor of NU. But since
329 // NU and FU are flagged together, this effectively creates a cycle.
330 bool HasFlagUse = false;
331 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
332 while ((VT == MVT::Flag && !Root->use_empty())) {
333 SDNode *FU = findFlagUse(Root);
334 if (FU == NULL)
335 break;
336 else {
337 Root = FU;
338 HasFlagUse = true;
339 }
340 VT = Root->getValueType(Root->getNumValues()-1);
341 }
342
343 if (HasFlagUse)
344 return !isNonImmUse(Root, N, Root, U);
345 return true;
346}
347
348/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
349/// and move load below the TokenFactor. Replace store's chain operand with
350/// load's chain result.
351static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
352 SDOperand Store, SDOperand TF) {
353 std::vector<SDOperand> Ops;
354 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
355 if (Load.Val == TF.Val->getOperand(i).Val)
356 Ops.push_back(Load.Val->getOperand(0));
357 else
358 Ops.push_back(TF.Val->getOperand(i));
359 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
360 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
361 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
362 Store.getOperand(2), Store.getOperand(3));
363}
364
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000365/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
366/// This is only run if not in -fast mode (aka -O0).
367/// This allows the instruction selector to pick more read-modify-write
368/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369///
370/// [Load chain]
371/// ^
372/// |
373/// [Load]
374/// ^ ^
375/// | |
376/// / \-
377/// / |
378/// [TokenFactor] [Op]
379/// ^ ^
380/// | |
381/// \ /
382/// \ /
383/// [Store]
384///
385/// The fact the store's chain operand != load's chain will prevent the
386/// (store (op (load))) instruction from being selected. We can transform it to:
387///
388/// [Load chain]
389/// ^
390/// |
391/// [TokenFactor]
392/// ^
393/// |
394/// [Load]
395/// ^ ^
396/// | |
397/// | \-
398/// | |
399/// | [Op]
400/// | ^
401/// | |
402/// \ /
403/// \ /
404/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000405void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
407 E = DAG.allnodes_end(); I != E; ++I) {
408 if (!ISD::isNON_TRUNCStore(I))
409 continue;
410 SDOperand Chain = I->getOperand(0);
411 if (Chain.Val->getOpcode() != ISD::TokenFactor)
412 continue;
413
414 SDOperand N1 = I->getOperand(1);
415 SDOperand N2 = I->getOperand(2);
416 if (MVT::isFloatingPoint(N1.getValueType()) ||
417 MVT::isVector(N1.getValueType()) ||
418 !N1.hasOneUse())
419 continue;
420
421 bool RModW = false;
422 SDOperand Load;
423 unsigned Opcode = N1.Val->getOpcode();
424 switch (Opcode) {
425 case ISD::ADD:
426 case ISD::MUL:
427 case ISD::AND:
428 case ISD::OR:
429 case ISD::XOR:
430 case ISD::ADDC:
431 case ISD::ADDE: {
432 SDOperand N10 = N1.getOperand(0);
433 SDOperand N11 = N1.getOperand(1);
434 if (ISD::isNON_EXTLoad(N10.Val))
435 RModW = true;
436 else if (ISD::isNON_EXTLoad(N11.Val)) {
437 RModW = true;
438 std::swap(N10, N11);
439 }
Evan Cheng9123cfa2008-03-04 00:40:35 +0000440 RModW = RModW && N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 (N10.getOperand(1) == N2) &&
442 (N10.Val->getValueType(0) == N1.getValueType());
443 if (RModW)
444 Load = N10;
445 break;
446 }
447 case ISD::SUB:
448 case ISD::SHL:
449 case ISD::SRA:
450 case ISD::SRL:
451 case ISD::ROTL:
452 case ISD::ROTR:
453 case ISD::SUBC:
454 case ISD::SUBE:
455 case X86ISD::SHLD:
456 case X86ISD::SHRD: {
457 SDOperand N10 = N1.getOperand(0);
458 if (ISD::isNON_EXTLoad(N10.Val))
Evan Cheng9123cfa2008-03-04 00:40:35 +0000459 RModW = N10.Val->isOperandOf(Chain.Val) && N10.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 (N10.getOperand(1) == N2) &&
461 (N10.Val->getValueType(0) == N1.getValueType());
462 if (RModW)
463 Load = N10;
464 break;
465 }
466 }
467
468 if (RModW) {
469 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
470 ++NumLoadMoved;
471 }
472 }
473}
474
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000475
476/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
477/// nodes that target the FP stack to be store and load to the stack. This is a
478/// gross hack. We would like to simply mark these as being illegal, but when
479/// we do that, legalize produces these when it expands calls, then expands
480/// these in the same legalize pass. We would like dag combine to be able to
481/// hack on these between the call expansion and the node legalization. As such
482/// this pass basically does "really late" legalization of these inline with the
483/// X86 isel pass.
484void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
485 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
486 E = DAG.allnodes_end(); I != E; ) {
487 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
488 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
489 continue;
490
491 // If the source and destination are SSE registers, then this is a legal
492 // conversion that should not be lowered.
493 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
494 MVT::ValueType DstVT = N->getValueType(0);
495 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
496 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
497 if (SrcIsSSE && DstIsSSE)
498 continue;
499
Chris Lattner5d294e52008-03-09 07:05:32 +0000500 if (!SrcIsSSE && !DstIsSSE) {
501 // If this is an FPStack extension, it is a noop.
502 if (N->getOpcode() == ISD::FP_EXTEND)
503 continue;
504 // If this is a value-preserving FPStack truncation, it is a noop.
505 if (N->getConstantOperandVal(1))
506 continue;
507 }
508
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000509 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
510 // FPStack has extload and truncstore. SSE can fold direct loads into other
511 // operations. Based on this, decide what we want to do.
512 MVT::ValueType MemVT;
513 if (N->getOpcode() == ISD::FP_ROUND)
514 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
515 else
516 MemVT = SrcIsSSE ? SrcVT : DstVT;
517
518 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
519
520 // FIXME: optimize the case where the src/dest is a load or store?
521 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
522 MemTmp, NULL, 0, MemVT);
523 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
524 NULL, 0, MemVT);
525
526 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
527 // extload we created. This will cause general havok on the dag because
528 // anything below the conversion could be folded into other existing nodes.
529 // To avoid invalidating 'I', back it up to the convert node.
530 --I;
531 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
532
533 // Now that we did that, the node is dead. Increment the iterator to the
534 // next node to process, then delete N.
535 ++I;
536 DAG.DeleteNode(N);
537 }
538}
539
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
541/// when it has created a SelectionDAG for us to codegen.
542void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
543 DEBUG(BB->dump());
544 MachineFunction::iterator FirstMBB = BB;
545
546 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000547 PreprocessForRMW(DAG);
548
549 // FIXME: This should only happen when not -fast.
550 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551
552 // Codegen the basic block.
553#ifndef NDEBUG
554 DOUT << "===== Instruction selection begins:\n";
555 Indent = 0;
556#endif
557 DAG.setRoot(SelectRoot(DAG.getRoot()));
558#ifndef NDEBUG
559 DOUT << "===== Instruction selection ends:\n";
560#endif
561
562 DAG.RemoveDeadNodes();
563
Chris Lattner04d64b22008-03-10 23:34:12 +0000564 // Emit machine code to BB. This can change 'BB' to the last block being
565 // inserted into.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 ScheduleAndEmitDAG(DAG);
567
568 // If we are emitting FP stack code, scan the basic block to determine if this
569 // block defines any FP values. If so, put an FP_REG_KILL instruction before
570 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000571
Dale Johannesen684887e2007-09-24 22:52:39 +0000572 // Note that FP stack instructions are used in all modes for long double,
573 // so we always need to do this check.
574 // Also note that it's possible for an FP stack register to be live across
575 // an instruction that produces multiple basic blocks (SSE CMOV) so we
576 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000577
578 // Scan all of the machine instructions in these MBBs, checking for FP
579 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
580 MachineFunction::iterator MBBI = FirstMBB;
Chris Lattner04d64b22008-03-10 23:34:12 +0000581 MachineFunction::iterator EndMBB = BB; ++EndMBB;
582 for (; MBBI != EndMBB; ++MBBI) {
583 MachineBasicBlock *MBB = MBBI;
584
585 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
586 // before the return.
587 if (!MBB->empty()) {
588 MachineBasicBlock::iterator EndI = MBB->end();
589 --EndI;
590 if (EndI->getDesc().isReturn())
591 continue;
592 }
593
Dale Johannesen684887e2007-09-24 22:52:39 +0000594 bool ContainsFPCode = false;
Chris Lattner04d64b22008-03-10 23:34:12 +0000595 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000596 !ContainsFPCode && I != E; ++I) {
597 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
598 const TargetRegisterClass *clas;
599 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
600 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Chris Lattner04d64b22008-03-10 23:34:12 +0000601 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000602 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000603 X86::RFP32RegisterClass ||
604 clas == X86::RFP64RegisterClass ||
605 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 ContainsFPCode = true;
607 break;
608 }
609 }
610 }
611 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000612 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
613 // a copy of the input value in this block. In SSE mode, we only care about
614 // 80-bit values.
615 if (!ContainsFPCode) {
616 // Final check, check LLVM BB's that are successors to the LLVM BB
617 // corresponding to BB for FP PHI nodes.
618 const BasicBlock *LLVMBB = BB->getBasicBlock();
619 const PHINode *PN;
620 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
621 !ContainsFPCode && SI != E; ++SI) {
622 for (BasicBlock::const_iterator II = SI->begin();
623 (PN = dyn_cast<PHINode>(II)); ++II) {
624 if (PN->getType()==Type::X86_FP80Ty ||
625 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
626 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
627 ContainsFPCode = true;
628 break;
629 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000630 }
631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000633 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
634 if (ContainsFPCode) {
Chris Lattner04d64b22008-03-10 23:34:12 +0000635 BuildMI(*MBB, MBBI->getFirstTerminator(),
Dale Johannesen684887e2007-09-24 22:52:39 +0000636 TM.getInstrInfo()->get(X86::FP_REG_KILL));
637 ++NumFPKill;
638 }
Chris Lattner04d64b22008-03-10 23:34:12 +0000639 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640}
641
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000642/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
643/// the main function.
644void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
645 MachineFrameInfo *MFI) {
646 const TargetInstrInfo *TII = TM.getInstrInfo();
647 if (Subtarget->isTargetCygMing())
648 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
649}
650
651void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
652 // If this is main, emit special code for main.
653 MachineBasicBlock *BB = MF.begin();
654 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
655 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
656}
657
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658/// MatchAddress - Add the specified node to the specified addressing mode,
659/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000660/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
662 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000663 // Limit recursion.
664 if (Depth > 5)
665 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666
667 // RIP relative addressing: %rip + 32-bit displacement!
668 if (AM.isRIPRel) {
669 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
670 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
671 if (isInt32(AM.Disp + Val)) {
672 AM.Disp += Val;
673 return false;
674 }
675 }
676 return true;
677 }
678
679 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000680 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681
682 switch (N.getOpcode()) {
683 default: break;
684 case ISD::Constant: {
685 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
686 if (isInt32(AM.Disp + Val)) {
687 AM.Disp += Val;
688 return false;
689 }
690 break;
691 }
692
693 case X86ISD::Wrapper: {
694 bool is64Bit = Subtarget->is64Bit();
695 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000696 // Also, base and index reg must be 0 in order to use rip as base.
697 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
698 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 break;
700 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
701 break;
702 // If value is available in a register both base and index components have
703 // been picked, we can't fit the result available in the register in the
704 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000705 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 SDOperand N0 = N.getOperand(0);
707 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
708 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000709 AM.GV = GV;
710 AM.Disp += G->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000711 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
712 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000713 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000715 AM.CP = CP->getConstVal();
716 AM.Align = CP->getAlignment();
717 AM.Disp += CP->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000718 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
719 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000720 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000722 AM.ES = S->getSymbol();
Evan Chenga54e14f2008-02-12 19:20:46 +0000723 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
724 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000725 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000727 AM.JT = J->getIndex();
Evan Chenga54e14f2008-02-12 19:20:46 +0000728 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
729 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000730 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731 }
732 }
733 break;
734 }
735
736 case ISD::FrameIndex:
737 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
738 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
739 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
740 return false;
741 }
742 break;
743
744 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000745 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000746 break;
747
748 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
749 unsigned Val = CN->getValue();
750 if (Val == 1 || Val == 2 || Val == 3) {
751 AM.Scale = 1 << Val;
752 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753
Chris Lattner7f06edd2007-12-08 07:22:58 +0000754 // Okay, we know that we have a scale by now. However, if the scaled
755 // value is an add of something and a constant, we can fold the
756 // constant into the disp field here.
757 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
758 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
759 AM.IndexReg = ShVal.Val->getOperand(0);
760 ConstantSDNode *AddVal =
761 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
762 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
763 if (isInt32(Disp))
764 AM.Disp = Disp;
765 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000767 } else {
768 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000770 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 }
772 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774
Dan Gohman35b99222007-10-22 20:22:24 +0000775 case ISD::SMUL_LOHI:
776 case ISD::UMUL_LOHI:
777 // A mul_lohi where we need the low part can be folded as a plain multiply.
778 if (N.ResNo != 0) break;
779 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 case ISD::MUL:
781 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000782 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 AM.BaseType == X86ISelAddressMode::RegBase &&
784 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000785 AM.IndexReg.Val == 0 &&
786 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
788 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
789 AM.Scale = unsigned(CN->getValue())-1;
790
791 SDOperand MulVal = N.Val->getOperand(0);
792 SDOperand Reg;
793
794 // Okay, we know that we have a scale by now. However, if the scaled
795 // value is an add of something and a constant, we can fold the
796 // constant into the disp field here.
797 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
798 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
799 Reg = MulVal.Val->getOperand(0);
800 ConstantSDNode *AddVal =
801 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
802 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
803 if (isInt32(Disp))
804 AM.Disp = Disp;
805 else
806 Reg = N.Val->getOperand(0);
807 } else {
808 Reg = N.Val->getOperand(0);
809 }
810
811 AM.IndexReg = AM.Base.Reg = Reg;
812 return false;
813 }
814 }
815 break;
816
817 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000818 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 X86ISelAddressMode Backup = AM;
820 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
821 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
822 return false;
823 AM = Backup;
824 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
825 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
826 return false;
827 AM = Backup;
828 }
829 break;
830
831 case ISD::OR:
832 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000833 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000834
835 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
836 X86ISelAddressMode Backup = AM;
837 // Start with the LHS as an addr mode.
838 if (!MatchAddress(N.getOperand(0), AM, false) &&
839 // Address could not have picked a GV address for the displacement.
840 AM.GV == NULL &&
841 // On x86-64, the resultant disp must fit in 32-bits.
842 isInt32(AM.Disp + CN->getSignExtended()) &&
843 // Check to see if the LHS & C is zero.
Dan Gohman07961cd2008-02-25 21:11:39 +0000844 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
Chris Lattner7f06edd2007-12-08 07:22:58 +0000845 AM.Disp += CN->getValue();
846 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000848 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
850 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000851
852 case ISD::AND: {
853 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
854 // allows us to fold the shift into this addressing mode.
855 if (AlreadySelected) break;
856 SDOperand Shift = N.getOperand(0);
857 if (Shift.getOpcode() != ISD::SHL) break;
858
859 // Scale must not be used already.
860 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000861
862 // Not when RIP is used as the base.
863 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000864
865 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
866 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
867 if (!C1 || !C2) break;
868
869 // Not likely to be profitable if either the AND or SHIFT node has more
870 // than one use (unless all uses are for address computation). Besides,
871 // isel mechanism requires their node ids to be reused.
872 if (!N.hasOneUse() || !Shift.hasOneUse())
873 break;
874
875 // Verify that the shift amount is something we can fold.
876 unsigned ShiftCst = C1->getValue();
877 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
878 break;
879
880 // Get the new AND mask, this folds to a constant.
881 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
882 SDOperand(C2, 0), SDOperand(C1, 0));
883 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
884 Shift.getOperand(0), NewANDMask);
885 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
886 NewAND.Val->setNodeId(N.Val->getNodeId());
887
888 AM.Scale = 1 << ShiftCst;
889 AM.IndexReg = NewAND;
890 return false;
891 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 }
893
Dan Gohmana60c1b32007-08-13 20:03:06 +0000894 return MatchAddressBase(N, AM, isRoot, Depth);
895}
896
897/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
898/// specified addressing mode without any further recursion.
899bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
900 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 // Is the base register already occupied?
902 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
903 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000904 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 AM.IndexReg = N;
906 AM.Scale = 1;
907 return false;
908 }
909
910 // Otherwise, we cannot select it.
911 return true;
912 }
913
914 // Default, generate it as a register.
915 AM.BaseType = X86ISelAddressMode::RegBase;
916 AM.Base.Reg = N;
917 return false;
918}
919
920/// SelectAddr - returns true if it is able pattern match an addressing mode.
921/// It returns the operands which make up the maximal addressing mode it can
922/// match by reference.
923bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
924 SDOperand &Scale, SDOperand &Index,
925 SDOperand &Disp) {
926 X86ISelAddressMode AM;
927 if (MatchAddress(N, AM))
928 return false;
929
930 MVT::ValueType VT = N.getValueType();
931 if (AM.BaseType == X86ISelAddressMode::RegBase) {
932 if (!AM.Base.Reg.Val)
933 AM.Base.Reg = CurDAG->getRegister(0, VT);
934 }
935
936 if (!AM.IndexReg.Val)
937 AM.IndexReg = CurDAG->getRegister(0, VT);
938
939 getAddressOperands(AM, Base, Scale, Index, Disp);
940 return true;
941}
942
943/// isZeroNode - Returns true if Elt is a constant zero or a floating point
944/// constant +0.0.
945static inline bool isZeroNode(SDOperand Elt) {
946 return ((isa<ConstantSDNode>(Elt) &&
947 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
948 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000949 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950}
951
952
953/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
954/// match a load whose top elements are either undef or zeros. The load flavor
955/// is derived from the type of N, which is either v4f32 or v2f64.
956bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
957 SDOperand N, SDOperand &Base,
958 SDOperand &Scale, SDOperand &Index,
959 SDOperand &Disp, SDOperand &InChain,
960 SDOperand &OutChain) {
961 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
962 InChain = N.getOperand(0).getValue(1);
963 if (ISD::isNON_EXTLoad(InChain.Val) &&
964 InChain.getValue(0).hasOneUse() &&
965 N.hasOneUse() &&
966 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
967 LoadSDNode *LD = cast<LoadSDNode>(InChain);
968 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
969 return false;
970 OutChain = LD->getChain();
971 return true;
972 }
973 }
974
975 // Also handle the case where we explicitly require zeros in the top
976 // elements. This is a vector shuffle from the zero vector.
977 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000978 // Check to see if the top elements are all zeros (or bitcast of zeros).
979 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
981 N.getOperand(1).Val->hasOneUse() &&
982 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
983 N.getOperand(1).getOperand(0).hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
985 // from the LHS.
Chris Lattnere6aa3862007-11-25 00:24:49 +0000986 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 SDOperand ShufMask = N.getOperand(2);
988 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
990 if (C->getValue() == VecWidth) {
991 for (unsigned i = 1; i != VecWidth; ++i) {
992 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
993 // ok.
994 } else {
995 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
996 if (C->getValue() >= VecWidth) return false;
997 }
998 }
999 }
1000
1001 // Okay, this is a zero extending load. Fold it.
1002 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
1003 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1004 return false;
1005 OutChain = LD->getChain();
1006 InChain = SDOperand(LD, 1);
1007 return true;
1008 }
1009 }
1010 return false;
1011}
1012
1013
1014/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1015/// mode it matches can be cost effectively emitted as an LEA instruction.
1016bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1017 SDOperand &Base, SDOperand &Scale,
1018 SDOperand &Index, SDOperand &Disp) {
1019 X86ISelAddressMode AM;
1020 if (MatchAddress(N, AM))
1021 return false;
1022
1023 MVT::ValueType VT = N.getValueType();
1024 unsigned Complexity = 0;
1025 if (AM.BaseType == X86ISelAddressMode::RegBase)
1026 if (AM.Base.Reg.Val)
1027 Complexity = 1;
1028 else
1029 AM.Base.Reg = CurDAG->getRegister(0, VT);
1030 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1031 Complexity = 4;
1032
1033 if (AM.IndexReg.Val)
1034 Complexity++;
1035 else
1036 AM.IndexReg = CurDAG->getRegister(0, VT);
1037
1038 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1039 // a simple shift.
1040 if (AM.Scale > 1)
1041 Complexity++;
1042
1043 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1044 // to a LEA. This is determined with some expermentation but is by no means
1045 // optimal (especially for code size consideration). LEA is nice because of
1046 // its three-address nature. Tweak the cost function again when we can run
1047 // convertToThreeAddress() at register allocation time.
1048 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1049 // For X86-64, we should always use lea to materialize RIP relative
1050 // addresses.
1051 if (Subtarget->is64Bit())
1052 Complexity = 4;
1053 else
1054 Complexity += 2;
1055 }
1056
1057 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1058 Complexity++;
1059
1060 if (Complexity > 2) {
1061 getAddressOperands(AM, Base, Scale, Index, Disp);
1062 return true;
1063 }
1064 return false;
1065}
1066
1067bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1068 SDOperand &Base, SDOperand &Scale,
1069 SDOperand &Index, SDOperand &Disp) {
1070 if (ISD::isNON_EXTLoad(N.Val) &&
1071 N.hasOneUse() &&
1072 CanBeFoldedBy(N.Val, P.Val, P.Val))
1073 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1074 return false;
1075}
1076
1077/// getGlobalBaseReg - Output the instructions required to put the
1078/// base address to use for accessing globals into a register.
1079///
1080SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1081 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1082 if (!GlobalBaseReg) {
1083 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001084 MachineFunction *MF = BB->getParent();
1085 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001087 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001088 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089
1090 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001091 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1092 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001093 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094
1095 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1096 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1097 if (TM.getRelocationModel() == Reloc::PIC_ &&
1098 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001099 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001100 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1101 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 } else {
1103 GlobalBaseReg = PC;
1104 }
1105
1106 }
1107 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1108}
1109
1110static SDNode *FindCallStartFromCall(SDNode *Node) {
1111 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1112 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1113 "Node doesn't have a token chain argument!");
1114 return FindCallStartFromCall(Node->getOperand(0).Val);
1115}
1116
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001117SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1118 SDOperand SRIdx;
1119 switch (VT) {
1120 case MVT::i8:
1121 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1122 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1123 if (!Subtarget->is64Bit()) {
1124 unsigned Opc;
1125 MVT::ValueType VT;
1126 switch (N0.getValueType()) {
1127 default: assert(0 && "Unknown truncate!");
1128 case MVT::i16:
1129 Opc = X86::MOV16to16_;
1130 VT = MVT::i16;
1131 break;
1132 case MVT::i32:
1133 Opc = X86::MOV32to32_;
1134 VT = MVT::i32;
1135 break;
1136 }
Evan Chenge1f39552007-10-12 07:55:53 +00001137 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1138 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1139 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001140 }
1141 break;
1142 case MVT::i16:
1143 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1144 break;
1145 case MVT::i32:
1146 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1147 break;
Evan Chenge1f39552007-10-12 07:55:53 +00001148 default: assert(0 && "Unknown truncate!"); break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001149 }
Evan Chenge1f39552007-10-12 07:55:53 +00001150 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001151}
1152
1153
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1155 SDNode *Node = N.Val;
1156 MVT::ValueType NVT = Node->getValueType(0);
1157 unsigned Opc, MOpc;
1158 unsigned Opcode = Node->getOpcode();
1159
1160#ifndef NDEBUG
1161 DOUT << std::string(Indent, ' ') << "Selecting: ";
1162 DEBUG(Node->dump(CurDAG));
1163 DOUT << "\n";
1164 Indent += 2;
1165#endif
1166
1167 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1168#ifndef NDEBUG
1169 DOUT << std::string(Indent-2, ' ') << "== ";
1170 DEBUG(Node->dump(CurDAG));
1171 DOUT << "\n";
1172 Indent -= 2;
1173#endif
1174 return NULL; // Already selected.
1175 }
1176
1177 switch (Opcode) {
1178 default: break;
1179 case X86ISD::GlobalBaseReg:
1180 return getGlobalBaseReg();
1181
Chris Lattnerb56cc342008-03-11 03:23:40 +00001182 // FIXME: This is a workaround for a tblgen problem: rdar://5791600
1183 case X86ISD::RET_FLAG:
1184 if (ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1185 if (Amt->getSignExtended() != 0) break;
1186
1187 // Match (X86retflag 0).
1188 SDOperand Chain = N.getOperand(0);
1189 bool HasInFlag = N.getOperand(N.getNumOperands()-1).getValueType()
1190 == MVT::Flag;
1191 SmallVector<SDOperand, 8> Ops0;
1192 AddToISelQueue(Chain);
1193 SDOperand InFlag(0, 0);
1194 if (HasInFlag) {
1195 InFlag = N.getOperand(N.getNumOperands()-1);
1196 AddToISelQueue(InFlag);
1197 }
1198 for (unsigned i = 2, e = N.getNumOperands()-(HasInFlag?1:0); i != e;
1199 ++i) {
1200 AddToISelQueue(N.getOperand(i));
1201 Ops0.push_back(N.getOperand(i));
1202 }
1203 Ops0.push_back(Chain);
1204 if (HasInFlag)
1205 Ops0.push_back(InFlag);
1206 return CurDAG->getTargetNode(X86::RET, MVT::Other,
1207 &Ops0[0], Ops0.size());
1208 }
1209 break;
1210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 case ISD::ADD: {
1212 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1213 // code and is matched first so to prevent it from being turned into
1214 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001215 // In 64-bit small code size mode, use LEA to take advantage of
1216 // RIP-relative addressing.
1217 if (TM.getCodeModel() != CodeModel::Small)
1218 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 MVT::ValueType PtrVT = TLI.getPointerTy();
1220 SDOperand N0 = N.getOperand(0);
1221 SDOperand N1 = N.getOperand(1);
1222 if (N.Val->getValueType(0) == PtrVT &&
1223 N0.getOpcode() == X86ISD::Wrapper &&
1224 N1.getOpcode() == ISD::Constant) {
1225 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1226 SDOperand C(0, 0);
1227 // TODO: handle ExternalSymbolSDNode.
1228 if (GlobalAddressSDNode *G =
1229 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1230 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1231 G->getOffset() + Offset);
1232 } else if (ConstantPoolSDNode *CP =
1233 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1234 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1235 CP->getAlignment(),
1236 CP->getOffset()+Offset);
1237 }
1238
1239 if (C.Val) {
1240 if (Subtarget->is64Bit()) {
1241 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1242 CurDAG->getRegister(0, PtrVT), C };
1243 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1244 } else
1245 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1246 }
1247 }
1248
1249 // Other cases are handled by auto-generated code.
1250 break;
1251 }
1252
Dan Gohman5a199552007-10-08 18:33:35 +00001253 case ISD::SMUL_LOHI:
1254 case ISD::UMUL_LOHI: {
1255 SDOperand N0 = Node->getOperand(0);
1256 SDOperand N1 = Node->getOperand(1);
1257
Dan Gohman5a199552007-10-08 18:33:35 +00001258 bool isSigned = Opcode == ISD::SMUL_LOHI;
1259 if (!isSigned)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 switch (NVT) {
1261 default: assert(0 && "Unsupported VT!");
1262 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1263 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1264 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1265 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1266 }
1267 else
1268 switch (NVT) {
1269 default: assert(0 && "Unsupported VT!");
1270 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1271 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1272 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1273 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1274 }
1275
1276 unsigned LoReg, HiReg;
1277 switch (NVT) {
1278 default: assert(0 && "Unsupported VT!");
1279 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1280 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1281 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1282 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1283 }
1284
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001286 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001287 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 if (!foldedLoad) {
1289 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001290 if (foldedLoad)
1291 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 }
1293
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001295 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1296 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297
1298 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001299 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 AddToISelQueue(Tmp0);
1301 AddToISelQueue(Tmp1);
1302 AddToISelQueue(Tmp2);
1303 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001304 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 SDNode *CNode =
1306 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001308 // Update the chain.
1309 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 } else {
1311 AddToISelQueue(N1);
1312 InFlag =
1313 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1314 }
1315
Dan Gohman5a199552007-10-08 18:33:35 +00001316 // Copy the low half of the result, if it is needed.
1317 if (!N.getValue(0).use_empty()) {
1318 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1319 LoReg, NVT, InFlag);
1320 InFlag = Result.getValue(2);
1321 ReplaceUses(N.getValue(0), Result);
1322#ifndef NDEBUG
1323 DOUT << std::string(Indent-2, ' ') << "=> ";
1324 DEBUG(Result.Val->dump(CurDAG));
1325 DOUT << "\n";
1326#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001327 }
Dan Gohman5a199552007-10-08 18:33:35 +00001328 // Copy the high half of the result, if it is needed.
1329 if (!N.getValue(1).use_empty()) {
1330 SDOperand Result;
1331 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1332 // Prevent use of AH in a REX instruction by referencing AX instead.
1333 // Shift it down 8 bits.
1334 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1335 X86::AX, MVT::i16, InFlag);
1336 InFlag = Result.getValue(2);
1337 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1338 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1339 // Then truncate it down to i8.
1340 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1341 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1342 MVT::i8, Result, SRIdx), 0);
1343 } else {
1344 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1345 HiReg, NVT, InFlag);
1346 InFlag = Result.getValue(2);
1347 }
1348 ReplaceUses(N.getValue(1), Result);
1349#ifndef NDEBUG
1350 DOUT << std::string(Indent-2, ' ') << "=> ";
1351 DEBUG(Result.Val->dump(CurDAG));
1352 DOUT << "\n";
1353#endif
1354 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355
1356#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 Indent -= 2;
1358#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001359
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 return NULL;
1361 }
1362
Dan Gohman5a199552007-10-08 18:33:35 +00001363 case ISD::SDIVREM:
1364 case ISD::UDIVREM: {
1365 SDOperand N0 = Node->getOperand(0);
1366 SDOperand N1 = Node->getOperand(1);
1367
1368 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 if (!isSigned)
1370 switch (NVT) {
1371 default: assert(0 && "Unsupported VT!");
1372 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1373 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1374 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1375 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1376 }
1377 else
1378 switch (NVT) {
1379 default: assert(0 && "Unsupported VT!");
1380 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1381 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1382 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1383 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1384 }
1385
1386 unsigned LoReg, HiReg;
1387 unsigned ClrOpcode, SExtOpcode;
1388 switch (NVT) {
1389 default: assert(0 && "Unsupported VT!");
1390 case MVT::i8:
1391 LoReg = X86::AL; HiReg = X86::AH;
1392 ClrOpcode = 0;
1393 SExtOpcode = X86::CBW;
1394 break;
1395 case MVT::i16:
1396 LoReg = X86::AX; HiReg = X86::DX;
1397 ClrOpcode = X86::MOV16r0;
1398 SExtOpcode = X86::CWD;
1399 break;
1400 case MVT::i32:
1401 LoReg = X86::EAX; HiReg = X86::EDX;
1402 ClrOpcode = X86::MOV32r0;
1403 SExtOpcode = X86::CDQ;
1404 break;
1405 case MVT::i64:
1406 LoReg = X86::RAX; HiReg = X86::RDX;
1407 ClrOpcode = X86::MOV64r0;
1408 SExtOpcode = X86::CQO;
1409 break;
1410 }
1411
Dan Gohman5a199552007-10-08 18:33:35 +00001412 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1413 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1414
1415 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 if (NVT == MVT::i8 && !isSigned) {
1417 // Special case for div8, just use a move with zero extension to AX to
1418 // clear the upper 8 bits (AH).
1419 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1420 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1421 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1422 AddToISelQueue(N0.getOperand(0));
1423 AddToISelQueue(Tmp0);
1424 AddToISelQueue(Tmp1);
1425 AddToISelQueue(Tmp2);
1426 AddToISelQueue(Tmp3);
1427 Move =
1428 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1429 Ops, 5), 0);
1430 Chain = Move.getValue(1);
1431 ReplaceUses(N0.getValue(1), Chain);
1432 } else {
1433 AddToISelQueue(N0);
1434 Move =
1435 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1436 Chain = CurDAG->getEntryNode();
1437 }
Dan Gohman5a199552007-10-08 18:33:35 +00001438 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 InFlag = Chain.getValue(1);
1440 } else {
1441 AddToISelQueue(N0);
1442 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001443 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1444 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 if (isSigned) {
1446 // Sign extend the low part into the high part.
1447 InFlag =
1448 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1449 } else {
1450 // Zero out the high part, effectively zero extending the input.
1451 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001452 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1453 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 }
1455 }
1456
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 if (foldedLoad) {
1458 AddToISelQueue(N1.getOperand(0));
1459 AddToISelQueue(Tmp0);
1460 AddToISelQueue(Tmp1);
1461 AddToISelQueue(Tmp2);
1462 AddToISelQueue(Tmp3);
1463 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1464 SDNode *CNode =
1465 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001467 // Update the chain.
1468 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 } else {
1470 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 InFlag =
1472 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1473 }
1474
Dan Gohman242a5ba2007-09-25 18:23:27 +00001475 // Copy the division (low) result, if it is needed.
1476 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001477 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1478 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001479 InFlag = Result.getValue(2);
1480 ReplaceUses(N.getValue(0), Result);
1481#ifndef NDEBUG
1482 DOUT << std::string(Indent-2, ' ') << "=> ";
1483 DEBUG(Result.Val->dump(CurDAG));
1484 DOUT << "\n";
1485#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001486 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001487 // Copy the remainder (high) result, if it is needed.
1488 if (!N.getValue(1).use_empty()) {
1489 SDOperand Result;
1490 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1491 // Prevent use of AH in a REX instruction by referencing AX instead.
1492 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001493 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1494 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001495 InFlag = Result.getValue(2);
1496 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1497 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1498 // Then truncate it down to i8.
1499 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1500 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1501 MVT::i8, Result, SRIdx), 0);
1502 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001503 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1504 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001505 InFlag = Result.getValue(2);
1506 }
1507 ReplaceUses(N.getValue(1), Result);
1508#ifndef NDEBUG
1509 DOUT << std::string(Indent-2, ' ') << "=> ";
1510 DEBUG(Result.Val->dump(CurDAG));
1511 DOUT << "\n";
1512#endif
1513 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514
1515#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 Indent -= 2;
1517#endif
1518
1519 return NULL;
1520 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001521
1522 case ISD::ANY_EXTEND: {
Christopher Lamb76d72da2008-03-16 03:12:01 +00001523 // Check if the type extended to supports subregs.
1524 if (NVT == MVT::i8)
1525 break;
1526
Christopher Lamb422213d2007-08-10 22:22:41 +00001527 SDOperand N0 = Node->getOperand(0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001528 // Get the subregsiter index for the type to extend.
1529 MVT::ValueType N0VT = N0.getValueType();
1530 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1531 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1532 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1533
1534 // If we don't have a subreg Idx, let generated ISel have a try.
1535 if (Idx == 0)
1536 break;
1537
1538 // If we have an index, generate an insert_subreg into undef.
Christopher Lamb422213d2007-08-10 22:22:41 +00001539 AddToISelQueue(N0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001540 SDOperand Undef =
Evan Cheng55a2dd02008-04-03 07:45:18 +00001541 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001542 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1543 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
Evan Cheng55a2dd02008-04-03 07:45:18 +00001544 NVT, Undef, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001545
1546#ifndef NDEBUG
Christopher Lamb76d72da2008-03-16 03:12:01 +00001547 DOUT << std::string(Indent-2, ' ') << "=> ";
1548 DEBUG(ResNode->dump(CurDAG));
1549 DOUT << "\n";
1550 Indent -= 2;
Christopher Lamb422213d2007-08-10 22:22:41 +00001551#endif
Christopher Lamb76d72da2008-03-16 03:12:01 +00001552 return ResNode;
Christopher Lamb422213d2007-08-10 22:22:41 +00001553 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001554
1555 case ISD::SIGN_EXTEND_INREG: {
1556 SDOperand N0 = Node->getOperand(0);
1557 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001559 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1560 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001561 unsigned Opc = 0;
Christopher Lamb444336c2007-07-29 01:24:57 +00001562 switch (NVT) {
Christopher Lamb444336c2007-07-29 01:24:57 +00001563 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001564 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1565 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001566 break;
1567 case MVT::i32:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001568 switch (SVT) {
1569 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1570 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1571 default: assert(0 && "Unknown sign_extend_inreg!");
1572 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001573 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001574 case MVT::i64:
1575 switch (SVT) {
1576 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1577 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1578 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1579 default: assert(0 && "Unknown sign_extend_inreg!");
1580 }
1581 break;
1582 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001583 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001584
1585 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1586
1587#ifndef NDEBUG
1588 DOUT << std::string(Indent-2, ' ') << "=> ";
1589 DEBUG(TruncOp.Val->dump(CurDAG));
1590 DOUT << "\n";
1591 DOUT << std::string(Indent-2, ' ') << "=> ";
1592 DEBUG(ResNode->dump(CurDAG));
1593 DOUT << "\n";
1594 Indent -= 2;
1595#endif
1596 return ResNode;
1597 break;
1598 }
1599
1600 case ISD::TRUNCATE: {
1601 SDOperand Input = Node->getOperand(0);
1602 AddToISelQueue(Node->getOperand(0));
1603 SDNode *ResNode = getTruncate(Input, NVT);
1604
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605#ifndef NDEBUG
1606 DOUT << std::string(Indent-2, ' ') << "=> ";
1607 DEBUG(ResNode->dump(CurDAG));
1608 DOUT << "\n";
1609 Indent -= 2;
1610#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001611 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612 break;
1613 }
1614 }
1615
1616 SDNode *ResNode = SelectCode(N);
1617
1618#ifndef NDEBUG
1619 DOUT << std::string(Indent-2, ' ') << "=> ";
1620 if (ResNode == NULL || ResNode == N.Val)
1621 DEBUG(N.Val->dump(CurDAG));
1622 else
1623 DEBUG(ResNode->dump(CurDAG));
1624 DOUT << "\n";
1625 Indent -= 2;
1626#endif
1627
1628 return ResNode;
1629}
1630
1631bool X86DAGToDAGISel::
1632SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1633 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1634 SDOperand Op0, Op1, Op2, Op3;
1635 switch (ConstraintCode) {
1636 case 'o': // offsetable ??
1637 case 'v': // not offsetable ??
1638 default: return true;
1639 case 'm': // memory
1640 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1641 return true;
1642 break;
1643 }
1644
1645 OutOps.push_back(Op0);
1646 OutOps.push_back(Op1);
1647 OutOps.push_back(Op2);
1648 OutOps.push_back(Op3);
1649 AddToISelQueue(Op0);
1650 AddToISelQueue(Op1);
1651 AddToISelQueue(Op2);
1652 AddToISelQueue(Op3);
1653 return false;
1654}
1655
1656/// createX86ISelDag - This pass converts a legalized DAG into a
1657/// X86-specific DAG, ready for instruction scheduling.
1658///
1659FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1660 return new X86DAGToDAGISel(TM, Fast);
1661}