blob: c8b341406ca2dd63495918bb9ea429b7083cfff3 [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"
39#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
Evan Chengd5bf2ca2008-02-19 23:36:51 +000047namespace {
48 static cl::opt<bool>
Evan Chenga4d55732008-02-20 20:57:32 +000049 AlwaysFoldAndInTest("always-fold-and-in-test",
50 cl::desc("Always fold and operation in test"),
51 cl::init(true), cl::Hidden);
Evan Chengd5bf2ca2008-02-19 23:36:51 +000052}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053
54//===----------------------------------------------------------------------===//
55// Pattern Matcher Implementation
56//===----------------------------------------------------------------------===//
57
58namespace {
59 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
60 /// SDOperand's instead of register numbers for the leaves of the matched
61 /// tree.
62 struct X86ISelAddressMode {
63 enum {
64 RegBase,
65 FrameIndexBase
66 } BaseType;
67
68 struct { // This is really a union, discriminated by BaseType!
69 SDOperand Reg;
70 int FrameIndex;
71 } Base;
72
Evan Cheng3b5a1272008-02-07 08:53:49 +000073 bool isRIPRel; // RIP as base?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 unsigned Scale;
75 SDOperand IndexReg;
76 unsigned Disp;
77 GlobalValue *GV;
78 Constant *CP;
79 const char *ES;
80 int JT;
81 unsigned Align; // CP alignment.
82
83 X86ISelAddressMode()
84 : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
85 GV(0), CP(0), ES(0), JT(-1), Align(0) {
86 }
87 };
88}
89
90namespace {
91 //===--------------------------------------------------------------------===//
92 /// ISel - X86 specific code to select X86 machine instructions for
93 /// SelectionDAG operations.
94 ///
95 class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
96 /// ContainsFPCode - Every instruction we select that uses or defines a FP
97 /// register should set this to true.
98 bool ContainsFPCode;
99
100 /// FastISel - Enable fast(er) instruction selection.
101 ///
102 bool FastISel;
103
104 /// TM - Keep a reference to X86TargetMachine.
105 ///
106 X86TargetMachine &TM;
107
108 /// X86Lowering - This object fully describes how to lower LLVM code to an
109 /// X86-specific SelectionDAG.
110 X86TargetLowering X86Lowering;
111
112 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
113 /// make the right decision when generating code for different targets.
114 const X86Subtarget *Subtarget;
115
116 /// GlobalBaseReg - keeps track of the virtual register mapped onto global
117 /// base register.
118 unsigned GlobalBaseReg;
119
120 public:
121 X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
122 : SelectionDAGISel(X86Lowering),
123 ContainsFPCode(false), FastISel(fast), TM(tm),
124 X86Lowering(*TM.getTargetLowering()),
125 Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
126
127 virtual bool runOnFunction(Function &Fn) {
128 // Make sure we re-emit a set of the global base reg if necessary
129 GlobalBaseReg = 0;
130 return SelectionDAGISel::runOnFunction(Fn);
131 }
132
133 virtual const char *getPassName() const {
134 return "X86 DAG->DAG Instruction Selection";
135 }
136
137 /// InstructionSelectBasicBlock - This callback is invoked by
138 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
139 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
140
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000141 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
142
Dan Gohmand6098272007-07-24 23:00:27 +0000143 virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144
145// Include the pieces autogenerated from the target description.
146#include "X86GenDAGISel.inc"
147
148 private:
149 SDNode *Select(SDOperand N);
150
151 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
152 bool isRoot = true, unsigned Depth = 0);
Dan Gohmana60c1b32007-08-13 20:03:06 +0000153 bool MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
154 bool isRoot, unsigned Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
156 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
157 bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
158 SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
159 bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
160 SDOperand N, SDOperand &Base, SDOperand &Scale,
161 SDOperand &Index, SDOperand &Disp,
162 SDOperand &InChain, SDOperand &OutChain);
163 bool TryFoldLoad(SDOperand P, SDOperand N,
164 SDOperand &Base, SDOperand &Scale,
165 SDOperand &Index, SDOperand &Disp);
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000166 void PreprocessForRMW(SelectionDAG &DAG);
167 void PreprocessForFPConvert(SelectionDAG &DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168
169 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
170 /// inline asm expressions.
171 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
172 char ConstraintCode,
173 std::vector<SDOperand> &OutOps,
174 SelectionDAG &DAG);
175
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000176 void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
177
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
179 SDOperand &Scale, SDOperand &Index,
180 SDOperand &Disp) {
181 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
182 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
183 AM.Base.Reg;
184 Scale = getI8Imm(AM.Scale);
185 Index = AM.IndexReg;
186 // These are 32-bit even in 64-bit mode since RIP relative offset
187 // is 32-bit.
188 if (AM.GV)
189 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
190 else if (AM.CP)
191 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
192 else if (AM.ES)
193 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
194 else if (AM.JT != -1)
195 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
196 else
197 Disp = getI32Imm(AM.Disp);
198 }
199
200 /// getI8Imm - Return a target constant with the specified value, of type
201 /// i8.
202 inline SDOperand getI8Imm(unsigned Imm) {
203 return CurDAG->getTargetConstant(Imm, MVT::i8);
204 }
205
206 /// getI16Imm - Return a target constant with the specified value, of type
207 /// i16.
208 inline SDOperand getI16Imm(unsigned Imm) {
209 return CurDAG->getTargetConstant(Imm, MVT::i16);
210 }
211
212 /// getI32Imm - Return a target constant with the specified value, of type
213 /// i32.
214 inline SDOperand getI32Imm(unsigned Imm) {
215 return CurDAG->getTargetConstant(Imm, MVT::i32);
216 }
217
218 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
219 /// base register. Return the virtual register that holds this value.
220 SDNode *getGlobalBaseReg();
221
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000222 /// getTruncate - return an SDNode that implements a subreg based truncate
223 /// of the specified operand to the the specified value type.
224 SDNode *getTruncate(SDOperand N0, MVT::ValueType VT);
225
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226#ifndef NDEBUG
227 unsigned Indent;
228#endif
229 };
230}
231
232static SDNode *findFlagUse(SDNode *N) {
233 unsigned FlagResNo = N->getNumValues()-1;
234 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
235 SDNode *User = *I;
236 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
237 SDOperand Op = User->getOperand(i);
238 if (Op.Val == N && Op.ResNo == FlagResNo)
239 return User;
240 }
241 }
242 return NULL;
243}
244
245static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
246 SDNode *Root, SDNode *Skip, bool &found,
247 std::set<SDNode *> &Visited) {
248 if (found ||
249 Use->getNodeId() > Def->getNodeId() ||
250 !Visited.insert(Use).second)
251 return;
252
253 for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
254 SDNode *N = Use->getOperand(i).Val;
255 if (N == Skip)
256 continue;
257 if (N == Def) {
258 if (Use == ImmedUse)
259 continue; // Immediate use is ok.
260 if (Use == Root) {
261 assert(Use->getOpcode() == ISD::STORE ||
262 Use->getOpcode() == X86ISD::CMP);
263 continue;
264 }
265 found = true;
266 break;
267 }
268 findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
269 }
270}
271
272/// isNonImmUse - Start searching from Root up the DAG to check is Def can
273/// be reached. Return true if that's the case. However, ignore direct uses
274/// by ImmedUse (which would be U in the example illustrated in
275/// CanBeFoldedBy) and by Root (which can happen in the store case).
276/// FIXME: to be really generic, we should allow direct use by any node
277/// that is being folded. But realisticly since we only fold loads which
278/// have one non-chain use, we only need to watch out for load/op/store
279/// and load/op/cmp case where the root (store / cmp) may reach the load via
280/// its chain operand.
281static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
282 SDNode *Skip = NULL) {
283 std::set<SDNode *> Visited;
284 bool found = false;
285 findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
286 return found;
287}
288
289
Dan Gohmand6098272007-07-24 23:00:27 +0000290bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 if (FastISel) return false;
292
293 // If U use can somehow reach N through another path then U can't fold N or
294 // it will create a cycle. e.g. In the following diagram, U can reach N
295 // through X. If N is folded into into U, then X is both a predecessor and
296 // a successor of U.
297 //
298 // [ N ]
299 // ^ ^
300 // | |
301 // / \---
302 // / [X]
303 // | ^
304 // [U]--------|
305
306 if (isNonImmUse(Root, N, U))
307 return false;
308
309 // If U produces a flag, then it gets (even more) interesting. Since it
310 // would have been "glued" together with its flag use, we need to check if
311 // it might reach N:
312 //
313 // [ N ]
314 // ^ ^
315 // | |
316 // [U] \--
317 // ^ [TF]
318 // | ^
319 // | |
320 // \ /
321 // [FU]
322 //
323 // If FU (flag use) indirectly reach N (the load), and U fold N (call it
324 // NU), then TF is a predecessor of FU and a successor of NU. But since
325 // NU and FU are flagged together, this effectively creates a cycle.
326 bool HasFlagUse = false;
327 MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
328 while ((VT == MVT::Flag && !Root->use_empty())) {
329 SDNode *FU = findFlagUse(Root);
330 if (FU == NULL)
331 break;
332 else {
333 Root = FU;
334 HasFlagUse = true;
335 }
336 VT = Root->getValueType(Root->getNumValues()-1);
337 }
338
339 if (HasFlagUse)
340 return !isNonImmUse(Root, N, Root, U);
341 return true;
342}
343
344/// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
345/// and move load below the TokenFactor. Replace store's chain operand with
346/// load's chain result.
347static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
348 SDOperand Store, SDOperand TF) {
349 std::vector<SDOperand> Ops;
350 for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
351 if (Load.Val == TF.Val->getOperand(i).Val)
352 Ops.push_back(Load.Val->getOperand(0));
353 else
354 Ops.push_back(TF.Val->getOperand(i));
355 DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
356 DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
357 DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
358 Store.getOperand(2), Store.getOperand(3));
359}
360
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000361/// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
362/// This is only run if not in -fast mode (aka -O0).
363/// This allows the instruction selector to pick more read-modify-write
364/// instructions. This is a common case:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365///
366/// [Load chain]
367/// ^
368/// |
369/// [Load]
370/// ^ ^
371/// | |
372/// / \-
373/// / |
374/// [TokenFactor] [Op]
375/// ^ ^
376/// | |
377/// \ /
378/// \ /
379/// [Store]
380///
381/// The fact the store's chain operand != load's chain will prevent the
382/// (store (op (load))) instruction from being selected. We can transform it to:
383///
384/// [Load chain]
385/// ^
386/// |
387/// [TokenFactor]
388/// ^
389/// |
390/// [Load]
391/// ^ ^
392/// | |
393/// | \-
394/// | |
395/// | [Op]
396/// | ^
397/// | |
398/// \ /
399/// \ /
400/// [Store]
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000401void X86DAGToDAGISel::PreprocessForRMW(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
403 E = DAG.allnodes_end(); I != E; ++I) {
404 if (!ISD::isNON_TRUNCStore(I))
405 continue;
406 SDOperand Chain = I->getOperand(0);
407 if (Chain.Val->getOpcode() != ISD::TokenFactor)
408 continue;
409
410 SDOperand N1 = I->getOperand(1);
411 SDOperand N2 = I->getOperand(2);
412 if (MVT::isFloatingPoint(N1.getValueType()) ||
413 MVT::isVector(N1.getValueType()) ||
414 !N1.hasOneUse())
415 continue;
416
417 bool RModW = false;
418 SDOperand Load;
419 unsigned Opcode = N1.Val->getOpcode();
420 switch (Opcode) {
421 case ISD::ADD:
422 case ISD::MUL:
423 case ISD::AND:
424 case ISD::OR:
425 case ISD::XOR:
426 case ISD::ADDC:
427 case ISD::ADDE: {
428 SDOperand N10 = N1.getOperand(0);
429 SDOperand N11 = N1.getOperand(1);
430 if (ISD::isNON_EXTLoad(N10.Val))
431 RModW = true;
432 else if (ISD::isNON_EXTLoad(N11.Val)) {
433 RModW = true;
434 std::swap(N10, N11);
435 }
436 RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
437 (N10.getOperand(1) == N2) &&
438 (N10.Val->getValueType(0) == N1.getValueType());
439 if (RModW)
440 Load = N10;
441 break;
442 }
443 case ISD::SUB:
444 case ISD::SHL:
445 case ISD::SRA:
446 case ISD::SRL:
447 case ISD::ROTL:
448 case ISD::ROTR:
449 case ISD::SUBC:
450 case ISD::SUBE:
451 case X86ISD::SHLD:
452 case X86ISD::SHRD: {
453 SDOperand N10 = N1.getOperand(0);
454 if (ISD::isNON_EXTLoad(N10.Val))
455 RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
456 (N10.getOperand(1) == N2) &&
457 (N10.Val->getValueType(0) == N1.getValueType());
458 if (RModW)
459 Load = N10;
460 break;
461 }
462 }
463
464 if (RModW) {
465 MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
466 ++NumLoadMoved;
467 }
468 }
469}
470
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000471
472/// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
473/// nodes that target the FP stack to be store and load to the stack. This is a
474/// gross hack. We would like to simply mark these as being illegal, but when
475/// we do that, legalize produces these when it expands calls, then expands
476/// these in the same legalize pass. We would like dag combine to be able to
477/// hack on these between the call expansion and the node legalization. As such
478/// this pass basically does "really late" legalization of these inline with the
479/// X86 isel pass.
480void X86DAGToDAGISel::PreprocessForFPConvert(SelectionDAG &DAG) {
481 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
482 E = DAG.allnodes_end(); I != E; ) {
483 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
484 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
485 continue;
486
487 // If the source and destination are SSE registers, then this is a legal
488 // conversion that should not be lowered.
489 MVT::ValueType SrcVT = N->getOperand(0).getValueType();
490 MVT::ValueType DstVT = N->getValueType(0);
491 bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
492 bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
493 if (SrcIsSSE && DstIsSSE)
494 continue;
495
496 // If this is an FPStack extension (but not a truncation), it is a noop.
497 if (!SrcIsSSE && !DstIsSSE && N->getOpcode() == ISD::FP_EXTEND)
498 continue;
499
500 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
501 // FPStack has extload and truncstore. SSE can fold direct loads into other
502 // operations. Based on this, decide what we want to do.
503 MVT::ValueType MemVT;
504 if (N->getOpcode() == ISD::FP_ROUND)
505 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
506 else
507 MemVT = SrcIsSSE ? SrcVT : DstVT;
508
509 SDOperand MemTmp = DAG.CreateStackTemporary(MemVT);
510
511 // FIXME: optimize the case where the src/dest is a load or store?
512 SDOperand Store = DAG.getTruncStore(DAG.getEntryNode(), N->getOperand(0),
513 MemTmp, NULL, 0, MemVT);
514 SDOperand Result = DAG.getExtLoad(ISD::EXTLOAD, DstVT, Store, MemTmp,
515 NULL, 0, MemVT);
516
517 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
518 // extload we created. This will cause general havok on the dag because
519 // anything below the conversion could be folded into other existing nodes.
520 // To avoid invalidating 'I', back it up to the convert node.
521 --I;
522 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result);
523
524 // Now that we did that, the node is dead. Increment the iterator to the
525 // next node to process, then delete N.
526 ++I;
527 DAG.DeleteNode(N);
528 }
529}
530
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531/// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
532/// when it has created a SelectionDAG for us to codegen.
533void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
534 DEBUG(BB->dump());
535 MachineFunction::iterator FirstMBB = BB;
536
537 if (!FastISel)
Chris Lattnerdec9cb52008-01-24 08:07:48 +0000538 PreprocessForRMW(DAG);
539
540 // FIXME: This should only happen when not -fast.
541 PreprocessForFPConvert(DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542
543 // Codegen the basic block.
544#ifndef NDEBUG
545 DOUT << "===== Instruction selection begins:\n";
546 Indent = 0;
547#endif
548 DAG.setRoot(SelectRoot(DAG.getRoot()));
549#ifndef NDEBUG
550 DOUT << "===== Instruction selection ends:\n";
551#endif
552
553 DAG.RemoveDeadNodes();
554
555 // Emit machine code to BB.
556 ScheduleAndEmitDAG(DAG);
557
558 // If we are emitting FP stack code, scan the basic block to determine if this
559 // block defines any FP values. If so, put an FP_REG_KILL instruction before
560 // the terminator of the block.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000561
Dale Johannesen684887e2007-09-24 22:52:39 +0000562 // Note that FP stack instructions are used in all modes for long double,
563 // so we always need to do this check.
564 // Also note that it's possible for an FP stack register to be live across
565 // an instruction that produces multiple basic blocks (SSE CMOV) so we
566 // must check all the generated basic blocks.
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000567
568 // Scan all of the machine instructions in these MBBs, checking for FP
569 // stores. (RFP32 and RFP64 will not exist in SSE mode, but RFP80 might.)
570 MachineFunction::iterator MBBI = FirstMBB;
571 do {
Dale Johannesen684887e2007-09-24 22:52:39 +0000572 bool ContainsFPCode = false;
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000573 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
574 !ContainsFPCode && I != E; ++I) {
575 if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
576 const TargetRegisterClass *clas;
577 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
578 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
Dan Gohman1e57df32008-02-10 18:45:23 +0000579 TargetRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
Chris Lattner1b989192007-12-31 04:13:23 +0000580 ((clas = RegInfo->getRegClass(I->getOperand(0).getReg())) ==
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000581 X86::RFP32RegisterClass ||
582 clas == X86::RFP64RegisterClass ||
583 clas == X86::RFP80RegisterClass)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 ContainsFPCode = true;
585 break;
586 }
587 }
588 }
589 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000590 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
591 // a copy of the input value in this block. In SSE mode, we only care about
592 // 80-bit values.
593 if (!ContainsFPCode) {
594 // Final check, check LLVM BB's that are successors to the LLVM BB
595 // corresponding to BB for FP PHI nodes.
596 const BasicBlock *LLVMBB = BB->getBasicBlock();
597 const PHINode *PN;
598 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
599 !ContainsFPCode && SI != E; ++SI) {
600 for (BasicBlock::const_iterator II = SI->begin();
601 (PN = dyn_cast<PHINode>(II)); ++II) {
602 if (PN->getType()==Type::X86_FP80Ty ||
603 (!Subtarget->hasSSE1() && PN->getType()->isFloatingPoint()) ||
604 (!Subtarget->hasSSE2() && PN->getType()==Type::DoubleTy)) {
605 ContainsFPCode = true;
606 break;
607 }
Dale Johannesenc428e0f2007-08-07 20:29:26 +0000608 }
609 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 }
Dale Johannesen684887e2007-09-24 22:52:39 +0000611 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
612 if (ContainsFPCode) {
613 BuildMI(*MBBI, MBBI->getFirstTerminator(),
614 TM.getInstrInfo()->get(X86::FP_REG_KILL));
615 ++NumFPKill;
616 }
617 } while (&*(MBBI++) != BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618}
619
Anton Korobeynikov34ef31e2007-09-25 21:52:30 +0000620/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
621/// the main function.
622void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
623 MachineFrameInfo *MFI) {
624 const TargetInstrInfo *TII = TM.getInstrInfo();
625 if (Subtarget->isTargetCygMing())
626 BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
627}
628
629void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
630 // If this is main, emit special code for main.
631 MachineBasicBlock *BB = MF.begin();
632 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
633 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
634}
635
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636/// MatchAddress - Add the specified node to the specified addressing mode,
637/// returning true if it cannot be done. This just pattern matches for the
Chris Lattner7f06edd2007-12-08 07:22:58 +0000638/// addressing mode.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
640 bool isRoot, unsigned Depth) {
Dan Gohmana60c1b32007-08-13 20:03:06 +0000641 // Limit recursion.
642 if (Depth > 5)
643 return MatchAddressBase(N, AM, isRoot, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644
645 // RIP relative addressing: %rip + 32-bit displacement!
646 if (AM.isRIPRel) {
647 if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
648 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
649 if (isInt32(AM.Disp + Val)) {
650 AM.Disp += Val;
651 return false;
652 }
653 }
654 return true;
655 }
656
657 int id = N.Val->getNodeId();
Evan Chengf2abee72007-12-13 00:43:27 +0000658 bool AlreadySelected = isSelected(id); // Already selected, not yet replaced.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659
660 switch (N.getOpcode()) {
661 default: break;
662 case ISD::Constant: {
663 int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
664 if (isInt32(AM.Disp + Val)) {
665 AM.Disp += Val;
666 return false;
667 }
668 break;
669 }
670
671 case X86ISD::Wrapper: {
672 bool is64Bit = Subtarget->is64Bit();
673 // Under X86-64 non-small code model, GV (and friends) are 64-bits.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000674 // Also, base and index reg must be 0 in order to use rip as base.
675 if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
676 AM.Base.Reg.Val || AM.IndexReg.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 break;
678 if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
679 break;
680 // If value is available in a register both base and index components have
681 // been picked, we can't fit the result available in the register in the
682 // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
Evan Chengf2abee72007-12-13 00:43:27 +0000683 if (!AlreadySelected || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 SDOperand N0 = N.getOperand(0);
685 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
686 GlobalValue *GV = G->getGlobal();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000687 AM.GV = GV;
688 AM.Disp += G->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000689 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
690 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000691 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000693 AM.CP = CP->getConstVal();
694 AM.Align = CP->getAlignment();
695 AM.Disp += CP->getOffset();
Evan Chenga54e14f2008-02-12 19:20:46 +0000696 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
697 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000698 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000700 AM.ES = S->getSymbol();
Evan Chenga54e14f2008-02-12 19:20:46 +0000701 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
702 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000703 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Evan Cheng3b5a1272008-02-07 08:53:49 +0000705 AM.JT = J->getIndex();
Evan Chenga54e14f2008-02-12 19:20:46 +0000706 AM.isRIPRel = TM.getRelocationModel() != Reloc::Static &&
707 Subtarget->isPICStyleRIPRel();
Evan Cheng3b5a1272008-02-07 08:53:49 +0000708 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 }
710 }
711 break;
712 }
713
714 case ISD::FrameIndex:
715 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
716 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
717 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
718 return false;
719 }
720 break;
721
722 case ISD::SHL:
Evan Cheng3b5a1272008-02-07 08:53:49 +0000723 if (AlreadySelected || AM.IndexReg.Val != 0 || AM.Scale != 1 || AM.isRIPRel)
Chris Lattner7f06edd2007-12-08 07:22:58 +0000724 break;
725
726 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
727 unsigned Val = CN->getValue();
728 if (Val == 1 || Val == 2 || Val == 3) {
729 AM.Scale = 1 << Val;
730 SDOperand ShVal = N.Val->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731
Chris Lattner7f06edd2007-12-08 07:22:58 +0000732 // Okay, we know that we have a scale by now. However, if the scaled
733 // value is an add of something and a constant, we can fold the
734 // constant into the disp field here.
735 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
736 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
737 AM.IndexReg = ShVal.Val->getOperand(0);
738 ConstantSDNode *AddVal =
739 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
740 uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
741 if (isInt32(Disp))
742 AM.Disp = Disp;
743 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744 AM.IndexReg = ShVal;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000745 } else {
746 AM.IndexReg = ShVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000748 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 }
750 break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000751 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752
Dan Gohman35b99222007-10-22 20:22:24 +0000753 case ISD::SMUL_LOHI:
754 case ISD::UMUL_LOHI:
755 // A mul_lohi where we need the low part can be folded as a plain multiply.
756 if (N.ResNo != 0) break;
757 // FALL THROUGH
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 case ISD::MUL:
759 // X*[3,5,9] -> X+X*[2,4,8]
Evan Chengf2abee72007-12-13 00:43:27 +0000760 if (!AlreadySelected &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 AM.BaseType == X86ISelAddressMode::RegBase &&
762 AM.Base.Reg.Val == 0 &&
Evan Cheng3b5a1272008-02-07 08:53:49 +0000763 AM.IndexReg.Val == 0 &&
764 !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
766 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
767 AM.Scale = unsigned(CN->getValue())-1;
768
769 SDOperand MulVal = N.Val->getOperand(0);
770 SDOperand Reg;
771
772 // Okay, we know that we have a scale by now. However, if the scaled
773 // value is an add of something and a constant, we can fold the
774 // constant into the disp field here.
775 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
776 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
777 Reg = MulVal.Val->getOperand(0);
778 ConstantSDNode *AddVal =
779 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
780 uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
781 if (isInt32(Disp))
782 AM.Disp = Disp;
783 else
784 Reg = N.Val->getOperand(0);
785 } else {
786 Reg = N.Val->getOperand(0);
787 }
788
789 AM.IndexReg = AM.Base.Reg = Reg;
790 return false;
791 }
792 }
793 break;
794
795 case ISD::ADD:
Evan Chengf2abee72007-12-13 00:43:27 +0000796 if (!AlreadySelected) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 X86ISelAddressMode Backup = AM;
798 if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
799 !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
800 return false;
801 AM = Backup;
802 if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
803 !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
804 return false;
805 AM = Backup;
806 }
807 break;
808
809 case ISD::OR:
810 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Evan Chengf2abee72007-12-13 00:43:27 +0000811 if (AlreadySelected) break;
Chris Lattner7f06edd2007-12-08 07:22:58 +0000812
813 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
814 X86ISelAddressMode Backup = AM;
815 // Start with the LHS as an addr mode.
816 if (!MatchAddress(N.getOperand(0), AM, false) &&
817 // Address could not have picked a GV address for the displacement.
818 AM.GV == NULL &&
819 // On x86-64, the resultant disp must fit in 32-bits.
820 isInt32(AM.Disp + CN->getSignExtended()) &&
821 // Check to see if the LHS & C is zero.
Dan Gohman07961cd2008-02-25 21:11:39 +0000822 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
Chris Lattner7f06edd2007-12-08 07:22:58 +0000823 AM.Disp += CN->getValue();
824 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
Chris Lattner7f06edd2007-12-08 07:22:58 +0000826 AM = Backup;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
828 break;
Evan Chengf2abee72007-12-13 00:43:27 +0000829
830 case ISD::AND: {
831 // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
832 // allows us to fold the shift into this addressing mode.
833 if (AlreadySelected) break;
834 SDOperand Shift = N.getOperand(0);
835 if (Shift.getOpcode() != ISD::SHL) break;
836
837 // Scale must not be used already.
838 if (AM.IndexReg.Val != 0 || AM.Scale != 1) break;
Evan Cheng3b5a1272008-02-07 08:53:49 +0000839
840 // Not when RIP is used as the base.
841 if (AM.isRIPRel) break;
Evan Chengf2abee72007-12-13 00:43:27 +0000842
843 ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
844 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
845 if (!C1 || !C2) break;
846
847 // Not likely to be profitable if either the AND or SHIFT node has more
848 // than one use (unless all uses are for address computation). Besides,
849 // isel mechanism requires their node ids to be reused.
850 if (!N.hasOneUse() || !Shift.hasOneUse())
851 break;
852
853 // Verify that the shift amount is something we can fold.
854 unsigned ShiftCst = C1->getValue();
855 if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
856 break;
857
858 // Get the new AND mask, this folds to a constant.
859 SDOperand NewANDMask = CurDAG->getNode(ISD::SRL, N.getValueType(),
860 SDOperand(C2, 0), SDOperand(C1, 0));
861 SDOperand NewAND = CurDAG->getNode(ISD::AND, N.getValueType(),
862 Shift.getOperand(0), NewANDMask);
863 NewANDMask.Val->setNodeId(Shift.Val->getNodeId());
864 NewAND.Val->setNodeId(N.Val->getNodeId());
865
866 AM.Scale = 1 << ShiftCst;
867 AM.IndexReg = NewAND;
868 return false;
869 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 }
871
Dan Gohmana60c1b32007-08-13 20:03:06 +0000872 return MatchAddressBase(N, AM, isRoot, Depth);
873}
874
875/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
876/// specified addressing mode without any further recursion.
877bool X86DAGToDAGISel::MatchAddressBase(SDOperand N, X86ISelAddressMode &AM,
878 bool isRoot, unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 // Is the base register already occupied?
880 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
881 // If so, check to see if the scale index register is set.
Evan Cheng3b5a1272008-02-07 08:53:49 +0000882 if (AM.IndexReg.Val == 0 && !AM.isRIPRel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883 AM.IndexReg = N;
884 AM.Scale = 1;
885 return false;
886 }
887
888 // Otherwise, we cannot select it.
889 return true;
890 }
891
892 // Default, generate it as a register.
893 AM.BaseType = X86ISelAddressMode::RegBase;
894 AM.Base.Reg = N;
895 return false;
896}
897
898/// SelectAddr - returns true if it is able pattern match an addressing mode.
899/// It returns the operands which make up the maximal addressing mode it can
900/// match by reference.
901bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
902 SDOperand &Scale, SDOperand &Index,
903 SDOperand &Disp) {
904 X86ISelAddressMode AM;
905 if (MatchAddress(N, AM))
906 return false;
907
908 MVT::ValueType VT = N.getValueType();
909 if (AM.BaseType == X86ISelAddressMode::RegBase) {
910 if (!AM.Base.Reg.Val)
911 AM.Base.Reg = CurDAG->getRegister(0, VT);
912 }
913
914 if (!AM.IndexReg.Val)
915 AM.IndexReg = CurDAG->getRegister(0, VT);
916
917 getAddressOperands(AM, Base, Scale, Index, Disp);
918 return true;
919}
920
921/// isZeroNode - Returns true if Elt is a constant zero or a floating point
922/// constant +0.0.
923static inline bool isZeroNode(SDOperand Elt) {
924 return ((isa<ConstantSDNode>(Elt) &&
925 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
926 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +0000927 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928}
929
930
931/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
932/// match a load whose top elements are either undef or zeros. The load flavor
933/// is derived from the type of N, which is either v4f32 or v2f64.
934bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
935 SDOperand N, SDOperand &Base,
936 SDOperand &Scale, SDOperand &Index,
937 SDOperand &Disp, SDOperand &InChain,
938 SDOperand &OutChain) {
939 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
940 InChain = N.getOperand(0).getValue(1);
941 if (ISD::isNON_EXTLoad(InChain.Val) &&
942 InChain.getValue(0).hasOneUse() &&
943 N.hasOneUse() &&
944 CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
945 LoadSDNode *LD = cast<LoadSDNode>(InChain);
946 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
947 return false;
948 OutChain = LD->getChain();
949 return true;
950 }
951 }
952
953 // Also handle the case where we explicitly require zeros in the top
954 // elements. This is a vector shuffle from the zero vector.
955 if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
Chris Lattnere6aa3862007-11-25 00:24:49 +0000956 // Check to see if the top elements are all zeros (or bitcast of zeros).
957 ISD::isBuildVectorAllZeros(N.getOperand(0).Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR &&
959 N.getOperand(1).Val->hasOneUse() &&
960 ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
961 N.getOperand(1).getOperand(0).hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
963 // from the LHS.
Chris Lattnere6aa3862007-11-25 00:24:49 +0000964 unsigned VecWidth=MVT::getVectorNumElements(N.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 SDOperand ShufMask = N.getOperand(2);
966 assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
967 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
968 if (C->getValue() == VecWidth) {
969 for (unsigned i = 1; i != VecWidth; ++i) {
970 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
971 // ok.
972 } else {
973 ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
974 if (C->getValue() >= VecWidth) return false;
975 }
976 }
977 }
978
979 // Okay, this is a zero extending load. Fold it.
980 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
981 if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
982 return false;
983 OutChain = LD->getChain();
984 InChain = SDOperand(LD, 1);
985 return true;
986 }
987 }
988 return false;
989}
990
991
992/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
993/// mode it matches can be cost effectively emitted as an LEA instruction.
994bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
995 SDOperand &Base, SDOperand &Scale,
996 SDOperand &Index, SDOperand &Disp) {
997 X86ISelAddressMode AM;
998 if (MatchAddress(N, AM))
999 return false;
1000
1001 MVT::ValueType VT = N.getValueType();
1002 unsigned Complexity = 0;
1003 if (AM.BaseType == X86ISelAddressMode::RegBase)
1004 if (AM.Base.Reg.Val)
1005 Complexity = 1;
1006 else
1007 AM.Base.Reg = CurDAG->getRegister(0, VT);
1008 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1009 Complexity = 4;
1010
1011 if (AM.IndexReg.Val)
1012 Complexity++;
1013 else
1014 AM.IndexReg = CurDAG->getRegister(0, VT);
1015
1016 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1017 // a simple shift.
1018 if (AM.Scale > 1)
1019 Complexity++;
1020
1021 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1022 // to a LEA. This is determined with some expermentation but is by no means
1023 // optimal (especially for code size consideration). LEA is nice because of
1024 // its three-address nature. Tweak the cost function again when we can run
1025 // convertToThreeAddress() at register allocation time.
1026 if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
1027 // For X86-64, we should always use lea to materialize RIP relative
1028 // addresses.
1029 if (Subtarget->is64Bit())
1030 Complexity = 4;
1031 else
1032 Complexity += 2;
1033 }
1034
1035 if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
1036 Complexity++;
1037
1038 if (Complexity > 2) {
1039 getAddressOperands(AM, Base, Scale, Index, Disp);
1040 return true;
1041 }
1042 return false;
1043}
1044
1045bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
1046 SDOperand &Base, SDOperand &Scale,
1047 SDOperand &Index, SDOperand &Disp) {
1048 if (ISD::isNON_EXTLoad(N.Val) &&
1049 N.hasOneUse() &&
1050 CanBeFoldedBy(N.Val, P.Val, P.Val))
1051 return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
1052 return false;
1053}
1054
1055/// getGlobalBaseReg - Output the instructions required to put the
1056/// base address to use for accessing globals into a register.
1057///
1058SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1059 assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
1060 if (!GlobalBaseReg) {
1061 // Insert the set of GlobalBaseReg into the first MBB of the function
Evan Cheng0729ccf2008-01-05 00:41:47 +00001062 MachineFunction *MF = BB->getParent();
1063 MachineBasicBlock &FirstMBB = MF->front();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Evan Cheng0729ccf2008-01-05 00:41:47 +00001065 MachineRegisterInfo &RegInfo = MF->getRegInfo();
Chris Lattner1b989192007-12-31 04:13:23 +00001066 unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067
1068 const TargetInstrInfo *TII = TM.getInstrInfo();
Evan Cheng34f93712007-12-22 02:26:46 +00001069 // Operand of MovePCtoStack is completely ignored by asm printer. It's
1070 // only used in JIT code emission as displacement to pc.
Evan Cheng0729ccf2008-01-05 00:41:47 +00001071 BuildMI(FirstMBB, MBBI, TII->get(X86::MOVPC32r), PC).addImm(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072
1073 // If we're using vanilla 'GOT' PIC style, we should use relative addressing
1074 // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
1075 if (TM.getRelocationModel() == Reloc::PIC_ &&
1076 Subtarget->isPICStyleGOT()) {
Chris Lattner1b989192007-12-31 04:13:23 +00001077 GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
Evan Cheng0729ccf2008-01-05 00:41:47 +00001078 BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg)
1079 .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 } else {
1081 GlobalBaseReg = PC;
1082 }
1083
1084 }
1085 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
1086}
1087
1088static SDNode *FindCallStartFromCall(SDNode *Node) {
1089 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1090 assert(Node->getOperand(0).getValueType() == MVT::Other &&
1091 "Node doesn't have a token chain argument!");
1092 return FindCallStartFromCall(Node->getOperand(0).Val);
1093}
1094
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001095SDNode *X86DAGToDAGISel::getTruncate(SDOperand N0, MVT::ValueType VT) {
1096 SDOperand SRIdx;
1097 switch (VT) {
1098 case MVT::i8:
1099 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1100 // Ensure that the source register has an 8-bit subreg on 32-bit targets
1101 if (!Subtarget->is64Bit()) {
1102 unsigned Opc;
1103 MVT::ValueType VT;
1104 switch (N0.getValueType()) {
1105 default: assert(0 && "Unknown truncate!");
1106 case MVT::i16:
1107 Opc = X86::MOV16to16_;
1108 VT = MVT::i16;
1109 break;
1110 case MVT::i32:
1111 Opc = X86::MOV32to32_;
1112 VT = MVT::i32;
1113 break;
1114 }
Evan Chenge1f39552007-10-12 07:55:53 +00001115 N0 = SDOperand(CurDAG->getTargetNode(Opc, VT, MVT::Flag, N0), 0);
1116 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1117 VT, N0, SRIdx, N0.getValue(1));
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001118 }
1119 break;
1120 case MVT::i16:
1121 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1122 break;
1123 case MVT::i32:
1124 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1125 break;
Evan Chenge1f39552007-10-12 07:55:53 +00001126 default: assert(0 && "Unknown truncate!"); break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001127 }
Evan Chenge1f39552007-10-12 07:55:53 +00001128 return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, VT, N0, SRIdx);
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001129}
1130
1131
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132SDNode *X86DAGToDAGISel::Select(SDOperand N) {
1133 SDNode *Node = N.Val;
1134 MVT::ValueType NVT = Node->getValueType(0);
1135 unsigned Opc, MOpc;
1136 unsigned Opcode = Node->getOpcode();
1137
1138#ifndef NDEBUG
1139 DOUT << std::string(Indent, ' ') << "Selecting: ";
1140 DEBUG(Node->dump(CurDAG));
1141 DOUT << "\n";
1142 Indent += 2;
1143#endif
1144
1145 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
1146#ifndef NDEBUG
1147 DOUT << std::string(Indent-2, ' ') << "== ";
1148 DEBUG(Node->dump(CurDAG));
1149 DOUT << "\n";
1150 Indent -= 2;
1151#endif
1152 return NULL; // Already selected.
1153 }
1154
1155 switch (Opcode) {
1156 default: break;
1157 case X86ISD::GlobalBaseReg:
1158 return getGlobalBaseReg();
1159
Evan Cheng931a8f42008-01-29 19:34:22 +00001160 case X86ISD::FP_GET_RESULT2: {
1161 SDOperand Chain = N.getOperand(0);
1162 SDOperand InFlag = N.getOperand(1);
1163 AddToISelQueue(Chain);
1164 AddToISelQueue(InFlag);
1165 std::vector<MVT::ValueType> Tys;
1166 Tys.push_back(MVT::f80);
1167 Tys.push_back(MVT::f80);
1168 Tys.push_back(MVT::Other);
1169 Tys.push_back(MVT::Flag);
1170 SDOperand Ops[] = { Chain, InFlag };
1171 SDNode *ResNode = CurDAG->getTargetNode(X86::FpGETRESULT80x2, Tys,
1172 Ops, 2);
1173 Chain = SDOperand(ResNode, 2);
1174 InFlag = SDOperand(ResNode, 3);
1175 ReplaceUses(SDOperand(N.Val, 2), Chain);
1176 ReplaceUses(SDOperand(N.Val, 3), InFlag);
1177 return ResNode;
1178 }
1179
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 case ISD::ADD: {
1181 // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1182 // code and is matched first so to prevent it from being turned into
1183 // LEA32r X+c.
Evan Cheng17e39d62008-01-08 02:06:11 +00001184 // In 64-bit small code size mode, use LEA to take advantage of
1185 // RIP-relative addressing.
1186 if (TM.getCodeModel() != CodeModel::Small)
1187 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 MVT::ValueType PtrVT = TLI.getPointerTy();
1189 SDOperand N0 = N.getOperand(0);
1190 SDOperand N1 = N.getOperand(1);
1191 if (N.Val->getValueType(0) == PtrVT &&
1192 N0.getOpcode() == X86ISD::Wrapper &&
1193 N1.getOpcode() == ISD::Constant) {
1194 unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1195 SDOperand C(0, 0);
1196 // TODO: handle ExternalSymbolSDNode.
1197 if (GlobalAddressSDNode *G =
1198 dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1199 C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1200 G->getOffset() + Offset);
1201 } else if (ConstantPoolSDNode *CP =
1202 dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1203 C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1204 CP->getAlignment(),
1205 CP->getOffset()+Offset);
1206 }
1207
1208 if (C.Val) {
1209 if (Subtarget->is64Bit()) {
1210 SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1211 CurDAG->getRegister(0, PtrVT), C };
1212 return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1213 } else
1214 return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1215 }
1216 }
1217
1218 // Other cases are handled by auto-generated code.
1219 break;
1220 }
1221
Dan Gohman5a199552007-10-08 18:33:35 +00001222 case ISD::SMUL_LOHI:
1223 case ISD::UMUL_LOHI: {
1224 SDOperand N0 = Node->getOperand(0);
1225 SDOperand N1 = Node->getOperand(1);
1226
Dan Gohmana5685ba2007-10-09 15:44:37 +00001227 // There are several forms of IMUL that just return the low part and
1228 // don't have fixed-register operands. If we don't need the high part,
1229 // use these instead. They can be selected with the generated ISel code.
Dan Gohman5a199552007-10-08 18:33:35 +00001230 if (NVT != MVT::i8 &&
1231 N.getValue(1).use_empty()) {
1232 N = CurDAG->getNode(ISD::MUL, NVT, N0, N1);
1233 break;
1234 }
1235
1236 bool isSigned = Opcode == ISD::SMUL_LOHI;
1237 if (!isSigned)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 switch (NVT) {
1239 default: assert(0 && "Unsupported VT!");
1240 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
1241 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1242 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1243 case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1244 }
1245 else
1246 switch (NVT) {
1247 default: assert(0 && "Unsupported VT!");
1248 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
1249 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1250 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1251 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1252 }
1253
1254 unsigned LoReg, HiReg;
1255 switch (NVT) {
1256 default: assert(0 && "Unsupported VT!");
1257 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
1258 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
1259 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1260 case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1261 }
1262
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
Evan Cheng508fe8b2007-08-02 05:48:35 +00001264 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001265 // multiplty is commmutative
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 if (!foldedLoad) {
1267 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
Evan Cheng508fe8b2007-08-02 05:48:35 +00001268 if (foldedLoad)
1269 std::swap(N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 }
1271
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 AddToISelQueue(N0);
Dan Gohman5a199552007-10-08 18:33:35 +00001273 SDOperand InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg,
1274 N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275
1276 if (foldedLoad) {
Dan Gohman5a199552007-10-08 18:33:35 +00001277 AddToISelQueue(N1.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 AddToISelQueue(Tmp0);
1279 AddToISelQueue(Tmp1);
1280 AddToISelQueue(Tmp2);
1281 AddToISelQueue(Tmp3);
Dan Gohman5a199552007-10-08 18:33:35 +00001282 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 SDNode *CNode =
1284 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001286 // Update the chain.
1287 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 } else {
1289 AddToISelQueue(N1);
1290 InFlag =
1291 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1292 }
1293
Dan Gohman5a199552007-10-08 18:33:35 +00001294 // Copy the low half of the result, if it is needed.
1295 if (!N.getValue(0).use_empty()) {
1296 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1297 LoReg, NVT, InFlag);
1298 InFlag = Result.getValue(2);
1299 ReplaceUses(N.getValue(0), Result);
1300#ifndef NDEBUG
1301 DOUT << std::string(Indent-2, ' ') << "=> ";
1302 DEBUG(Result.Val->dump(CurDAG));
1303 DOUT << "\n";
1304#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001305 }
Dan Gohman5a199552007-10-08 18:33:35 +00001306 // Copy the high half of the result, if it is needed.
1307 if (!N.getValue(1).use_empty()) {
1308 SDOperand Result;
1309 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1310 // Prevent use of AH in a REX instruction by referencing AX instead.
1311 // Shift it down 8 bits.
1312 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1313 X86::AX, MVT::i16, InFlag);
1314 InFlag = Result.getValue(2);
1315 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1316 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1317 // Then truncate it down to i8.
1318 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1319 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1320 MVT::i8, Result, SRIdx), 0);
1321 } else {
1322 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1323 HiReg, NVT, InFlag);
1324 InFlag = Result.getValue(2);
1325 }
1326 ReplaceUses(N.getValue(1), Result);
1327#ifndef NDEBUG
1328 DOUT << std::string(Indent-2, ' ') << "=> ";
1329 DEBUG(Result.Val->dump(CurDAG));
1330 DOUT << "\n";
1331#endif
1332 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333
1334#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 Indent -= 2;
1336#endif
Dan Gohman5a199552007-10-08 18:33:35 +00001337
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 return NULL;
1339 }
1340
Dan Gohman5a199552007-10-08 18:33:35 +00001341 case ISD::SDIVREM:
1342 case ISD::UDIVREM: {
1343 SDOperand N0 = Node->getOperand(0);
1344 SDOperand N1 = Node->getOperand(1);
1345
1346 bool isSigned = Opcode == ISD::SDIVREM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 if (!isSigned)
1348 switch (NVT) {
1349 default: assert(0 && "Unsupported VT!");
1350 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
1351 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1352 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1353 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1354 }
1355 else
1356 switch (NVT) {
1357 default: assert(0 && "Unsupported VT!");
1358 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
1359 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1360 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1361 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1362 }
1363
1364 unsigned LoReg, HiReg;
1365 unsigned ClrOpcode, SExtOpcode;
1366 switch (NVT) {
1367 default: assert(0 && "Unsupported VT!");
1368 case MVT::i8:
1369 LoReg = X86::AL; HiReg = X86::AH;
1370 ClrOpcode = 0;
1371 SExtOpcode = X86::CBW;
1372 break;
1373 case MVT::i16:
1374 LoReg = X86::AX; HiReg = X86::DX;
1375 ClrOpcode = X86::MOV16r0;
1376 SExtOpcode = X86::CWD;
1377 break;
1378 case MVT::i32:
1379 LoReg = X86::EAX; HiReg = X86::EDX;
1380 ClrOpcode = X86::MOV32r0;
1381 SExtOpcode = X86::CDQ;
1382 break;
1383 case MVT::i64:
1384 LoReg = X86::RAX; HiReg = X86::RDX;
1385 ClrOpcode = X86::MOV64r0;
1386 SExtOpcode = X86::CQO;
1387 break;
1388 }
1389
Dan Gohman5a199552007-10-08 18:33:35 +00001390 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1391 bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1392
1393 SDOperand InFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 if (NVT == MVT::i8 && !isSigned) {
1395 // Special case for div8, just use a move with zero extension to AX to
1396 // clear the upper 8 bits (AH).
1397 SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1398 if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1399 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1400 AddToISelQueue(N0.getOperand(0));
1401 AddToISelQueue(Tmp0);
1402 AddToISelQueue(Tmp1);
1403 AddToISelQueue(Tmp2);
1404 AddToISelQueue(Tmp3);
1405 Move =
1406 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1407 Ops, 5), 0);
1408 Chain = Move.getValue(1);
1409 ReplaceUses(N0.getValue(1), Chain);
1410 } else {
1411 AddToISelQueue(N0);
1412 Move =
1413 SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1414 Chain = CurDAG->getEntryNode();
1415 }
Dan Gohman5a199552007-10-08 18:33:35 +00001416 Chain = CurDAG->getCopyToReg(Chain, X86::AX, Move, SDOperand());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 InFlag = Chain.getValue(1);
1418 } else {
1419 AddToISelQueue(N0);
1420 InFlag =
Dan Gohman5a199552007-10-08 18:33:35 +00001421 CurDAG->getCopyToReg(CurDAG->getEntryNode(),
1422 LoReg, N0, SDOperand()).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 if (isSigned) {
1424 // Sign extend the low part into the high part.
1425 InFlag =
1426 SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1427 } else {
1428 // Zero out the high part, effectively zero extending the input.
1429 SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
Dan Gohman5a199552007-10-08 18:33:35 +00001430 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg,
1431 ClrNode, InFlag).getValue(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 }
1433 }
1434
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435 if (foldedLoad) {
1436 AddToISelQueue(N1.getOperand(0));
1437 AddToISelQueue(Tmp0);
1438 AddToISelQueue(Tmp1);
1439 AddToISelQueue(Tmp2);
1440 AddToISelQueue(Tmp3);
1441 SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1442 SDNode *CNode =
1443 CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444 InFlag = SDOperand(CNode, 1);
Dan Gohman5a199552007-10-08 18:33:35 +00001445 // Update the chain.
1446 ReplaceUses(N1.getValue(1), SDOperand(CNode, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 } else {
1448 AddToISelQueue(N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 InFlag =
1450 SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1451 }
1452
Dan Gohman242a5ba2007-09-25 18:23:27 +00001453 // Copy the division (low) result, if it is needed.
1454 if (!N.getValue(0).use_empty()) {
Dan Gohman5a199552007-10-08 18:33:35 +00001455 SDOperand Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1456 LoReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001457 InFlag = Result.getValue(2);
1458 ReplaceUses(N.getValue(0), Result);
1459#ifndef NDEBUG
1460 DOUT << std::string(Indent-2, ' ') << "=> ";
1461 DEBUG(Result.Val->dump(CurDAG));
1462 DOUT << "\n";
1463#endif
Evan Cheng6f0f0dd2007-08-09 21:59:35 +00001464 }
Dan Gohman242a5ba2007-09-25 18:23:27 +00001465 // Copy the remainder (high) result, if it is needed.
1466 if (!N.getValue(1).use_empty()) {
1467 SDOperand Result;
1468 if (HiReg == X86::AH && Subtarget->is64Bit()) {
1469 // Prevent use of AH in a REX instruction by referencing AX instead.
1470 // Shift it down 8 bits.
Dan Gohman5a199552007-10-08 18:33:35 +00001471 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1472 X86::AX, MVT::i16, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001473 InFlag = Result.getValue(2);
1474 Result = SDOperand(CurDAG->getTargetNode(X86::SHR16ri, MVT::i16, Result,
1475 CurDAG->getTargetConstant(8, MVT::i8)), 0);
1476 // Then truncate it down to i8.
1477 SDOperand SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1478 Result = SDOperand(CurDAG->getTargetNode(X86::EXTRACT_SUBREG,
1479 MVT::i8, Result, SRIdx), 0);
1480 } else {
Dan Gohman5a199552007-10-08 18:33:35 +00001481 Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
1482 HiReg, NVT, InFlag);
Dan Gohman242a5ba2007-09-25 18:23:27 +00001483 InFlag = Result.getValue(2);
1484 }
1485 ReplaceUses(N.getValue(1), Result);
1486#ifndef NDEBUG
1487 DOUT << std::string(Indent-2, ' ') << "=> ";
1488 DEBUG(Result.Val->dump(CurDAG));
1489 DOUT << "\n";
1490#endif
1491 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492
1493#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 Indent -= 2;
1495#endif
1496
1497 return NULL;
1498 }
Christopher Lamb422213d2007-08-10 22:22:41 +00001499
1500 case ISD::ANY_EXTEND: {
1501 SDOperand N0 = Node->getOperand(0);
1502 AddToISelQueue(N0);
1503 if (NVT == MVT::i64 || NVT == MVT::i32 || NVT == MVT::i16) {
1504 SDOperand SRIdx;
1505 switch(N0.getValueType()) {
1506 case MVT::i32:
1507 SRIdx = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1508 break;
1509 case MVT::i16:
1510 SRIdx = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1511 break;
1512 case MVT::i8:
1513 if (Subtarget->is64Bit())
1514 SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1515 break;
1516 default: assert(0 && "Unknown any_extend!");
1517 }
1518 if (SRIdx.Val) {
Evan Chenge1f39552007-10-12 07:55:53 +00001519 SDNode *ResNode = CurDAG->getTargetNode(X86::INSERT_SUBREG,
1520 NVT, N0, SRIdx);
Christopher Lamb422213d2007-08-10 22:22:41 +00001521
1522#ifndef NDEBUG
1523 DOUT << std::string(Indent-2, ' ') << "=> ";
1524 DEBUG(ResNode->dump(CurDAG));
1525 DOUT << "\n";
1526 Indent -= 2;
1527#endif
1528 return ResNode;
1529 } // Otherwise let generated ISel handle it.
1530 }
1531 break;
1532 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001533
1534 case ISD::SIGN_EXTEND_INREG: {
1535 SDOperand N0 = Node->getOperand(0);
1536 AddToISelQueue(N0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001538 MVT::ValueType SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1539 SDOperand TruncOp = SDOperand(getTruncate(N0, SVT), 0);
Bill Wendling79bb1a22007-11-01 08:51:44 +00001540 unsigned Opc = 0;
Christopher Lamb444336c2007-07-29 01:24:57 +00001541 switch (NVT) {
Christopher Lamb444336c2007-07-29 01:24:57 +00001542 case MVT::i16:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001543 if (SVT == MVT::i8) Opc = X86::MOVSX16rr8;
1544 else assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001545 break;
1546 case MVT::i32:
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001547 switch (SVT) {
1548 case MVT::i8: Opc = X86::MOVSX32rr8; break;
1549 case MVT::i16: Opc = X86::MOVSX32rr16; break;
1550 default: assert(0 && "Unknown sign_extend_inreg!");
1551 }
Christopher Lamb444336c2007-07-29 01:24:57 +00001552 break;
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001553 case MVT::i64:
1554 switch (SVT) {
1555 case MVT::i8: Opc = X86::MOVSX64rr8; break;
1556 case MVT::i16: Opc = X86::MOVSX64rr16; break;
1557 case MVT::i32: Opc = X86::MOVSX64rr32; break;
1558 default: assert(0 && "Unknown sign_extend_inreg!");
1559 }
1560 break;
1561 default: assert(0 && "Unknown sign_extend_inreg!");
Christopher Lamb444336c2007-07-29 01:24:57 +00001562 }
Christopher Lamb0a7c8662007-08-10 21:48:46 +00001563
1564 SDNode *ResNode = CurDAG->getTargetNode(Opc, NVT, TruncOp);
1565
1566#ifndef NDEBUG
1567 DOUT << std::string(Indent-2, ' ') << "=> ";
1568 DEBUG(TruncOp.Val->dump(CurDAG));
1569 DOUT << "\n";
1570 DOUT << std::string(Indent-2, ' ') << "=> ";
1571 DEBUG(ResNode->dump(CurDAG));
1572 DOUT << "\n";
1573 Indent -= 2;
1574#endif
1575 return ResNode;
1576 break;
1577 }
1578
1579 case ISD::TRUNCATE: {
1580 SDOperand Input = Node->getOperand(0);
1581 AddToISelQueue(Node->getOperand(0));
1582 SDNode *ResNode = getTruncate(Input, NVT);
1583
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584#ifndef NDEBUG
1585 DOUT << std::string(Indent-2, ' ') << "=> ";
1586 DEBUG(ResNode->dump(CurDAG));
1587 DOUT << "\n";
1588 Indent -= 2;
1589#endif
Christopher Lamb444336c2007-07-29 01:24:57 +00001590 return ResNode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 break;
1592 }
1593 }
1594
1595 SDNode *ResNode = SelectCode(N);
1596
1597#ifndef NDEBUG
1598 DOUT << std::string(Indent-2, ' ') << "=> ";
1599 if (ResNode == NULL || ResNode == N.Val)
1600 DEBUG(N.Val->dump(CurDAG));
1601 else
1602 DEBUG(ResNode->dump(CurDAG));
1603 DOUT << "\n";
1604 Indent -= 2;
1605#endif
1606
1607 return ResNode;
1608}
1609
1610bool X86DAGToDAGISel::
1611SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1612 std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1613 SDOperand Op0, Op1, Op2, Op3;
1614 switch (ConstraintCode) {
1615 case 'o': // offsetable ??
1616 case 'v': // not offsetable ??
1617 default: return true;
1618 case 'm': // memory
1619 if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1620 return true;
1621 break;
1622 }
1623
1624 OutOps.push_back(Op0);
1625 OutOps.push_back(Op1);
1626 OutOps.push_back(Op2);
1627 OutOps.push_back(Op3);
1628 AddToISelQueue(Op0);
1629 AddToISelQueue(Op1);
1630 AddToISelQueue(Op2);
1631 AddToISelQueue(Op3);
1632 return false;
1633}
1634
1635/// createX86ISelDag - This pass converts a legalized DAG into a
1636/// X86-specific DAG, ready for instruction scheduling.
1637///
1638FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1639 return new X86DAGToDAGISel(TM, Fast);
1640}