blob: 74100f8362a004dd6acc448bdae2c055463069de [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"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/MathExtras.h"
Evan Cheng656269e2008-04-25 08:22:20 +000038#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/ADT/Statistic.h"
40#include <queue>
41#include <set>
42using namespace llvm;
43
44STATISTIC(NumFPKill , "Number of FP_REG_KILL instructions added");
45STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
46
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047//===----------------------------------------------------------------------===//
48// Pattern Matcher Implementation
49//===----------------------------------------------------------------------===//
50
51namespace {
52 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
53 /// SDOperand's instead of register numbers for the leaves of the matched
54 /// tree.
55 struct X86ISelAddressMode {
56 enum {
57 RegBase,
58 FrameIndexBase
59 } BaseType;
60
61 struct { // This is really a union, discriminated by BaseType!
62 SDOperand Reg;
63 int FrameIndex;
64 } Base;
65
Evan Cheng3b5a1272008-02-07 08:53:49 +000066 bool isRIPRel; // RIP as base?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067 unsigned Scale;
68 SDOperand IndexReg;
69 unsigned Disp;
70 GlobalValue *GV;
71 Constant *CP;
72 const char *ES;
73 int JT;
74 unsigned Align; // CP alignment.
75
76 X86ISelAddressMode()
77 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
78 GV(0), CP(0), ES(0), JT(-1), Align(0) {
79 }
80 };
81}
82
83namespace {
84 //===--------------------------------------------------------------------===//
85 /// ISel - X86 specific code to select X86 machine instructions for
86 /// SelectionDAG operations.
87 ///
88 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
89 /// ContainsFPCode - Every instruction we select that uses or defines a FP
90 /// register should set this to true.
91 bool ContainsFPCode;
92
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 /// TM - Keep a reference to X86TargetMachine.
94 ///
95 X86TargetMachine &TM;
96
97 /// X86Lowering - This object fully describes how to lower LLVM code to an
98 /// X86-specific SelectionDAG.
99 X86TargetLowering X86Lowering;
100
101 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
102 /// make the right decision when generating code for different targets.
103 const X86Subtarget *Subtarget;
104
105 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
106 /// base register.
107 unsigned GlobalBaseReg;
108
Evan Cheng34fd4f32008-06-30 20:45:06 +0000109 /// CurBB - Current BB being isel'd.
110 ///
111 MachineBasicBlock *CurBB;
112
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 public:
114 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
Evan Cheng9b77cae2008-07-01 18:05:03 +0000115 : SelectionDAGISel(X86Lowering, fast),
116 ContainsFPCode(false), TM(tm),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 X86Lowering(*TM.getTargetLowering()),
118 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
119
120 virtual bool runOnFunction(Function &Fn) {
121 // Make sure we re-emit a set of the global base reg if necessary
122 GlobalBaseReg = 0;
123 return SelectionDAGISel::runOnFunction(Fn);
124 }
125
126 virtual const char *getPassName() const {
127 return "X86 DAG->DAG Instruction Selection";
128 }
129
Evan Cheng34fd4f32008-06-30 20:45:06 +0000130 /// InstructionSelect - This callback is invoked by
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
Evan Cheng34fd4f32008-06-30 20:45:06 +0000132 virtual void InstructionSelect(SelectionDAG &DAG);
133
134 /// InstructionSelectPostProcessing - Post processing of selected and
135 /// scheduled basic blocks.
136 virtual void InstructionSelectPostProcessing(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000138 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
139
Dan Gohmand6098272007-07-24 23:00:27 +0000140 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141
142// Include the pieces autogenerated from the target description.
143#include "X86GenDAGISel.inc"
144
145 private:
146 SDNode *Select(SDOperand N);
147
148 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
149 bool isRoot = true, unsigned Depth = 0);
Dan Gohmana60c1b32007-08-13 20:03:06 +0000150 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
151 bool isRoot, unsigned Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
153 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
154 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
155 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
156 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
157 SDOperand N, SDOperand &Base, SDOperand &Scale,
158 SDOperand &Index, SDOperand &Disp,
159 SDOperand &InChain, SDOperand &OutChain);
160 bool TryFoldLoad(SDOperand P, SDOperand N,
161 SDOperand &Base, SDOperand &Scale,
162 SDOperand &Index, SDOperand &Disp);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000163 void PreprocessForRMW(SelectionDAG &DAG);
164 void PreprocessForFPConvert(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165
166 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
167 /// inline asm expressions.
168 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
169 char ConstraintCode,
170 std::vector<SDOperand> &OutOps,
171 SelectionDAG &DAG);
172
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000173 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
174
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
176 SDOperand &Scale, SDOperand &Index,
177 SDOperand &Disp) {
178 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
179 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
180 AM.Base.Reg;
181 Scale = getI8Imm(AM.Scale);
182 Index = AM.IndexReg;
183 // These are 32-bit even in 64-bit mode since RIP relative offset
184 // is 32-bit.
185 if (AM.GV)
186 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
187 else if (AM.CP)
188 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
189 else if (AM.ES)
190 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
191 else if (AM.JT != -1)
192 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
193 else
194 Disp = getI32Imm(AM.Disp);
195 }
196
197 /// getI8Imm - Return a target constant with the specified value, of type
198 /// i8.
199 inline SDOperand getI8Imm(unsigned Imm) {
200 return CurDAG->getTargetConstant(Imm, MVT::i8);
201 }
202
203 /// getI16Imm - Return a target constant with the specified value, of type
204 /// i16.
205 inline SDOperand getI16Imm(unsigned Imm) {
206 return CurDAG->getTargetConstant(Imm, MVT::i16);
207 }
208
209 /// getI32Imm - Return a target constant with the specified value, of type
210 /// i32.
211 inline SDOperand getI32Imm(unsigned Imm) {
212 return CurDAG->getTargetConstant(Imm, MVT::i32);
213 }
214
215 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
216 /// base register. Return the virtual register that holds this value.
217 SDNode *getGlobalBaseReg();
218
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000219 /// getTruncate - return an SDNode that implements a subreg based truncate
220 /// of the specified operand to the the specified value type.
Duncan Sands92c43912008-06-06 12:08:01 +0000221 SDNode *getTruncate(SDOperand N0, MVT VT);
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000222
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223#ifndef NDEBUG
224 unsigned Indent;
225#endif
226 };
227}
228
Evan Cheng656269e2008-04-25 08:22:20 +0000229/// findFlagUse - Return use of MVT::Flag value produced by the specified SDNode.
230///
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231static SDNode *findFlagUse(SDNode *N) {
232 unsigned FlagResNo = N->getNumValues()-1;
233 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
Roman Levenstein05650fd2008-04-07 10:06:32 +0000234 SDNode *User = I->getUser();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
236 SDOperand Op = User->getOperand(i);
237 if (Op.Val == N && Op.ResNo == FlagResNo)
238 return User;
239 }
240 }
241 return NULL;
242}
243
Evan Cheng656269e2008-04-25 08:22:20 +0000244/// findNonImmUse - Return true by reference in "found" if "Use" is an
245/// non-immediate use of "Def". This function recursively traversing
246/// up the operand chain ignoring certain nodes.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
248 SDNode *Root, SDNode *Skip, bool &found,
Evan Cheng656269e2008-04-25 08:22:20 +0000249 SmallPtrSet<SDNode*, 16> &Visited) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 if (found ||
251 Use->getNodeId() > Def->getNodeId() ||
Evan Cheng656269e2008-04-25 08:22:20 +0000252 !Visited.insert(Use))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 return;
Evan Cheng656269e2008-04-25 08:22:20 +0000254
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
256 SDNode *N = Use->getOperand(i).Val;
257 if (N == Skip)
258 continue;
259 if (N == Def) {
260 if (Use == ImmedUse)
Evan Cheng9ea310c2008-04-25 08:55:28 +0000261 continue; // We are not looking for immediate use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 if (Use == Root) {
Evan Cheng9ea310c2008-04-25 08:55:28 +0000263 // Must be a chain reading node where it is possible to reach its own
264 // chain operand through a path started from another operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 assert(Use->getOpcode() == ISD::STORE ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000266 Use->getOpcode() == X86ISD::CMP ||
Chris Lattnercfbb2722008-04-25 05:13:01 +0000267 Use->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
268 Use->getOpcode() == ISD::INTRINSIC_VOID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 continue;
270 }
271 found = true;
272 break;
273 }
Evan Cheng656269e2008-04-25 08:22:20 +0000274
275 // Traverse up the operand chain.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
277 }
278}
279
280/// isNonImmUse - Start searching from Root up the DAG to check is Def can
281/// be reached. Return true if that's the case. However, ignore direct uses
282/// by ImmedUse (which would be U in the example illustrated in
283/// CanBeFoldedBy) and by Root (which can happen in the store case).
284/// FIXME: to be really generic, we should allow direct use by any node
285/// that is being folded. But realisticly since we only fold loads which
286/// have one non-chain use, we only need to watch out for load/op/store
287/// and load/op/cmp case where the root (store / cmp) may reach the load via
288/// its chain operand.
289static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
290 SDNode *Skip = NULL) {
Evan Cheng656269e2008-04-25 08:22:20 +0000291 SmallPtrSet<SDNode*, 16> Visited;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 bool found = false;
293 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
294 return found;
295}
296
297
Dan Gohmand6098272007-07-24 23:00:27 +0000298bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 if (FastISel) return false;
300
301 // If U use can somehow reach N through another path then U can't fold N or
302 // it will create a cycle. e.g. In the following diagram, U can reach N
303 // through X. If N is folded into into U, then X is both a predecessor and
304 // a successor of U.
305 //
306 // [ N ]
307 // ^ ^
308 // | |
309 // / \---
310 // / [X]
311 // | ^
312 // [U]--------|
313
314 if (isNonImmUse(Root, N, U))
315 return false;
316
317 // If U produces a flag, then it gets (even more) interesting. Since it
318 // would have been "glued" together with its flag use, we need to check if
319 // it might reach N:
320 //
321 // [ N ]
322 // ^ ^
323 // | |
324 // [U] \--
325 // ^ [TF]
326 // | ^
327 // | |
328 // \ /
329 // [FU]
330 //
331 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
332 // NU), then TF is a predecessor of FU and a successor of NU. But since
333 // NU and FU are flagged together, this effectively creates a cycle.
334 bool HasFlagUse = false;
Duncan Sands92c43912008-06-06 12:08:01 +0000335 MVT VT = Root->getValueType(Root->getNumValues()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 while ((VT == MVT::Flag && !Root->use_empty())) {
337 SDNode *FU = findFlagUse(Root);
338 if (FU == NULL)
339 break;
340 else {
341 Root = FU;
342 HasFlagUse = true;
343 }
344 VT = Root->getValueType(Root->getNumValues()-1);
345 }
346
347 if (HasFlagUse)
348 return !isNonImmUse(Root, N, Root, U);
349 return true;
350}
351
352/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
353/// and move load below the TokenFactor. Replace store's chain operand with
354/// load's chain result.
355static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
356 SDOperand Store, SDOperand TF) {
357 std::vector<SDOperand> Ops;
358 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
359 if (Load.Val == TF.Val->getOperand(i).Val)
360 Ops.push_back(Load.Val->getOperand(0));
361 else
362 Ops.push_back(TF.Val->getOperand(i));
363 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
364 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
365 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
366 Store.getOperand(2), Store.getOperand(3));
367}
368
Evan Cheng2b2a7012008-05-23 21:23:16 +0000369/// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
370///
371static bool isRMWLoad(SDOperand N, SDOperand Chain, SDOperand Address,
372 SDOperand &Load) {
373 if (N.getOpcode() == ISD::BIT_CONVERT)
374 N = N.getOperand(0);
375
376 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
377 if (!LD || LD->isVolatile())
378 return false;
379 if (LD->getAddressingMode() != ISD::UNINDEXED)
380 return false;
381
382 ISD::LoadExtType ExtType = LD->getExtensionType();
383 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
384 return false;
385
386 if (N.hasOneUse() &&
387 N.getOperand(1) == Address &&
388 N.Val->isOperandOf(Chain.Val)) {
389 Load = N;
390 return true;
391 }
392 return false;
393}
394
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000395/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
396/// This is only run if not in -fast mode (aka -O0).
397/// This allows the instruction selector to pick more read-modify-write
398/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399///
400/// [Load chain]
401/// ^
402/// |
403/// [Load]
404/// ^ ^
405/// | |
406/// / \-
407/// / |
408/// [TokenFactor] [Op]
409/// ^ ^
410/// | |
411/// \ /
412/// \ /
413/// [Store]
414///
415/// The fact the store's chain operand != load's chain will prevent the
416/// (store (op (load))) instruction from being selected. We can transform it to:
417///
418/// [Load chain]
419/// ^
420/// |
421/// [TokenFactor]
422/// ^
423/// |
424/// [Load]
425/// ^ ^
426/// | |
427/// | \-
428/// | |
429/// | [Op]
430/// | ^
431/// | |
432/// \ /
433/// \ /
434/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000435void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
437 E = DAG.allnodes_end(); I != E; ++I) {
438 if (!ISD::isNON_TRUNCStore(I))
439 continue;
440 SDOperand Chain = I->getOperand(0);
441 if (Chain.Val->getOpcode() != ISD::TokenFactor)
442 continue;
443
444 SDOperand N1 = I->getOperand(1);
445 SDOperand N2 = I->getOperand(2);
Duncan Sands92c43912008-06-06 12:08:01 +0000446 if ((N1.getValueType().isFloatingPoint() &&
447 !N1.getValueType().isVector()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 !N1.hasOneUse())
449 continue;
450
451 bool RModW = false;
452 SDOperand Load;
453 unsigned Opcode = N1.Val->getOpcode();
454 switch (Opcode) {
455 case ISD::ADD:
456 case ISD::MUL:
457 case ISD::AND:
458 case ISD::OR:
459 case ISD::XOR:
460 case ISD::ADDC:
Evan Cheng2b2a7012008-05-23 21:23:16 +0000461 case ISD::ADDE:
462 case ISD::VECTOR_SHUFFLE: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463 SDOperand N10 = N1.getOperand(0);
464 SDOperand N11 = N1.getOperand(1);
Evan Cheng2b2a7012008-05-23 21:23:16 +0000465 RModW = isRMWLoad(N10, Chain, N2, Load);
466 if (!RModW)
467 RModW = isRMWLoad(N11, Chain, N2, Load);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 break;
469 }
470 case ISD::SUB:
471 case ISD::SHL:
472 case ISD::SRA:
473 case ISD::SRL:
474 case ISD::ROTL:
475 case ISD::ROTR:
476 case ISD::SUBC:
477 case ISD::SUBE:
478 case X86ISD::SHLD:
479 case X86ISD::SHRD: {
480 SDOperand N10 = N1.getOperand(0);
Evan Cheng2b2a7012008-05-23 21:23:16 +0000481 RModW = isRMWLoad(N10, Chain, N2, Load);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 break;
483 }
484 }
485
486 if (RModW) {
487 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
488 ++NumLoadMoved;
489 }
490 }
491}
492
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000493
494/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
495/// nodes that target the FP stack to be store and load to the stack. This is a
496/// gross hack. We would like to simply mark these as being illegal, but when
497/// we do that, legalize produces these when it expands calls, then expands
498/// these in the same legalize pass. We would like dag combine to be able to
499/// hack on these between the call expansion and the node legalization. As such
500/// this pass basically does "really late" legalization of these inline with the
501/// X86 isel pass.
502void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
503 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
504 E = DAG.allnodes_end(); I != E; ) {
505 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
506 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
507 continue;
508
509 // If the source and destination are SSE registers, then this is a legal
510 // conversion that should not be lowered.
Duncan Sands92c43912008-06-06 12:08:01 +0000511 MVT SrcVT = N->getOperand(0).getValueType();
512 MVT DstVT = N->getValueType(0);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000513 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
514 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
515 if (SrcIsSSE && DstIsSSE)
516 continue;
517
Chris Lattner5d294e52008-03-09 07:05:32 +0000518 if (!SrcIsSSE && !DstIsSSE) {
519 // If this is an FPStack extension, it is a noop.
520 if (N->getOpcode() == ISD::FP_EXTEND)
521 continue;
522 // If this is a value-preserving FPStack truncation, it is a noop.
523 if (N->getConstantOperandVal(1))
524 continue;
525 }
526
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000527 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
528 // FPStack has extload and truncstore. SSE can fold direct loads into other
529 // operations. Based on this, decide what we want to do.
Duncan Sands92c43912008-06-06 12:08:01 +0000530 MVT MemVT;
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000531 if (N->getOpcode() == ISD::FP_ROUND)
532 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
533 else
534 MemVT = SrcIsSSE ? SrcVT : DstVT;
535
536 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
537
538 // FIXME: optimize the case where the src/dest is a load or store?
539 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
540 MemTmp, NULL, 0, MemVT);
541 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
542 NULL, 0, MemVT);
543
544 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
545 // extload we created. This will cause general havok on the dag because
546 // anything below the conversion could be folded into other existing nodes.
547 // To avoid invalidating 'I', back it up to the convert node.
548 --I;
549 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
550
551 // Now that we did that, the node is dead. Increment the iterator to the
552 // next node to process, then delete N.
553 ++I;
554 DAG.DeleteNode(N);
555 }
556}
557
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
559/// when it has created a SelectionDAG for us to codegen.
Evan Cheng34fd4f32008-06-30 20:45:06 +0000560void X86DAGToDAGISel::InstructionSelect(SelectionDAG &DAG) {
561 CurBB = BB; // BB can change as result of isel.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562
Evan Cheng34fd4f32008-06-30 20:45:06 +0000563 DEBUG(BB->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000565 PreprocessForRMW(DAG);
566
567 // FIXME: This should only happen when not -fast.
568 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569
570 // Codegen the basic block.
571#ifndef NDEBUG
572 DOUT << "===== Instruction selection begins:\n";
573 Indent = 0;
574#endif
575 DAG.setRoot(SelectRoot(DAG.getRoot()));
576#ifndef NDEBUG
577 DOUT << "===== Instruction selection ends:\n";
578#endif
579
580 DAG.RemoveDeadNodes();
Evan Cheng34fd4f32008-06-30 20:45:06 +0000581}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582
Evan Cheng34fd4f32008-06-30 20:45:06 +0000583void X86DAGToDAGISel::InstructionSelectPostProcessing(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 // If we are emitting FP stack code, scan the basic block to determine if this
585 // block defines any FP values. If so, put an FP_REG_KILL instruction before
586 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000587
Dale Johannesen684887e2007-09-24 22:52:39 +0000588 // Note that FP stack instructions are used in all modes for long double,
589 // so we always need to do this check.
590 // Also note that it's possible for an FP stack register to be live across
591 // an instruction that produces multiple basic blocks (SSE CMOV) so we
592 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000593
594 // Scan all of the machine instructions in these MBBs, checking for FP
595 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
Evan Cheng34fd4f32008-06-30 20:45:06 +0000596 MachineFunction::iterator MBBI = CurBB;
Chris Lattner04d64b22008-03-10 23:34:12 +0000597 MachineFunction::iterator EndMBB = BB; ++EndMBB;
598 for (; MBBI != EndMBB; ++MBBI) {
599 MachineBasicBlock *MBB = MBBI;
600
601 // If this block returns, ignore it. We don't want to insert an FP_REG_KILL
602 // before the return.
603 if (!MBB->empty()) {
604 MachineBasicBlock::iterator EndI = MBB->end();
605 --EndI;
606 if (EndI->getDesc().isReturn())
607 continue;
608 }
609
Dale Johannesen684887e2007-09-24 22:52:39 +0000610 bool ContainsFPCode = false;
Chris Lattner04d64b22008-03-10 23:34:12 +0000611 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000612 !ContainsFPCode && I != E; ++I) {
613 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
614 const TargetRegisterClass *clas;
615 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
616 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Chris Lattner04d64b22008-03-10 23:34:12 +0000617 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000618 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000619 X86::RFP32RegisterClass ||
620 clas == X86::RFP64RegisterClass ||
621 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 ContainsFPCode = true;
623 break;
624 }
625 }
626 }
627 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000628 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
629 // a copy of the input value in this block. In SSE mode, we only care about
630 // 80-bit values.
631 if (!ContainsFPCode) {
632 // Final check, check LLVM BB's that are successors to the LLVM BB
633 // corresponding to BB for FP PHI nodes.
634 const BasicBlock *LLVMBB = BB->getBasicBlock();
635 const PHINode *PN;
636 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
637 !ContainsFPCode && SI != E; ++SI) {
638 for (BasicBlock::const_iterator II = SI->begin();
639 (PN = dyn_cast<PHINode>(II)); ++II) {
640 if (PN->getType()==Type::X86_FP80Ty ||
641 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
642 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
643 ContainsFPCode = true;
644 break;
645 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000646 }
647 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000649 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
650 if (ContainsFPCode) {
Chris Lattner04d64b22008-03-10 23:34:12 +0000651 BuildMI(*MBB, MBBI->getFirstTerminator(),
Dale Johannesen684887e2007-09-24 22:52:39 +0000652 TM.getInstrInfo()->get(X86::FP_REG_KILL));
653 ++NumFPKill;
654 }
Chris Lattner04d64b22008-03-10 23:34:12 +0000655 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656}
657
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000658/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
659/// the main function.
660void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
661 MachineFrameInfo *MFI) {
662 const TargetInstrInfo *TII = TM.getInstrInfo();
663 if (Subtarget->isTargetCygMing())
664 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
665}
666
667void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
668 // If this is main, emit special code for main.
669 MachineBasicBlock *BB = MF.begin();
670 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
671 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
672}
673
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674/// MatchAddress - Add the specified node to the specified addressing mode,
675/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000676/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
678 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000679 // Limit recursion.
680 if (Depth > 5)
681 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682
683 // RIP relative addressing: %rip + 32-bit displacement!
684 if (AM.isRIPRel) {
685 if (!AM.ES && AM.JT != -1 && N.getOpcode() == 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 }
692 return true;
693 }
694
695 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000696 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697
698 switch (N.getOpcode()) {
699 default: break;
700 case ISD::Constant: {
701 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
702 if (isInt32(AM.Disp + Val)) {
703 AM.Disp += Val;
704 return false;
705 }
706 break;
707 }
708
709 case X86ISD::Wrapper: {
710 bool is64Bit = Subtarget->is64Bit();
711 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000712 // Also, base and index reg must be 0 in order to use rip as base.
713 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
714 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 break;
716 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
717 break;
718 // If value is available in a register both base and index components have
719 // been picked, we can't fit the result available in the register in the
720 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000721 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 SDOperand N0 = N.getOperand(0);
723 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
724 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000725 AM.GV = GV;
726 AM.Disp += G->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000727 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
728 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000729 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000731 AM.CP = CP->getConstVal();
732 AM.Align = CP->getAlignment();
733 AM.Disp += CP->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000734 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
735 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000736 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000738 AM.ES = S->getSymbol();
Evan Chenga54e14f2008-02-12 19:20:46 +0000739 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
740 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000741 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000743 AM.JT = J->getIndex();
Evan Chenga54e14f2008-02-12 19:20:46 +0000744 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
745 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000746 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 }
748 }
749 break;
750 }
751
752 case ISD::FrameIndex:
753 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
754 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
755 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
756 return false;
757 }
758 break;
759
760 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000761 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000762 break;
763
764 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
765 unsigned Val = CN->getValue();
766 if (Val == 1 || Val == 2 || Val == 3) {
767 AM.Scale = 1 << Val;
768 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769
Chris Lattner7f06edd2007-12-08 07:22:58 +0000770 // Okay, we know that we have a scale by now. However, if the scaled
771 // value is an add of something and a constant, we can fold the
772 // constant into the disp field here.
773 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
774 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
775 AM.IndexReg = ShVal.Val->getOperand(0);
776 ConstantSDNode *AddVal =
777 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
778 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
779 if (isInt32(Disp))
780 AM.Disp = Disp;
781 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000783 } else {
784 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000786 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 }
788 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000789 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790
Dan Gohman35b99222007-10-22 20:22:24 +0000791 case ISD::SMUL_LOHI:
792 case ISD::UMUL_LOHI:
793 // A mul_lohi where we need the low part can be folded as a plain multiply.
794 if (N.ResNo != 0) break;
795 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 case ISD::MUL:
797 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000798 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 AM.BaseType == X86ISelAddressMode::RegBase &&
800 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000801 AM.IndexReg.Val == 0 &&
802 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
804 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
805 AM.Scale = unsigned(CN->getValue())-1;
806
807 SDOperand MulVal = N.Val->getOperand(0);
808 SDOperand Reg;
809
810 // Okay, we know that we have a scale by now. However, if the scaled
811 // value is an add of something and a constant, we can fold the
812 // constant into the disp field here.
813 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
814 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
815 Reg = MulVal.Val->getOperand(0);
816 ConstantSDNode *AddVal =
817 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
818 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
819 if (isInt32(Disp))
820 AM.Disp = Disp;
821 else
822 Reg = N.Val->getOperand(0);
823 } else {
824 Reg = N.Val->getOperand(0);
825 }
826
827 AM.IndexReg = AM.Base.Reg = Reg;
828 return false;
829 }
830 }
831 break;
832
833 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000834 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 X86ISelAddressMode Backup = AM;
836 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
837 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
838 return false;
839 AM = Backup;
840 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
841 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
842 return false;
843 AM = Backup;
844 }
845 break;
846
847 case ISD::OR:
848 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000849 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000850
851 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
852 X86ISelAddressMode Backup = AM;
853 // Start with the LHS as an addr mode.
854 if (!MatchAddress(N.getOperand(0), AM, false) &&
855 // Address could not have picked a GV address for the displacement.
856 AM.GV == NULL &&
857 // On x86-64, the resultant disp must fit in 32-bits.
858 isInt32(AM.Disp + CN->getSignExtended()) &&
859 // Check to see if the LHS & C is zero.
Dan Gohman07961cd2008-02-25 21:11:39 +0000860 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
Chris Lattner7f06edd2007-12-08 07:22:58 +0000861 AM.Disp += CN->getValue();
862 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000864 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 }
866 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000867
868 case ISD::AND: {
869 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
870 // allows us to fold the shift into this addressing mode.
871 if (AlreadySelected) break;
872 SDOperand Shift = N.getOperand(0);
873 if (Shift.getOpcode() != ISD::SHL) break;
874
875 // Scale must not be used already.
876 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000877
878 // Not when RIP is used as the base.
879 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000880
881 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
882 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
883 if (!C1 || !C2) break;
884
885 // Not likely to be profitable if either the AND or SHIFT node has more
886 // than one use (unless all uses are for address computation). Besides,
887 // isel mechanism requires their node ids to be reused.
888 if (!N.hasOneUse() || !Shift.hasOneUse())
889 break;
890
891 // Verify that the shift amount is something we can fold.
892 unsigned ShiftCst = C1->getValue();
893 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
894 break;
895
896 // Get the new AND mask, this folds to a constant.
897 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
898 SDOperand(C2, 0), SDOperand(C1, 0));
899 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
900 Shift.getOperand(0), NewANDMask);
901 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
902 NewAND.Val->setNodeId(N.Val->getNodeId());
903
904 AM.Scale = 1 << ShiftCst;
905 AM.IndexReg = NewAND;
906 return false;
907 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 }
909
Dan Gohmana60c1b32007-08-13 20:03:06 +0000910 return MatchAddressBase(N, AM, isRoot, Depth);
911}
912
913/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
914/// specified addressing mode without any further recursion.
915bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
916 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 // Is the base register already occupied?
918 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
919 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000920 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 AM.IndexReg = N;
922 AM.Scale = 1;
923 return false;
924 }
925
926 // Otherwise, we cannot select it.
927 return true;
928 }
929
930 // Default, generate it as a register.
931 AM.BaseType = X86ISelAddressMode::RegBase;
932 AM.Base.Reg = N;
933 return false;
934}
935
936/// SelectAddr - returns true if it is able pattern match an addressing mode.
937/// It returns the operands which make up the maximal addressing mode it can
938/// match by reference.
939bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
940 SDOperand &Scale, SDOperand &Index,
941 SDOperand &Disp) {
942 X86ISelAddressMode AM;
943 if (MatchAddress(N, AM))
944 return false;
945
Duncan Sands92c43912008-06-06 12:08:01 +0000946 MVT VT = N.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 if (AM.BaseType == X86ISelAddressMode::RegBase) {
948 if (!AM.Base.Reg.Val)
949 AM.Base.Reg = CurDAG->getRegister(0, VT);
950 }
951
952 if (!AM.IndexReg.Val)
953 AM.IndexReg = CurDAG->getRegister(0, VT);
954
955 getAddressOperands(AM, Base, Scale, Index, Disp);
956 return true;
957}
958
959/// isZeroNode - Returns true if Elt is a constant zero or a floating point
960/// constant +0.0.
961static inline bool isZeroNode(SDOperand Elt) {
962 return ((isa<ConstantSDNode>(Elt) &&
963 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
964 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000965 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966}
967
968
969/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
970/// match a load whose top elements are either undef or zeros. The load flavor
971/// is derived from the type of N, which is either v4f32 or v2f64.
972bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
973 SDOperand N, SDOperand &Base,
974 SDOperand &Scale, SDOperand &Index,
975 SDOperand &Disp, SDOperand &InChain,
976 SDOperand &OutChain) {
977 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
978 InChain = N.getOperand(0).getValue(1);
979 if (ISD::isNON_EXTLoad(InChain.Val) &&
980 InChain.getValue(0).hasOneUse() &&
981 N.hasOneUse() &&
982 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
983 LoadSDNode *LD = cast<LoadSDNode>(InChain);
984 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
985 return false;
986 OutChain = LD->getChain();
987 return true;
988 }
989 }
990
991 // Also handle the case where we explicitly require zeros in the top
992 // elements. This is a vector shuffle from the zero vector.
Evan Chenge9b9c672008-05-09 21:53:03 +0000993 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000994 // Check to see if the top elements are all zeros (or bitcast of zeros).
Evan Cheng40ee6e52008-05-08 00:57:18 +0000995 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
996 N.getOperand(0).Val->hasOneUse() &&
997 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).Val) &&
998 N.getOperand(0).getOperand(0).hasOneUse()) {
999 // Okay, this is a zero extending load. Fold it.
1000 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1001 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
1002 return false;
1003 OutChain = LD->getChain();
1004 InChain = SDOperand(LD, 1);
1005 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 }
1007 return false;
1008}
1009
1010
1011/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1012/// mode it matches can be cost effectively emitted as an LEA instruction.
1013bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
1014 SDOperand &Base, SDOperand &Scale,
1015 SDOperand &Index, SDOperand &Disp) {
1016 X86ISelAddressMode AM;
1017 if (MatchAddress(N, AM))
1018 return false;
1019
Duncan Sands92c43912008-06-06 12:08:01 +00001020 MVT VT = N.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 unsigned Complexity = 0;
1022 if (AM.BaseType == X86ISelAddressMode::RegBase)
1023 if (AM.Base.Reg.Val)
1024 Complexity = 1;
1025 else
1026 AM.Base.Reg = CurDAG->getRegister(0, VT);
1027 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1028 Complexity = 4;
1029
1030 if (AM.IndexReg.Val)
1031 Complexity++;
1032 else
1033 AM.IndexReg = CurDAG->getRegister(0, VT);
1034
1035 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1036 // a simple shift.
1037 if (AM.Scale > 1)
1038 Complexity++;
1039
1040 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1041 // to a LEA. This is determined with some expermentation but is by no means
1042 // optimal (especially for code size consideration). LEA is nice because of
1043 // its three-address nature. Tweak the cost function again when we can run
1044 // convertToThreeAddress() at register allocation time.
1045 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1046 // For X86-64, we should always use lea to materialize RIP relative
1047 // addresses.
1048 if (Subtarget->is64Bit())
1049 Complexity = 4;
1050 else
1051 Complexity += 2;
1052 }
1053
1054 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1055 Complexity++;
1056
1057 if (Complexity > 2) {
1058 getAddressOperands(AM, Base, Scale, Index, Disp);
1059 return true;
1060 }
1061 return false;
1062}
1063
1064bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1065 SDOperand &Base, SDOperand &Scale,
1066 SDOperand &Index, SDOperand &Disp) {
1067 if (ISD::isNON_EXTLoad(N.Val) &&
1068 N.hasOneUse() &&
1069 CanBeFoldedBy(N.Val, P.Val, P.Val))
1070 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1071 return false;
1072}
1073
1074/// getGlobalBaseReg - Output the instructions required to put the
1075/// base address to use for accessing globals into a register.
1076///
1077SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1078 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1079 if (!GlobalBaseReg) {
1080 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001081 MachineFunction *MF = BB->getParent();
1082 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001084 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001085 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086
1087 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001088 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1089 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001090 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091
1092 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1093 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1094 if (TM.getRelocationModel() == Reloc::PIC_ &&
1095 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001096 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001097 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1098 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 } else {
1100 GlobalBaseReg = PC;
1101 }
1102
1103 }
1104 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1105}
1106
1107static SDNode *FindCallStartFromCall(SDNode *Node) {
1108 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1109 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1110 "Node doesn't have a token chain argument!");
1111 return FindCallStartFromCall(Node->getOperand(0).Val);
1112}
1113
Duncan Sands92c43912008-06-06 12:08:01 +00001114SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT VT) {
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001115 SDOperand SRIdx;
Duncan Sands92c43912008-06-06 12:08:01 +00001116 switch (VT.getSimpleVT()) {
1117 default: assert(0 && "Unknown truncate!");
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001118 case MVT::i8:
1119 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1120 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1121 if (!Subtarget->is64Bit()) {
1122 unsigned Opc;
Dan Gohmand5a14852008-07-16 16:20:48 +00001123 MVT N0VT = N0.getValueType();
1124 switch (N0VT.getSimpleVT()) {
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001125 default: assert(0 && "Unknown truncate!");
1126 case MVT::i16:
1127 Opc = X86::MOV16to16_;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001128 break;
1129 case MVT::i32:
1130 Opc = X86::MOV32to32_;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001131 break;
1132 }
Dan Gohmand5a14852008-07-16 16:20:48 +00001133 N0 = SDOperand(CurDAG->getTargetNode(Opc, N0VT, MVT::Flag, N0), 0);
Evan Chenge1f39552007-10-12 07:55:53 +00001134 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1135 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001136 }
1137 break;
1138 case MVT::i16:
1139 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1140 break;
1141 case MVT::i32:
1142 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1143 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001144 }
Evan Chenge1f39552007-10-12 07:55:53 +00001145 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001146}
1147
1148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1150 SDNode *Node = N.Val;
Duncan Sands92c43912008-06-06 12:08:01 +00001151 MVT NVT = Node->getValueType(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 unsigned Opc, MOpc;
1153 unsigned Opcode = Node->getOpcode();
1154
1155#ifndef NDEBUG
1156 DOUT << std::string(Indent, ' ') << "Selecting: ";
1157 DEBUG(Node->dump(CurDAG));
1158 DOUT << "\n";
1159 Indent += 2;
1160#endif
1161
Dan Gohmanbd68c792008-07-17 19:10:17 +00001162 if (Node->isMachineOpcode()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163#ifndef NDEBUG
1164 DOUT << std::string(Indent-2, ' ') << "== ";
1165 DEBUG(Node->dump(CurDAG));
1166 DOUT << "\n";
1167 Indent -= 2;
1168#endif
1169 return NULL; // Already selected.
1170 }
1171
1172 switch (Opcode) {
1173 default: break;
1174 case X86ISD::GlobalBaseReg:
1175 return getGlobalBaseReg();
1176
1177 case ISD::ADD: {
1178 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1179 // code and is matched first so to prevent it from being turned into
1180 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001181 // In 64-bit small code size mode, use LEA to take advantage of
1182 // RIP-relative addressing.
1183 if (TM.getCodeModel() != CodeModel::Small)
1184 break;
Duncan Sands92c43912008-06-06 12:08:01 +00001185 MVT PtrVT = TLI.getPointerTy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 SDOperand N0 = N.getOperand(0);
1187 SDOperand N1 = N.getOperand(1);
1188 if (N.Val->getValueType(0) == PtrVT &&
1189 N0.getOpcode() == X86ISD::Wrapper &&
1190 N1.getOpcode() == ISD::Constant) {
1191 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1192 SDOperand C(0, 0);
1193 // TODO: handle ExternalSymbolSDNode.
1194 if (GlobalAddressSDNode *G =
1195 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1196 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1197 G->getOffset() + Offset);
1198 } else if (ConstantPoolSDNode *CP =
1199 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1200 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1201 CP->getAlignment(),
1202 CP->getOffset()+Offset);
1203 }
1204
1205 if (C.Val) {
1206 if (Subtarget->is64Bit()) {
1207 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1208 CurDAG->getRegister(0, PtrVT), C };
1209 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1210 } else
1211 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1212 }
1213 }
1214
1215 // Other cases are handled by auto-generated code.
1216 break;
1217 }
1218
Dan Gohman5a199552007-10-08 18:33:35 +00001219 case ISD::SMUL_LOHI:
1220 case ISD::UMUL_LOHI: {
1221 SDOperand N0 = Node->getOperand(0);
1222 SDOperand N1 = Node->getOperand(1);
1223
Dan Gohman5a199552007-10-08 18:33:35 +00001224 bool isSigned = Opcode == ISD::SMUL_LOHI;
1225 if (!isSigned)
Duncan Sands92c43912008-06-06 12:08:01 +00001226 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 default: assert(0 && "Unsupported VT!");
1228 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1229 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1230 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1231 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1232 }
1233 else
Duncan Sands92c43912008-06-06 12:08:01 +00001234 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 default: assert(0 && "Unsupported VT!");
1236 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1237 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1238 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1239 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1240 }
1241
1242 unsigned LoReg, HiReg;
Duncan Sands92c43912008-06-06 12:08:01 +00001243 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 default: assert(0 && "Unsupported VT!");
1245 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1246 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1247 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1248 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1249 }
1250
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001252 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001253 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 if (!foldedLoad) {
1255 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001256 if (foldedLoad)
1257 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 }
1259
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001261 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1262 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263
1264 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001265 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 AddToISelQueue(Tmp0);
1267 AddToISelQueue(Tmp1);
1268 AddToISelQueue(Tmp2);
1269 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001270 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 SDNode *CNode =
1272 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001274 // Update the chain.
1275 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 } else {
1277 AddToISelQueue(N1);
1278 InFlag =
1279 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1280 }
1281
Dan Gohman5a199552007-10-08 18:33:35 +00001282 // Copy the low half of the result, if it is needed.
1283 if (!N.getValue(0).use_empty()) {
1284 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1285 LoReg, NVT, InFlag);
1286 InFlag = Result.getValue(2);
1287 ReplaceUses(N.getValue(0), Result);
1288#ifndef NDEBUG
1289 DOUT << std::string(Indent-2, ' ') << "=> ";
1290 DEBUG(Result.Val->dump(CurDAG));
1291 DOUT << "\n";
1292#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001293 }
Dan Gohman5a199552007-10-08 18:33:35 +00001294 // Copy the high half of the result, if it is needed.
1295 if (!N.getValue(1).use_empty()) {
1296 SDOperand Result;
1297 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1298 // Prevent use of AH in a REX instruction by referencing AX instead.
1299 // Shift it down 8 bits.
1300 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1301 X86::AX, MVT::i16, InFlag);
1302 InFlag = Result.getValue(2);
1303 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1304 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1305 // Then truncate it down to i8.
1306 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1307 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1308 MVT::i8, Result, SRIdx), 0);
1309 } else {
1310 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1311 HiReg, NVT, InFlag);
1312 InFlag = Result.getValue(2);
1313 }
1314 ReplaceUses(N.getValue(1), Result);
1315#ifndef NDEBUG
1316 DOUT << std::string(Indent-2, ' ') << "=> ";
1317 DEBUG(Result.Val->dump(CurDAG));
1318 DOUT << "\n";
1319#endif
1320 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321
1322#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 Indent -= 2;
1324#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001325
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 return NULL;
1327 }
1328
Dan Gohman5a199552007-10-08 18:33:35 +00001329 case ISD::SDIVREM:
1330 case ISD::UDIVREM: {
1331 SDOperand N0 = Node->getOperand(0);
1332 SDOperand N1 = Node->getOperand(1);
1333
1334 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 if (!isSigned)
Duncan Sands92c43912008-06-06 12:08:01 +00001336 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 default: assert(0 && "Unsupported VT!");
1338 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1339 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1340 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1341 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1342 }
1343 else
Duncan Sands92c43912008-06-06 12:08:01 +00001344 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 default: assert(0 && "Unsupported VT!");
1346 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1347 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1348 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1349 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1350 }
1351
1352 unsigned LoReg, HiReg;
1353 unsigned ClrOpcode, SExtOpcode;
Duncan Sands92c43912008-06-06 12:08:01 +00001354 switch (NVT.getSimpleVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 default: assert(0 && "Unsupported VT!");
1356 case MVT::i8:
1357 LoReg = X86::AL; HiReg = X86::AH;
1358 ClrOpcode = 0;
1359 SExtOpcode = X86::CBW;
1360 break;
1361 case MVT::i16:
1362 LoReg = X86::AX; HiReg = X86::DX;
1363 ClrOpcode = X86::MOV16r0;
1364 SExtOpcode = X86::CWD;
1365 break;
1366 case MVT::i32:
1367 LoReg = X86::EAX; HiReg = X86::EDX;
1368 ClrOpcode = X86::MOV32r0;
1369 SExtOpcode = X86::CDQ;
1370 break;
1371 case MVT::i64:
1372 LoReg = X86::RAX; HiReg = X86::RDX;
1373 ClrOpcode = X86::MOV64r0;
1374 SExtOpcode = X86::CQO;
1375 break;
1376 }
1377
Dan Gohman5a199552007-10-08 18:33:35 +00001378 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1379 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1380
1381 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 if (NVT == MVT::i8 && !isSigned) {
1383 // Special case for div8, just use a move with zero extension to AX to
1384 // clear the upper 8 bits (AH).
1385 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1386 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1387 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1388 AddToISelQueue(N0.getOperand(0));
1389 AddToISelQueue(Tmp0);
1390 AddToISelQueue(Tmp1);
1391 AddToISelQueue(Tmp2);
1392 AddToISelQueue(Tmp3);
1393 Move =
1394 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1395 Ops, 5), 0);
1396 Chain = Move.getValue(1);
1397 ReplaceUses(N0.getValue(1), Chain);
1398 } else {
1399 AddToISelQueue(N0);
1400 Move =
1401 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1402 Chain = CurDAG->getEntryNode();
1403 }
Dan Gohman5a199552007-10-08 18:33:35 +00001404 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 InFlag = Chain.getValue(1);
1406 } else {
1407 AddToISelQueue(N0);
1408 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001409 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1410 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 if (isSigned) {
1412 // Sign extend the low part into the high part.
1413 InFlag =
1414 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1415 } else {
1416 // Zero out the high part, effectively zero extending the input.
1417 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001418 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1419 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 }
1421 }
1422
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 if (foldedLoad) {
1424 AddToISelQueue(N1.getOperand(0));
1425 AddToISelQueue(Tmp0);
1426 AddToISelQueue(Tmp1);
1427 AddToISelQueue(Tmp2);
1428 AddToISelQueue(Tmp3);
1429 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1430 SDNode *CNode =
1431 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001433 // Update the chain.
1434 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435 } else {
1436 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 InFlag =
1438 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1439 }
1440
Dan Gohman242a5ba2007-09-25 18:23:27 +00001441 // Copy the division (low) result, if it is needed.
1442 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001443 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1444 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001445 InFlag = Result.getValue(2);
1446 ReplaceUses(N.getValue(0), Result);
1447#ifndef NDEBUG
1448 DOUT << std::string(Indent-2, ' ') << "=> ";
1449 DEBUG(Result.Val->dump(CurDAG));
1450 DOUT << "\n";
1451#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001452 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001453 // Copy the remainder (high) result, if it is needed.
1454 if (!N.getValue(1).use_empty()) {
1455 SDOperand Result;
1456 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1457 // Prevent use of AH in a REX instruction by referencing AX instead.
1458 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001459 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1460 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001461 InFlag = Result.getValue(2);
1462 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1463 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1464 // Then truncate it down to i8.
1465 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1466 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1467 MVT::i8, Result, SRIdx), 0);
1468 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001469 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1470 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001471 InFlag = Result.getValue(2);
1472 }
1473 ReplaceUses(N.getValue(1), Result);
1474#ifndef NDEBUG
1475 DOUT << std::string(Indent-2, ' ') << "=> ";
1476 DEBUG(Result.Val->dump(CurDAG));
1477 DOUT << "\n";
1478#endif
1479 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001480
1481#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482 Indent -= 2;
1483#endif
1484
1485 return NULL;
1486 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001487
1488 case ISD::ANY_EXTEND: {
Christopher Lamb76d72da2008-03-16 03:12:01 +00001489 // Check if the type extended to supports subregs.
1490 if (NVT == MVT::i8)
1491 break;
1492
Christopher Lamb422213d2007-08-10 22:22:41 +00001493 SDOperand N0 = Node->getOperand(0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001494 // Get the subregsiter index for the type to extend.
Duncan Sands92c43912008-06-06 12:08:01 +00001495 MVT N0VT = N0.getValueType();
Christopher Lamb76d72da2008-03-16 03:12:01 +00001496 unsigned Idx = (N0VT == MVT::i32) ? X86::SUBREG_32BIT :
1497 (N0VT == MVT::i16) ? X86::SUBREG_16BIT :
1498 (Subtarget->is64Bit()) ? X86::SUBREG_8BIT : 0;
1499
1500 // If we don't have a subreg Idx, let generated ISel have a try.
1501 if (Idx == 0)
1502 break;
1503
1504 // If we have an index, generate an insert_subreg into undef.
Christopher Lamb422213d2007-08-10 22:22:41 +00001505 AddToISelQueue(N0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001506 SDOperand Undef =
Evan Cheng55a2dd02008-04-03 07:45:18 +00001507 SDOperand(CurDAG->getTargetNode(X86::IMPLICIT_DEF, NVT), 0);
Christopher Lamb76d72da2008-03-16 03:12:01 +00001508 SDOperand SRIdx = CurDAG->getTargetConstant(Idx, MVT::i32);
1509 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
Evan Cheng55a2dd02008-04-03 07:45:18 +00001510 NVT, Undef, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001511
1512#ifndef NDEBUG
Christopher Lamb76d72da2008-03-16 03:12:01 +00001513 DOUT << std::string(Indent-2, ' ') << "=> ";
1514 DEBUG(ResNode->dump(CurDAG));
1515 DOUT << "\n";
1516 Indent -= 2;
Christopher Lamb422213d2007-08-10 22:22:41 +00001517#endif
Christopher Lamb76d72da2008-03-16 03:12:01 +00001518 return ResNode;
Christopher Lamb422213d2007-08-10 22:22:41 +00001519 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001520
1521 case ISD::SIGN_EXTEND_INREG: {
1522 SDOperand N0 = Node->getOperand(0);
1523 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524
Duncan Sands92c43912008-06-06 12:08:01 +00001525 MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001526 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001527 unsigned Opc = 0;
Duncan Sands92c43912008-06-06 12:08:01 +00001528 switch (NVT.getSimpleVT()) {
1529 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001530 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001531 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1532 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001533 break;
1534 case MVT::i32:
Duncan Sands92c43912008-06-06 12:08:01 +00001535 switch (SVT.getSimpleVT()) {
1536 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001537 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1538 case MVT::i16: Opc = X86::MOVSX32rr16; break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001539 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001540 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001541 case MVT::i64:
Duncan Sands92c43912008-06-06 12:08:01 +00001542 switch (SVT.getSimpleVT()) {
1543 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001544 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1545 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1546 case MVT::i32: Opc = X86::MOVSX64rr32; break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001547 }
1548 break;
Christopher Lamb444336c2007-07-29 01:24:57 +00001549 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001550
1551 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1552
1553#ifndef NDEBUG
1554 DOUT << std::string(Indent-2, ' ') << "=> ";
1555 DEBUG(TruncOp.Val->dump(CurDAG));
1556 DOUT << "\n";
1557 DOUT << std::string(Indent-2, ' ') << "=> ";
1558 DEBUG(ResNode->dump(CurDAG));
1559 DOUT << "\n";
1560 Indent -= 2;
1561#endif
1562 return ResNode;
1563 break;
1564 }
1565
1566 case ISD::TRUNCATE: {
1567 SDOperand Input = Node->getOperand(0);
1568 AddToISelQueue(Node->getOperand(0));
1569 SDNode *ResNode = getTruncate(Input, NVT);
1570
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001571#ifndef NDEBUG
1572 DOUT << std::string(Indent-2, ' ') << "=> ";
1573 DEBUG(ResNode->dump(CurDAG));
1574 DOUT << "\n";
1575 Indent -= 2;
1576#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001577 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001578 break;
1579 }
Evan Chengd4cebcd2008-06-17 02:01:22 +00001580
1581 case ISD::DECLARE: {
1582 // Handle DECLARE nodes here because the second operand may have been
1583 // wrapped in X86ISD::Wrapper.
1584 SDOperand Chain = Node->getOperand(0);
1585 SDOperand N1 = Node->getOperand(1);
1586 SDOperand N2 = Node->getOperand(2);
Evan Cheng651e1442008-06-18 02:48:27 +00001587 if (!isa<FrameIndexSDNode>(N1))
1588 break;
1589 int FI = cast<FrameIndexSDNode>(N1)->getIndex();
1590 if (N2.getOpcode() == ISD::ADD &&
1591 N2.getOperand(0).getOpcode() == X86ISD::GlobalBaseReg)
1592 N2 = N2.getOperand(1);
1593 if (N2.getOpcode() == X86ISD::Wrapper &&
Evan Chengd4cebcd2008-06-17 02:01:22 +00001594 isa<GlobalAddressSDNode>(N2.getOperand(0))) {
Evan Chengd4cebcd2008-06-17 02:01:22 +00001595 GlobalValue *GV =
1596 cast<GlobalAddressSDNode>(N2.getOperand(0))->getGlobal();
1597 SDOperand Tmp1 = CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());
1598 SDOperand Tmp2 = CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());
1599 AddToISelQueue(Chain);
1600 SDOperand Ops[] = { Tmp1, Tmp2, Chain };
1601 return CurDAG->getTargetNode(TargetInstrInfo::DECLARE,
1602 MVT::Other, Ops, 3);
1603 }
1604 break;
1605 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 }
1607
1608 SDNode *ResNode = SelectCode(N);
1609
1610#ifndef NDEBUG
1611 DOUT << std::string(Indent-2, ' ') << "=> ";
1612 if (ResNode == NULL || ResNode == N.Val)
1613 DEBUG(N.Val->dump(CurDAG));
1614 else
1615 DEBUG(ResNode->dump(CurDAG));
1616 DOUT << "\n";
1617 Indent -= 2;
1618#endif
1619
1620 return ResNode;
1621}
1622
1623bool X86DAGToDAGISel::
1624SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1625 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1626 SDOperand Op0, Op1, Op2, Op3;
1627 switch (ConstraintCode) {
1628 case 'o': // offsetable ??
1629 case 'v': // not offsetable ??
1630 default: return true;
1631 case 'm': // memory
1632 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1633 return true;
1634 break;
1635 }
1636
1637 OutOps.push_back(Op0);
1638 OutOps.push_back(Op1);
1639 OutOps.push_back(Op2);
1640 OutOps.push_back(Op3);
1641 AddToISelQueue(Op0);
1642 AddToISelQueue(Op1);
1643 AddToISelQueue(Op2);
1644 AddToISelQueue(Op3);
1645 return false;
1646}
1647
1648/// createX86ISelDag - This pass converts a legalized DAG into a
1649/// X86-specific DAG, ready for instruction scheduling.
1650///
1651FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1652 return new X86DAGToDAGISel(TM, Fast);
1653}