blob: 6b23e62a2d359fe5877e79756d20f3cb4aaccdcf [file] [log] [blame]
Chris Lattner5930d3d2005-11-16 22:59:19 +00001//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
Chris Lattner655e7df2005-11-16 01:54:32 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner655e7df2005-11-16 01:54:32 +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#include "X86.h"
Evan Chengbc7a0f442006-01-11 06:09:51 +000016#include "X86InstrBuilder.h"
Evan Chengf55b7382008-01-05 00:41:47 +000017#include "X86MachineFunctionInfo.h"
Chris Lattner7c551262006-01-11 01:15:34 +000018#include "X86RegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000019#include "X86Subtarget.h"
Evan Cheng2dd2c652006-03-13 23:20:37 +000020#include "X86TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Statistic.h"
Evan Cheng73a1ad92006-01-10 20:26:56 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner7c551262006-01-11 01:15:34 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000026#include "llvm/CodeGen/SelectionDAGISel.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000027#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000031#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000032#include "llvm/Support/ErrorHandling.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000033#include "llvm/Support/MathExtras.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Robin Morisset880580b2014-10-07 23:53:57 +000037#include <stdint.h>
Chris Lattner655e7df2005-11-16 01:54:32 +000038using namespace llvm;
39
Chandler Carruth84e68b22014-04-22 02:41:26 +000040#define DEBUG_TYPE "x86-isel"
41
Chris Lattner1ef9cd42006-12-19 22:59:26 +000042STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
43
Chris Lattner655e7df2005-11-16 01:54:32 +000044//===----------------------------------------------------------------------===//
45// Pattern Matcher Implementation
46//===----------------------------------------------------------------------===//
47
48namespace {
Chris Lattner3f0f71b2005-11-19 02:11:08 +000049 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000050 /// SDValue's instead of register numbers for the leaves of the matched
Chris Lattner3f0f71b2005-11-19 02:11:08 +000051 /// tree.
52 struct X86ISelAddressMode {
53 enum {
54 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000055 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000056 } BaseType;
57
Dan Gohman0fd54fb2010-04-29 23:30:41 +000058 // This is really a union, discriminated by BaseType!
59 SDValue Base_Reg;
60 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000061
62 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000063 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000064 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000065 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000066 const GlobalValue *GV;
67 const Constant *CP;
68 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000069 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000070 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000071 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000072 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000073 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000074
75 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000076 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
77 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
78 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000079
80 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000081 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000082 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000083 }
Chad Rosier24c19d22012-08-01 18:39:17 +000084
Chris Lattnerfea81da2009-06-27 04:16:01 +000085 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000086 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000087 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000088 }
Chad Rosier24c19d22012-08-01 18:39:17 +000089
Chris Lattnerfea81da2009-06-27 04:16:01 +000090 /// isRIPRelative - Return true if this addressing mode is already RIP
91 /// relative.
92 bool isRIPRelative() const {
93 if (BaseType != RegBase) return false;
94 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +000095 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +000096 return RegNode->getReg() == X86::RIP;
97 return false;
98 }
Chad Rosier24c19d22012-08-01 18:39:17 +000099
Chris Lattnerfea81da2009-06-27 04:16:01 +0000100 void setBaseReg(SDValue Reg) {
101 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000102 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000103 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000104
Manman Ren19f49ac2012-09-11 22:23:19 +0000105#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesendafdbf72008-08-11 23:46:25 +0000106 void dump() {
David Greenedbdb1b22010-01-05 01:29:08 +0000107 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000108 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000109 if (Base_Reg.getNode())
Chad Rosier24c19d22012-08-01 18:39:17 +0000110 Base_Reg.getNode()->dump();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000111 else
David Greenedbdb1b22010-01-05 01:29:08 +0000112 dbgs() << "nul";
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000113 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000114 << " Scale" << Scale << '\n'
115 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000116 if (IndexReg.getNode())
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000117 IndexReg.getNode()->dump();
118 else
Chad Rosier24c19d22012-08-01 18:39:17 +0000119 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000120 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000121 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000122 if (GV)
123 GV->dump();
124 else
David Greenedbdb1b22010-01-05 01:29:08 +0000125 dbgs() << "nul";
126 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000127 if (CP)
128 CP->dump();
129 else
David Greenedbdb1b22010-01-05 01:29:08 +0000130 dbgs() << "nul";
131 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000132 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000133 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000134 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000135 else
David Greenedbdb1b22010-01-05 01:29:08 +0000136 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000137 dbgs() << " MCSym ";
138 if (MCSym)
139 dbgs() << MCSym;
140 else
141 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000142 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000143 }
Manman Ren742534c2012-09-06 19:06:06 +0000144#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000145 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000146}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000147
148namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000149 //===--------------------------------------------------------------------===//
150 /// ISel - X86 specific code to select X86 machine instructions for
151 /// SelectionDAG operations.
152 ///
Craig Topper26eec092014-03-31 06:22:15 +0000153 class X86DAGToDAGISel final : public SelectionDAGISel {
Chris Lattner655e7df2005-11-16 01:54:32 +0000154 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
155 /// make the right decision when generating code for different targets.
156 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000157
Evan Cheng7d6fa972008-09-26 23:41:32 +0000158 /// OptForSize - If true, selector should try to optimize for code size
159 /// instead of performance.
160 bool OptForSize;
161
Chris Lattner655e7df2005-11-16 01:54:32 +0000162 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000163 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Eric Christopher05b81972015-02-02 17:38:43 +0000164 : SelectionDAGISel(tm, OptLevel), OptForSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000165
Craig Topper2d9361e2014-03-09 07:44:38 +0000166 const char *getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000167 return "X86 DAG->DAG Instruction Selection";
168 }
169
Eric Christopher4f09c592014-05-22 01:53:26 +0000170 bool runOnMachineFunction(MachineFunction &MF) override {
171 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000172 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000173 SelectionDAGISel::runOnMachineFunction(MF);
174 return true;
175 }
176
Craig Topper2d9361e2014-03-09 07:44:38 +0000177 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000178
Craig Topper2d9361e2014-03-09 07:44:38 +0000179 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000180
Craig Topper2d9361e2014-03-09 07:44:38 +0000181 void PreprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000182
Jakob Stoklund Olesen08aede22010-09-03 00:35:18 +0000183 inline bool immSext8(SDNode *N) const {
184 return isInt<8>(cast<ConstantSDNode>(N)->getSExtValue());
185 }
186
187 // i64immSExt32 predicate - True if the 64-bit immediate fits in a 32-bit
188 // sign extended field.
189 inline bool i64immSExt32(SDNode *N) const {
190 uint64_t v = cast<ConstantSDNode>(N)->getZExtValue();
191 return (int64_t)v == (int32_t)v;
192 }
193
Chris Lattner655e7df2005-11-16 01:54:32 +0000194// Include the pieces autogenerated from the target description.
195#include "X86GenDAGISel.inc"
196
197 private:
Craig Topper2d9361e2014-03-09 07:44:38 +0000198 SDNode *Select(SDNode *N) override;
Manman Rena0982042012-06-26 19:47:59 +0000199 SDNode *SelectGather(SDNode *N, unsigned Opc);
Craig Topper83e042a2013-08-15 05:57:07 +0000200 SDNode *SelectAtomicLoadArith(SDNode *Node, MVT NVT);
Chris Lattner655e7df2005-11-16 01:54:32 +0000201
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000202 bool FoldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
Chris Lattner8a236b62010-09-22 04:39:11 +0000203 bool MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000204 bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
Dan Gohman824ab402009-07-22 23:26:55 +0000205 bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
206 bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
207 unsigned Depth);
Rafael Espindola92773792009-03-31 16:16:57 +0000208 bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
Chris Lattnerd58d7c12010-09-21 22:07:31 +0000209 bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000210 SDValue &Scale, SDValue &Index, SDValue &Disp,
211 SDValue &Segment);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000212 bool SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
213 SDValue &Scale, SDValue &Index, SDValue &Disp,
214 SDValue &Segment);
Tim Northover3a1fd4c2013-06-01 09:55:14 +0000215 bool SelectMOV64Imm32(SDValue N, SDValue &Imm);
Chris Lattner0e023ea2010-09-21 20:31:19 +0000216 bool SelectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000217 SDValue &Scale, SDValue &Index, SDValue &Disp,
218 SDValue &Segment);
Tim Northover6833e3f2013-06-10 20:43:49 +0000219 bool SelectLEA64_32Addr(SDValue N, SDValue &Base,
220 SDValue &Scale, SDValue &Index, SDValue &Disp,
221 SDValue &Segment);
Chris Lattner0e023ea2010-09-21 20:31:19 +0000222 bool SelectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000223 SDValue &Scale, SDValue &Index, SDValue &Disp,
224 SDValue &Segment);
Chris Lattnerbd6e1932010-03-01 22:51:11 +0000225 bool SelectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000226 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000228 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000229 SDValue &NodeWithChain);
Chad Rosier24c19d22012-08-01 18:39:17 +0000230
Dan Gohmanea6f91f2010-01-05 01:24:18 +0000231 bool TryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000232 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000233 SDValue &Index, SDValue &Disp,
234 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000235
Chris Lattnerba1ed582006-06-08 18:03:49 +0000236 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
237 /// inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000238 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000239 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000240 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000241
David Majnemerd5ab35f2015-02-21 05:49:45 +0000242 void EmitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000243
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000244 inline void getAddressOperands(X86ISelAddressMode &AM, SDLoc DL,
245 SDValue &Base, SDValue &Scale,
246 SDValue &Index, SDValue &Disp,
247 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000248 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
249 ? CurDAG->getTargetFrameIndex(AM.Base_FrameIndex,
250 TLI->getPointerTy())
251 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000252 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000253 Index = AM.IndexReg;
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000254 // These are 32-bit even in 64-bit mode since RIP relative offset
255 // is 32-bit.
256 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000257 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000258 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000259 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000260 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000261 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000262 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000263 else if (AM.ES) {
264 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000265 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000266 } else if (AM.MCSym) {
267 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
268 assert(AM.SymbolFlags == 0 && "oo");
269 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000270 } else if (AM.JT != -1) {
271 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000272 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000273 } else if (AM.BlockAddr)
274 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
275 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000276 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000277 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000278
279 if (AM.Segment.getNode())
280 Segment = AM.Segment;
281 else
Owen Anderson9f944592009-08-11 20:47:22 +0000282 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000283 }
284
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000285 /// getI8Imm - Return a target constant with the specified value, of type
286 /// i8.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000287 inline SDValue getI8Imm(unsigned Imm, SDLoc DL) {
288 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000289 }
290
Chris Lattner655e7df2005-11-16 01:54:32 +0000291 /// getI32Imm - Return a target constant with the specified value, of type
292 /// i32.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000293 inline SDValue getI32Imm(unsigned Imm, SDLoc DL) {
294 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000295 }
Evan Chengd49cc362006-02-10 22:24:32 +0000296
Dan Gohman24300732008-09-23 18:22:58 +0000297 /// getGlobalBaseReg - Return an SDNode that returns the value of
298 /// the global base register. Output instructions required to
299 /// initialize the global base register, if necessary.
300 ///
Evan Cheng61413a32006-08-26 05:34:46 +0000301 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000302
Dan Gohman4751bb92009-06-03 20:20:00 +0000303 /// getTargetMachine - Return a reference to the TargetMachine, casted
304 /// to the target-specific type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000305 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000306 return static_cast<const X86TargetMachine &>(TM);
307 }
308
309 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
310 /// to the target-specific type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000311 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000312 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000313 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000314
315 /// \brief Address-mode matching performs shift-of-and to and-of-shift
316 /// reassociation in order to expose more scaled addressing
317 /// opportunities.
318 bool ComplexPatternFuncMutatesDAG() const override {
319 return true;
320 }
Chris Lattner655e7df2005-11-16 01:54:32 +0000321 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000322}
Chris Lattner655e7df2005-11-16 01:54:32 +0000323
Evan Cheng72bb66a2006-08-08 00:31:00 +0000324
Evan Cheng5e73ff22010-02-15 19:41:07 +0000325bool
326X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000327 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000328
Evan Cheng5e73ff22010-02-15 19:41:07 +0000329 if (!N.hasOneUse())
330 return false;
331
332 if (N.getOpcode() != ISD::LOAD)
333 return true;
334
335 // If N is a load, do additional profitability checks.
336 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000337 switch (U->getOpcode()) {
338 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000339 case X86ISD::ADD:
340 case X86ISD::SUB:
341 case X86ISD::AND:
342 case X86ISD::XOR:
343 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000344 case ISD::ADD:
345 case ISD::ADDC:
346 case ISD::ADDE:
347 case ISD::AND:
348 case ISD::OR:
349 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000350 SDValue Op1 = U->getOperand(1);
351
Evan Cheng83bdb382008-11-27 00:49:46 +0000352 // If the other operand is a 8-bit immediate we should fold the immediate
353 // instead. This reduces code size.
354 // e.g.
355 // movl 4(%esp), %eax
356 // addl $4, %eax
357 // vs.
358 // movl $4, %eax
359 // addl 4(%esp), %eax
360 // The former is 2 bytes shorter. In case where the increment is 1, then
361 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000362 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000363 if (Imm->getAPIntValue().isSignedIntN(8))
364 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000365
366 // If the other operand is a TLS address, we should fold it instead.
367 // This produces
368 // movl %gs:0, %eax
369 // leal i@NTPOFF(%eax), %eax
370 // instead of
371 // movl $i@NTPOFF, %eax
372 // addl %gs:0, %eax
373 // if the block also has an access to a second TLS address this will save
374 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000375 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000376 if (Op1.getOpcode() == X86ISD::Wrapper) {
377 SDValue Val = Op1.getOperand(0);
378 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
379 return false;
380 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000381 }
382 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000383 }
384
385 return true;
386}
387
Evan Chengd703df62010-03-14 03:48:46 +0000388/// MoveBelowCallOrigChain - Replace the original chain operand of the call with
389/// load's chain operand and move load below the call's chain operand.
390static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
Evan Cheng214156c2012-10-02 23:49:13 +0000391 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000392 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000393 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000394 if (Chain.getNode() == Load.getNode())
395 Ops.push_back(Load.getOperand(0));
396 else {
397 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000398 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000399 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
400 if (Chain.getOperand(i).getNode() == Load.getNode())
401 Ops.push_back(Load.getOperand(0));
402 else
403 Ops.push_back(Chain.getOperand(i));
404 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000405 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000406 Ops.clear();
407 Ops.push_back(NewChain);
408 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000409 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000410 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000411 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000412 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000413
Evan Chengf00f1e52008-08-25 21:27:18 +0000414 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000415 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000416 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000417 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000418}
419
420/// isCalleeLoad - Return true if call address is a load and it can be
421/// moved below CALLSEQ_START and the chains leading up to the call.
422/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000423/// In the case of a tail call, there isn't a callseq node between the call
424/// chain and the load.
425static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000426 // The transformation is somewhat dangerous if the call's chain was glued to
427 // the call. After MoveBelowOrigChain the load is moved between the call and
428 // the chain, this can create a cycle if the load is not folded. So it is
429 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000430 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000431 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000432 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000433 if (!LD ||
434 LD->isVolatile() ||
435 LD->getAddressingMode() != ISD::UNINDEXED ||
436 LD->getExtensionType() != ISD::NON_EXTLOAD)
437 return false;
438
439 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000440 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000441 if (!Chain.hasOneUse())
442 return false;
443 Chain = Chain.getOperand(0);
444 }
Evan Chengd703df62010-03-14 03:48:46 +0000445
446 if (!Chain.getNumOperands())
447 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000448 // Since we are not checking for AA here, conservatively abort if the chain
449 // writes to memory. It's not safe to move the callee (a load) across a store.
450 if (isa<MemSDNode>(Chain.getNode()) &&
451 cast<MemSDNode>(Chain.getNode())->writeMem())
452 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000453 if (Chain.getOperand(0).getNode() == Callee.getNode())
454 return true;
455 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000456 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
457 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000458 return true;
459 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000460}
461
Chris Lattner8d637042010-03-02 23:12:51 +0000462void X86DAGToDAGISel::PreprocessISelDAG() {
Chris Lattner82cc5332010-03-04 01:43:43 +0000463 // OptForSize is used in pattern predicates that isel is matching.
Duncan P. N. Exon Smith5975a702015-02-14 01:59:52 +0000464 OptForSize = MF->getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
Chad Rosier24c19d22012-08-01 18:39:17 +0000465
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000466 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
467 E = CurDAG->allnodes_end(); I != E; ) {
Chris Lattnera91f77e2008-01-24 08:07:48 +0000468 SDNode *N = I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000469
Evan Chengd703df62010-03-14 03:48:46 +0000470 if (OptLevel != CodeGenOpt::None &&
Michael Liao96b42602013-03-28 23:13:21 +0000471 // Only does this when target favors doesn't favor register indirect
472 // call.
473 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000474 (N->getOpcode() == X86ISD::TC_RETURN &&
Nick Lewyckyf41a80e2013-01-13 19:03:55 +0000475 // Only does this if load can be folded into TC_RETURN.
Evan Cheng847ad442012-10-05 01:48:22 +0000476 (Subtarget->is64Bit() ||
477 getTargetMachine().getRelocationModel() != Reloc::PIC_)))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000478 /// Also try moving call address load from outside callseq_start to just
479 /// before the call to allow it to be folded.
480 ///
481 /// [Load chain]
482 /// ^
483 /// |
484 /// [Load]
485 /// ^ ^
486 /// | |
487 /// / \--
488 /// / |
489 ///[CALLSEQ_START] |
490 /// ^ |
491 /// | |
492 /// [LOAD/C2Reg] |
493 /// | |
494 /// \ /
495 /// \ /
496 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000497 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000498 SDValue Chain = N->getOperand(0);
499 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000500 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000501 continue;
Evan Chengd703df62010-03-14 03:48:46 +0000502 MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000503 ++NumLoadMoved;
504 continue;
505 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000506
Chris Lattner8d637042010-03-02 23:12:51 +0000507 // Lower fpround and fpextend nodes that target the FP stack to be store and
508 // load to the stack. This is a gross hack. We would like to simply mark
509 // these as being illegal, but when we do that, legalize produces these when
510 // it expands calls, then expands these in the same legalize pass. We would
511 // like dag combine to be able to hack on these between the call expansion
512 // and the node legalization. As such this pass basically does "really
513 // late" legalization of these inline with the X86 isel pass.
514 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000515 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
516 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000517
Craig Topper83e042a2013-08-15 05:57:07 +0000518 MVT SrcVT = N->getOperand(0).getSimpleValueType();
519 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000520
521 // If any of the sources are vectors, no fp stack involved.
522 if (SrcVT.isVector() || DstVT.isVector())
523 continue;
524
525 // If the source and destination are SSE registers, then this is a legal
526 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000527 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000528 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000529 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
530 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000531 if (SrcIsSSE && DstIsSSE)
532 continue;
533
Chris Lattnerd587e582008-03-09 07:05:32 +0000534 if (!SrcIsSSE && !DstIsSSE) {
535 // If this is an FPStack extension, it is a noop.
536 if (N->getOpcode() == ISD::FP_EXTEND)
537 continue;
538 // If this is a value-preserving FPStack truncation, it is a noop.
539 if (N->getConstantOperandVal(1))
540 continue;
541 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000542
Chris Lattnera91f77e2008-01-24 08:07:48 +0000543 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
544 // FPStack has extload and truncstore. SSE can fold direct loads into other
545 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000546 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000547 if (N->getOpcode() == ISD::FP_ROUND)
548 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
549 else
550 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000551
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000552 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000553 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000554
Chris Lattnera91f77e2008-01-24 08:07:48 +0000555 // FIXME: optimize the case where the src/dest is a load or store?
Dale Johannesen14f2d9d2009-02-03 21:48:12 +0000556 SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000557 N->getOperand(0),
Chris Lattner3d178ed2010-09-21 17:04:51 +0000558 MemTmp, MachinePointerInfo(), MemVT,
David Greenecbd39c52010-02-15 16:57:43 +0000559 false, false, 0);
Stuart Hastings81c43062011-02-16 16:23:55 +0000560 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Chris Lattner3d178ed2010-09-21 17:04:51 +0000561 MachinePointerInfo(),
Louis Gerbarg67474e32014-07-31 21:45:05 +0000562 MemVT, false, false, false, 0);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000563
564 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
565 // extload we created. This will cause general havok on the dag because
566 // anything below the conversion could be folded into other existing nodes.
567 // To avoid invalidating 'I', back it up to the convert node.
568 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000569 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000570
Chris Lattnera91f77e2008-01-24 08:07:48 +0000571 // Now that we did that, the node is dead. Increment the iterator to the
572 // next node to process, then delete N.
573 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000574 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000575 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000576}
577
Chris Lattner655e7df2005-11-16 01:54:32 +0000578
Anton Korobeynikov90910742007-09-25 21:52:30 +0000579/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
580/// the main function.
David Majnemerd5ab35f2015-02-21 05:49:45 +0000581void X86DAGToDAGISel::EmitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000582 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000583 TargetLowering::ArgListTy Args;
584
585 TargetLowering::CallLoweringInfo CLI(*CurDAG);
586 CLI.setChain(CurDAG->getRoot())
587 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
588 CurDAG->getExternalSymbol("__main", TLI->getPointerTy()),
589 std::move(Args), 0);
590 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
591 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
592 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000593 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000594}
595
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000596void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000597 // If this is main, emit special code for main.
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000598 if (const Function *Fn = MF->getFunction())
599 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
David Majnemerd5ab35f2015-02-21 05:49:45 +0000600 EmitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000601}
602
Eli Friedman344ec792011-07-13 21:29:53 +0000603static bool isDispSafeForFrameIndex(int64_t Val) {
604 // On 64-bit platforms, we can run into an issue where a frame index
605 // includes a displacement that, when added to the explicit displacement,
606 // will overflow the displacement field. Assuming that the frame index
607 // displacement fits into a 31-bit integer (which is only slightly more
608 // aggressive than the current fundamental assumption that it fits into
609 // a 32-bit integer), a 31-bit disp should always be safe.
610 return isInt<31>(Val);
611}
612
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000613bool X86DAGToDAGISel::FoldOffsetIntoAddress(uint64_t Offset,
614 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000615 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000616 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000617 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000618 int64_t Val = AM.Disp + Offset;
619 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000620 if (Subtarget->is64Bit()) {
621 if (!X86::isOffsetSuitableForCodeModel(Val, M,
622 AM.hasSymbolicDisplacement()))
623 return true;
624 // In addition to the checks required for a register base, check that
625 // we do not try to use an unsafe Disp with a frame index.
626 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
627 !isDispSafeForFrameIndex(Val))
628 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000629 }
Eli Friedman344ec792011-07-13 21:29:53 +0000630 AM.Disp = Val;
631 return false;
632
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000633}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000634
Chris Lattner8a236b62010-09-22 04:39:11 +0000635bool X86DAGToDAGISel::MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
636 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000637
Chris Lattner8a236b62010-09-22 04:39:11 +0000638 // load gs:0 -> GS segment register.
639 // load fs:0 -> FS segment register.
640 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000641 // This optimization is valid because the GNU TLS model defines that
642 // gs:0 (or fs:0 on X86-64) contains its own address.
643 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000644 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000645 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
David Chisnall5b8c1682012-07-24 20:04:16 +0000646 Subtarget->isTargetLinux())
Chris Lattner8a236b62010-09-22 04:39:11 +0000647 switch (N->getPointerInfo().getAddrSpace()) {
648 case 256:
649 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
650 return false;
651 case 257:
652 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
653 return false;
654 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000655
Rafael Espindola3b2df102009-04-08 21:14:34 +0000656 return true;
657}
658
Chris Lattnerfea81da2009-06-27 04:16:01 +0000659/// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
660/// into an addressing mode. These wrap things that will resolve down into a
661/// symbol reference. If no match is possible, this returns true, otherwise it
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000662/// returns false.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000663bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000664 // If the addressing mode already has a symbol as the displacement, we can
665 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000666 if (AM.hasSymbolicDisplacement())
667 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000668
669 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000670 CodeModel::Model M = TM.getCodeModel();
671
Chris Lattnerfea81da2009-06-27 04:16:01 +0000672 // Handle X86-64 rip-relative addresses. We check this before checking direct
673 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000674 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000675 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
676 // they cannot be folded into immediate fields.
677 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000678 (M == CodeModel::Small || M == CodeModel::Kernel)) {
679 // Base and index reg must be 0 in order to use %rip as base.
680 if (AM.hasBaseOrIndexReg())
681 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000682 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000683 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000684 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000685 AM.SymbolFlags = G->getTargetFlags();
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000686 if (FoldOffsetIntoAddress(G->getOffset(), AM)) {
687 AM = Backup;
688 return true;
689 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000690 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000691 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000692 AM.CP = CP->getConstVal();
693 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000694 AM.SymbolFlags = CP->getTargetFlags();
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000695 if (FoldOffsetIntoAddress(CP->getOffset(), AM)) {
696 AM = Backup;
697 return true;
698 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000699 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
700 AM.ES = S->getSymbol();
701 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000702 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
703 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000704 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000705 AM.JT = J->getIndex();
706 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000707 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
708 X86ISelAddressMode Backup = AM;
709 AM.BlockAddr = BA->getBlockAddress();
710 AM.SymbolFlags = BA->getTargetFlags();
711 if (FoldOffsetIntoAddress(BA->getOffset(), AM)) {
712 AM = Backup;
713 return true;
714 }
715 } else
716 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000717
Chris Lattnerfea81da2009-06-27 04:16:01 +0000718 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000719 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000720 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000721 }
722
723 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000724 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
725 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000726 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000727 M == CodeModel::Small || M == CodeModel::Kernel) {
728 assert(N.getOpcode() != X86ISD::WrapperRIP &&
729 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000730 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
731 AM.GV = G->getGlobal();
732 AM.Disp += G->getOffset();
733 AM.SymbolFlags = G->getTargetFlags();
734 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
735 AM.CP = CP->getConstVal();
736 AM.Align = CP->getAlignment();
737 AM.Disp += CP->getOffset();
738 AM.SymbolFlags = CP->getTargetFlags();
739 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
740 AM.ES = S->getSymbol();
741 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000742 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
743 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000744 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000745 AM.JT = J->getIndex();
746 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000747 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
748 AM.BlockAddr = BA->getBlockAddress();
749 AM.Disp += BA->getOffset();
750 AM.SymbolFlags = BA->getTargetFlags();
751 } else
752 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000753 return false;
754 }
755
756 return true;
757}
758
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000759/// MatchAddress - Add the specified node to the specified addressing mode,
760/// returning true if it cannot be done. This just pattern matches for the
Chris Lattnerff87f05e2007-12-08 07:22:58 +0000761/// addressing mode.
Dan Gohman824ab402009-07-22 23:26:55 +0000762bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
Dan Gohman99ba4da2010-06-18 01:24:29 +0000763 if (MatchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000764 return true;
765
766 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
767 // a smaller encoding and avoids a scaled-index.
768 if (AM.Scale == 2 &&
769 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000770 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000771 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000772 AM.Scale = 1;
773 }
774
Dan Gohman05046082009-08-20 18:23:44 +0000775 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
776 // because it has a smaller encoding.
777 // TODO: Which other code models can use this?
778 if (TM.getCodeModel() == CodeModel::Small &&
779 Subtarget->is64Bit() &&
780 AM.Scale == 1 &&
781 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000782 AM.Base_Reg.getNode() == nullptr &&
783 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000784 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000785 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000786 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000787
Dan Gohman824ab402009-07-22 23:26:55 +0000788 return false;
789}
790
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000791// Insert a node into the DAG at least before the Pos node's position. This
792// will reposition the node as needed, and will assign it a node ID that is <=
793// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
794// IDs! The selection DAG must no longer depend on their uniqueness when this
795// is used.
796static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
797 if (N.getNode()->getNodeId() == -1 ||
798 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
799 DAG.RepositionNode(Pos.getNode(), N.getNode());
800 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
801 }
802}
803
Adam Nemet0c7caf42014-09-16 17:14:10 +0000804// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
805// safe. This allows us to convert the shift and and into an h-register
806// extract and a scaled index. Returns false if the simplification is
807// performed.
Chandler Carruth51d30762012-01-11 08:48:20 +0000808static bool FoldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
809 uint64_t Mask,
810 SDValue Shift, SDValue X,
811 X86ISelAddressMode &AM) {
812 if (Shift.getOpcode() != ISD::SRL ||
813 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
814 !Shift.hasOneUse())
815 return true;
816
817 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
818 if (ScaleLog <= 0 || ScaleLog >= 4 ||
819 Mask != (0xffu << ScaleLog))
820 return true;
821
Craig Topper83e042a2013-08-15 05:57:07 +0000822 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000823 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000824 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
825 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +0000826 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
827 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000828 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +0000829 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
830
Chandler Carrutheb21da02012-01-12 01:34:44 +0000831 // Insert the new nodes into the topological ordering. We must do this in
832 // a valid topological ordering as nothing is going to go back and re-sort
833 // these nodes. We continually insert before 'N' in sequence as this is
834 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
835 // hierarchy left to express.
836 InsertDAGNode(DAG, N, Eight);
837 InsertDAGNode(DAG, N, Srl);
838 InsertDAGNode(DAG, N, NewMask);
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000839 InsertDAGNode(DAG, N, And);
Chandler Carrutheb21da02012-01-12 01:34:44 +0000840 InsertDAGNode(DAG, N, ShlCount);
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000841 InsertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +0000842 DAG.ReplaceAllUsesWith(N, Shl);
843 AM.IndexReg = And;
844 AM.Scale = (1 << ScaleLog);
845 return false;
846}
847
Chandler Carruthaa01e662012-01-11 09:35:00 +0000848// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
849// allows us to fold the shift into this addressing mode. Returns false if the
850// transform succeeded.
851static bool FoldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
852 uint64_t Mask,
853 SDValue Shift, SDValue X,
854 X86ISelAddressMode &AM) {
855 if (Shift.getOpcode() != ISD::SHL ||
856 !isa<ConstantSDNode>(Shift.getOperand(1)))
857 return true;
858
859 // Not likely to be profitable if either the AND or SHIFT node has more
860 // than one use (unless all uses are for address computation). Besides,
861 // isel mechanism requires their node ids to be reused.
862 if (!N.hasOneUse() || !Shift.hasOneUse())
863 return true;
864
865 // Verify that the shift amount is something we can fold.
866 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
867 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
868 return true;
869
Craig Topper83e042a2013-08-15 05:57:07 +0000870 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000871 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000872 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +0000873 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
874 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
875
Chandler Carrutheb21da02012-01-12 01:34:44 +0000876 // Insert the new nodes into the topological ordering. We must do this in
877 // a valid topological ordering as nothing is going to go back and re-sort
878 // these nodes. We continually insert before 'N' in sequence as this is
879 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
880 // hierarchy left to express.
881 InsertDAGNode(DAG, N, NewMask);
882 InsertDAGNode(DAG, N, NewAnd);
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000883 InsertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +0000884 DAG.ReplaceAllUsesWith(N, NewShift);
885
886 AM.Scale = 1 << ShiftAmt;
887 AM.IndexReg = NewAnd;
888 return false;
889}
890
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000891// Implement some heroics to detect shifts of masked values where the mask can
892// be replaced by extending the shift and undoing that in the addressing mode
893// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
894// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
895// the addressing mode. This results in code such as:
896//
897// int f(short *y, int *lookup_table) {
898// ...
899// return *y + lookup_table[*y >> 11];
900// }
901//
902// Turning into:
903// movzwl (%rdi), %eax
904// movl %eax, %ecx
905// shrl $11, %ecx
906// addl (%rsi,%rcx,4), %eax
907//
908// Instead of:
909// movzwl (%rdi), %eax
910// movl %eax, %ecx
911// shrl $9, %ecx
912// andl $124, %rcx
913// addl (%rsi,%rcx), %eax
914//
Chandler Carruth3dbcda82012-01-11 09:35:02 +0000915// Note that this function assumes the mask is provided as a mask *after* the
916// value is shifted. The input chain may or may not match that, but computing
917// such a mask is trivial.
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000918static bool FoldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
Chandler Carruth3dbcda82012-01-11 09:35:02 +0000919 uint64_t Mask,
920 SDValue Shift, SDValue X,
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000921 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +0000922 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
923 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000924 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000925
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000926 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000927 unsigned MaskLZ = countLeadingZeros(Mask);
928 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000929
930 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +0000931 // from the trailing zeros of the mask.
932 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000933
934 // There is nothing we can do here unless the mask is removing some bits.
935 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
936 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
937
938 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000939 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000940
941 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +0000942 // Also scale it down based on the size of the shift.
Craig Topper83e042a2013-08-15 05:57:07 +0000943 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000944
945 // The final check is to ensure that any masked out high bits of X are
946 // already known to be zero. Otherwise, the mask has a semantic impact
947 // other than masking out a couple of low bits. Unfortunately, because of
948 // the mask, zero extensions will be removed from operands in some cases.
949 // This code works extra hard to look through extensions because we can
950 // replace them with zero extensions cheaply if necessary.
951 bool ReplacingAnyExtend = false;
952 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +0000953 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
954 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000955 // Assume that we'll replace the any-extend with a zero-extend, and
956 // narrow the search to the extended value.
957 X = X.getOperand(0);
958 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
959 ReplacingAnyExtend = true;
960 }
Craig Topper83e042a2013-08-15 05:57:07 +0000961 APInt MaskedHighBits =
962 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000963 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +0000964 DAG.computeKnownBits(X, KnownZero, KnownOne);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000965 if (MaskedHighBits != KnownZero) return true;
966
967 // We've identified a pattern that can be transformed into a single shift
968 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +0000969 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000970 if (ReplacingAnyExtend) {
971 assert(X.getValueType() != VT);
972 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000973 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000974 InsertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000975 X = NewX;
976 }
Andrew Trickef9de2a2013-05-25 02:42:55 +0000977 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000978 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000979 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000980 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000981 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +0000982
983 // Insert the new nodes into the topological ordering. We must do this in
984 // a valid topological ordering as nothing is going to go back and re-sort
985 // these nodes. We continually insert before 'N' in sequence as this is
986 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
987 // hierarchy left to express.
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000988 InsertDAGNode(DAG, N, NewSRLAmt);
989 InsertDAGNode(DAG, N, NewSRL);
990 InsertDAGNode(DAG, N, NewSHLAmt);
991 InsertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +0000992 DAG.ReplaceAllUsesWith(N, NewSHL);
993
994 AM.Scale = 1 << AMShiftAmt;
995 AM.IndexReg = NewSRL;
996 return false;
997}
998
Dan Gohman824ab402009-07-22 23:26:55 +0000999bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1000 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001001 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001002 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001003 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001004 AM.dump();
1005 });
Dan Gohmanccb36112007-08-13 20:03:06 +00001006 // Limit recursion.
1007 if (Depth > 5)
Rafael Espindola92773792009-03-31 16:16:57 +00001008 return MatchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001009
Chris Lattnerfea81da2009-06-27 04:16:01 +00001010 // If this is already a %rip relative address, we can only merge immediates
1011 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001012 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001013 if (AM.isRIPRelative()) {
1014 // FIXME: JumpTable and ExternalSymbol address currently don't like
1015 // displacements. It isn't very important, but this should be fixed for
1016 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001017 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1018 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001019
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001020 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1021 if (!FoldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001022 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001023 return true;
1024 }
1025
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001026 switch (N.getOpcode()) {
1027 default: break;
David Majnemer71b9b6b2015-03-05 18:50:12 +00001028 case ISD::FRAME_ALLOC_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001029 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001030 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1031 // Use the symbol and don't prefix it.
1032 AM.MCSym = ESNode->getMCSymbol();
1033 return false;
1034 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001035 break;
1036 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001037 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001038 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001039 if (!FoldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001040 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001041 break;
1042 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001043
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001044 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001045 case X86ISD::WrapperRIP:
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001046 if (!MatchWrapper(N, AM))
1047 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001048 break;
1049
Rafael Espindola3b2df102009-04-08 21:14:34 +00001050 case ISD::LOAD:
Chris Lattner8a236b62010-09-22 04:39:11 +00001051 if (!MatchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001052 return false;
1053 break;
1054
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001055 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001056 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001057 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001058 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001059 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001060 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001061 return false;
1062 }
1063 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001064
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001065 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001066 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001067 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001068
Gabor Greif81d6a382008-08-31 15:37:04 +00001069 if (ConstantSDNode
1070 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001071 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001072 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1073 // that the base operand remains free for further matching. If
1074 // the base doesn't end up getting used, a post-processing step
1075 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001076 if (Val == 1 || Val == 2 || Val == 3) {
1077 AM.Scale = 1 << Val;
Gabor Greiff304a7a2008-08-28 21:40:38 +00001078 SDValue ShVal = N.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001079
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001080 // Okay, we know that we have a scale by now. However, if the scaled
1081 // value is an add of something and a constant, we can fold the
1082 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001083 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001084 AM.IndexReg = ShVal.getNode()->getOperand(0);
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001085 ConstantSDNode *AddVal =
Gabor Greiff304a7a2008-08-28 21:40:38 +00001086 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001087 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001088 if (!FoldOffsetIntoAddress(Disp, AM))
1089 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001090 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001091
1092 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001093 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001094 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001095 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001096 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001097
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001098 case ISD::SRL: {
1099 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001100 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001101
1102 SDValue And = N.getOperand(0);
1103 if (And.getOpcode() != ISD::AND) break;
1104 SDValue X = And.getOperand(0);
1105
1106 // We only handle up to 64-bit values here as those are what matter for
1107 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001108 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001109
1110 // The mask used for the transform is expected to be post-shift, but we
1111 // found the shift first so just apply the shift to the mask before passing
1112 // it down.
1113 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1114 !isa<ConstantSDNode>(And.getOperand(1)))
1115 break;
1116 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1117
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001118 // Try to fold the mask and shift into the scale, and return false if we
1119 // succeed.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001120 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001121 return false;
1122 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001123 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001124
Dan Gohmanbf474952007-10-22 20:22:24 +00001125 case ISD::SMUL_LOHI:
1126 case ISD::UMUL_LOHI:
1127 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001128 if (N.getResNo() != 0) break;
Dan Gohmanbf474952007-10-22 20:22:24 +00001129 // FALL THROUGH
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001130 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001131 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001132 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001133 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001134 AM.Base_Reg.getNode() == nullptr &&
1135 AM.IndexReg.getNode() == nullptr) {
Gabor Greif81d6a382008-08-31 15:37:04 +00001136 if (ConstantSDNode
1137 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001138 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1139 CN->getZExtValue() == 9) {
1140 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001141
Gabor Greiff304a7a2008-08-28 21:40:38 +00001142 SDValue MulVal = N.getNode()->getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001143 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001144
1145 // Okay, we know that we have a scale by now. However, if the scaled
1146 // value is an add of something and a constant, we can fold the
1147 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001148 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1149 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1150 Reg = MulVal.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001151 ConstantSDNode *AddVal =
Gabor Greiff304a7a2008-08-28 21:40:38 +00001152 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001153 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1154 if (FoldOffsetIntoAddress(Disp, AM))
Gabor Greiff304a7a2008-08-28 21:40:38 +00001155 Reg = N.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001156 } else {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001157 Reg = N.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001158 }
1159
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001160 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001161 return false;
1162 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001163 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001164 break;
1165
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001166 case ISD::SUB: {
1167 // Given A-B, if A can be completely folded into the address and
1168 // the index field with the index field unused, use -B as the index.
1169 // This is a win if a has multiple parts that can be folded into
1170 // the address. Also, this saves a mov if the base register has
1171 // other uses, since it avoids a two-address sub instruction, however
1172 // it costs an additional mov if the index register has other uses.
1173
Dan Gohman99ba4da2010-06-18 01:24:29 +00001174 // Add an artificial use to this node so that we can keep track of
1175 // it if it gets CSE'd with a different node.
1176 HandleSDNode Handle(N);
1177
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001178 // Test if the LHS of the sub can be folded.
1179 X86ISelAddressMode Backup = AM;
Dan Gohman99ba4da2010-06-18 01:24:29 +00001180 if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001181 AM = Backup;
1182 break;
1183 }
1184 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001185 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001186 AM = Backup;
1187 break;
1188 }
Evan Cheng68333f52010-03-17 23:58:35 +00001189
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001190 int Cost = 0;
Dan Gohman99ba4da2010-06-18 01:24:29 +00001191 SDValue RHS = Handle.getValue().getNode()->getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001192 // If the RHS involves a register with multiple uses, this
1193 // transformation incurs an extra mov, due to the neg instruction
1194 // clobbering its operand.
1195 if (!RHS.getNode()->hasOneUse() ||
1196 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1197 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1198 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1199 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Owen Anderson9f944592009-08-11 20:47:22 +00001200 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001201 ++Cost;
1202 // If the base is a register with multiple uses, this
1203 // transformation may save a mov.
1204 if ((AM.BaseType == X86ISelAddressMode::RegBase &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001205 AM.Base_Reg.getNode() &&
1206 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001207 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1208 --Cost;
1209 // If the folded LHS was interesting, this transformation saves
1210 // address arithmetic.
1211 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1212 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1213 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1214 --Cost;
1215 // If it doesn't look like it may be an overall win, don't do it.
1216 if (Cost >= 0) {
1217 AM = Backup;
1218 break;
1219 }
1220
1221 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001222 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001223 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1224 AM.IndexReg = Neg;
1225 AM.Scale = 1;
1226
1227 // Insert the new nodes into the topological ordering.
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001228 InsertDAGNode(*CurDAG, N, Zero);
1229 InsertDAGNode(*CurDAG, N, Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001230 return false;
1231 }
1232
Evan Chengbf38a5e2009-01-17 07:09:27 +00001233 case ISD::ADD: {
Dan Gohman99ba4da2010-06-18 01:24:29 +00001234 // Add an artificial use to this node so that we can keep track of
1235 // it if it gets CSE'd with a different node.
1236 HandleSDNode Handle(N);
Dan Gohman99ba4da2010-06-18 01:24:29 +00001237
Evan Chengbf38a5e2009-01-17 07:09:27 +00001238 X86ISelAddressMode Backup = AM;
Chris Lattner35a2e652011-01-16 08:48:11 +00001239 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1240 !MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001241 return false;
1242 AM = Backup;
Chad Rosier24c19d22012-08-01 18:39:17 +00001243
Evan Cheng68333f52010-03-17 23:58:35 +00001244 // Try again after commuting the operands.
Chris Lattner35a2e652011-01-16 08:48:11 +00001245 if (!MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)&&
1246 !MatchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001247 return false;
Evan Chengbf38a5e2009-01-17 07:09:27 +00001248 AM = Backup;
Dan Gohmana1d92422009-03-13 02:25:09 +00001249
1250 // If we couldn't fold both operands into the address at the same time,
1251 // see if we can just put each operand into a register and fold at least
1252 // the add.
1253 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001254 !AM.Base_Reg.getNode() &&
Chris Lattnerfea81da2009-06-27 04:16:01 +00001255 !AM.IndexReg.getNode()) {
Chris Lattner35a2e652011-01-16 08:48:11 +00001256 N = Handle.getValue();
1257 AM.Base_Reg = N.getOperand(0);
1258 AM.IndexReg = N.getOperand(1);
Dan Gohmana1d92422009-03-13 02:25:09 +00001259 AM.Scale = 1;
1260 return false;
1261 }
Chris Lattner35a2e652011-01-16 08:48:11 +00001262 N = Handle.getValue();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001263 break;
Evan Chengbf38a5e2009-01-17 07:09:27 +00001264 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001265
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001266 case ISD::OR:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001267 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
Chris Lattner46c01a32011-02-13 22:25:43 +00001268 if (CurDAG->isBaseWithConstantOffset(N)) {
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001269 X86ISelAddressMode Backup = AM;
Chris Lattner84776782010-04-20 23:18:40 +00001270 ConstantSDNode *CN = cast<ConstantSDNode>(N.getOperand(1));
Evan Cheng68333f52010-03-17 23:58:35 +00001271
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001272 // Start with the LHS as an addr mode.
Dan Gohman99ba4da2010-06-18 01:24:29 +00001273 if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001274 !FoldOffsetIntoAddress(CN->getSExtValue(), AM))
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001275 return false;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001276 AM = Backup;
Evan Cheng734e1e22006-05-30 06:59:36 +00001277 }
1278 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001279
Evan Cheng827d30d2007-12-13 00:43:27 +00001280 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001281 // Perform some heroic transforms on an and of a constant-count shift
1282 // with a constant to enable use of the scaled offset field.
1283
Evan Cheng827d30d2007-12-13 00:43:27 +00001284 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001285 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001286
Chandler Carruthaa01e662012-01-11 09:35:00 +00001287 SDValue Shift = N.getOperand(0);
1288 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001289 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001290
1291 // We only handle up to 64-bit values here as those are what matter for
1292 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001293 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001294
Chandler Carruthb0049f42012-01-11 09:35:04 +00001295 if (!isa<ConstantSDNode>(N.getOperand(1)))
1296 break;
1297 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001298
Chandler Carruth51d30762012-01-11 08:48:20 +00001299 // Try to fold the mask and shift into an extract and scale.
Chandler Carruthb0049f42012-01-11 09:35:04 +00001300 if (!FoldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001301 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001302
Chandler Carruth51d30762012-01-11 08:48:20 +00001303 // Try to fold the mask and shift directly into the scale.
Chandler Carruthb0049f42012-01-11 09:35:04 +00001304 if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001305 return false;
1306
Chandler Carruthaa01e662012-01-11 09:35:00 +00001307 // Try to swap the mask and shift to place shifts which can be done as
1308 // a scale on the outside of the mask.
Chandler Carruthb0049f42012-01-11 09:35:04 +00001309 if (!FoldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001310 return false;
1311 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001312 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001313 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001314
Rafael Espindola92773792009-03-31 16:16:57 +00001315 return MatchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001316}
1317
1318/// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1319/// specified addressing mode without any further recursion.
Rafael Espindola92773792009-03-31 16:16:57 +00001320bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001321 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001322 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001323 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001324 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001325 AM.IndexReg = N;
1326 AM.Scale = 1;
1327 return false;
1328 }
1329
1330 // Otherwise, we cannot select it.
1331 return true;
1332 }
1333
1334 // Default, generate it as a register.
1335 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001336 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001337 return false;
1338}
1339
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001340bool X86DAGToDAGISel::SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1341 SDValue &Scale, SDValue &Index,
1342 SDValue &Disp, SDValue &Segment) {
1343
1344 MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1345 if (!Mgs)
1346 return false;
1347 X86ISelAddressMode AM;
1348 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1349 // AddrSpace 256 -> GS, 257 -> FS.
1350 if (AddrSpace == 256)
1351 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1352 if (AddrSpace == 257)
1353 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1354
1355 SDLoc DL(N);
1356 Base = Mgs->getBasePtr();
1357 Index = Mgs->getIndex();
1358 unsigned ScalarSize = Mgs->getValue().getValueType().getScalarSizeInBits();
1359 Scale = getI8Imm(ScalarSize/8, DL);
1360
1361 // If Base is 0, the whole address is in index and the Scale is 1
Daniel Jasper232778a2015-04-30 09:01:21 +00001362 if (isa<ConstantSDNode>(Base)) {
1363 assert(dyn_cast<ConstantSDNode>(Base)->isNullValue() &&
1364 "Unexpected base in gather/scatter");
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001365 Scale = getI8Imm(1, DL);
1366 Base = CurDAG->getRegister(0, MVT::i32);
1367 }
1368 if (AM.Segment.getNode())
1369 Segment = AM.Segment;
1370 else
1371 Segment = CurDAG->getRegister(0, MVT::i32);
1372 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1373 return true;
1374}
1375
Evan Chengc9fab312005-12-08 02:01:35 +00001376/// SelectAddr - returns true if it is able pattern match an addressing mode.
1377/// It returns the operands which make up the maximal addressing mode it can
1378/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001379///
1380/// Parent is the parent node of the addr operand that is being matched. It
1381/// is always a load, store, atomic node, or null. It is only null when
1382/// checking memory operands for inline asm nodes.
1383bool X86DAGToDAGISel::SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001384 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001385 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001386 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001387
Chris Lattner8a236b62010-09-22 04:39:11 +00001388 if (Parent &&
1389 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1390 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001391 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001392 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001393 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1394 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1395 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001396 unsigned AddrSpace =
1397 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1398 // AddrSpace 256 -> GS, 257 -> FS.
1399 if (AddrSpace == 256)
1400 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1401 if (AddrSpace == 257)
1402 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1403 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001404
Evan Cheng3dfd04e2009-12-18 01:59:21 +00001405 if (MatchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001406 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001407
Craig Topper83e042a2013-08-15 05:57:07 +00001408 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001409 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001410 if (!AM.Base_Reg.getNode())
1411 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001412 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001413
Gabor Greiff304a7a2008-08-28 21:40:38 +00001414 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001415 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001416
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001417 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001418 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001419}
1420
Chris Lattner398195e2006-10-07 21:55:32 +00001421/// SelectScalarSSELoad - Match a scalar SSE load. In particular, we want to
1422/// match a load whose top elements are either undef or zeros. The load flavor
1423/// is derived from the type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001424///
1425/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001426/// PatternChainNode: this is the matched node that has a chain input and
1427/// output.
Chris Lattnerbd6e1932010-03-01 22:51:11 +00001428bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001429 SDValue N, SDValue &Base,
1430 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001431 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001432 SDValue &PatternNodeWithChain) {
Chris Lattner398195e2006-10-07 21:55:32 +00001433 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001434 PatternNodeWithChain = N.getOperand(0);
1435 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1436 PatternNodeWithChain.hasOneUse() &&
Chris Lattner3c29aff2010-02-21 04:53:34 +00001437 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
Dan Gohman21cea8a2010-04-17 15:26:15 +00001438 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001439 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001440 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
Chris Lattner398195e2006-10-07 21:55:32 +00001441 return false;
1442 return true;
1443 }
1444 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001445
1446 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001447 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001448 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001449 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001450 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001451 N.getOperand(0).getNode()->hasOneUse() &&
1452 ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
Chris Lattnerafac7dad2010-02-16 22:35:06 +00001453 N.getOperand(0).getOperand(0).hasOneUse() &&
1454 IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
Dan Gohman21cea8a2010-04-17 15:26:15 +00001455 IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
Evan Cheng78af38c2008-05-08 00:57:18 +00001456 // Okay, this is a zero extending load. Fold it.
1457 LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001458 if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
Evan Cheng78af38c2008-05-08 00:57:18 +00001459 return false;
Chris Lattner18a32ce2010-02-21 03:17:59 +00001460 PatternNodeWithChain = SDValue(LD, 0);
Evan Cheng78af38c2008-05-08 00:57:18 +00001461 return true;
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001462 }
Chris Lattner398195e2006-10-07 21:55:32 +00001463 return false;
1464}
1465
1466
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001467bool X86DAGToDAGISel::SelectMOV64Imm32(SDValue N, SDValue &Imm) {
1468 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1469 uint64_t ImmVal = CN->getZExtValue();
1470 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1471 return false;
1472
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001473 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001474 return true;
1475 }
1476
1477 // In static codegen with small code model, we can get the address of a label
1478 // into a register with 'movl'. TableGen has already made sure we're looking
1479 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001480 assert(N->getOpcode() == X86ISD::Wrapper &&
1481 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001482 N = N.getOperand(0);
1483
1484 if (N->getOpcode() != ISD::TargetConstantPool &&
1485 N->getOpcode() != ISD::TargetJumpTable &&
1486 N->getOpcode() != ISD::TargetGlobalAddress &&
1487 N->getOpcode() != ISD::TargetExternalSymbol &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00001488 N->getOpcode() != ISD::MCSymbol &&
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001489 N->getOpcode() != ISD::TargetBlockAddress)
1490 return false;
1491
1492 Imm = N;
1493 return TM.getCodeModel() == CodeModel::Small;
1494}
1495
Tim Northover6833e3f2013-06-10 20:43:49 +00001496bool X86DAGToDAGISel::SelectLEA64_32Addr(SDValue N, SDValue &Base,
1497 SDValue &Scale, SDValue &Index,
1498 SDValue &Disp, SDValue &Segment) {
1499 if (!SelectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1500 return false;
1501
1502 SDLoc DL(N);
1503 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1504 if (RN && RN->getReg() == 0)
1505 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001506 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001507 // Base could already be %rip, particularly in the x32 ABI.
1508 Base = SDValue(CurDAG->getMachineNode(
1509 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001510 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001511 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001512 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001513 0);
1514 }
1515
1516 RN = dyn_cast<RegisterSDNode>(Index);
1517 if (RN && RN->getReg() == 0)
1518 Index = CurDAG->getRegister(0, MVT::i64);
1519 else {
1520 assert(Index.getValueType() == MVT::i32 &&
1521 "Expect to be extending 32-bit registers for use in LEA");
1522 Index = SDValue(CurDAG->getMachineNode(
1523 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001524 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001525 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001526 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1527 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001528 0);
1529 }
1530
1531 return true;
1532}
1533
Evan Cheng77d86ff2006-02-25 10:09:08 +00001534/// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1535/// mode it matches can be cost effectively emitted as an LEA instruction.
Chris Lattner0e023ea2010-09-21 20:31:19 +00001536bool X86DAGToDAGISel::SelectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001537 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001538 SDValue &Index, SDValue &Disp,
1539 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001540 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001541
1542 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1543 // segments.
1544 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001545 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001546 AM.Segment = T;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001547 if (MatchAddress(N, AM))
1548 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001549 assert (T == AM.Segment);
1550 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001551
Craig Topper83e042a2013-08-15 05:57:07 +00001552 MVT VT = N.getSimpleValueType();
Evan Cheng77d86ff2006-02-25 10:09:08 +00001553 unsigned Complexity = 0;
1554 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001555 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001556 Complexity = 1;
1557 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001558 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001559 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1560 Complexity = 4;
1561
Gabor Greiff304a7a2008-08-28 21:40:38 +00001562 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001563 Complexity++;
1564 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001565 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001566
Chris Lattner3e1d9172007-03-20 06:08:29 +00001567 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1568 // a simple shift.
1569 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001570 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001571
1572 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1573 // to a LEA. This is determined with some expermentation but is by no means
1574 // optimal (especially for code size consideration). LEA is nice because of
1575 // its three-address nature. Tweak the cost function again when we can run
1576 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001577 if (AM.hasSymbolicDisplacement()) {
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001578 // For X86-64, we should always use lea to materialize RIP relative
1579 // addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001580 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001581 Complexity = 4;
1582 else
1583 Complexity += 2;
1584 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001585
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001586 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001587 Complexity++;
1588
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001589 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001590 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001591 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001592
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001593 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001594 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001595}
1596
Chris Lattner7d2b0492009-06-20 20:38:48 +00001597/// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
Chris Lattner0e023ea2010-09-21 20:31:19 +00001598bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001599 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001600 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001601 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1602 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001603
Chris Lattner7d2b0492009-06-20 20:38:48 +00001604 X86ISelAddressMode AM;
1605 AM.GV = GA->getGlobal();
1606 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001607 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001608 AM.SymbolFlags = GA->getTargetFlags();
1609
Owen Anderson9f944592009-08-11 20:47:22 +00001610 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001611 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001612 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001613 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001614 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001615 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001616
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001617 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001618 return true;
1619}
1620
1621
Dan Gohmanea6f91f2010-01-05 01:24:18 +00001622bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001623 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001624 SDValue &Index, SDValue &Disp,
1625 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001626 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1627 !IsProfitableToFold(N, P, P) ||
Dan Gohman21cea8a2010-04-17 15:26:15 +00001628 !IsLegalToFold(N, P, P, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001629 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001630
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001631 return SelectAddr(N.getNode(),
1632 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001633}
1634
Dan Gohman24300732008-09-23 18:22:58 +00001635/// getGlobalBaseReg - Return an SDNode that returns the value of
1636/// the global base register. Output instructions required to
1637/// initialize the global base register, if necessary.
Evan Cheng5588de92006-02-18 00:15:05 +00001638///
Evan Cheng61413a32006-08-26 05:34:46 +00001639SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001640 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Eric Christopherb17140d2014-10-08 07:32:17 +00001641 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy()).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001642}
1643
Michael Liao83725392012-09-19 19:36:58 +00001644/// Atomic opcode table
1645///
Eric Christophereb47a2a2011-05-17 07:47:55 +00001646enum AtomicOpc {
Michael Liao83725392012-09-19 19:36:58 +00001647 ADD,
1648 SUB,
1649 INC,
1650 DEC,
Eric Christopherabfe3132011-05-17 07:50:41 +00001651 OR,
Eric Christophera1d9e292011-05-17 08:10:18 +00001652 AND,
1653 XOR,
Eric Christopherabfe3132011-05-17 07:50:41 +00001654 AtomicOpcEnd
Eric Christophereb47a2a2011-05-17 07:47:55 +00001655};
1656
1657enum AtomicSz {
1658 ConstantI8,
1659 I8,
1660 SextConstantI16,
1661 ConstantI16,
1662 I16,
1663 SextConstantI32,
1664 ConstantI32,
1665 I32,
1666 SextConstantI64,
1667 ConstantI64,
Eric Christopherabfe3132011-05-17 07:50:41 +00001668 I64,
1669 AtomicSzEnd
Eric Christophereb47a2a2011-05-17 07:47:55 +00001670};
1671
Craig Topper2dac9622012-03-09 07:45:21 +00001672static const uint16_t AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] = {
Eric Christopher2a9dbbb2011-05-11 21:44:58 +00001673 {
Michael Liao83725392012-09-19 19:36:58 +00001674 X86::LOCK_ADD8mi,
1675 X86::LOCK_ADD8mr,
1676 X86::LOCK_ADD16mi8,
1677 X86::LOCK_ADD16mi,
1678 X86::LOCK_ADD16mr,
1679 X86::LOCK_ADD32mi8,
1680 X86::LOCK_ADD32mi,
1681 X86::LOCK_ADD32mr,
1682 X86::LOCK_ADD64mi8,
1683 X86::LOCK_ADD64mi32,
1684 X86::LOCK_ADD64mr,
1685 },
1686 {
1687 X86::LOCK_SUB8mi,
1688 X86::LOCK_SUB8mr,
1689 X86::LOCK_SUB16mi8,
1690 X86::LOCK_SUB16mi,
1691 X86::LOCK_SUB16mr,
1692 X86::LOCK_SUB32mi8,
1693 X86::LOCK_SUB32mi,
1694 X86::LOCK_SUB32mr,
1695 X86::LOCK_SUB64mi8,
1696 X86::LOCK_SUB64mi32,
1697 X86::LOCK_SUB64mr,
1698 },
1699 {
1700 0,
1701 X86::LOCK_INC8m,
1702 0,
1703 0,
1704 X86::LOCK_INC16m,
1705 0,
1706 0,
1707 X86::LOCK_INC32m,
1708 0,
1709 0,
1710 X86::LOCK_INC64m,
1711 },
1712 {
1713 0,
1714 X86::LOCK_DEC8m,
1715 0,
1716 0,
1717 X86::LOCK_DEC16m,
1718 0,
1719 0,
1720 X86::LOCK_DEC32m,
1721 0,
1722 0,
1723 X86::LOCK_DEC64m,
1724 },
1725 {
Eric Christopher2a9dbbb2011-05-11 21:44:58 +00001726 X86::LOCK_OR8mi,
1727 X86::LOCK_OR8mr,
1728 X86::LOCK_OR16mi8,
1729 X86::LOCK_OR16mi,
1730 X86::LOCK_OR16mr,
1731 X86::LOCK_OR32mi8,
1732 X86::LOCK_OR32mi,
1733 X86::LOCK_OR32mr,
1734 X86::LOCK_OR64mi8,
1735 X86::LOCK_OR64mi32,
Michael Liao83725392012-09-19 19:36:58 +00001736 X86::LOCK_OR64mr,
Eric Christophera1d9e292011-05-17 08:10:18 +00001737 },
1738 {
1739 X86::LOCK_AND8mi,
1740 X86::LOCK_AND8mr,
1741 X86::LOCK_AND16mi8,
1742 X86::LOCK_AND16mi,
1743 X86::LOCK_AND16mr,
1744 X86::LOCK_AND32mi8,
1745 X86::LOCK_AND32mi,
1746 X86::LOCK_AND32mr,
1747 X86::LOCK_AND64mi8,
1748 X86::LOCK_AND64mi32,
Michael Liao83725392012-09-19 19:36:58 +00001749 X86::LOCK_AND64mr,
Eric Christophera1d9e292011-05-17 08:10:18 +00001750 },
1751 {
1752 X86::LOCK_XOR8mi,
1753 X86::LOCK_XOR8mr,
1754 X86::LOCK_XOR16mi8,
1755 X86::LOCK_XOR16mi,
1756 X86::LOCK_XOR16mr,
1757 X86::LOCK_XOR32mi8,
1758 X86::LOCK_XOR32mi,
1759 X86::LOCK_XOR32mr,
1760 X86::LOCK_XOR64mi8,
1761 X86::LOCK_XOR64mi32,
Michael Liao83725392012-09-19 19:36:58 +00001762 X86::LOCK_XOR64mr,
Eric Christopher2a9dbbb2011-05-11 21:44:58 +00001763 }
1764};
1765
Michael Liao83725392012-09-19 19:36:58 +00001766// Return the target constant operand for atomic-load-op and do simple
1767// translations, such as from atomic-load-add to lock-sub. The return value is
1768// one of the following 3 cases:
1769// + target-constant, the operand could be supported as a target constant.
1770// + empty, the operand is not needed any more with the new op selected.
1771// + non-empty, otherwise.
1772static SDValue getAtomicLoadArithTargetConstant(SelectionDAG *CurDAG,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001773 SDLoc dl,
Craig Topper83e042a2013-08-15 05:57:07 +00001774 enum AtomicOpc &Op, MVT NVT,
Robin Morisset6f3d04e2014-10-08 23:16:23 +00001775 SDValue Val,
1776 const X86Subtarget *Subtarget) {
Michael Liao83725392012-09-19 19:36:58 +00001777 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val)) {
1778 int64_t CNVal = CN->getSExtValue();
1779 // Quit if not 32-bit imm.
1780 if ((int32_t)CNVal != CNVal)
1781 return Val;
Robin Morisset880580b2014-10-07 23:53:57 +00001782 // Quit if INT32_MIN: it would be negated as it is negative and overflow,
1783 // producing an immediate that does not fit in the 32 bits available for
1784 // an immediate operand to sub. However, it still fits in 32 bits for the
1785 // add (since it is not negated) so we can return target-constant.
1786 if (CNVal == INT32_MIN)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001787 return CurDAG->getTargetConstant(CNVal, dl, NVT);
Michael Liao83725392012-09-19 19:36:58 +00001788 // For atomic-load-add, we could do some optimizations.
1789 if (Op == ADD) {
1790 // Translate to INC/DEC if ADD by 1 or -1.
Robin Morisset6f3d04e2014-10-08 23:16:23 +00001791 if (((CNVal == 1) || (CNVal == -1)) && !Subtarget->slowIncDec()) {
Michael Liao83725392012-09-19 19:36:58 +00001792 Op = (CNVal == 1) ? INC : DEC;
1793 // No more constant operand after being translated into INC/DEC.
1794 return SDValue();
1795 }
1796 // Translate to SUB if ADD by negative value.
1797 if (CNVal < 0) {
1798 Op = SUB;
1799 CNVal = -CNVal;
1800 }
1801 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001802 return CurDAG->getTargetConstant(CNVal, dl, NVT);
Michael Liao83725392012-09-19 19:36:58 +00001803 }
1804
1805 // If the value operand is single-used, try to optimize it.
1806 if (Op == ADD && Val.hasOneUse()) {
1807 // Translate (atomic-load-add ptr (sub 0 x)) back to (lock-sub x).
1808 if (Val.getOpcode() == ISD::SUB && X86::isZeroNode(Val.getOperand(0))) {
1809 Op = SUB;
1810 return Val.getOperand(1);
1811 }
1812 // A special case for i16, which needs truncating as, in most cases, it's
1813 // promoted to i32. We will translate
1814 // (atomic-load-add (truncate (sub 0 x))) to (lock-sub (EXTRACT_SUBREG x))
1815 if (Val.getOpcode() == ISD::TRUNCATE && NVT == MVT::i16 &&
1816 Val.getOperand(0).getOpcode() == ISD::SUB &&
1817 X86::isZeroNode(Val.getOperand(0).getOperand(0))) {
1818 Op = SUB;
1819 Val = Val.getOperand(0);
1820 return CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl, NVT,
1821 Val.getOperand(1));
1822 }
1823 }
1824
1825 return Val;
1826}
1827
Craig Topper83e042a2013-08-15 05:57:07 +00001828SDNode *X86DAGToDAGISel::SelectAtomicLoadArith(SDNode *Node, MVT NVT) {
Eric Christopher4a34e612011-05-10 23:57:45 +00001829 if (Node->hasAnyUseOfValue(0))
Craig Topper062a2ba2014-04-25 05:30:21 +00001830 return nullptr;
Chad Rosier24c19d22012-08-01 18:39:17 +00001831
Andrew Trickef9de2a2013-05-25 02:42:55 +00001832 SDLoc dl(Node);
Michael Liao83725392012-09-19 19:36:58 +00001833
Eric Christopher56a42eb2011-05-17 08:16:14 +00001834 // Optimize common patterns for __sync_or_and_fetch and similar arith
1835 // operations where the result is not used. This allows us to use the "lock"
1836 // version of the arithmetic instruction.
Eric Christopher4a34e612011-05-10 23:57:45 +00001837 SDValue Chain = Node->getOperand(0);
1838 SDValue Ptr = Node->getOperand(1);
1839 SDValue Val = Node->getOperand(2);
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001840 SDValue Base, Scale, Index, Disp, Segment;
1841 if (!SelectAddr(Node, Ptr, Base, Scale, Index, Disp, Segment))
Craig Topper062a2ba2014-04-25 05:30:21 +00001842 return nullptr;
Eric Christopher4a34e612011-05-10 23:57:45 +00001843
Eric Christophera1d9e292011-05-17 08:10:18 +00001844 // Which index into the table.
1845 enum AtomicOpc Op;
1846 switch (Node->getOpcode()) {
Michael Liao83725392012-09-19 19:36:58 +00001847 default:
Craig Topper062a2ba2014-04-25 05:30:21 +00001848 return nullptr;
Eric Christophera1d9e292011-05-17 08:10:18 +00001849 case ISD::ATOMIC_LOAD_OR:
1850 Op = OR;
1851 break;
1852 case ISD::ATOMIC_LOAD_AND:
1853 Op = AND;
1854 break;
1855 case ISD::ATOMIC_LOAD_XOR:
1856 Op = XOR;
1857 break;
Michael Liao83725392012-09-19 19:36:58 +00001858 case ISD::ATOMIC_LOAD_ADD:
1859 Op = ADD;
1860 break;
Eric Christophera1d9e292011-05-17 08:10:18 +00001861 }
Andrew Trick52b83872013-04-13 06:07:36 +00001862
Robin Morisset6f3d04e2014-10-08 23:16:23 +00001863 Val = getAtomicLoadArithTargetConstant(CurDAG, dl, Op, NVT, Val, Subtarget);
Michael Liao83725392012-09-19 19:36:58 +00001864 bool isUnOp = !Val.getNode();
1865 bool isCN = Val.getNode() && (Val.getOpcode() == ISD::TargetConstant);
Chad Rosier24c19d22012-08-01 18:39:17 +00001866
Eric Christopher4a34e612011-05-10 23:57:45 +00001867 unsigned Opc = 0;
Craig Topper83e042a2013-08-15 05:57:07 +00001868 switch (NVT.SimpleTy) {
Craig Topper062a2ba2014-04-25 05:30:21 +00001869 default: return nullptr;
Eric Christopher4a34e612011-05-10 23:57:45 +00001870 case MVT::i8:
1871 if (isCN)
Eric Christophereb47a2a2011-05-17 07:47:55 +00001872 Opc = AtomicOpcTbl[Op][ConstantI8];
Eric Christopher4a34e612011-05-10 23:57:45 +00001873 else
Eric Christophereb47a2a2011-05-17 07:47:55 +00001874 Opc = AtomicOpcTbl[Op][I8];
Eric Christopher4a34e612011-05-10 23:57:45 +00001875 break;
1876 case MVT::i16:
1877 if (isCN) {
1878 if (immSext8(Val.getNode()))
Eric Christophereb47a2a2011-05-17 07:47:55 +00001879 Opc = AtomicOpcTbl[Op][SextConstantI16];
Eric Christopher4a34e612011-05-10 23:57:45 +00001880 else
Eric Christophereb47a2a2011-05-17 07:47:55 +00001881 Opc = AtomicOpcTbl[Op][ConstantI16];
Eric Christopher4a34e612011-05-10 23:57:45 +00001882 } else
Eric Christophereb47a2a2011-05-17 07:47:55 +00001883 Opc = AtomicOpcTbl[Op][I16];
Eric Christopher4a34e612011-05-10 23:57:45 +00001884 break;
1885 case MVT::i32:
1886 if (isCN) {
1887 if (immSext8(Val.getNode()))
Eric Christophereb47a2a2011-05-17 07:47:55 +00001888 Opc = AtomicOpcTbl[Op][SextConstantI32];
Eric Christopher4a34e612011-05-10 23:57:45 +00001889 else
Eric Christophereb47a2a2011-05-17 07:47:55 +00001890 Opc = AtomicOpcTbl[Op][ConstantI32];
Eric Christopher4a34e612011-05-10 23:57:45 +00001891 } else
Eric Christophereb47a2a2011-05-17 07:47:55 +00001892 Opc = AtomicOpcTbl[Op][I32];
Eric Christopher4a34e612011-05-10 23:57:45 +00001893 break;
1894 case MVT::i64:
1895 if (isCN) {
1896 if (immSext8(Val.getNode()))
Eric Christophereb47a2a2011-05-17 07:47:55 +00001897 Opc = AtomicOpcTbl[Op][SextConstantI64];
Eric Christopher4a34e612011-05-10 23:57:45 +00001898 else if (i64immSExt32(Val.getNode()))
Eric Christophereb47a2a2011-05-17 07:47:55 +00001899 Opc = AtomicOpcTbl[Op][ConstantI64];
Robin Morisset880580b2014-10-07 23:53:57 +00001900 else
1901 llvm_unreachable("True 64 bits constant in SelectAtomicLoadArith");
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001902 } else
1903 Opc = AtomicOpcTbl[Op][I64];
Eric Christopher4a34e612011-05-10 23:57:45 +00001904 break;
1905 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001906
Eric Christopherc93217372011-06-30 00:48:30 +00001907 assert(Opc != 0 && "Invalid arith lock transform!");
1908
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001909 // Building the new node.
Michael Liao83725392012-09-19 19:36:58 +00001910 SDValue Ret;
Michael Liao83725392012-09-19 19:36:58 +00001911 if (isUnOp) {
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001912 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Chain };
Michael Liaob53d8962013-04-19 22:22:57 +00001913 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
Michael Liao83725392012-09-19 19:36:58 +00001914 } else {
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001915 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Val, Chain };
Michael Liaob53d8962013-04-19 22:22:57 +00001916 Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
Michael Liao83725392012-09-19 19:36:58 +00001917 }
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001918
1919 // Copying the MachineMemOperand.
1920 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1921 MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
Eric Christopher4a34e612011-05-10 23:57:45 +00001922 cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
Robin Morisset5ce0ce42014-08-29 20:19:23 +00001923
1924 // We need to have two outputs as that is what the original instruction had.
1925 // So we add a dummy, undefined output. This is safe as we checked first
1926 // that no-one uses our output anyway.
1927 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1928 dl, NVT), 0);
Eric Christopher4a34e612011-05-10 23:57:45 +00001929 SDValue RetVals[] = { Undef, Ret };
Craig Topper64941d92014-04-27 19:20:57 +00001930 return CurDAG->getMergeValues(RetVals, dl).getNode();
Eric Christopher4a34e612011-05-10 23:57:45 +00001931}
1932
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001933/// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1934/// any uses which require the SF or OF bits to be accurate.
1935static bool HasNoSignedComparisonUses(SDNode *N) {
1936 // Examine each user of the node.
1937 for (SDNode::use_iterator UI = N->use_begin(),
1938 UE = N->use_end(); UI != UE; ++UI) {
1939 // Only examine CopyToReg uses.
1940 if (UI->getOpcode() != ISD::CopyToReg)
1941 return false;
1942 // Only examine CopyToReg uses that copy to EFLAGS.
1943 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1944 X86::EFLAGS)
1945 return false;
1946 // Examine each user of the CopyToReg use.
1947 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1948 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1949 // Only examine the Flag result.
1950 if (FlagUI.getUse().getResNo() != 1) continue;
1951 // Anything unusual: assume conservatively.
1952 if (!FlagUI->isMachineOpcode()) return false;
1953 // Examine the opcode of the user.
1954 switch (FlagUI->getMachineOpcode()) {
1955 // These comparisons don't treat the most significant bit specially.
1956 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1957 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1958 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1959 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001960 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1961 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001962 case X86::CMOVA16rr: case X86::CMOVA16rm:
1963 case X86::CMOVA32rr: case X86::CMOVA32rm:
1964 case X86::CMOVA64rr: case X86::CMOVA64rm:
1965 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1966 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1967 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1968 case X86::CMOVB16rr: case X86::CMOVB16rm:
1969 case X86::CMOVB32rr: case X86::CMOVB32rm:
1970 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001971 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1972 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1973 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001974 case X86::CMOVE16rr: case X86::CMOVE16rm:
1975 case X86::CMOVE32rr: case X86::CMOVE32rm:
1976 case X86::CMOVE64rr: case X86::CMOVE64rm:
1977 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1978 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1979 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1980 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1981 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1982 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1983 case X86::CMOVP16rr: case X86::CMOVP16rm:
1984 case X86::CMOVP32rr: case X86::CMOVP32rm:
1985 case X86::CMOVP64rr: case X86::CMOVP64rm:
1986 continue;
1987 // Anything else: assume conservatively.
1988 default: return false;
1989 }
1990 }
1991 }
1992 return true;
1993}
1994
Joel Jones68d59e82012-03-29 05:45:48 +00001995/// isLoadIncOrDecStore - Check whether or not the chain ending in StoreNode
1996/// is suitable for doing the {load; increment or decrement; store} to modify
1997/// transformation.
Chad Rosier24c19d22012-08-01 18:39:17 +00001998static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
Evan Cheng3e869f02012-04-12 19:14:21 +00001999 SDValue StoredVal, SelectionDAG *CurDAG,
2000 LoadSDNode* &LoadNode, SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002001
2002 // is the value stored the result of a DEC or INC?
2003 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
2004
Joel Jones68d59e82012-03-29 05:45:48 +00002005 // is the stored value result 0 of the load?
2006 if (StoredVal.getResNo() != 0) return false;
2007
2008 // are there other uses of the loaded value than the inc or dec?
2009 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2010
Joel Jones68d59e82012-03-29 05:45:48 +00002011 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002012 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002013 return false;
2014
Evan Cheng3e869f02012-04-12 19:14:21 +00002015 SDValue Load = StoredVal->getOperand(0);
2016 // Is the stored value a non-extending and non-indexed load?
2017 if (!ISD::isNormalLoad(Load.getNode())) return false;
2018
2019 // Return LoadNode by reference.
2020 LoadNode = cast<LoadSDNode>(Load);
2021 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
Chad Rosier24c19d22012-08-01 18:39:17 +00002022 EVT LdVT = LoadNode->getMemoryVT();
2023 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
Evan Cheng3e869f02012-04-12 19:14:21 +00002024 LdVT != MVT::i8)
2025 return false;
2026
2027 // Is store the only read of the loaded value?
2028 if (!Load.hasOneUse())
2029 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002030
Evan Cheng3e869f02012-04-12 19:14:21 +00002031 // Is the address of the store the same as the load?
2032 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2033 LoadNode->getOffset() != StoreNode->getOffset())
2034 return false;
2035
2036 // Check if the chain is produced by the load or is a TokenFactor with
2037 // the load output chain as an operand. Return InputChain by reference.
2038 SDValue Chain = StoreNode->getChain();
2039
2040 bool ChainCheck = false;
2041 if (Chain == Load.getValue(1)) {
2042 ChainCheck = true;
2043 InputChain = LoadNode->getChain();
2044 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2045 SmallVector<SDValue, 4> ChainOps;
2046 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2047 SDValue Op = Chain.getOperand(i);
2048 if (Op == Load.getValue(1)) {
2049 ChainCheck = true;
2050 continue;
2051 }
Evan Cheng58a95f02012-05-16 01:54:27 +00002052
2053 // Make sure using Op as part of the chain would not cause a cycle here.
2054 // In theory, we could check whether the chain node is a predecessor of
2055 // the load. But that can be very expensive. Instead visit the uses and
2056 // make sure they all have smaller node id than the load.
2057 int LoadId = LoadNode->getNodeId();
2058 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2059 UE = UI->use_end(); UI != UE; ++UI) {
2060 if (UI.getUse().getResNo() != 0)
2061 continue;
2062 if (UI->getNodeId() > LoadId)
2063 return false;
2064 }
2065
Evan Cheng3e869f02012-04-12 19:14:21 +00002066 ChainOps.push_back(Op);
2067 }
2068
2069 if (ChainCheck)
2070 // Make a new TokenFactor with all the other input chains except
2071 // for the load.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002072 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
Craig Topper48d114b2014-04-26 18:35:24 +00002073 MVT::Other, ChainOps);
Evan Cheng3e869f02012-04-12 19:14:21 +00002074 }
2075 if (!ChainCheck)
Joel Jones68d59e82012-03-29 05:45:48 +00002076 return false;
2077
2078 return true;
2079}
2080
Benjamin Kramer8619c372012-03-29 12:37:26 +00002081/// getFusedLdStOpcode - Get the appropriate X86 opcode for an in memory
2082/// increment or decrement. Opc should be X86ISD::DEC or X86ISD::INC.
Joel Jones68d59e82012-03-29 05:45:48 +00002083static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
2084 if (Opc == X86ISD::DEC) {
2085 if (LdVT == MVT::i64) return X86::DEC64m;
2086 if (LdVT == MVT::i32) return X86::DEC32m;
2087 if (LdVT == MVT::i16) return X86::DEC16m;
2088 if (LdVT == MVT::i8) return X86::DEC8m;
Benjamin Kramer8619c372012-03-29 12:37:26 +00002089 } else {
2090 assert(Opc == X86ISD::INC && "unrecognized opcode");
Joel Jones68d59e82012-03-29 05:45:48 +00002091 if (LdVT == MVT::i64) return X86::INC64m;
2092 if (LdVT == MVT::i32) return X86::INC32m;
2093 if (LdVT == MVT::i16) return X86::INC16m;
2094 if (LdVT == MVT::i8) return X86::INC8m;
Joel Jones68d59e82012-03-29 05:45:48 +00002095 }
Benjamin Kramer8619c372012-03-29 12:37:26 +00002096 llvm_unreachable("unrecognized size for LdVT");
Joel Jones68d59e82012-03-29 05:45:48 +00002097}
2098
Manman Rena0982042012-06-26 19:47:59 +00002099/// SelectGather - Customized ISel for GATHER operations.
2100///
2101SDNode *X86DAGToDAGISel::SelectGather(SDNode *Node, unsigned Opc) {
2102 // Operands of Gather: VSrc, Base, VIdx, VMask, Scale
2103 SDValue Chain = Node->getOperand(0);
2104 SDValue VSrc = Node->getOperand(2);
2105 SDValue Base = Node->getOperand(3);
2106 SDValue VIdx = Node->getOperand(4);
2107 SDValue VMask = Node->getOperand(5);
2108 ConstantSDNode *Scale = dyn_cast<ConstantSDNode>(Node->getOperand(6));
Craig Topperfbb954f72012-07-01 02:17:08 +00002109 if (!Scale)
Craig Topper062a2ba2014-04-25 05:30:21 +00002110 return nullptr;
Manman Rena0982042012-06-26 19:47:59 +00002111
Craig Topperf7755df2012-07-12 06:52:41 +00002112 SDVTList VTs = CurDAG->getVTList(VSrc.getValueType(), VSrc.getValueType(),
2113 MVT::Other);
2114
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002115 SDLoc DL(Node);
2116
Manman Rena0982042012-06-26 19:47:59 +00002117 // Memory Operands: Base, Scale, Index, Disp, Segment
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002118 SDValue Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
Manman Rena0982042012-06-26 19:47:59 +00002119 SDValue Segment = CurDAG->getRegister(0, MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002120 const SDValue Ops[] = { VSrc, Base, getI8Imm(Scale->getSExtValue(), DL), VIdx,
Manman Rena0982042012-06-26 19:47:59 +00002121 Disp, Segment, VMask, Chain};
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002122 SDNode *ResNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
Craig Topperf7755df2012-07-12 06:52:41 +00002123 // Node has 2 outputs: VDst and MVT::Other.
2124 // ResNode has 3 outputs: VDst, VMask_wb, and MVT::Other.
2125 // We replace VDst of Node with VDst of ResNode, and Other of Node with Other
2126 // of ResNode.
2127 ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
2128 ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 2));
Manman Rena0982042012-06-26 19:47:59 +00002129 return ResNode;
2130}
2131
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002132SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002133 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002134 unsigned Opc, MOpc;
2135 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002136 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002137
Chris Lattnerf98f1242010-03-02 06:34:30 +00002138 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
Evan Chengd49cc362006-02-10 22:24:32 +00002139
Dan Gohman17059682008-07-17 19:10:17 +00002140 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002141 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002142 Node->setNodeId(-1);
Craig Topper062a2ba2014-04-25 05:30:21 +00002143 return nullptr; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002144 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002145
Evan Cheng10d27902006-01-06 20:36:21 +00002146 switch (Opcode) {
Dan Gohman757eee82009-08-02 16:10:52 +00002147 default: break;
Manman Rena0982042012-06-26 19:47:59 +00002148 case ISD::INTRINSIC_W_CHAIN: {
2149 unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2150 switch (IntNo) {
2151 default: break;
2152 case Intrinsic::x86_avx2_gather_d_pd:
Manman Rena0982042012-06-26 19:47:59 +00002153 case Intrinsic::x86_avx2_gather_d_pd_256:
Manman Rena0982042012-06-26 19:47:59 +00002154 case Intrinsic::x86_avx2_gather_q_pd:
Manman Rena0982042012-06-26 19:47:59 +00002155 case Intrinsic::x86_avx2_gather_q_pd_256:
Manman Rena0982042012-06-26 19:47:59 +00002156 case Intrinsic::x86_avx2_gather_d_ps:
Manman Rena0982042012-06-26 19:47:59 +00002157 case Intrinsic::x86_avx2_gather_d_ps_256:
Manman Rena0982042012-06-26 19:47:59 +00002158 case Intrinsic::x86_avx2_gather_q_ps:
Manman Rena0982042012-06-26 19:47:59 +00002159 case Intrinsic::x86_avx2_gather_q_ps_256:
Manman Ren98a5bf22012-06-29 00:54:20 +00002160 case Intrinsic::x86_avx2_gather_d_q:
Manman Ren98a5bf22012-06-29 00:54:20 +00002161 case Intrinsic::x86_avx2_gather_d_q_256:
Manman Ren98a5bf22012-06-29 00:54:20 +00002162 case Intrinsic::x86_avx2_gather_q_q:
Manman Ren98a5bf22012-06-29 00:54:20 +00002163 case Intrinsic::x86_avx2_gather_q_q_256:
Manman Ren98a5bf22012-06-29 00:54:20 +00002164 case Intrinsic::x86_avx2_gather_d_d:
Manman Ren98a5bf22012-06-29 00:54:20 +00002165 case Intrinsic::x86_avx2_gather_d_d_256:
Manman Ren98a5bf22012-06-29 00:54:20 +00002166 case Intrinsic::x86_avx2_gather_q_d:
Craig Topperdef044b2012-07-01 02:05:52 +00002167 case Intrinsic::x86_avx2_gather_q_d_256: {
Michael Liao00b20cc2013-06-05 18:12:26 +00002168 if (!Subtarget->hasAVX2())
2169 break;
Craig Topperdef044b2012-07-01 02:05:52 +00002170 unsigned Opc;
2171 switch (IntNo) {
Craig Topper3af251d2012-07-01 02:55:34 +00002172 default: llvm_unreachable("Impossible intrinsic");
Craig Topperdef044b2012-07-01 02:05:52 +00002173 case Intrinsic::x86_avx2_gather_d_pd: Opc = X86::VGATHERDPDrm; break;
2174 case Intrinsic::x86_avx2_gather_d_pd_256: Opc = X86::VGATHERDPDYrm; break;
2175 case Intrinsic::x86_avx2_gather_q_pd: Opc = X86::VGATHERQPDrm; break;
2176 case Intrinsic::x86_avx2_gather_q_pd_256: Opc = X86::VGATHERQPDYrm; break;
2177 case Intrinsic::x86_avx2_gather_d_ps: Opc = X86::VGATHERDPSrm; break;
2178 case Intrinsic::x86_avx2_gather_d_ps_256: Opc = X86::VGATHERDPSYrm; break;
2179 case Intrinsic::x86_avx2_gather_q_ps: Opc = X86::VGATHERQPSrm; break;
2180 case Intrinsic::x86_avx2_gather_q_ps_256: Opc = X86::VGATHERQPSYrm; break;
2181 case Intrinsic::x86_avx2_gather_d_q: Opc = X86::VPGATHERDQrm; break;
2182 case Intrinsic::x86_avx2_gather_d_q_256: Opc = X86::VPGATHERDQYrm; break;
2183 case Intrinsic::x86_avx2_gather_q_q: Opc = X86::VPGATHERQQrm; break;
2184 case Intrinsic::x86_avx2_gather_q_q_256: Opc = X86::VPGATHERQQYrm; break;
2185 case Intrinsic::x86_avx2_gather_d_d: Opc = X86::VPGATHERDDrm; break;
2186 case Intrinsic::x86_avx2_gather_d_d_256: Opc = X86::VPGATHERDDYrm; break;
2187 case Intrinsic::x86_avx2_gather_q_d: Opc = X86::VPGATHERQDrm; break;
2188 case Intrinsic::x86_avx2_gather_q_d_256: Opc = X86::VPGATHERQDYrm; break;
2189 }
Craig Topperfbb954f72012-07-01 02:17:08 +00002190 SDNode *RetVal = SelectGather(Node, Opc);
2191 if (RetVal)
Craig Topperf7755df2012-07-12 06:52:41 +00002192 // We already called ReplaceUses inside SelectGather.
Craig Topper062a2ba2014-04-25 05:30:21 +00002193 return nullptr;
Craig Toppere15e5f72012-07-01 02:18:18 +00002194 break;
Craig Topperdef044b2012-07-01 02:05:52 +00002195 }
Manman Rena0982042012-06-26 19:47:59 +00002196 }
2197 break;
2198 }
Dan Gohman757eee82009-08-02 16:10:52 +00002199 case X86ISD::GlobalBaseReg:
2200 return getGlobalBaseReg();
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002201
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002202 case X86ISD::SHRUNKBLEND: {
2203 // SHRUNKBLEND selects like a regular VSELECT.
2204 SDValue VSelect = CurDAG->getNode(
2205 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2206 Node->getOperand(1), Node->getOperand(2));
2207 ReplaceUses(SDValue(Node, 0), VSelect);
2208 SelectCode(VSelect.getNode());
2209 // We already called ReplaceUses.
2210 return nullptr;
2211 }
Craig Topper3af251d2012-07-01 02:55:34 +00002212
Eric Christophera1d9e292011-05-17 08:10:18 +00002213 case ISD::ATOMIC_LOAD_XOR:
2214 case ISD::ATOMIC_LOAD_AND:
Michael Liao83725392012-09-19 19:36:58 +00002215 case ISD::ATOMIC_LOAD_OR:
2216 case ISD::ATOMIC_LOAD_ADD: {
Eric Christophera1d9e292011-05-17 08:10:18 +00002217 SDNode *RetVal = SelectAtomicLoadArith(Node, NVT);
Eric Christopher4a34e612011-05-10 23:57:45 +00002218 if (RetVal)
2219 return RetVal;
2220 break;
2221 }
Benjamin Kramer4c816242011-04-22 15:30:40 +00002222 case ISD::AND:
2223 case ISD::OR:
2224 case ISD::XOR: {
2225 // For operations of the form (x << C1) op C2, check if we can use a smaller
2226 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2227 SDValue N0 = Node->getOperand(0);
2228 SDValue N1 = Node->getOperand(1);
2229
2230 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2231 break;
2232
2233 // i8 is unshrinkable, i16 should be promoted to i32.
2234 if (NVT != MVT::i32 && NVT != MVT::i64)
2235 break;
2236
2237 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2238 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2239 if (!Cst || !ShlCst)
2240 break;
2241
2242 int64_t Val = Cst->getSExtValue();
2243 uint64_t ShlVal = ShlCst->getZExtValue();
2244
2245 // Make sure that we don't change the operation by removing bits.
2246 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002247 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2248 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002249 break;
2250
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002251 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002252 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002253
2254 // Check the minimum bitwidth for the new constant.
2255 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2256 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2257 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2258 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2259 CstVT = MVT::i8;
2260 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2261 CstVT = MVT::i32;
2262
2263 // Bail if there is no smaller encoding.
2264 if (NVT == CstVT)
2265 break;
2266
Craig Topper83e042a2013-08-15 05:57:07 +00002267 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002268 default: llvm_unreachable("Unsupported VT!");
2269 case MVT::i32:
2270 assert(CstVT == MVT::i8);
2271 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002272 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002273
2274 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002275 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002276 case ISD::AND: Op = X86::AND32ri8; break;
2277 case ISD::OR: Op = X86::OR32ri8; break;
2278 case ISD::XOR: Op = X86::XOR32ri8; break;
2279 }
2280 break;
2281 case MVT::i64:
2282 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2283 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002284 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002285
2286 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002287 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002288 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2289 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2290 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2291 }
2292 break;
2293 }
2294
2295 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002296 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002297 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002298 if (ShlVal == 1)
2299 return CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2300 SDValue(New, 0));
Benjamin Kramer4c816242011-04-22 15:30:40 +00002301 return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002302 getI8Imm(ShlVal, dl));
Benjamin Kramer4c816242011-04-22 15:30:40 +00002303 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002304 case X86ISD::UMUL8:
2305 case X86ISD::SMUL8: {
2306 SDValue N0 = Node->getOperand(0);
2307 SDValue N1 = Node->getOperand(1);
2308
2309 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2310
2311 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2312 N0, SDValue()).getValue(1);
2313
2314 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2315 SDValue Ops[] = {N1, InFlag};
2316 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2317
2318 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2319 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2320 return nullptr;
2321 }
2322
Chris Lattner364bb0a2010-12-05 07:30:36 +00002323 case X86ISD::UMUL: {
2324 SDValue N0 = Node->getOperand(0);
2325 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002326
Ted Kremenekb5241b22011-01-14 22:34:13 +00002327 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002328 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002329 default: llvm_unreachable("Unsupported VT!");
Ted Kremenekb5241b22011-01-14 22:34:13 +00002330 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2331 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2332 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2333 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002334 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002335
Chris Lattner364bb0a2010-12-05 07:30:36 +00002336 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2337 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002338
Chris Lattner364bb0a2010-12-05 07:30:36 +00002339 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2340 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002341 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002342
Chris Lattner364bb0a2010-12-05 07:30:36 +00002343 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2344 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2345 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 2));
Craig Topper062a2ba2014-04-25 05:30:21 +00002346 return nullptr;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002347 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002348
Dan Gohman757eee82009-08-02 16:10:52 +00002349 case ISD::SMUL_LOHI:
2350 case ISD::UMUL_LOHI: {
2351 SDValue N0 = Node->getOperand(0);
2352 SDValue N1 = Node->getOperand(1);
2353
2354 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002355 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002356 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002357 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002358 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002359 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2360 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002361 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2362 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2363 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2364 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002365 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002366 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002367 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002368 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002369 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2370 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2371 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2372 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002373 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002374 }
Dan Gohman757eee82009-08-02 16:10:52 +00002375
Michael Liaof9f7b552012-09-26 08:22:37 +00002376 unsigned SrcReg, LoReg, HiReg;
2377 switch (Opc) {
2378 default: llvm_unreachable("Unknown MUL opcode!");
2379 case X86::IMUL8r:
2380 case X86::MUL8r:
2381 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2382 break;
2383 case X86::IMUL16r:
2384 case X86::MUL16r:
2385 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2386 break;
2387 case X86::IMUL32r:
2388 case X86::MUL32r:
2389 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2390 break;
2391 case X86::IMUL64r:
2392 case X86::MUL64r:
2393 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2394 break;
2395 case X86::MULX32rr:
2396 SrcReg = X86::EDX; LoReg = HiReg = 0;
2397 break;
2398 case X86::MULX64rr:
2399 SrcReg = X86::RDX; LoReg = HiReg = 0;
2400 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002401 }
2402
2403 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002404 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002405 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002406 if (!foldedLoad) {
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002407 foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002408 if (foldedLoad)
2409 std::swap(N0, N1);
2410 }
2411
Michael Liaof9f7b552012-09-26 08:22:37 +00002412 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002413 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002414 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002415
2416 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002417 SDValue Chain;
Dan Gohman757eee82009-08-02 16:10:52 +00002418 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2419 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002420 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2421 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002422 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002423 ResHi = SDValue(CNode, 0);
2424 ResLo = SDValue(CNode, 1);
2425 Chain = SDValue(CNode, 2);
2426 InFlag = SDValue(CNode, 3);
2427 } else {
2428 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002429 SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002430 Chain = SDValue(CNode, 0);
2431 InFlag = SDValue(CNode, 1);
2432 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002433
Dan Gohman757eee82009-08-02 16:10:52 +00002434 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002435 ReplaceUses(N1.getValue(1), Chain);
Dan Gohman757eee82009-08-02 16:10:52 +00002436 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002437 SDValue Ops[] = { N1, InFlag };
2438 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2439 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002440 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002441 ResHi = SDValue(CNode, 0);
2442 ResLo = SDValue(CNode, 1);
2443 InFlag = SDValue(CNode, 2);
2444 } else {
2445 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002446 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002447 InFlag = SDValue(CNode, 0);
2448 }
Dan Gohman757eee82009-08-02 16:10:52 +00002449 }
2450
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002451 // Prevent use of AH in a REX instruction by referencing AX instead.
2452 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2453 !SDValue(Node, 1).use_empty()) {
2454 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2455 X86::AX, MVT::i16, InFlag);
2456 InFlag = Result.getValue(2);
2457 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2458 // registers.
2459 if (!SDValue(Node, 0).use_empty())
2460 ReplaceUses(SDValue(Node, 1),
2461 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2462
2463 // Shift AX down 8 bits.
2464 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2465 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002466 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2467 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002468 // Then truncate it down to i8.
2469 ReplaceUses(SDValue(Node, 1),
2470 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2471 }
Dan Gohman757eee82009-08-02 16:10:52 +00002472 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002473 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002474 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002475 assert(LoReg && "Register for low half is not defined!");
2476 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2477 InFlag);
2478 InFlag = ResLo.getValue(2);
2479 }
2480 ReplaceUses(SDValue(Node, 0), ResLo);
2481 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002482 }
2483 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002484 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002485 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002486 assert(HiReg && "Register for high half is not defined!");
2487 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2488 InFlag);
2489 InFlag = ResHi.getValue(2);
2490 }
2491 ReplaceUses(SDValue(Node, 1), ResHi);
2492 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002493 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002494
Craig Topper062a2ba2014-04-25 05:30:21 +00002495 return nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002496 }
2497
2498 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002499 case ISD::UDIVREM:
2500 case X86ISD::SDIVREM8_SEXT_HREG:
2501 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002502 SDValue N0 = Node->getOperand(0);
2503 SDValue N1 = Node->getOperand(1);
2504
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002505 bool isSigned = (Opcode == ISD::SDIVREM ||
2506 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002507 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002508 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002509 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002510 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2511 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2512 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2513 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002514 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002515 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002516 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002517 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002518 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2519 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2520 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2521 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002522 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002523 }
Dan Gohman757eee82009-08-02 16:10:52 +00002524
Chris Lattner518b0372009-12-23 01:45:04 +00002525 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002526 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002527 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002528 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002529 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002530 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002531 SExtOpcode = X86::CBW;
2532 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002533 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002534 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002535 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002536 SExtOpcode = X86::CWD;
2537 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002538 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002539 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002540 SExtOpcode = X86::CDQ;
2541 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002542 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002543 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002544 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002545 break;
2546 }
2547
Dan Gohman757eee82009-08-02 16:10:52 +00002548 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002549 bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002550 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002551
Dan Gohman757eee82009-08-02 16:10:52 +00002552 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002553 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002554 // Special case for div8, just use a move with zero extension to AX to
2555 // clear the upper 8 bits (AH).
2556 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002557 if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002558 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2559 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002560 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002561 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002562 Chain = Move.getValue(1);
2563 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002564 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002565 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002566 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002567 Chain = CurDAG->getEntryNode();
2568 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002569 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002570 InFlag = Chain.getValue(1);
2571 } else {
2572 InFlag =
2573 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2574 LoReg, N0, SDValue()).getValue(1);
2575 if (isSigned && !signBitIsZero) {
2576 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002577 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002578 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002579 } else {
2580 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002581 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002582 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002583 case MVT::i16:
2584 ClrNode =
2585 SDValue(CurDAG->getMachineNode(
2586 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002587 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2588 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002589 0);
2590 break;
2591 case MVT::i32:
2592 break;
2593 case MVT::i64:
2594 ClrNode =
2595 SDValue(CurDAG->getMachineNode(
2596 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002597 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2598 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2599 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002600 0);
2601 break;
2602 default:
2603 llvm_unreachable("Unexpected division source");
2604 }
2605
Chris Lattner518b0372009-12-23 01:45:04 +00002606 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00002607 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00002608 }
Evan Cheng92e27972006-01-06 23:19:29 +00002609 }
Dan Gohmana1603612007-10-08 18:33:35 +00002610
Dan Gohman757eee82009-08-02 16:10:52 +00002611 if (foldedLoad) {
2612 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2613 InFlag };
2614 SDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00002615 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00002616 InFlag = SDValue(CNode, 1);
2617 // Update the chain.
2618 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2619 } else {
2620 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002621 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002622 }
Evan Cheng92e27972006-01-06 23:19:29 +00002623
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002624 // Prevent use of AH in a REX instruction by explicitly copying it to
2625 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00002626 //
2627 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002628 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00002629 // the allocator and/or the backend get enhanced to be more robust in
2630 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002631 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2632 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2633 unsigned AHExtOpcode =
2634 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002635
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002636 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2637 MVT::Glue, AHCopy, InFlag);
2638 SDValue Result(RNode, 0);
2639 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002640
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002641 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2642 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2643 if (Node->getValueType(1) == MVT::i64) {
2644 // It's not possible to directly movsx AH to a 64bit register, because
2645 // the latter needs the REX prefix, but the former can't have it.
2646 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2647 "Unexpected i64 sext of h-register");
2648 Result =
2649 SDValue(CurDAG->getMachineNode(
2650 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002651 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2652 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2653 MVT::i32)),
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002654 0);
2655 }
2656 } else {
2657 Result =
2658 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2659 }
2660 ReplaceUses(SDValue(Node, 1), Result);
2661 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002662 }
Dan Gohman757eee82009-08-02 16:10:52 +00002663 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002664 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00002665 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2666 LoReg, NVT, InFlag);
2667 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002668 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002669 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002670 }
2671 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002672 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002673 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2674 HiReg, NVT, InFlag);
2675 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002676 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002677 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002678 }
Craig Topper062a2ba2014-04-25 05:30:21 +00002679 return nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002680 }
2681
Manman Ren1be131b2012-08-08 00:51:41 +00002682 case X86ISD::CMP:
2683 case X86ISD::SUB: {
2684 // Sometimes a SUB is used to perform comparison.
2685 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2686 // This node is not a CMP.
2687 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00002688 SDValue N0 = Node->getOperand(0);
2689 SDValue N1 = Node->getOperand(1);
2690
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002691 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002692 HasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002693 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002694
Dan Gohmanac33a902009-08-19 18:16:17 +00002695 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2696 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002697 // Look past the truncate if CMP is the only use of it.
Dan Gohman198b7ff2011-11-03 21:49:52 +00002698 if ((N0.getNode()->getOpcode() == ISD::AND ||
2699 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2700 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00002701 N0.getValueType() != MVT::i8 &&
2702 X86::isZeroNode(N1)) {
2703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2704 if (!C) break;
2705
2706 // For example, convert "testl %eax, $8" to "testb %al, $8"
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002707 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2708 (!(C->getZExtValue() & 0x80) ||
2709 HasNoSignedComparisonUses(Node))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002710 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
Dan Gohmanac33a902009-08-19 18:16:17 +00002711 SDValue Reg = N0.getNode()->getOperand(0);
2712
2713 // On x86-32, only the ABCD registers have 8-bit subregisters.
2714 if (!Subtarget->is64Bit()) {
Craig Toppercc830f82012-02-22 07:28:11 +00002715 const TargetRegisterClass *TRC;
Craig Topper56710102013-08-15 02:33:50 +00002716 switch (N0.getSimpleValueType().SimpleTy) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002717 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2718 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2719 default: llvm_unreachable("Unsupported TEST operand type!");
2720 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002721 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Dan Gohman32f71d72009-09-25 18:54:59 +00002722 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2723 Reg.getValueType(), Reg, RC), 0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002724 }
2725
2726 // Extract the l-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002727 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002728 MVT::i8, Reg);
2729
2730 // Emit a testb.
Manman Ren511c6d02012-09-28 18:53:24 +00002731 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2732 Subreg, Imm);
2733 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2734 // one, do not call ReplaceAllUsesWith.
2735 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2736 SDValue(NewNode, 0));
Craig Topper062a2ba2014-04-25 05:30:21 +00002737 return nullptr;
Dan Gohmanac33a902009-08-19 18:16:17 +00002738 }
2739
2740 // For example, "testl %eax, $2048" to "testb %ah, $8".
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002741 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2742 (!(C->getZExtValue() & 0x8000) ||
2743 HasNoSignedComparisonUses(Node))) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002744 // Shift the immediate right by 8 bits.
2745 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002746 dl, MVT::i8);
Dan Gohmanac33a902009-08-19 18:16:17 +00002747 SDValue Reg = N0.getNode()->getOperand(0);
2748
2749 // Put the value in an ABCD register.
Craig Toppercc830f82012-02-22 07:28:11 +00002750 const TargetRegisterClass *TRC;
Craig Topper56710102013-08-15 02:33:50 +00002751 switch (N0.getSimpleValueType().SimpleTy) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002752 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2753 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2754 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2755 default: llvm_unreachable("Unsupported TEST operand type!");
2756 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002757 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Dan Gohman32f71d72009-09-25 18:54:59 +00002758 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2759 Reg.getValueType(), Reg, RC), 0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002760
2761 // Extract the h-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002762 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002763 MVT::i8, Reg);
2764
Jakob Stoklund Olesen729abd32011-10-08 18:28:28 +00002765 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2766 // target GR8_NOREX registers, so make sure the register class is
2767 // forced.
Manman Ren511c6d02012-09-28 18:53:24 +00002768 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2769 MVT::i32, Subreg, ShiftedImm);
2770 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2771 // one, do not call ReplaceAllUsesWith.
2772 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2773 SDValue(NewNode, 0));
Craig Topper062a2ba2014-04-25 05:30:21 +00002774 return nullptr;
Dan Gohmanac33a902009-08-19 18:16:17 +00002775 }
2776
2777 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2778 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002779 N0.getValueType() != MVT::i16 &&
2780 (!(C->getZExtValue() & 0x8000) ||
2781 HasNoSignedComparisonUses(Node))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002782 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2783 MVT::i16);
Dan Gohmanac33a902009-08-19 18:16:17 +00002784 SDValue Reg = N0.getNode()->getOperand(0);
2785
2786 // Extract the 16-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002787 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002788 MVT::i16, Reg);
2789
2790 // Emit a testw.
Manman Ren511c6d02012-09-28 18:53:24 +00002791 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2792 Subreg, Imm);
2793 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2794 // one, do not call ReplaceAllUsesWith.
2795 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2796 SDValue(NewNode, 0));
Craig Topper062a2ba2014-04-25 05:30:21 +00002797 return nullptr;
Dan Gohmanac33a902009-08-19 18:16:17 +00002798 }
2799
2800 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2801 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002802 N0.getValueType() == MVT::i64 &&
2803 (!(C->getZExtValue() & 0x80000000) ||
2804 HasNoSignedComparisonUses(Node))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002805 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2806 MVT::i32);
Dan Gohmanac33a902009-08-19 18:16:17 +00002807 SDValue Reg = N0.getNode()->getOperand(0);
2808
2809 // Extract the 32-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002810 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002811 MVT::i32, Reg);
2812
2813 // Emit a testl.
Manman Ren511c6d02012-09-28 18:53:24 +00002814 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2815 Subreg, Imm);
2816 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2817 // one, do not call ReplaceAllUsesWith.
2818 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2819 SDValue(NewNode, 0));
Craig Topper062a2ba2014-04-25 05:30:21 +00002820 return nullptr;
Dan Gohmanac33a902009-08-19 18:16:17 +00002821 }
2822 }
2823 break;
2824 }
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002825 case ISD::STORE: {
Joel Jones68d59e82012-03-29 05:45:48 +00002826 // Change a chain of {load; incr or dec; store} of the same value into
2827 // a simple increment or decrement through memory of that value, if the
2828 // uses of the modified value and its address are suitable.
Pete Cooper48784ed2011-11-16 19:03:23 +00002829 // The DEC64m tablegen pattern is currently not able to match the case where
Chad Rosier24c19d22012-08-01 18:39:17 +00002830 // the EFLAGS on the original DEC are used. (This also applies to
Joel Jones68d59e82012-03-29 05:45:48 +00002831 // {INC,DEC}X{64,32,16,8}.)
2832 // We'll need to improve tablegen to allow flags to be transferred from a
Pete Cooper48784ed2011-11-16 19:03:23 +00002833 // node in the pattern to the result node. probably with a new keyword
2834 // for example, we have this
2835 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2836 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2837 // (implicit EFLAGS)]>;
2838 // but maybe need something like this
2839 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2840 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2841 // (transferrable EFLAGS)]>;
Joel Jones68d59e82012-03-29 05:45:48 +00002842
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002843 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002844 SDValue StoredVal = StoreNode->getOperand(1);
Joel Jones68d59e82012-03-29 05:45:48 +00002845 unsigned Opc = StoredVal->getOpcode();
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002846
Craig Topper062a2ba2014-04-25 05:30:21 +00002847 LoadSDNode *LoadNode = nullptr;
Evan Cheng3e869f02012-04-12 19:14:21 +00002848 SDValue InputChain;
2849 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2850 LoadNode, InputChain))
2851 break;
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002852
2853 SDValue Base, Scale, Index, Disp, Segment;
2854 if (!SelectAddr(LoadNode, LoadNode->getBasePtr(),
2855 Base, Scale, Index, Disp, Segment))
2856 break;
2857
2858 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2859 MemOp[0] = StoreNode->getMemOperand();
2860 MemOp[1] = LoadNode->getMemOperand();
2861 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
Chad Rosier24c19d22012-08-01 18:39:17 +00002862 EVT LdVT = LoadNode->getMemoryVT();
Joel Jones68d59e82012-03-29 05:45:48 +00002863 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2864 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002865 SDLoc(Node),
Michael Liaob53d8962013-04-19 22:22:57 +00002866 MVT::i32, MVT::Other, Ops);
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002867 Result->setMemRefs(MemOp, MemOp + 2);
2868
2869 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2870 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2871
2872 return Result;
2873 }
Chris Lattner655e7df2005-11-16 01:54:32 +00002874 }
2875
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002876 SDNode *ResNode = SelectCode(Node);
Evan Chengbd1c5a82006-08-11 09:08:15 +00002877
Chris Lattnerf98f1242010-03-02 06:34:30 +00002878 DEBUG(dbgs() << "=> ";
Craig Toppere73658d2014-04-28 04:05:08 +00002879 if (ResNode == nullptr || ResNode == Node)
Chris Lattnerf98f1242010-03-02 06:34:30 +00002880 Node->dump(CurDAG);
2881 else
2882 ResNode->dump(CurDAG);
2883 dbgs() << '\n');
Evan Chengbd1c5a82006-08-11 09:08:15 +00002884
2885 return ResNode;
Chris Lattner655e7df2005-11-16 01:54:32 +00002886}
2887
Chris Lattnerba1ed582006-06-08 18:03:49 +00002888bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00002889SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00002890 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00002891 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00002892 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00002893 default:
2894 llvm_unreachable("Unexpected asm memory constraint");
2895 case InlineAsm::Constraint_i:
2896 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2897 // be an immediate and not a memory constraint.
2898 // Fallthrough.
Daniel Sanders60f1db02015-03-13 12:45:09 +00002899 case InlineAsm::Constraint_o: // offsetable ??
2900 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00002901 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00002902 case InlineAsm::Constraint_X:
Craig Topper062a2ba2014-04-25 05:30:21 +00002903 if (!SelectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00002904 return true;
2905 break;
2906 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002907
Evan Cheng2d487222006-08-26 01:05:16 +00002908 OutOps.push_back(Op0);
2909 OutOps.push_back(Op1);
2910 OutOps.push_back(Op2);
2911 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00002912 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00002913 return false;
2914}
2915
Chad Rosier24c19d22012-08-01 18:39:17 +00002916/// createX86ISelDag - This pass converts a legalized DAG into a
Chris Lattner655e7df2005-11-16 01:54:32 +00002917/// X86-specific DAG, ready for instruction scheduling.
2918///
Bill Wendling026e5d72009-04-29 23:29:43 +00002919FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00002920 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00002921 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00002922}