blob: b015afc1353b8b5e81878df525a93651064edc88 [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 Chengf55b7382008-01-05 00:41:47 +000016#include "X86MachineFunctionInfo.h"
Chris Lattner7c551262006-01-11 01:15:34 +000017#include "X86RegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000018#include "X86Subtarget.h"
Evan Cheng2dd2c652006-03-13 23:20:37 +000019#include "X86TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Statistic.h"
Evan Cheng73a1ad92006-01-10 20:26:56 +000021#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000023#include "llvm/CodeGen/SelectionDAGISel.h"
Nico Weber432a3882018-04-30 14:59:11 +000024#include "llvm/Config/llvm-config.h"
Peter Collingbourne235c2752016-12-08 19:01:00 +000025#include "llvm/IR/ConstantRange.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000026#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Type.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000030#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000031#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000032#include "llvm/Support/KnownBits.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"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +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
Sanjay Patel40aa8672018-08-23 15:58:07 +000044static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
45 cl::desc("Enable setting constant bits to reduce size of mask immediates"),
46 cl::Hidden);
47
Chris Lattner655e7df2005-11-16 01:54:32 +000048//===----------------------------------------------------------------------===//
49// Pattern Matcher Implementation
50//===----------------------------------------------------------------------===//
51
52namespace {
Sanjay Patelb5723d02015-10-13 15:12:27 +000053 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
54 /// numbers for the leaves of the matched tree.
Chris Lattner3f0f71b2005-11-19 02:11:08 +000055 struct X86ISelAddressMode {
56 enum {
57 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000058 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000059 } BaseType;
60
Dan Gohman0fd54fb2010-04-29 23:30:41 +000061 // This is really a union, discriminated by BaseType!
62 SDValue Base_Reg;
63 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000064
65 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000066 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000067 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000068 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000069 const GlobalValue *GV;
70 const Constant *CP;
71 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000072 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000073 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000074 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000075 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000076 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000077
78 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000079 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
80 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
81 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000082
83 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000084 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000085 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000086 }
Chad Rosier24c19d22012-08-01 18:39:17 +000087
Chris Lattnerfea81da2009-06-27 04:16:01 +000088 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000089 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000090 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000091 }
Chad Rosier24c19d22012-08-01 18:39:17 +000092
Sanjay Patelb5723d02015-10-13 15:12:27 +000093 /// Return true if this addressing mode is already RIP-relative.
Chris Lattnerfea81da2009-06-27 04:16:01 +000094 bool isRIPRelative() const {
95 if (BaseType != RegBase) return false;
96 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +000097 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +000098 return RegNode->getReg() == X86::RIP;
99 return false;
100 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000101
Chris Lattnerfea81da2009-06-27 04:16:01 +0000102 void setBaseReg(SDValue Reg) {
103 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000104 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000105 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000106
Aaron Ballman615eb472017-10-15 14:32:27 +0000107#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Craig Topper25007c42018-03-16 21:10:07 +0000108 void dump(SelectionDAG *DAG = nullptr) {
David Greenedbdb1b22010-01-05 01:29:08 +0000109 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000110 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000111 if (Base_Reg.getNode())
Craig Topper25007c42018-03-16 21:10:07 +0000112 Base_Reg.getNode()->dump(DAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000113 else
Craig Toppereff84ed2017-12-22 17:18:10 +0000114 dbgs() << "nul\n";
115 if (BaseType == FrameIndexBase)
116 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
117 dbgs() << " Scale " << Scale << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000118 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000119 if (IndexReg.getNode())
Craig Topper25007c42018-03-16 21:10:07 +0000120 IndexReg.getNode()->dump(DAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000121 else
Craig Toppereff84ed2017-12-22 17:18:10 +0000122 dbgs() << "nul\n";
David Greenedbdb1b22010-01-05 01:29:08 +0000123 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000124 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000125 if (GV)
126 GV->dump();
127 else
David Greenedbdb1b22010-01-05 01:29:08 +0000128 dbgs() << "nul";
129 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000130 if (CP)
131 CP->dump();
132 else
David Greenedbdb1b22010-01-05 01:29:08 +0000133 dbgs() << "nul";
134 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000135 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000136 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000137 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000138 else
David Greenedbdb1b22010-01-05 01:29:08 +0000139 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000140 dbgs() << " MCSym ";
141 if (MCSym)
142 dbgs() << MCSym;
143 else
144 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000145 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000146 }
Manman Ren742534c2012-09-06 19:06:06 +0000147#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000148 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000149}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000150
151namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000152 //===--------------------------------------------------------------------===//
Sanjay Patelb5723d02015-10-13 15:12:27 +0000153 /// ISel - X86-specific code to select X86 machine instructions for
Chris Lattner655e7df2005-11-16 01:54:32 +0000154 /// SelectionDAG operations.
155 ///
Craig Topper26eec092014-03-31 06:22:15 +0000156 class X86DAGToDAGISel final : public SelectionDAGISel {
Sanjay Patelb5723d02015-10-13 15:12:27 +0000157 /// Keep a pointer to the X86Subtarget around so that we can
Chris Lattner655e7df2005-11-16 01:54:32 +0000158 /// make the right decision when generating code for different targets.
159 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000160
Sanjay Patelb5723d02015-10-13 15:12:27 +0000161 /// If true, selector should try to optimize for code size instead of
162 /// performance.
Evan Cheng7d6fa972008-09-26 23:41:32 +0000163 bool OptForSize;
164
Hans Wennborg4ae51192016-03-25 01:10:56 +0000165 /// If true, selector should try to optimize for minimum code size.
166 bool OptForMinSize;
167
Kristina Brooks312fcc12018-10-18 03:14:37 +0000168 /// Disable direct TLS access through segment registers.
169 bool IndirectTlsSegRefs;
170
Chris Lattner655e7df2005-11-16 01:54:32 +0000171 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000172 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000173 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Matt Morehouse9e658c92017-12-01 22:20:26 +0000174 OptForMinSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000175
Mehdi Amini117296c2016-10-01 02:56:57 +0000176 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000177 return "X86 DAG->DAG Instruction Selection";
178 }
179
Eric Christopher4f09c592014-05-22 01:53:26 +0000180 bool runOnMachineFunction(MachineFunction &MF) override {
181 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000182 Subtarget = &MF.getSubtarget<X86Subtarget>();
Kristina Brooks312fcc12018-10-18 03:14:37 +0000183 IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
184 "indirect-tls-seg-refs");
Eric Christopher4f09c592014-05-22 01:53:26 +0000185 SelectionDAGISel::runOnMachineFunction(MF);
186 return true;
187 }
188
Craig Topper2d9361e2014-03-09 07:44:38 +0000189 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000190
Craig Topper2d9361e2014-03-09 07:44:38 +0000191 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000192
Craig Topper2d9361e2014-03-09 07:44:38 +0000193 void PreprocessISelDAG() override;
Craig Toppere6913ec2018-03-16 17:13:42 +0000194 void PostprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000195
Chris Lattner655e7df2005-11-16 01:54:32 +0000196// Include the pieces autogenerated from the target description.
197#include "X86GenDAGISel.inc"
198
199 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000200 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000201
Sanjay Patel85030aa2015-10-13 16:23:00 +0000202 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
203 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
204 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
205 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Craig Topperc314f462017-11-13 17:53:59 +0000206 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000207 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000208 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000209 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000210 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
211 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000212 SDValue &Scale, SDValue &Index, SDValue &Disp,
213 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000214 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000215 SDValue &Scale, SDValue &Index, SDValue &Disp,
216 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000217 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
218 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000219 SDValue &Scale, SDValue &Index, SDValue &Disp,
220 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000221 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000222 SDValue &Scale, SDValue &Index, SDValue &Disp,
223 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000224 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000225 SDValue &Scale, SDValue &Index, SDValue &Disp,
226 SDValue &Segment);
Craig Topperb0e986f2018-06-17 16:29:46 +0000227 bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000228 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000229 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000230 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000231 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000232 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000233
Craig Topper78a77042017-11-08 20:17:33 +0000234 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000236 SDValue &Index, SDValue &Disp,
237 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000238
Craig Topperd6564102018-04-27 22:15:33 +0000239 // Convenience method where P is also root.
Craig Topper78a77042017-11-08 20:17:33 +0000240 bool tryFoldLoad(SDNode *P, SDValue N,
241 SDValue &Base, SDValue &Scale,
242 SDValue &Index, SDValue &Disp,
243 SDValue &Segment) {
244 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
245 }
246
Sanjay Patelb5723d02015-10-13 15:12:27 +0000247 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000248 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000249 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000250 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000251
Sanjay Patel85030aa2015-10-13 16:23:00 +0000252 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000253
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000254 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000255 SDValue &Base, SDValue &Scale,
256 SDValue &Index, SDValue &Disp,
257 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000258 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000259 ? CurDAG->getTargetFrameIndex(
260 AM.Base_FrameIndex,
261 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000262 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000263 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000264 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000265 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000266 // is 32-bit.
267 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000268 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000269 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000270 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000271 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000272 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000273 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000274 else if (AM.ES) {
275 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000276 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000277 } else if (AM.MCSym) {
278 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
279 assert(AM.SymbolFlags == 0 && "oo");
280 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000281 } else if (AM.JT != -1) {
282 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000283 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000284 } else if (AM.BlockAddr)
285 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
286 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000287 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000288 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000289
290 if (AM.Segment.getNode())
291 Segment = AM.Segment;
292 else
Owen Anderson9f944592009-08-11 20:47:22 +0000293 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000294 }
295
Michael Kuperstein243c0732015-08-11 14:10:58 +0000296 // Utility function to determine whether we should avoid selecting
297 // immediate forms of instructions for better code size or not.
298 // At a high level, we'd like to avoid such instructions when
299 // we have similar constants used within the same basic block
300 // that can be kept in a register.
301 //
302 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
303 uint32_t UseCount = 0;
304
305 // Do not want to hoist if we're not optimizing for size.
306 // TODO: We'd like to remove this restriction.
307 // See the comment in X86InstrInfo.td for more info.
308 if (!OptForSize)
309 return false;
310
311 // Walk all the users of the immediate.
312 for (SDNode::use_iterator UI = N->use_begin(),
313 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000314
Michael Kuperstein243c0732015-08-11 14:10:58 +0000315 SDNode *User = *UI;
316
317 // This user is already selected. Count it as a legitimate use and
318 // move on.
319 if (User->isMachineOpcode()) {
320 UseCount++;
321 continue;
322 }
323
324 // We want to count stores of immediates as real uses.
325 if (User->getOpcode() == ISD::STORE &&
326 User->getOperand(1).getNode() == N) {
327 UseCount++;
328 continue;
329 }
330
331 // We don't currently match users that have > 2 operands (except
332 // for stores, which are handled above)
333 // Those instruction won't match in ISEL, for now, and would
334 // be counted incorrectly.
335 // This may change in the future as we add additional instruction
336 // types.
337 if (User->getNumOperands() != 2)
338 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000339
Michael Kuperstein243c0732015-08-11 14:10:58 +0000340 // Immediates that are used for offsets as part of stack
341 // manipulation should be left alone. These are typically
342 // used to indicate SP offsets for argument passing and
343 // will get pulled into stores/pushes (implicitly).
344 if (User->getOpcode() == X86ISD::ADD ||
345 User->getOpcode() == ISD::ADD ||
346 User->getOpcode() == X86ISD::SUB ||
347 User->getOpcode() == ISD::SUB) {
348
349 // Find the other operand of the add/sub.
350 SDValue OtherOp = User->getOperand(0);
351 if (OtherOp.getNode() == N)
352 OtherOp = User->getOperand(1);
353
354 // Don't count if the other operand is SP.
355 RegisterSDNode *RegNode;
356 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
357 (RegNode = dyn_cast_or_null<RegisterSDNode>(
358 OtherOp->getOperand(1).getNode())))
359 if ((RegNode->getReg() == X86::ESP) ||
360 (RegNode->getReg() == X86::RSP))
361 continue;
362 }
363
364 // ... otherwise, count this and move on.
365 UseCount++;
366 }
367
368 // If we have more than 1 use, then recommend for hoisting.
369 return (UseCount > 1);
370 }
371
Sanjay Patelb5723d02015-10-13 15:12:27 +0000372 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000373 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000374 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000375 }
376
Sanjay Patelb5723d02015-10-13 15:12:27 +0000377 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000378 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000379 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000380 }
Evan Chengd49cc362006-02-10 22:24:32 +0000381
Craig Topper2b2d8c52018-02-15 19:57:35 +0000382 /// Return a target constant with the specified value, of type i64.
383 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
384 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
385 }
386
Craig Topper092c2f42017-09-23 05:34:07 +0000387 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
388 const SDLoc &DL) {
389 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
390 uint64_t Index = N->getConstantOperandVal(1);
391 MVT VecVT = N->getOperand(0).getSimpleValueType();
Craig Topper9563cab2017-10-08 01:33:42 +0000392 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000393 }
394
395 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
396 const SDLoc &DL) {
397 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
398 uint64_t Index = N->getConstantOperandVal(2);
399 MVT VecVT = N->getSimpleValueType(0);
Craig Topper9563cab2017-10-08 01:33:42 +0000400 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000401 }
402
Sanjay Patelb5723d02015-10-13 15:12:27 +0000403 /// Return an SDNode that returns the value of the global base register.
404 /// Output instructions required to initialize the global base register,
405 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000406 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000407
Sanjay Patelb5723d02015-10-13 15:12:27 +0000408 /// Return a reference to the TargetMachine, casted to the target-specific
409 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000410 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000411 return static_cast<const X86TargetMachine &>(TM);
412 }
413
Sanjay Patelb5723d02015-10-13 15:12:27 +0000414 /// Return a reference to the TargetInstrInfo, casted to the target-specific
415 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000416 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000417 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000418 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000419
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000420 /// Address-mode matching performs shift-of-and to and-of-shift
Adam Nemetff63a2d2014-10-03 20:00:34 +0000421 /// reassociation in order to expose more scaled addressing
422 /// opportunities.
423 bool ComplexPatternFuncMutatesDAG() const override {
424 return true;
425 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000426
427 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
428
429 /// Returns whether this is a relocatable immediate in the range
430 /// [-2^Width .. 2^Width-1].
431 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
432 if (auto *CN = dyn_cast<ConstantSDNode>(N))
433 return isInt<Width>(CN->getSExtValue());
434 return isSExtAbsoluteSymbolRef(Width, N);
435 }
Craig Topper4de6f582017-08-19 23:21:22 +0000436
437 // Indicates we should prefer to use a non-temporal load for this load.
438 bool useNonTemporalLoad(LoadSDNode *N) const {
439 if (!N->isNonTemporal())
440 return false;
441
442 unsigned StoreSize = N->getMemoryVT().getStoreSize();
443
444 if (N->getAlignment() < StoreSize)
445 return false;
446
447 switch (StoreSize) {
448 default: llvm_unreachable("Unsupported store size");
Simon Pilgrimc844bc82018-10-12 10:20:16 +0000449 case 4:
450 case 8:
451 return false;
Craig Topper4de6f582017-08-19 23:21:22 +0000452 case 16:
453 return Subtarget->hasSSE41();
454 case 32:
455 return Subtarget->hasAVX2();
456 case 64:
457 return Subtarget->hasAVX512();
458 }
459 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000460
461 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Toppere0a99292018-10-16 22:29:36 +0000462 MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
Roman Lebedev89880852018-10-22 14:12:44 +0000463 bool matchBitExtract(SDNode *Node);
Sanjay Patel74a1eef2018-01-19 16:37:25 +0000464 bool shrinkAndImmediate(SDNode *N);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000465 bool isMaskZeroExtended(SDNode *N) const;
Craig Topper538f8ab2018-08-22 19:39:09 +0000466 bool tryShiftAmountMod(SDNode *N);
Craig Topperd6564102018-04-27 22:15:33 +0000467
468 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
469 const SDLoc &dl, MVT VT, SDNode *Node);
470 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
471 const SDLoc &dl, MVT VT, SDNode *Node,
472 SDValue &InFlag);
Craig Topper5eea94e2018-10-21 21:07:27 +0000473
474 bool tryOptimizeRem8Extend(SDNode *N);
Chris Lattner655e7df2005-11-16 01:54:32 +0000475 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000476}
477
Evan Cheng72bb66a2006-08-08 00:31:00 +0000478
Craig Topperba3cc2e2017-09-25 18:43:13 +0000479// Returns true if this masked compare can be implemented legally with this
480// type.
481static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
Uriel Korachbb866862017-11-06 09:22:38 +0000482 unsigned Opcode = N->getOpcode();
Craig Topperc2696d52018-06-20 21:05:02 +0000483 if (Opcode == X86ISD::CMPM || Opcode == ISD::SETCC ||
Craig Topper48d5ed22018-02-28 08:14:28 +0000484 Opcode == X86ISD::CMPM_RND || Opcode == X86ISD::VFPCLASS) {
Craig Topperba3cc2e2017-09-25 18:43:13 +0000485 // We can get 256-bit 8 element types here without VLX being enabled. When
486 // this happens we will use 512-bit operations and the mask will not be
487 // zero extended.
Uriel Koracheb47d952017-11-06 08:32:45 +0000488 EVT OpVT = N->getOperand(0).getValueType();
Craig Topperd58c1652018-01-07 18:20:37 +0000489 if (OpVT.is256BitVector() || OpVT.is128BitVector())
Craig Topperba3cc2e2017-09-25 18:43:13 +0000490 return Subtarget->hasVLX();
491
492 return true;
493 }
Craig Topper48d5ed22018-02-28 08:14:28 +0000494 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
495 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
496 Opcode == X86ISD::FSETCCM_RND)
497 return true;
Craig Topperba3cc2e2017-09-25 18:43:13 +0000498
499 return false;
500}
501
502// Returns true if we can assume the writer of the mask has zero extended it
503// for us.
504bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
505 // If this is an AND, check if we have a compare on either side. As long as
506 // one side guarantees the mask is zero extended, the AND will preserve those
507 // zeros.
508 if (N->getOpcode() == ISD::AND)
509 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
510 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
511
512 return isLegalMaskCompare(N, Subtarget);
513}
514
Evan Cheng5e73ff22010-02-15 19:41:07 +0000515bool
516X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000517 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000518
Evan Cheng5e73ff22010-02-15 19:41:07 +0000519 if (!N.hasOneUse())
520 return false;
521
522 if (N.getOpcode() != ISD::LOAD)
523 return true;
524
Craig Topperb5421c42018-10-10 21:48:34 +0000525 // Don't fold non-temporal loads if we have an instruction for them.
526 if (useNonTemporalLoad(cast<LoadSDNode>(N)))
527 return false;
528
Evan Cheng5e73ff22010-02-15 19:41:07 +0000529 // If N is a load, do additional profitability checks.
530 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000531 switch (U->getOpcode()) {
532 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000533 case X86ISD::ADD:
Craig Topper0fd5cde2018-09-06 22:41:44 +0000534 case X86ISD::ADC:
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000535 case X86ISD::SUB:
Craig Topper0fd5cde2018-09-06 22:41:44 +0000536 case X86ISD::SBB:
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000537 case X86ISD::AND:
538 case X86ISD::XOR:
539 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000540 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000541 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000542 case ISD::AND:
543 case ISD::OR:
544 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000545 SDValue Op1 = U->getOperand(1);
546
Evan Cheng83bdb382008-11-27 00:49:46 +0000547 // If the other operand is a 8-bit immediate we should fold the immediate
548 // instead. This reduces code size.
549 // e.g.
550 // movl 4(%esp), %eax
551 // addl $4, %eax
552 // vs.
553 // movl $4, %eax
554 // addl 4(%esp), %eax
555 // The former is 2 bytes shorter. In case where the increment is 1, then
556 // the saving can be 4 bytes (by using incl %eax).
Craig Topper7e42af82018-04-10 03:44:15 +0000557 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
Dan Gohman2293eb62009-03-14 02:07:16 +0000558 if (Imm->getAPIntValue().isSignedIntN(8))
559 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000560
Craig Topper7e42af82018-04-10 03:44:15 +0000561 // If this is a 64-bit AND with an immediate that fits in 32-bits,
562 // prefer using the smaller and over folding the load. This is needed to
563 // make sure immediates created by shrinkAndImmediate are always folded.
564 // Ideally we would narrow the load during DAG combine and get the
565 // best of both worlds.
566 if (U->getOpcode() == ISD::AND &&
567 Imm->getAPIntValue().getBitWidth() == 64 &&
568 Imm->getAPIntValue().isIntN(32))
569 return false;
570 }
571
Rafael Espindolabb834f02009-04-10 10:09:34 +0000572 // If the other operand is a TLS address, we should fold it instead.
573 // This produces
574 // movl %gs:0, %eax
575 // leal i@NTPOFF(%eax), %eax
576 // instead of
577 // movl $i@NTPOFF, %eax
578 // addl %gs:0, %eax
579 // if the block also has an access to a second TLS address this will save
580 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000581 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000582 if (Op1.getOpcode() == X86ISD::Wrapper) {
583 SDValue Val = Op1.getOperand(0);
584 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
585 return false;
586 }
Craig Topperab70f582018-06-28 00:47:41 +0000587
Craig Topper90317d12018-06-28 17:58:01 +0000588 // Don't fold load if this matches the BTS/BTR/BTC patterns.
589 // BTS: (or X, (shl 1, n))
590 // BTR: (and X, (rotl -2, n))
591 // BTC: (xor X, (shl 1, n))
592 if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
593 if (U->getOperand(0).getOpcode() == ISD::SHL &&
594 isOneConstant(U->getOperand(0).getOperand(0)))
595 return false;
596
597 if (U->getOperand(1).getOpcode() == ISD::SHL &&
598 isOneConstant(U->getOperand(1).getOperand(0)))
599 return false;
600 }
601 if (U->getOpcode() == ISD::AND) {
602 SDValue U0 = U->getOperand(0);
603 SDValue U1 = U->getOperand(1);
604 if (U0.getOpcode() == ISD::ROTL) {
605 auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
606 if (C && C->getSExtValue() == -2)
607 return false;
608 }
609
610 if (U1.getOpcode() == ISD::ROTL) {
611 auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
612 if (C && C->getSExtValue() == -2)
613 return false;
614 }
615 }
616
Craig Topperab70f582018-06-28 00:47:41 +0000617 break;
Evan Cheng83bdb382008-11-27 00:49:46 +0000618 }
Craig Topperab70f582018-06-28 00:47:41 +0000619 case ISD::SHL:
620 case ISD::SRA:
621 case ISD::SRL:
622 // Don't fold a load into a shift by immediate. The BMI2 instructions
623 // support folding a load, but not an immediate. The legacy instructions
624 // support folding an immediate, but can't fold a load. Folding an
625 // immediate is preferable to folding a load.
626 if (isa<ConstantSDNode>(U->getOperand(1)))
627 return false;
628
629 break;
Evan Cheng83bdb382008-11-27 00:49:46 +0000630 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000631 }
632
Craig Topper38b290f2018-07-11 18:09:04 +0000633 // Prevent folding a load if this can implemented with an insert_subreg or
634 // a move that implicitly zeroes.
Craig Topper08b81a52018-07-10 06:19:54 +0000635 if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
Craig Topper38b290f2018-07-11 18:09:04 +0000636 isNullConstant(Root->getOperand(2)) &&
637 (Root->getOperand(0).isUndef() ||
638 ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
Craig Topper08b81a52018-07-10 06:19:54 +0000639 return false;
640
Evan Cheng5e73ff22010-02-15 19:41:07 +0000641 return true;
642}
643
Sanjay Patelb5723d02015-10-13 15:12:27 +0000644/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000645/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000646static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
647 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000648 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000649 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000650 if (Chain.getNode() == Load.getNode())
651 Ops.push_back(Load.getOperand(0));
652 else {
653 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000654 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000655 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
656 if (Chain.getOperand(i).getNode() == Load.getNode())
657 Ops.push_back(Load.getOperand(0));
658 else
659 Ops.push_back(Chain.getOperand(i));
660 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000661 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000662 Ops.clear();
663 Ops.push_back(NewChain);
664 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000665 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000666 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000667 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000668 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000669
Evan Chengf00f1e52008-08-25 21:27:18 +0000670 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000671 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000672 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000673 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000674}
675
Sanjay Patelb5723d02015-10-13 15:12:27 +0000676/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000677/// moved below CALLSEQ_START and the chains leading up to the call.
678/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000679/// In the case of a tail call, there isn't a callseq node between the call
680/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000681static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000682 // The transformation is somewhat dangerous if the call's chain was glued to
683 // the call. After MoveBelowOrigChain the load is moved between the call and
684 // the chain, this can create a cycle if the load is not folded. So it is
685 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000686 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000687 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000688 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000689 if (!LD ||
690 LD->isVolatile() ||
691 LD->getAddressingMode() != ISD::UNINDEXED ||
692 LD->getExtensionType() != ISD::NON_EXTLOAD)
693 return false;
694
695 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000696 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000697 if (!Chain.hasOneUse())
698 return false;
699 Chain = Chain.getOperand(0);
700 }
Evan Chengd703df62010-03-14 03:48:46 +0000701
702 if (!Chain.getNumOperands())
703 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000704 // Since we are not checking for AA here, conservatively abort if the chain
705 // writes to memory. It's not safe to move the callee (a load) across a store.
706 if (isa<MemSDNode>(Chain.getNode()) &&
707 cast<MemSDNode>(Chain.getNode())->writeMem())
708 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000709 if (Chain.getOperand(0).getNode() == Callee.getNode())
710 return true;
711 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000712 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
713 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000714 return true;
715 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000716}
717
Chris Lattner8d637042010-03-02 23:12:51 +0000718void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000719 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Matthias Braunf1caa282017-12-15 22:22:58 +0000720 OptForSize = MF->getFunction().optForSize();
721 OptForMinSize = MF->getFunction().optForMinSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000722 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000723
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000724 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
725 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000726 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000727
Craig Topper7e910a92018-02-01 17:08:39 +0000728 // If this is a target specific AND node with no flag usages, turn it back
729 // into ISD::AND to enable test instruction matching.
730 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
731 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
732 N->getOperand(0), N->getOperand(1));
733 --I;
734 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
735 ++I;
736 CurDAG->DeleteNode(N);
Craig Topper880e34e2018-06-27 20:58:46 +0000737 continue;
Craig Topper7e910a92018-02-01 17:08:39 +0000738 }
739
Evan Chengd703df62010-03-14 03:48:46 +0000740 if (OptLevel != CodeGenOpt::None &&
Chandler Carruthc58f2162018-01-22 22:05:25 +0000741 // Only do this when the target can fold the load into the call or
742 // jmp.
Chandler Carruthae0cafe2018-08-23 06:06:38 +0000743 !Subtarget->useRetpolineIndirectCalls() &&
Craig Topper62c47a22017-08-29 05:14:27 +0000744 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000745 (N->getOpcode() == X86ISD::TC_RETURN &&
Evan Cheng847ad442012-10-05 01:48:22 +0000746 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000747 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000748 /// Also try moving call address load from outside callseq_start to just
749 /// before the call to allow it to be folded.
750 ///
751 /// [Load chain]
752 /// ^
753 /// |
754 /// [Load]
755 /// ^ ^
756 /// | |
757 /// / \--
758 /// / |
759 ///[CALLSEQ_START] |
760 /// ^ |
761 /// | |
762 /// [LOAD/C2Reg] |
763 /// | |
764 /// \ /
765 /// \ /
766 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000767 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000768 SDValue Chain = N->getOperand(0);
769 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000770 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000771 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000772 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000773 ++NumLoadMoved;
774 continue;
775 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000776
Chris Lattner8d637042010-03-02 23:12:51 +0000777 // Lower fpround and fpextend nodes that target the FP stack to be store and
778 // load to the stack. This is a gross hack. We would like to simply mark
779 // these as being illegal, but when we do that, legalize produces these when
780 // it expands calls, then expands these in the same legalize pass. We would
781 // like dag combine to be able to hack on these between the call expansion
782 // and the node legalization. As such this pass basically does "really
783 // late" legalization of these inline with the X86 isel pass.
784 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000785 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
786 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000787
Craig Topper83e042a2013-08-15 05:57:07 +0000788 MVT SrcVT = N->getOperand(0).getSimpleValueType();
789 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000790
791 // If any of the sources are vectors, no fp stack involved.
792 if (SrcVT.isVector() || DstVT.isVector())
793 continue;
794
795 // If the source and destination are SSE registers, then this is a legal
796 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000797 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000798 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000799 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
800 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000801 if (SrcIsSSE && DstIsSSE)
802 continue;
803
Chris Lattnerd587e582008-03-09 07:05:32 +0000804 if (!SrcIsSSE && !DstIsSSE) {
805 // If this is an FPStack extension, it is a noop.
806 if (N->getOpcode() == ISD::FP_EXTEND)
807 continue;
808 // If this is a value-preserving FPStack truncation, it is a noop.
809 if (N->getConstantOperandVal(1))
810 continue;
811 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000812
Chris Lattnera91f77e2008-01-24 08:07:48 +0000813 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
814 // FPStack has extload and truncstore. SSE can fold direct loads into other
815 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000816 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000817 if (N->getOpcode() == ISD::FP_ROUND)
818 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
819 else
820 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000821
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000822 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000823 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000824
Chris Lattnera91f77e2008-01-24 08:07:48 +0000825 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000826 SDValue Store =
827 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
828 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000829 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000830 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000831
832 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
833 // extload we created. This will cause general havok on the dag because
834 // anything below the conversion could be folded into other existing nodes.
835 // To avoid invalidating 'I', back it up to the convert node.
836 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000837 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000838
Chris Lattnera91f77e2008-01-24 08:07:48 +0000839 // Now that we did that, the node is dead. Increment the iterator to the
840 // next node to process, then delete N.
841 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000842 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000843 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000844}
845
Craig Topper5eea94e2018-10-21 21:07:27 +0000846// Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
847bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
848 unsigned Opc = N->getMachineOpcode();
849 if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
850 Opc != X86::MOVSX64rr8)
851 return false;
852
853 SDValue N0 = N->getOperand(0);
854
855 // We need to be extracting the lower bit of an extend.
856 if (!N0.isMachineOpcode() ||
857 N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
858 N0.getConstantOperandVal(1) != X86::sub_8bit)
859 return false;
860
861 // We're looking for either a movsx or movzx to match the original opcode.
862 unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
863 : X86::MOVSX32rr8_NOREX;
864 SDValue N00 = N0.getOperand(0);
865 if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
866 return false;
867
868 if (Opc == X86::MOVSX64rr8) {
869 // If we had a sign extend from 8 to 64 bits. We still need to go from 32
870 // to 64.
871 MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
872 MVT::i64, N00);
873 ReplaceUses(N, Extend);
874 } else {
875 // Ok we can drop this extend and just use the original extend.
876 ReplaceUses(N, N00.getNode());
877 }
878
879 return true;
880}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000881
Craig Toppere6913ec2018-03-16 17:13:42 +0000882void X86DAGToDAGISel::PostprocessISelDAG() {
883 // Skip peepholes at -O0.
884 if (TM.getOptLevel() == CodeGenOpt::None)
885 return;
886
Craig Topper5c81c682018-10-19 19:24:42 +0000887 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
Craig Toppere6913ec2018-03-16 17:13:42 +0000888
Craig Topper5eea94e2018-10-21 21:07:27 +0000889 bool MadeChange = false;
Craig Toppere6913ec2018-03-16 17:13:42 +0000890 while (Position != CurDAG->allnodes_begin()) {
891 SDNode *N = &*--Position;
892 // Skip dead nodes and any non-machine opcodes.
893 if (N->use_empty() || !N->isMachineOpcode())
894 continue;
895
Craig Topper5eea94e2018-10-21 21:07:27 +0000896 if (tryOptimizeRem8Extend(N)) {
897 MadeChange = true;
898 continue;
899 }
900
901 // Attempt to remove vectors moves that were inserted to zero upper bits.
902
Craig Toppere6913ec2018-03-16 17:13:42 +0000903 if (N->getMachineOpcode() != TargetOpcode::SUBREG_TO_REG)
904 continue;
905
906 unsigned SubRegIdx = N->getConstantOperandVal(2);
907 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
908 continue;
909
910 SDValue Move = N->getOperand(1);
911 if (!Move.isMachineOpcode())
912 continue;
913
914 // Make sure its one of the move opcodes we recognize.
915 switch (Move.getMachineOpcode()) {
916 default:
917 continue;
918 case X86::VMOVAPDrr: case X86::VMOVUPDrr:
919 case X86::VMOVAPSrr: case X86::VMOVUPSrr:
920 case X86::VMOVDQArr: case X86::VMOVDQUrr:
921 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr:
922 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr:
923 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr:
924 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr:
925 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr:
926 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
927 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
928 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr:
929 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr:
930 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
931 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
932 break;
933 }
934
935 SDValue In = Move.getOperand(0);
936 if (!In.isMachineOpcode() ||
937 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
938 continue;
939
Craig Toppera80352c2018-08-03 04:49:42 +0000940 // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
941 // the SHA instructions which use a legacy encoding.
942 uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
943 if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
944 (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
945 (TSFlags & X86II::EncodingMask) != X86II::XOP)
946 continue;
947
Craig Toppere6913ec2018-03-16 17:13:42 +0000948 // Producing instruction is another vector instruction. We can drop the
949 // move.
950 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
Craig Topper5eea94e2018-10-21 21:07:27 +0000951 MadeChange = true;
Craig Toppere6913ec2018-03-16 17:13:42 +0000952 }
Craig Topper5eea94e2018-10-21 21:07:27 +0000953
954 if (MadeChange)
955 CurDAG->RemoveDeadNodes();
Craig Toppere6913ec2018-03-16 17:13:42 +0000956}
957
958
Sanjay Patelb5723d02015-10-13 15:12:27 +0000959/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000960void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000961 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000962 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000963 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000964
965 TargetLowering::CallLoweringInfo CLI(*CurDAG);
966 CLI.setChain(CurDAG->getRoot())
967 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000968 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000969 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000970 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
971 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
972 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000973 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000974}
975
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000976void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000977 // If this is main, emit special code for main.
Matthias Braunf1caa282017-12-15 22:22:58 +0000978 const Function &F = MF->getFunction();
979 if (F.hasExternalLinkage() && F.getName() == "main")
980 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000981}
982
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000983static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000984 // On 64-bit platforms, we can run into an issue where a frame index
985 // includes a displacement that, when added to the explicit displacement,
986 // will overflow the displacement field. Assuming that the frame index
987 // displacement fits into a 31-bit integer (which is only slightly more
988 // aggressive than the current fundamental assumption that it fits into
989 // a 32-bit integer), a 31-bit disp should always be safe.
990 return isInt<31>(Val);
991}
992
Sanjay Patel85030aa2015-10-13 16:23:00 +0000993bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000994 X86ISelAddressMode &AM) {
Reid Kleckner537917d2018-05-21 21:03:19 +0000995 // If there's no offset to fold, we don't need to do any work.
996 if (Offset == 0)
997 return false;
998
Reid Kleckner9dad2272015-05-04 23:22:36 +0000999 // Cannot combine ExternalSymbol displacements with integer offsets.
Reid Kleckner537917d2018-05-21 21:03:19 +00001000 if (AM.ES || AM.MCSym)
Reid Kleckner9dad2272015-05-04 23:22:36 +00001001 return true;
Reid Kleckner537917d2018-05-21 21:03:19 +00001002
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001003 int64_t Val = AM.Disp + Offset;
1004 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +00001005 if (Subtarget->is64Bit()) {
1006 if (!X86::isOffsetSuitableForCodeModel(Val, M,
1007 AM.hasSymbolicDisplacement()))
1008 return true;
1009 // In addition to the checks required for a register base, check that
1010 // we do not try to use an unsafe Disp with a frame index.
1011 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1012 !isDispSafeForFrameIndex(Val))
1013 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001014 }
Eli Friedman344ec792011-07-13 21:29:53 +00001015 AM.Disp = Val;
1016 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001017
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001018}
Rafael Espindola3b2df102009-04-08 21:14:34 +00001019
Sanjay Patel85030aa2015-10-13 16:23:00 +00001020bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +00001021 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00001022
Chris Lattner8a236b62010-09-22 04:39:11 +00001023 // load gs:0 -> GS segment register.
1024 // load fs:0 -> FS segment register.
1025 //
Rafael Espindola3b2df102009-04-08 21:14:34 +00001026 // This optimization is valid because the GNU TLS model defines that
1027 // gs:0 (or fs:0 on X86-64) contains its own address.
1028 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +00001029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +00001030 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Kristina Brooks312fcc12018-10-18 03:14:37 +00001031 !IndirectTlsSegRefs &&
Petr Hoseka7d59162017-02-24 03:10:10 +00001032 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1033 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +00001034 switch (N->getPointerInfo().getAddrSpace()) {
1035 case 256:
1036 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1037 return false;
1038 case 257:
1039 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1040 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001041 // Address space 258 is not handled here, because it is not used to
1042 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +00001043 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001044
Rafael Espindola3b2df102009-04-08 21:14:34 +00001045 return true;
1046}
1047
Sanjay Patelb5723d02015-10-13 15:12:27 +00001048/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1049/// mode. These wrap things that will resolve down into a symbol reference.
1050/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001051bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +00001052 // If the addressing mode already has a symbol as the displacement, we can
1053 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001054 if (AM.hasSymbolicDisplacement())
1055 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001056
Reid Kleckner537917d2018-05-21 21:03:19 +00001057 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1058
Reid Kleckner980c4df2018-07-23 21:14:35 +00001059 // We can't use an addressing mode in the 64-bit large code model. In the
1060 // medium code model, we use can use an mode when RIP wrappers are present.
1061 // That signifies access to globals that are known to be "near", such as the
1062 // GOT itself.
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001063 CodeModel::Model M = TM.getCodeModel();
Reid Kleckner980c4df2018-07-23 21:14:35 +00001064 if (Subtarget->is64Bit() &&
1065 (M == CodeModel::Large || (M == CodeModel::Medium && !IsRIPRel)))
Reid Kleckner537917d2018-05-21 21:03:19 +00001066 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001067
Reid Kleckner537917d2018-05-21 21:03:19 +00001068 // Base and index reg must be 0 in order to use %rip as base.
1069 if (IsRIPRel && AM.hasBaseOrIndexReg())
1070 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001071
Reid Kleckner537917d2018-05-21 21:03:19 +00001072 // Make a local copy in case we can't do this fold.
1073 X86ISelAddressMode Backup = AM;
1074
1075 int64_t Offset = 0;
1076 SDValue N0 = N.getOperand(0);
1077 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1078 AM.GV = G->getGlobal();
1079 AM.SymbolFlags = G->getTargetFlags();
1080 Offset = G->getOffset();
1081 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1082 AM.CP = CP->getConstVal();
1083 AM.Align = CP->getAlignment();
1084 AM.SymbolFlags = CP->getTargetFlags();
1085 Offset = CP->getOffset();
1086 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1087 AM.ES = S->getSymbol();
1088 AM.SymbolFlags = S->getTargetFlags();
1089 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1090 AM.MCSym = S->getMCSymbol();
1091 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1092 AM.JT = J->getIndex();
1093 AM.SymbolFlags = J->getTargetFlags();
1094 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1095 AM.BlockAddr = BA->getBlockAddress();
1096 AM.SymbolFlags = BA->getTargetFlags();
1097 Offset = BA->getOffset();
1098 } else
1099 llvm_unreachable("Unhandled symbol reference node.");
1100
1101 if (foldOffsetIntoAddress(Offset, AM)) {
1102 AM = Backup;
1103 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +00001104 }
1105
Reid Kleckner537917d2018-05-21 21:03:19 +00001106 if (IsRIPRel)
1107 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001108
Reid Kleckner537917d2018-05-21 21:03:19 +00001109 // Commit the changes now that we know this fold is safe.
1110 return false;
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001111}
1112
Sanjay Patelb5723d02015-10-13 15:12:27 +00001113/// Add the specified node to the specified addressing mode, returning true if
1114/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001115bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1116 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +00001117 return true;
1118
1119 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1120 // a smaller encoding and avoids a scaled-index.
1121 if (AM.Scale == 2 &&
1122 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001123 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001124 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +00001125 AM.Scale = 1;
1126 }
1127
Dan Gohman05046082009-08-20 18:23:44 +00001128 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1129 // because it has a smaller encoding.
1130 // TODO: Which other code models can use this?
1131 if (TM.getCodeModel() == CodeModel::Small &&
1132 Subtarget->is64Bit() &&
1133 AM.Scale == 1 &&
1134 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001135 AM.Base_Reg.getNode() == nullptr &&
1136 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +00001137 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +00001138 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001139 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +00001140
Dan Gohman824ab402009-07-22 23:26:55 +00001141 return false;
1142}
1143
Sanjay Patelefab8b02015-10-21 18:56:06 +00001144bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
1145 unsigned Depth) {
1146 // Add an artificial use to this node so that we can keep track of
1147 // it if it gets CSE'd with a different node.
1148 HandleSDNode Handle(N);
1149
1150 X86ISelAddressMode Backup = AM;
1151 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1152 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1153 return false;
1154 AM = Backup;
1155
1156 // Try again after commuting the operands.
1157 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
1158 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1159 return false;
1160 AM = Backup;
1161
1162 // If we couldn't fold both operands into the address at the same time,
1163 // see if we can just put each operand into a register and fold at least
1164 // the add.
1165 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1166 !AM.Base_Reg.getNode() &&
1167 !AM.IndexReg.getNode()) {
1168 N = Handle.getValue();
1169 AM.Base_Reg = N.getOperand(0);
1170 AM.IndexReg = N.getOperand(1);
1171 AM.Scale = 1;
1172 return false;
1173 }
1174 N = Handle.getValue();
1175 return true;
1176}
1177
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001178// Insert a node into the DAG at least before the Pos node's position. This
1179// will reposition the node as needed, and will assign it a node ID that is <=
1180// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1181// IDs! The selection DAG must no longer depend on their uniqueness when this
1182// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001183static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Nirav Dave8c5f47a2018-03-22 19:32:07 +00001184 if (N->getNodeId() == -1 ||
1185 (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1186 SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1187 DAG.RepositionNode(Pos->getIterator(), N.getNode());
1188 // Mark Node as invalid for pruning as after this it may be a successor to a
1189 // selected node but otherwise be in the same position of Pos.
1190 // Conservatively mark it with the same -abs(Id) to assure node id
1191 // invariant is preserved.
1192 N->setNodeId(Pos->getNodeId());
1193 SelectionDAGISel::InvalidateNodeId(N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001194 }
1195}
1196
Adam Nemet0c7caf42014-09-16 17:14:10 +00001197// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1198// safe. This allows us to convert the shift and and into an h-register
1199// extract and a scaled index. Returns false if the simplification is
1200// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001201static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1202 uint64_t Mask,
1203 SDValue Shift, SDValue X,
1204 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001205 if (Shift.getOpcode() != ISD::SRL ||
1206 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1207 !Shift.hasOneUse())
1208 return true;
1209
1210 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1211 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1212 Mask != (0xffu << ScaleLog))
1213 return true;
1214
Craig Topper83e042a2013-08-15 05:57:07 +00001215 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001216 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001217 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1218 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001219 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1220 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001221 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001222 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1223
Chandler Carrutheb21da02012-01-12 01:34:44 +00001224 // Insert the new nodes into the topological ordering. We must do this in
1225 // a valid topological ordering as nothing is going to go back and re-sort
1226 // these nodes. We continually insert before 'N' in sequence as this is
1227 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1228 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001229 insertDAGNode(DAG, N, Eight);
1230 insertDAGNode(DAG, N, Srl);
1231 insertDAGNode(DAG, N, NewMask);
1232 insertDAGNode(DAG, N, And);
1233 insertDAGNode(DAG, N, ShlCount);
1234 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001235 DAG.ReplaceAllUsesWith(N, Shl);
1236 AM.IndexReg = And;
1237 AM.Scale = (1 << ScaleLog);
1238 return false;
1239}
1240
Chandler Carruthaa01e662012-01-11 09:35:00 +00001241// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1242// allows us to fold the shift into this addressing mode. Returns false if the
1243// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001244static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1245 uint64_t Mask,
1246 SDValue Shift, SDValue X,
1247 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001248 if (Shift.getOpcode() != ISD::SHL ||
1249 !isa<ConstantSDNode>(Shift.getOperand(1)))
1250 return true;
1251
1252 // Not likely to be profitable if either the AND or SHIFT node has more
1253 // than one use (unless all uses are for address computation). Besides,
1254 // isel mechanism requires their node ids to be reused.
1255 if (!N.hasOneUse() || !Shift.hasOneUse())
1256 return true;
1257
1258 // Verify that the shift amount is something we can fold.
1259 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1260 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1261 return true;
1262
Craig Topper83e042a2013-08-15 05:57:07 +00001263 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001264 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001265 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001266 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1267 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1268
Chandler Carrutheb21da02012-01-12 01:34:44 +00001269 // Insert the new nodes into the topological ordering. We must do this in
1270 // a valid topological ordering as nothing is going to go back and re-sort
1271 // these nodes. We continually insert before 'N' in sequence as this is
1272 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1273 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001274 insertDAGNode(DAG, N, NewMask);
1275 insertDAGNode(DAG, N, NewAnd);
1276 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001277 DAG.ReplaceAllUsesWith(N, NewShift);
1278
1279 AM.Scale = 1 << ShiftAmt;
1280 AM.IndexReg = NewAnd;
1281 return false;
1282}
1283
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001284// Implement some heroics to detect shifts of masked values where the mask can
1285// be replaced by extending the shift and undoing that in the addressing mode
1286// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1287// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1288// the addressing mode. This results in code such as:
1289//
1290// int f(short *y, int *lookup_table) {
1291// ...
1292// return *y + lookup_table[*y >> 11];
1293// }
1294//
1295// Turning into:
1296// movzwl (%rdi), %eax
1297// movl %eax, %ecx
1298// shrl $11, %ecx
1299// addl (%rsi,%rcx,4), %eax
1300//
1301// Instead of:
1302// movzwl (%rdi), %eax
1303// movl %eax, %ecx
1304// shrl $9, %ecx
1305// andl $124, %rcx
1306// addl (%rsi,%rcx), %eax
1307//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001308// Note that this function assumes the mask is provided as a mask *after* the
1309// value is shifted. The input chain may or may not match that, but computing
1310// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001311static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1312 uint64_t Mask,
1313 SDValue Shift, SDValue X,
1314 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001315 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1316 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001317 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001318
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001319 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001320 unsigned MaskLZ = countLeadingZeros(Mask);
1321 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001322
1323 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001324 // from the trailing zeros of the mask.
1325 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001326
1327 // There is nothing we can do here unless the mask is removing some bits.
1328 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1329 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1330
1331 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001332 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001333
1334 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001335 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001336 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1337 if (MaskLZ < ScaleDown)
1338 return true;
1339 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001340
1341 // The final check is to ensure that any masked out high bits of X are
1342 // already known to be zero. Otherwise, the mask has a semantic impact
1343 // other than masking out a couple of low bits. Unfortunately, because of
1344 // the mask, zero extensions will be removed from operands in some cases.
1345 // This code works extra hard to look through extensions because we can
1346 // replace them with zero extensions cheaply if necessary.
1347 bool ReplacingAnyExtend = false;
1348 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001349 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1350 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001351 // Assume that we'll replace the any-extend with a zero-extend, and
1352 // narrow the search to the extended value.
1353 X = X.getOperand(0);
1354 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1355 ReplacingAnyExtend = true;
1356 }
Craig Topper83e042a2013-08-15 05:57:07 +00001357 APInt MaskedHighBits =
1358 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001359 KnownBits Known;
1360 DAG.computeKnownBits(X, Known);
1361 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001362
1363 // We've identified a pattern that can be transformed into a single shift
1364 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001365 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001366 if (ReplacingAnyExtend) {
1367 assert(X.getValueType() != VT);
1368 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001369 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001370 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001371 X = NewX;
1372 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001373 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001374 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001375 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001376 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001377 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001378
1379 // Insert the new nodes into the topological ordering. We must do this in
1380 // a valid topological ordering as nothing is going to go back and re-sort
1381 // these nodes. We continually insert before 'N' in sequence as this is
1382 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1383 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001384 insertDAGNode(DAG, N, NewSRLAmt);
1385 insertDAGNode(DAG, N, NewSRL);
1386 insertDAGNode(DAG, N, NewSHLAmt);
1387 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001388 DAG.ReplaceAllUsesWith(N, NewSHL);
1389
1390 AM.Scale = 1 << AMShiftAmt;
1391 AM.IndexReg = NewSRL;
1392 return false;
1393}
Matt Morehouse9e658c92017-12-01 22:20:26 +00001394
Craig Topperfb2ac892018-10-11 18:06:07 +00001395// Transform "(X >> SHIFT) & (MASK << C1)" to
1396// "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
1397// matched to a BEXTR later. Returns false if the simplification is performed.
1398static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,
1399 uint64_t Mask,
1400 SDValue Shift, SDValue X,
1401 X86ISelAddressMode &AM,
1402 const X86Subtarget &Subtarget) {
1403 if (Shift.getOpcode() != ISD::SRL ||
1404 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1405 !Shift.hasOneUse() || !N.hasOneUse())
1406 return true;
1407
1408 // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
1409 if (!Subtarget.hasTBM() &&
1410 !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
1411 return true;
1412
1413 // We need to ensure that mask is a continuous run of bits.
1414 if (!isShiftedMask_64(Mask)) return true;
1415
1416 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1417
1418 // The amount of shift we're trying to fit into the addressing mode is taken
1419 // from the trailing zeros of the mask.
1420 unsigned AMShiftAmt = countTrailingZeros(Mask);
1421
1422 // There is nothing we can do here unless the mask is removing some bits.
1423 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1424 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1425
1426 MVT VT = N.getSimpleValueType();
1427 SDLoc DL(N);
1428 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1429 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1430 SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT);
1431 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask);
1432 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1433 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt);
1434
1435 // Insert the new nodes into the topological ordering. We must do this in
1436 // a valid topological ordering as nothing is going to go back and re-sort
1437 // these nodes. We continually insert before 'N' in sequence as this is
1438 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1439 // hierarchy left to express.
1440 insertDAGNode(DAG, N, NewSRLAmt);
1441 insertDAGNode(DAG, N, NewSRL);
1442 insertDAGNode(DAG, N, NewMask);
1443 insertDAGNode(DAG, N, NewAnd);
1444 insertDAGNode(DAG, N, NewSHLAmt);
1445 insertDAGNode(DAG, N, NewSHL);
1446 DAG.ReplaceAllUsesWith(N, NewSHL);
1447
1448 AM.Scale = 1 << AMShiftAmt;
1449 AM.IndexReg = NewAnd;
1450 return false;
1451}
1452
Sanjay Patel85030aa2015-10-13 16:23:00 +00001453bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001454 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001455 SDLoc dl(N);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001456 LLVM_DEBUG({
1457 dbgs() << "MatchAddress: ";
1458 AM.dump(CurDAG);
1459 });
Matt Morehouse9e658c92017-12-01 22:20:26 +00001460 // Limit recursion.
1461 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001462 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001463
Chris Lattnerfea81da2009-06-27 04:16:01 +00001464 // If this is already a %rip relative address, we can only merge immediates
1465 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001466 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001467 if (AM.isRIPRelative()) {
1468 // FIXME: JumpTable and ExternalSymbol address currently don't like
1469 // displacements. It isn't very important, but this should be fixed for
1470 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001471 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1472 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001473
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001474 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001475 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001476 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001477 return true;
1478 }
1479
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001480 switch (N.getOpcode()) {
1481 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001482 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001483 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001484 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1485 // Use the symbol and don't prefix it.
1486 AM.MCSym = ESNode->getMCSymbol();
1487 return false;
1488 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001489 break;
1490 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001491 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001492 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001493 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001494 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001495 break;
1496 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001497
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001498 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001499 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001500 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001501 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001502 break;
1503
Rafael Espindola3b2df102009-04-08 21:14:34 +00001504 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001505 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001506 return false;
1507 break;
1508
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001509 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001510 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001511 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001512 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001513 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001514 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001515 return false;
1516 }
1517 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001518
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001519 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001520 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001521 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001522
Simon Pilgrim7f032312017-05-12 13:08:45 +00001523 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001524 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001525 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1526 // that the base operand remains free for further matching. If
1527 // the base doesn't end up getting used, a post-processing step
1528 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001529 if (Val == 1 || Val == 2 || Val == 3) {
1530 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001531 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001532
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001533 // Okay, we know that we have a scale by now. However, if the scaled
1534 // value is an add of something and a constant, we can fold the
1535 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001536 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001537 AM.IndexReg = ShVal.getOperand(0);
1538 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001539 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001540 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001541 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001542 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001543
1544 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001545 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001546 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001547 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001548 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001549
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001550 case ISD::SRL: {
1551 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001552 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001553
1554 SDValue And = N.getOperand(0);
1555 if (And.getOpcode() != ISD::AND) break;
1556 SDValue X = And.getOperand(0);
1557
1558 // We only handle up to 64-bit values here as those are what matter for
1559 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001560 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001561
1562 // The mask used for the transform is expected to be post-shift, but we
1563 // found the shift first so just apply the shift to the mask before passing
1564 // it down.
1565 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1566 !isa<ConstantSDNode>(And.getOperand(1)))
1567 break;
1568 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1569
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001570 // Try to fold the mask and shift into the scale, and return false if we
1571 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001572 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001573 return false;
1574 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001575 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001576
Dan Gohmanbf474952007-10-22 20:22:24 +00001577 case ISD::SMUL_LOHI:
1578 case ISD::UMUL_LOHI:
1579 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001580 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001581 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001582 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001583 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001584 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001585 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001586 AM.Base_Reg.getNode() == nullptr &&
1587 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001588 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001589 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1590 CN->getZExtValue() == 9) {
1591 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001592
Simon Pilgrim7f032312017-05-12 13:08:45 +00001593 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001594 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001595
1596 // Okay, we know that we have a scale by now. However, if the scaled
1597 // value is an add of something and a constant, we can fold the
1598 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001599 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001600 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1601 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001602 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001603 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001604 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001605 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001606 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001607 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001608 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001609 }
1610
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001611 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001612 return false;
1613 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001614 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001615 break;
1616
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001617 case ISD::SUB: {
1618 // Given A-B, if A can be completely folded into the address and
1619 // the index field with the index field unused, use -B as the index.
1620 // This is a win if a has multiple parts that can be folded into
1621 // the address. Also, this saves a mov if the base register has
1622 // other uses, since it avoids a two-address sub instruction, however
1623 // it costs an additional mov if the index register has other uses.
1624
Dan Gohman99ba4da2010-06-18 01:24:29 +00001625 // Add an artificial use to this node so that we can keep track of
1626 // it if it gets CSE'd with a different node.
1627 HandleSDNode Handle(N);
1628
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001629 // Test if the LHS of the sub can be folded.
1630 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001631 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001632 AM = Backup;
1633 break;
1634 }
1635 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001636 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001637 AM = Backup;
1638 break;
1639 }
Evan Cheng68333f52010-03-17 23:58:35 +00001640
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001641 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001642 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001643 // If the RHS involves a register with multiple uses, this
1644 // transformation incurs an extra mov, due to the neg instruction
1645 // clobbering its operand.
1646 if (!RHS.getNode()->hasOneUse() ||
1647 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1648 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1649 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1650 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001651 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001652 ++Cost;
1653 // If the base is a register with multiple uses, this
1654 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001655 // FIXME: Don't rely on DELETED_NODEs.
1656 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1657 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001658 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001659 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1660 --Cost;
1661 // If the folded LHS was interesting, this transformation saves
1662 // address arithmetic.
1663 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1664 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1665 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1666 --Cost;
1667 // If it doesn't look like it may be an overall win, don't do it.
1668 if (Cost >= 0) {
1669 AM = Backup;
1670 break;
1671 }
1672
1673 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001674 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001675 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1676 AM.IndexReg = Neg;
1677 AM.Scale = 1;
1678
1679 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001680 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1681 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001682 return false;
1683 }
1684
Sanjay Patelefab8b02015-10-21 18:56:06 +00001685 case ISD::ADD:
1686 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001687 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001688 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001689
Sanjay Patel533c10c2015-11-09 23:31:38 +00001690 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001691 // We want to look through a transform in InstCombine and DAGCombiner that
1692 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001693 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001694 // An 'lea' can then be used to match the shift (multiply) and add:
1695 // and $1, %esi
1696 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001697 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1698 !matchAdd(N, AM, Depth))
1699 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001700 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001701
Evan Cheng827d30d2007-12-13 00:43:27 +00001702 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001703 // Perform some heroic transforms on an and of a constant-count shift
1704 // with a constant to enable use of the scaled offset field.
1705
Evan Cheng827d30d2007-12-13 00:43:27 +00001706 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001707 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001708
Chandler Carruthaa01e662012-01-11 09:35:00 +00001709 SDValue Shift = N.getOperand(0);
1710 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001711 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001712
1713 // We only handle up to 64-bit values here as those are what matter for
1714 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001715 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001716
Chandler Carruthb0049f42012-01-11 09:35:04 +00001717 if (!isa<ConstantSDNode>(N.getOperand(1)))
1718 break;
1719 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001720
Chandler Carruth51d30762012-01-11 08:48:20 +00001721 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001722 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001723 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001724
Chandler Carruth51d30762012-01-11 08:48:20 +00001725 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001726 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001727 return false;
1728
Chandler Carruthaa01e662012-01-11 09:35:00 +00001729 // Try to swap the mask and shift to place shifts which can be done as
1730 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001731 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001732 return false;
Craig Topperfb2ac892018-10-11 18:06:07 +00001733
1734 // Try to fold the mask and shift into BEXTR and scale.
1735 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
1736 return false;
1737
Chandler Carruthaa01e662012-01-11 09:35:00 +00001738 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001739 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001740 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001741
Sanjay Patel85030aa2015-10-13 16:23:00 +00001742 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001743}
1744
Sanjay Patelb5723d02015-10-13 15:12:27 +00001745/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001746/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001747bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001748 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001749 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001750 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001751 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001752 AM.IndexReg = N;
1753 AM.Scale = 1;
1754 return false;
1755 }
1756
1757 // Otherwise, we cannot select it.
1758 return true;
1759 }
1760
1761 // Default, generate it as a register.
1762 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001763 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001764 return false;
1765}
1766
Craig Topperc314f462017-11-13 17:53:59 +00001767/// Helper for selectVectorAddr. Handles things that can be folded into a
1768/// gather scatter address. The index register and scale should have already
1769/// been handled.
1770bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
1771 // TODO: Support other operations.
1772 switch (N.getOpcode()) {
Craig Topperaf4eb172018-01-10 19:16:05 +00001773 case ISD::Constant: {
1774 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1775 if (!foldOffsetIntoAddress(Val, AM))
1776 return false;
1777 break;
1778 }
Craig Topperc314f462017-11-13 17:53:59 +00001779 case X86ISD::Wrapper:
1780 if (!matchWrapper(N, AM))
1781 return false;
1782 break;
1783 }
1784
1785 return matchAddressBase(N, AM);
1786}
1787
Craig Topperbb001c6d2017-11-10 19:26:04 +00001788bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1789 SDValue &Scale, SDValue &Index,
1790 SDValue &Disp, SDValue &Segment) {
Craig Topperc314f462017-11-13 17:53:59 +00001791 X86ISelAddressMode AM;
Craig Topperee740442017-11-22 08:10:54 +00001792 auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
1793 AM.IndexReg = Mgs->getIndex();
Craig Topperaf4eb172018-01-10 19:16:05 +00001794 AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
Craig Topperbb001c6d2017-11-10 19:26:04 +00001795
Craig Topperbb001c6d2017-11-10 19:26:04 +00001796 unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001797 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001798 if (AddrSpace == 256)
1799 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1800 if (AddrSpace == 257)
1801 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001802 if (AddrSpace == 258)
1803 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001804
Craig Topperaf4eb172018-01-10 19:16:05 +00001805 // Try to match into the base and displacement fields.
1806 if (matchVectorAddress(N, AM))
Craig Topperc314f462017-11-13 17:53:59 +00001807 return false;
1808
1809 MVT VT = N.getSimpleValueType();
1810 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1811 if (!AM.Base_Reg.getNode())
1812 AM.Base_Reg = CurDAG->getRegister(0, VT);
1813 }
1814
1815 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001816 return true;
1817}
1818
Sanjay Patelb5723d02015-10-13 15:12:27 +00001819/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001820/// It returns the operands which make up the maximal addressing mode it can
1821/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001822///
1823/// Parent is the parent node of the addr operand that is being matched. It
1824/// is always a load, store, atomic node, or null. It is only null when
1825/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001826bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001827 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001828 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001829 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001830
Chris Lattner8a236b62010-09-22 04:39:11 +00001831 if (Parent &&
1832 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1833 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001834 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001835 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001836 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1837 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1838 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001839 unsigned AddrSpace =
1840 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001841 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001842 if (AddrSpace == 256)
1843 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1844 if (AddrSpace == 257)
1845 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001846 if (AddrSpace == 258)
1847 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001848 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001849
Sanjay Patel85030aa2015-10-13 16:23:00 +00001850 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001851 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001852
Craig Topper83e042a2013-08-15 05:57:07 +00001853 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001854 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001855 if (!AM.Base_Reg.getNode())
1856 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001857 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001858
Gabor Greiff304a7a2008-08-28 21:40:38 +00001859 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001860 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001861
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001862 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001863 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001864}
1865
Craig Topper8078dd22017-08-21 16:04:04 +00001866// We can only fold a load if all nodes between it and the root node have a
1867// single use. If there are additional uses, we could end up duplicating the
1868// load.
Craig Topperb0e986f2018-06-17 16:29:46 +00001869static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) {
Craig Topper8078dd22017-08-21 16:04:04 +00001870 while (User != Root) {
1871 if (!User->hasOneUse())
1872 return false;
1873 User = *User->use_begin();
1874 }
1875
1876 return true;
1877}
1878
Sanjay Patelb5723d02015-10-13 15:12:27 +00001879/// Match a scalar SSE load. In particular, we want to match a load whose top
1880/// elements are either undef or zeros. The load flavor is derived from the
1881/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001882///
1883/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001884/// PatternChainNode: this is the matched node that has a chain input and
1885/// output.
Craig Topperb0e986f2018-06-17 16:29:46 +00001886bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001887 SDValue N, SDValue &Base,
1888 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001889 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001890 SDValue &PatternNodeWithChain) {
Craig Topperb0e986f2018-06-17 16:29:46 +00001891 if (!hasSingleUsesFromRoot(Root, Parent))
1892 return false;
1893
Craig Topper36ecce92016-12-12 07:57:24 +00001894 // We can allow a full vector load here since narrowing a load is ok.
1895 if (ISD::isNON_EXTLoad(N.getNode())) {
1896 PatternNodeWithChain = N;
1897 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001898 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001899 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1900 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1901 Segment);
1902 }
1903 }
1904
1905 // We can also match the special zero extended load opcode.
1906 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1907 PatternNodeWithChain = N;
1908 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001909 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001910 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1911 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1912 Segment);
1913 }
1914 }
1915
Craig Topper991d1ca2016-11-26 17:29:25 +00001916 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1917 // once. Otherwise the load might get duplicated and the chain output of the
1918 // duplicate load will not be observed by all dependencies.
1919 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001920 PatternNodeWithChain = N.getOperand(0);
1921 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001922 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001923 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001924 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001925 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1926 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001927 }
1928 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001929
1930 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001931 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001932 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001933 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001934 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001935 N.getOperand(0).getNode()->hasOneUse()) {
1936 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1937 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001938 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001939 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Craig Toppere266e122016-11-26 18:43:24 +00001940 // Okay, this is a zero extending load. Fold it.
1941 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1942 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1943 Segment);
1944 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001945 }
Craig Toppere266e122016-11-26 18:43:24 +00001946
Chris Lattner398195e2006-10-07 21:55:32 +00001947 return false;
1948}
1949
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001950
Sanjay Patel85030aa2015-10-13 16:23:00 +00001951bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001952 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1953 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001954 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001955 return false;
1956
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001957 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001958 return true;
1959 }
1960
1961 // In static codegen with small code model, we can get the address of a label
Simon Pilgrim3d141582018-06-06 10:52:10 +00001962 // into a register with 'movl'
1963 if (N->getOpcode() != X86ISD::Wrapper)
1964 return false;
1965
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001966 N = N.getOperand(0);
1967
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001968 // At least GNU as does not accept 'movl' for TPOFF relocations.
1969 // FIXME: We could use 'movl' when we know we are targeting MC.
1970 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001971 return false;
1972
1973 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001974 if (N->getOpcode() != ISD::TargetGlobalAddress)
1975 return TM.getCodeModel() == CodeModel::Small;
1976
1977 Optional<ConstantRange> CR =
1978 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1979 if (!CR)
1980 return TM.getCodeModel() == CodeModel::Small;
1981
1982 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001983}
1984
Sanjay Patel85030aa2015-10-13 16:23:00 +00001985bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001986 SDValue &Scale, SDValue &Index,
1987 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001988 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1989 SDLoc DL(N);
Matt Morehouse9e658c92017-12-01 22:20:26 +00001990
Sanjay Patel85030aa2015-10-13 16:23:00 +00001991 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001992 return false;
1993
Tim Northover6833e3f2013-06-10 20:43:49 +00001994 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1995 if (RN && RN->getReg() == 0)
1996 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001997 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001998 // Base could already be %rip, particularly in the x32 ABI.
1999 Base = SDValue(CurDAG->getMachineNode(
2000 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002001 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00002002 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002003 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00002004 0);
2005 }
2006
2007 RN = dyn_cast<RegisterSDNode>(Index);
2008 if (RN && RN->getReg() == 0)
2009 Index = CurDAG->getRegister(0, MVT::i64);
2010 else {
2011 assert(Index.getValueType() == MVT::i32 &&
2012 "Expect to be extending 32-bit registers for use in LEA");
2013 Index = SDValue(CurDAG->getMachineNode(
2014 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002015 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00002016 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002017 CurDAG->getTargetConstant(X86::sub_32bit, DL,
2018 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00002019 0);
2020 }
2021
2022 return true;
2023}
2024
Sanjay Patelb5723d02015-10-13 15:12:27 +00002025/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00002026/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00002027bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002028 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00002029 SDValue &Index, SDValue &Disp,
2030 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00002031 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00002032
Justin Bogner32ad24d2016-04-12 21:34:24 +00002033 // Save the DL and VT before calling matchAddress, it can invalidate N.
2034 SDLoc DL(N);
2035 MVT VT = N.getSimpleValueType();
2036
Rafael Espindolabb834f02009-04-10 10:09:34 +00002037 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
2038 // segments.
2039 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00002040 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00002041 AM.Segment = T;
Matt Morehouse9e658c92017-12-01 22:20:26 +00002042 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00002043 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00002044 assert (T == AM.Segment);
2045 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00002046
Evan Cheng77d86ff2006-02-25 10:09:08 +00002047 unsigned Complexity = 0;
2048 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00002049 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00002050 Complexity = 1;
2051 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00002052 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00002053 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2054 Complexity = 4;
2055
Gabor Greiff304a7a2008-08-28 21:40:38 +00002056 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00002057 Complexity++;
2058 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00002059 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00002060
Chris Lattner3e1d9172007-03-20 06:08:29 +00002061 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
2062 // a simple shift.
2063 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00002064 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00002065
2066 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00002067 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00002068 // optimal (especially for code size consideration). LEA is nice because of
2069 // its three-address nature. Tweak the cost function again when we can run
2070 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00002071 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00002072 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00002073 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00002074 Complexity = 4;
2075 else
2076 Complexity += 2;
2077 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00002078
Dan Gohman0fd54fb2010-04-29 23:30:41 +00002079 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00002080 Complexity++;
2081
Chris Lattner4d10f1a2009-07-11 22:50:33 +00002082 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00002083 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00002084 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002085
Justin Bogner32ad24d2016-04-12 21:34:24 +00002086 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00002087 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00002088}
2089
Sanjay Patelb5723d02015-10-13 15:12:27 +00002090/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00002091bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00002092 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00002093 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00002094 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
2095 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00002096
Chris Lattner7d2b0492009-06-20 20:38:48 +00002097 X86ISelAddressMode AM;
2098 AM.GV = GA->getGlobal();
2099 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00002100 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00002101 AM.SymbolFlags = GA->getTargetFlags();
2102
Owen Anderson9f944592009-08-11 20:47:22 +00002103 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00002104 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00002105 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00002106 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00002107 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00002108 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002109
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002110 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00002111 return true;
2112}
2113
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002114bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2115 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2116 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
2117 N.getValueType());
2118 return true;
2119 }
2120
Peter Collingbourne235c2752016-12-08 19:01:00 +00002121 // Keep track of the original value type and whether this value was
2122 // truncated. If we see a truncation from pointer type to VT that truncates
2123 // bits that are known to be zero, we can use a narrow reference.
2124 EVT VT = N.getValueType();
2125 bool WasTruncated = false;
2126 if (N.getOpcode() == ISD::TRUNCATE) {
2127 WasTruncated = true;
2128 N = N.getOperand(0);
2129 }
2130
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002131 if (N.getOpcode() != X86ISD::Wrapper)
2132 return false;
2133
Peter Collingbourne235c2752016-12-08 19:01:00 +00002134 // We can only use non-GlobalValues as immediates if they were not truncated,
2135 // as we do not have any range information. If we have a GlobalValue and the
2136 // address was not truncated, we can select it as an operand directly.
2137 unsigned Opc = N.getOperand(0)->getOpcode();
2138 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2139 Op = N.getOperand(0);
2140 // We can only select the operand directly if we didn't have to look past a
2141 // truncate.
2142 return !WasTruncated;
2143 }
2144
2145 // Check that the global's range fits into VT.
2146 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2147 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2148 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2149 return false;
2150
2151 // Okay, we can use a narrow reference.
2152 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2153 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00002154 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002155}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002156
Craig Topper78a77042017-11-08 20:17:33 +00002157bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002158 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00002159 SDValue &Index, SDValue &Disp,
2160 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00002161 if (!ISD::isNON_EXTLoad(N.getNode()) ||
Craig Topper78a77042017-11-08 20:17:33 +00002162 !IsProfitableToFold(N, P, Root) ||
2163 !IsLegalToFold(N, P, Root, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00002164 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002165
Sanjay Patel85030aa2015-10-13 16:23:00 +00002166 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00002167 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00002168}
2169
Sanjay Patelb5723d02015-10-13 15:12:27 +00002170/// Return an SDNode that returns the value of the global base register.
2171/// Output instructions required to initialize the global base register,
2172/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00002173SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00002174 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00002175 auto &DL = MF->getDataLayout();
2176 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00002177}
2178
Peter Collingbourneef089bd2017-02-09 22:02:28 +00002179bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2180 if (N->getOpcode() == ISD::TRUNCATE)
2181 N = N->getOperand(0).getNode();
2182 if (N->getOpcode() != X86ISD::Wrapper)
2183 return false;
2184
2185 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2186 if (!GA)
2187 return false;
2188
2189 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2190 return CR && CR->getSignedMin().sge(-1ull << Width) &&
2191 CR->getSignedMax().slt(1ull << Width);
2192}
2193
Sanjay Patelb5723d02015-10-13 15:12:27 +00002194/// Test whether the given X86ISD::CMP node has any uses which require the SF
2195/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002196static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002197 // Examine each user of the node.
2198 for (SDNode::use_iterator UI = N->use_begin(),
2199 UE = N->use_end(); UI != UE; ++UI) {
2200 // Only examine CopyToReg uses.
2201 if (UI->getOpcode() != ISD::CopyToReg)
2202 return false;
2203 // Only examine CopyToReg uses that copy to EFLAGS.
2204 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
2205 X86::EFLAGS)
2206 return false;
2207 // Examine each user of the CopyToReg use.
2208 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2209 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2210 // Only examine the Flag result.
2211 if (FlagUI.getUse().getResNo() != 1) continue;
2212 // Anything unusual: assume conservatively.
2213 if (!FlagUI->isMachineOpcode()) return false;
2214 // Examine the opcode of the user.
2215 switch (FlagUI->getMachineOpcode()) {
2216 // These comparisons don't treat the most significant bit specially.
2217 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
2218 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
2219 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
2220 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00002221 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
2222 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002223 case X86::CMOVA16rr: case X86::CMOVA16rm:
2224 case X86::CMOVA32rr: case X86::CMOVA32rm:
2225 case X86::CMOVA64rr: case X86::CMOVA64rm:
2226 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
2227 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
2228 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
2229 case X86::CMOVB16rr: case X86::CMOVB16rm:
2230 case X86::CMOVB32rr: case X86::CMOVB32rm:
2231 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00002232 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
2233 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
2234 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002235 case X86::CMOVE16rr: case X86::CMOVE16rm:
2236 case X86::CMOVE32rr: case X86::CMOVE32rm:
2237 case X86::CMOVE64rr: case X86::CMOVE64rm:
2238 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
2239 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
2240 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
2241 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
2242 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2243 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2244 case X86::CMOVP16rr: case X86::CMOVP16rm:
2245 case X86::CMOVP32rr: case X86::CMOVP32rm:
2246 case X86::CMOVP64rr: case X86::CMOVP64rm:
2247 continue;
2248 // Anything else: assume conservatively.
2249 default: return false;
2250 }
2251 }
2252 }
2253 return true;
2254}
2255
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002256/// Test whether the given node which sets flags has any uses which require the
2257/// CF flag to be accurate.
2258static bool hasNoCarryFlagUses(SDNode *N) {
2259 // Examine each user of the node.
2260 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
2261 ++UI) {
2262 // Only check things that use the flags.
2263 if (UI.getUse().getResNo() != 1)
2264 continue;
2265 // Only examine CopyToReg uses.
2266 if (UI->getOpcode() != ISD::CopyToReg)
2267 return false;
2268 // Only examine CopyToReg uses that copy to EFLAGS.
2269 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2270 return false;
2271 // Examine each user of the CopyToReg use.
2272 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2273 FlagUI != FlagUE; ++FlagUI) {
2274 // Only examine the Flag result.
2275 if (FlagUI.getUse().getResNo() != 1)
2276 continue;
2277 // Anything unusual: assume conservatively.
2278 if (!FlagUI->isMachineOpcode())
2279 return false;
2280 // Examine the opcode of the user.
2281 switch (FlagUI->getMachineOpcode()) {
2282 // Comparisons which don't examine the CF flag.
2283 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2284 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2285 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2286 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2287 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2288 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2289 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2290 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2291 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2292 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2293 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2294 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2295 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2296 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2297 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2298 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2299 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2300 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2301 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2302 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2303 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2304 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2305 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2306 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2307 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2308 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2309 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2310 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2311 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2312 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2313 continue;
2314 // Anything else: assume conservatively.
2315 default:
2316 return false;
2317 }
2318 }
2319 }
2320 return true;
2321}
2322
Sanjay Patelb5723d02015-10-13 15:12:27 +00002323/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002324/// the {load; op; store} to modify transformation.
2325static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2326 SDValue StoredVal, SelectionDAG *CurDAG,
Craig Topper313d09a2018-09-07 16:27:55 +00002327 unsigned LoadOpNo,
Chandler Carruth96db3082017-08-25 02:06:36 +00002328 LoadSDNode *&LoadNode,
2329 SDValue &InputChain) {
Craig Topper13148562018-09-07 01:29:42 +00002330 // Is the stored value result 0 of the operation?
Joel Jones68d59e82012-03-29 05:45:48 +00002331 if (StoredVal.getResNo() != 0) return false;
2332
Craig Topper13148562018-09-07 01:29:42 +00002333 // Are there other uses of the operation other than the store?
Joel Jones68d59e82012-03-29 05:45:48 +00002334 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2335
Craig Topper13148562018-09-07 01:29:42 +00002336 // Is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002337 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002338 return false;
2339
Craig Topper313d09a2018-09-07 16:27:55 +00002340 SDValue Load = StoredVal->getOperand(LoadOpNo);
Evan Cheng3e869f02012-04-12 19:14:21 +00002341 // Is the stored value a non-extending and non-indexed load?
2342 if (!ISD::isNormalLoad(Load.getNode())) return false;
2343
2344 // Return LoadNode by reference.
2345 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002346
2347 // Is store the only read of the loaded value?
2348 if (!Load.hasOneUse())
2349 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002350
Evan Cheng3e869f02012-04-12 19:14:21 +00002351 // Is the address of the store the same as the load?
2352 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2353 LoadNode->getOffset() != StoreNode->getOffset())
2354 return false;
2355
Nirav Dave3264c1b2018-03-19 20:19:46 +00002356 bool FoundLoad = false;
2357 SmallVector<SDValue, 4> ChainOps;
2358 SmallVector<const SDNode *, 4> LoopWorklist;
2359 SmallPtrSet<const SDNode *, 16> Visited;
2360 const unsigned int Max = 1024;
2361
2362 // Visualization of Load-Op-Store fusion:
2363 // -------------------------
2364 // Legend:
2365 // *-lines = Chain operand dependencies.
2366 // |-lines = Normal operand dependencies.
2367 // Dependencies flow down and right. n-suffix references multiple nodes.
2368 //
2369 // C Xn C
2370 // * * *
2371 // * * *
2372 // Xn A-LD Yn TF Yn
2373 // * * \ | * |
2374 // * * \ | * |
2375 // * * \ | => A--LD_OP_ST
2376 // * * \| \
2377 // TF OP \
2378 // * | \ Zn
2379 // * | \
2380 // A-ST Zn
2381 //
2382
2383 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2384 // #2: Yn -> LD
2385 // #3: ST -> Zn
2386
2387 // Ensure the transform is safe by checking for the dual
2388 // dependencies to make sure we do not induce a loop.
2389
2390 // As LD is a predecessor to both OP and ST we can do this by checking:
2391 // a). if LD is a predecessor to a member of Xn or Yn.
2392 // b). if a Zn is a predecessor to ST.
2393
2394 // However, (b) can only occur through being a chain predecessor to
2395 // ST, which is the same as Zn being a member or predecessor of Xn,
2396 // which is a subset of LD being a predecessor of Xn. So it's
2397 // subsumed by check (a).
2398
Evan Cheng3e869f02012-04-12 19:14:21 +00002399 SDValue Chain = StoreNode->getChain();
2400
Nirav Dave3264c1b2018-03-19 20:19:46 +00002401 // Gather X elements in ChainOps.
Evan Cheng3e869f02012-04-12 19:14:21 +00002402 if (Chain == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002403 FoundLoad = true;
2404 ChainOps.push_back(Load.getOperand(0));
Nirav Dave0fab4172018-03-09 20:58:07 +00002405 } else if (Chain.getOpcode() == ISD::TokenFactor) {
Evan Cheng3e869f02012-04-12 19:14:21 +00002406 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2407 SDValue Op = Chain.getOperand(i);
2408 if (Op == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002409 FoundLoad = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002410 // Drop Load, but keep its chain. No cycle check necessary.
2411 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002412 continue;
2413 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002414 LoopWorklist.push_back(Op.getNode());
Evan Cheng3e869f02012-04-12 19:14:21 +00002415 ChainOps.push_back(Op);
2416 }
Nirav Daved668f692018-03-09 20:57:42 +00002417 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002418
2419 if (!FoundLoad)
Nirav Dave0fab4172018-03-09 20:58:07 +00002420 return false;
2421
Nirav Dave3264c1b2018-03-19 20:19:46 +00002422 // Worklist is currently Xn. Add Yn to worklist.
2423 for (SDValue Op : StoredVal->ops())
2424 if (Op.getNode() != LoadNode)
2425 LoopWorklist.push_back(Op.getNode());
2426
2427 // Check (a) if Load is a predecessor to Xn + Yn
2428 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2429 true))
2430 return false;
2431
2432 InputChain =
2433 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
Nirav Dave0fab4172018-03-09 20:58:07 +00002434 return true;
Nirav Dave042678b2018-03-10 02:16:15 +00002435}
Joel Jones68d59e82012-03-29 05:45:48 +00002436
Chandler Carruth4b611a82017-08-25 22:50:52 +00002437// Change a chain of {load; op; store} of the same value into a simple op
2438// through memory of that value, if the uses of the modified value and its
2439// address are suitable.
2440//
2441// The tablegen pattern memory operand pattern is currently not able to match
2442// the case where the EFLAGS on the original operation are used.
2443//
2444// To move this to tablegen, we'll need to improve tablegen to allow flags to
2445// be transferred from a node in the pattern to the result node, probably with
2446// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002447// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2448// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2449// (implicit EFLAGS)]>;
2450// but maybe need something like this
2451// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2452// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2453// (transferrable EFLAGS)]>;
2454//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002455// Until then, we manually fold these and instruction select the operation
2456// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002457bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2458 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2459 SDValue StoredVal = StoreNode->getOperand(1);
2460 unsigned Opc = StoredVal->getOpcode();
2461
Chandler Carruth4b611a82017-08-25 22:50:52 +00002462 // Before we try to select anything, make sure this is memory operand size
2463 // and opcode we can handle. Note that this must match the code below that
2464 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002465 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002466 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2467 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002468 return false;
Craig Topper313d09a2018-09-07 16:27:55 +00002469
2470 bool IsCommutable = false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002471 switch (Opc) {
2472 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002473 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002474 case X86ISD::INC:
2475 case X86ISD::DEC:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002476 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002477 case X86ISD::SBB:
Craig Topper313d09a2018-09-07 16:27:55 +00002478 break;
2479 case X86ISD::ADD:
2480 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002481 case X86ISD::AND:
2482 case X86ISD::OR:
2483 case X86ISD::XOR:
Craig Topper313d09a2018-09-07 16:27:55 +00002484 IsCommutable = true;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002485 break;
2486 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002487
Craig Topper313d09a2018-09-07 16:27:55 +00002488 unsigned LoadOpNo = 0;
Chandler Carruth03258f22017-08-25 02:04:03 +00002489 LoadSDNode *LoadNode = nullptr;
2490 SDValue InputChain;
Craig Topper313d09a2018-09-07 16:27:55 +00002491 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2492 LoadNode, InputChain)) {
2493 if (!IsCommutable)
2494 return false;
2495
2496 // This operation is commutable, try the other operand.
2497 LoadOpNo = 1;
2498 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2499 LoadNode, InputChain))
2500 return false;
2501 }
Chandler Carruth03258f22017-08-25 02:04:03 +00002502
2503 SDValue Base, Scale, Index, Disp, Segment;
2504 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2505 Segment))
2506 return false;
2507
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002508 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002509 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002510 switch (MemVT.getSimpleVT().SimpleTy) {
2511 case MVT::i64:
2512 return Opc64;
2513 case MVT::i32:
2514 return Opc32;
2515 case MVT::i16:
2516 return Opc16;
2517 case MVT::i8:
2518 return Opc8;
2519 default:
2520 llvm_unreachable("Invalid size!");
2521 }
2522 };
2523
2524 MachineSDNode *Result;
2525 switch (Opc) {
2526 case X86ISD::INC:
2527 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002528 unsigned NewOpc =
2529 Opc == X86ISD::INC
2530 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2531 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002532 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2533 Result =
2534 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2535 break;
2536 }
2537 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002538 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002539 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002540 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002541 case X86ISD::AND:
2542 case X86ISD::OR:
2543 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002544 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2545 switch (Opc) {
2546 case X86ISD::ADD:
2547 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2548 X86::ADD8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002549 case X86ISD::ADC:
2550 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2551 X86::ADC8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002552 case X86ISD::SUB:
2553 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2554 X86::SUB8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002555 case X86ISD::SBB:
2556 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2557 X86::SBB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002558 case X86ISD::AND:
2559 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2560 X86::AND8mr);
2561 case X86ISD::OR:
2562 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2563 case X86ISD::XOR:
2564 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2565 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002566 default:
2567 llvm_unreachable("Invalid opcode!");
2568 }
2569 };
2570 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2571 switch (Opc) {
2572 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002573 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002574 case X86ISD::ADC:
2575 return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002576 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002577 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002578 case X86ISD::SBB:
2579 return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002580 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002581 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002582 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002583 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002584 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002585 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002586 default:
2587 llvm_unreachable("Invalid opcode!");
2588 }
2589 };
2590 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2591 switch (Opc) {
2592 case X86ISD::ADD:
2593 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2594 X86::ADD8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002595 case X86ISD::ADC:
2596 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2597 X86::ADC8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002598 case X86ISD::SUB:
2599 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2600 X86::SUB8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002601 case X86ISD::SBB:
2602 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2603 X86::SBB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002604 case X86ISD::AND:
2605 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2606 X86::AND8mi);
2607 case X86ISD::OR:
2608 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2609 X86::OR8mi);
2610 case X86ISD::XOR:
2611 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2612 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002613 default:
2614 llvm_unreachable("Invalid opcode!");
2615 }
2616 };
2617
2618 unsigned NewOpc = SelectRegOpcode(Opc);
Craig Topper313d09a2018-09-07 16:27:55 +00002619 SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002620
2621 // See if the operand is a constant that we can fold into an immediate
2622 // operand.
2623 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2624 auto OperandV = OperandC->getAPIntValue();
2625
2626 // Check if we can shrink the operand enough to fit in an immediate (or
2627 // fit into a smaller immediate) by negating it and switching the
2628 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002629 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2630 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002631 (-OperandV).getMinSignedBits() <= 8) ||
2632 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2633 (-OperandV).getMinSignedBits() <= 32)) &&
2634 hasNoCarryFlagUses(StoredVal.getNode())) {
2635 OperandV = -OperandV;
2636 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2637 }
2638
2639 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2640 // the larger immediate operand.
2641 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2642 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2643 NewOpc = SelectImm8Opcode(Opc);
2644 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2645 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2646 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2647 NewOpc = SelectImmOpcode(Opc);
2648 }
2649 }
2650
Nirav Dave72d32f22018-01-19 15:37:57 +00002651 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2652 SDValue CopyTo =
2653 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2654 StoredVal.getOperand(2), SDValue());
2655
2656 const SDValue Ops[] = {Base, Scale, Index, Disp,
2657 Segment, Operand, CopyTo, CopyTo.getValue(1)};
2658 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2659 Ops);
2660 } else {
2661 const SDValue Ops[] = {Base, Scale, Index, Disp,
2662 Segment, Operand, InputChain};
2663 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2664 Ops);
2665 }
Chandler Carruth4b611a82017-08-25 22:50:52 +00002666 break;
2667 }
2668 default:
2669 llvm_unreachable("Invalid opcode!");
2670 }
2671
Chandler Carruth66654b72018-08-14 23:30:32 +00002672 MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
2673 LoadNode->getMemOperand()};
2674 CurDAG->setNodeMemRefs(Result, MemOps);
Chandler Carruth03258f22017-08-25 02:04:03 +00002675
Nirav Dave3264c1b2018-03-19 20:19:46 +00002676 // Update Load Chain uses as well.
2677 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
Chandler Carruth03258f22017-08-25 02:04:03 +00002678 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2679 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2680 CurDAG->RemoveDeadNode(Node);
2681 return true;
2682}
2683
Roman Lebedev89880852018-10-22 14:12:44 +00002684// See if this is an X & Mask that we can match to BEXTR/BZHI.
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002685// Where Mask is one of the following patterns:
2686// a) x & (1 << nbits) - 1
2687// b) x & ~(-1 << nbits)
2688// c) x & (-1 >> (32 - y))
2689// d) x << (32 - y) >> (32 - y)
Roman Lebedev89880852018-10-22 14:12:44 +00002690bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
Roman Lebedev06e4db02018-10-23 13:19:31 +00002691 assert(
2692 (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) &&
2693 "Should be either an and-mask, or right-shift after clearing high bits.");
2694
Roman Lebedev89880852018-10-22 14:12:44 +00002695 // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
2696 if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002697 return false;
2698
2699 MVT NVT = Node->getSimpleValueType(0);
2700
2701 // Only supported for 32 and 64 bits.
2702 if (NVT != MVT::i32 && NVT != MVT::i64)
2703 return false;
2704
Roman Lebedev06e4db02018-10-23 13:19:31 +00002705 unsigned Size = NVT.getSizeInBits();
2706
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002707 SDValue NBits;
2708
Roman Lebedev89880852018-10-22 14:12:44 +00002709 // If we have BMI2's BZHI, we are ok with muti-use patterns.
2710 // Else, if we only have BMI1's BEXTR, we require one-use.
2711 const bool CanHaveExtraUses = Subtarget->hasBMI2();
Roman Lebedev2fae9852018-10-23 18:27:10 +00002712 auto checkUses = [CanHaveExtraUses](SDValue Op, unsigned NUses) {
Roman Lebedev06e4db02018-10-23 13:19:31 +00002713 return CanHaveExtraUses ||
2714 Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
Roman Lebedev89880852018-10-22 14:12:44 +00002715 };
Roman Lebedev2fae9852018-10-23 18:27:10 +00002716 auto checkOneUse = [checkUses](SDValue Op) { return checkUses(Op, 1); };
2717 auto checkTwoUse = [checkUses](SDValue Op) { return checkUses(Op, 2); };
Roman Lebedev89880852018-10-22 14:12:44 +00002718
Roman Lebedev13c5ab22018-10-22 13:54:17 +00002719 // a) x & ((1 << nbits) + (-1))
Roman Lebedev89880852018-10-22 14:12:44 +00002720 auto matchPatternA = [&checkOneUse, &NBits](SDValue Mask) -> bool {
Roman Lebedev13c5ab22018-10-22 13:54:17 +00002721 // Match `add`. Must only have one use!
Roman Lebedev89880852018-10-22 14:12:44 +00002722 if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
Roman Lebedev13c5ab22018-10-22 13:54:17 +00002723 return false;
2724 // We should be adding all-ones constant (i.e. subtracting one.)
2725 if (!isAllOnesConstant(Mask->getOperand(1)))
2726 return false;
2727 // Match `1 << nbits`. Must only have one use!
2728 SDValue M0 = Mask->getOperand(0);
Roman Lebedev89880852018-10-22 14:12:44 +00002729 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
Roman Lebedev13c5ab22018-10-22 13:54:17 +00002730 return false;
2731 if (!isOneConstant(M0->getOperand(0)))
2732 return false;
2733 NBits = M0->getOperand(1);
2734 return true;
2735 };
2736
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002737 // b) x & ~(-1 << nbits)
Roman Lebedev89880852018-10-22 14:12:44 +00002738 auto matchPatternB = [&checkOneUse, &NBits](SDValue Mask) -> bool {
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002739 // Match `~()`. Must only have one use!
Roman Lebedev89880852018-10-22 14:12:44 +00002740 if (!isBitwiseNot(Mask) || !checkOneUse(Mask))
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002741 return false;
2742 // Match `-1 << nbits`. Must only have one use!
2743 SDValue M0 = Mask->getOperand(0);
Roman Lebedev89880852018-10-22 14:12:44 +00002744 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002745 return false;
2746 if (!isAllOnesConstant(M0->getOperand(0)))
2747 return false;
2748 NBits = M0->getOperand(1);
2749 return true;
2750 };
2751
Roman Lebedevb3a14202018-10-30 11:12:34 +00002752 // Match potentially-truncated (bitwidth - y)
2753 auto matchShiftAmt = [checkOneUse, Size, &NBits](SDValue ShiftAmt) {
2754 // Skip over a truncate of the shift amount.
2755 if (ShiftAmt.getOpcode() == ISD::TRUNCATE) {
2756 ShiftAmt = ShiftAmt.getOperand(0);
2757 // The trunc should have been the only user of the real shift amount.
2758 if (!checkOneUse(ShiftAmt))
2759 return false;
2760 }
2761 // Match the shift amount as: (bitwidth - y). It should go away, too.
2762 if (ShiftAmt.getOpcode() != ISD::SUB)
2763 return false;
2764 auto V0 = dyn_cast<ConstantSDNode>(ShiftAmt.getOperand(0));
2765 if (!V0 || V0->getZExtValue() != Size)
2766 return false;
2767 NBits = ShiftAmt.getOperand(1);
2768 return true;
2769 };
2770
2771 // c) x & (-1 >> (32 - y))
2772 auto matchPatternC = [&checkOneUse, matchShiftAmt](SDValue Mask) -> bool {
2773 // Match `l>>`. Must only have one use!
2774 if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
2775 return false;
2776 // We should be shifting all-ones constant.
2777 if (!isAllOnesConstant(Mask.getOperand(0)))
2778 return false;
2779 SDValue M1 = Mask.getOperand(1);
2780 // The shift amount should not be used externally.
2781 if (!checkOneUse(M1))
2782 return false;
2783 return matchShiftAmt(M1);
2784 };
2785
Roman Lebedev06e4db02018-10-23 13:19:31 +00002786 SDValue X;
2787
2788 // d) x << (32 - y) >> (32 - y)
Roman Lebedevb3a14202018-10-30 11:12:34 +00002789 auto matchPatternD = [&checkOneUse, &checkTwoUse, matchShiftAmt,
2790 &X](SDNode *Node) -> bool {
Roman Lebedev06e4db02018-10-23 13:19:31 +00002791 if (Node->getOpcode() != ISD::SRL)
2792 return false;
2793 SDValue N0 = Node->getOperand(0);
2794 if (N0->getOpcode() != ISD::SHL || !checkOneUse(N0))
2795 return false;
2796 SDValue N1 = Node->getOperand(1);
2797 SDValue N01 = N0->getOperand(1);
2798 // Both of the shifts must be by the exact same value.
2799 // There should not be any uses of the shift amount outside of the pattern.
Roman Lebedev2fae9852018-10-23 18:27:10 +00002800 if (N1 != N01 || !checkTwoUse(N1))
Roman Lebedev06e4db02018-10-23 13:19:31 +00002801 return false;
Roman Lebedevb3a14202018-10-30 11:12:34 +00002802 if (!matchShiftAmt(N1))
Roman Lebedev06e4db02018-10-23 13:19:31 +00002803 return false;
2804 X = N0->getOperand(0);
Roman Lebedev06e4db02018-10-23 13:19:31 +00002805 return true;
2806 };
2807
Roman Lebedevb3a14202018-10-30 11:12:34 +00002808 auto matchLowBitMask = [&matchPatternA, &matchPatternB,
2809 &matchPatternC](SDValue Mask) -> bool {
Roman Lebedev06e4db02018-10-23 13:19:31 +00002810 // FIXME: pattern c.
Roman Lebedevb3a14202018-10-30 11:12:34 +00002811 return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002812 };
2813
Roman Lebedev06e4db02018-10-23 13:19:31 +00002814 if (Node->getOpcode() == ISD::AND) {
2815 X = Node->getOperand(0);
2816 SDValue Mask = Node->getOperand(1);
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002817
Roman Lebedev06e4db02018-10-23 13:19:31 +00002818 if (matchLowBitMask(Mask)) {
2819 // Great.
2820 } else {
2821 std::swap(X, Mask);
2822 if (!matchLowBitMask(Mask))
2823 return false;
2824 }
2825 } else if (!matchPatternD(Node))
2826 return false;
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002827
2828 SDLoc DL(Node);
2829
Roman Lebedevc29dbbd2018-10-23 10:34:57 +00002830 SDValue OrigNBits = NBits;
Roman Lebedev06e4db02018-10-23 13:19:31 +00002831 if (NBits.getValueType() != NVT) {
2832 // Truncate the shift amount.
2833 NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
2834 insertDAGNode(*CurDAG, OrigNBits, NBits);
2835
2836 // Insert 8-bit NBits into lowest 8 bits of NVT-sized (32 or 64-bit)
2837 // register. All the other bits are undefined, we do not care about them.
2838 SDValue ImplDef =
2839 SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, NVT), 0);
2840 insertDAGNode(*CurDAG, OrigNBits, ImplDef);
2841 NBits =
2842 CurDAG->getTargetInsertSubreg(X86::sub_8bit, DL, NVT, ImplDef, NBits);
2843 insertDAGNode(*CurDAG, OrigNBits, NBits);
2844 }
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002845
Roman Lebedev89880852018-10-22 14:12:44 +00002846 if (Subtarget->hasBMI2()) {
2847 // Great, just emit the the BZHI..
2848 SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
2849 ReplaceNode(Node, Extract.getNode());
2850 SelectCode(Extract.getNode());
2851 return true;
2852 }
2853
2854 // Else, emitting BEXTR requires one more step.
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002855 // The 'control' of BEXTR has the pattern of:
2856 // [15...8 bit][ 7...0 bit] location
2857 // [ bit count][ shift] name
2858 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11
2859
2860 // Shift NBits left by 8 bits, thus producing 'control'.
Roman Lebedev90c5b3f2018-11-16 13:04:54 +00002861 // This makes the low 8 bits to be zero.
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002862 SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
2863 SDValue Control = CurDAG->getNode(ISD::SHL, DL, NVT, NBits, C8);
2864 insertDAGNode(*CurDAG, OrigNBits, Control);
Roman Lebedev90c5b3f2018-11-16 13:04:54 +00002865
2866 // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
2867 if (X.getOpcode() == ISD::SRL) {
2868 SDValue ShiftAmt = X.getOperand(1);
2869 X = X.getOperand(0);
2870
2871 assert(ShiftAmt.getValueType() == MVT::i8 &&
2872 "Expected shift amount to be i8");
2873
2874 // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
2875 SDValue OrigShiftAmt = ShiftAmt;
2876 ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, NVT, ShiftAmt);
2877 insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
2878
2879 // And now 'or' these low 8 bits of shift amount into the 'control'.
2880 Control = CurDAG->getNode(ISD::OR, DL, NVT, Control, ShiftAmt);
2881 insertDAGNode(*CurDAG, OrigNBits, Control);
2882 }
Roman Lebedev4225f4a2018-10-11 07:51:13 +00002883
2884 // And finally, form the BEXTR itself.
2885 SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, NVT, X, Control);
2886 ReplaceNode(Node, Extract.getNode());
2887 SelectCode(Extract.getNode());
2888
2889 return true;
2890}
2891
Craig Topperfb2ac892018-10-11 18:06:07 +00002892// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
Craig Toppere0a99292018-10-16 22:29:36 +00002893MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
Craig Topperfb2ac892018-10-11 18:06:07 +00002894 MVT NVT = Node->getSimpleValueType(0);
2895 SDLoc dl(Node);
2896
2897 SDValue N0 = Node->getOperand(0);
2898 SDValue N1 = Node->getOperand(1);
2899
2900 // If we have TBM we can use an immediate for the control. If we have BMI
2901 // we should only do this if the BEXTR instruction is implemented well.
2902 // Otherwise moving the control into a register makes this more costly.
2903 // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
2904 // hoisting the move immediate would make it worthwhile with a less optimal
2905 // BEXTR?
2906 if (!Subtarget->hasTBM() &&
2907 !(Subtarget->hasBMI() && Subtarget->hasFastBEXTR()))
Craig Toppere0a99292018-10-16 22:29:36 +00002908 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002909
2910 // Must have a shift right.
2911 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
Craig Toppere0a99292018-10-16 22:29:36 +00002912 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002913
2914 // Shift can't have additional users.
2915 if (!N0->hasOneUse())
Craig Toppere0a99292018-10-16 22:29:36 +00002916 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002917
2918 // Only supported for 32 and 64 bits.
2919 if (NVT != MVT::i32 && NVT != MVT::i64)
Craig Toppere0a99292018-10-16 22:29:36 +00002920 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002921
2922 // Shift amount and RHS of and must be constant.
2923 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2924 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2925 if (!MaskCst || !ShiftCst)
Craig Toppere0a99292018-10-16 22:29:36 +00002926 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002927
2928 // And RHS must be a mask.
2929 uint64_t Mask = MaskCst->getZExtValue();
2930 if (!isMask_64(Mask))
Craig Toppere0a99292018-10-16 22:29:36 +00002931 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002932
2933 uint64_t Shift = ShiftCst->getZExtValue();
2934 uint64_t MaskSize = countPopulation(Mask);
2935
2936 // Don't interfere with something that can be handled by extracting AH.
2937 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2938 if (Shift == 8 && MaskSize == 8)
Craig Toppere0a99292018-10-16 22:29:36 +00002939 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002940
2941 // Make sure we are only using bits that were in the original value, not
2942 // shifted in.
2943 if (Shift + MaskSize > NVT.getSizeInBits())
Craig Toppere0a99292018-10-16 22:29:36 +00002944 return nullptr;
Craig Topperfb2ac892018-10-11 18:06:07 +00002945
2946 SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
2947 unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
2948 unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
2949
2950 // BMI requires the immediate to placed in a register.
2951 if (!Subtarget->hasTBM()) {
2952 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
2953 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
2954 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
2955 New = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, New), 0);
2956 }
2957
2958 MachineSDNode *NewNode;
2959 SDValue Input = N0->getOperand(0);
2960 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2961 if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2962 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
2963 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
2964 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2965 // Update the chain.
2966 ReplaceUses(Input.getValue(1), SDValue(NewNode, 1));
2967 // Record the mem-refs
2968 CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
2969 } else {
2970 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
2971 }
2972
Craig Toppere0a99292018-10-16 22:29:36 +00002973 return NewNode;
Craig Topperfb2ac892018-10-11 18:06:07 +00002974}
2975
Craig Topperd6564102018-04-27 22:15:33 +00002976// Emit a PCMISTR(I/M) instruction.
2977MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
2978 bool MayFoldLoad, const SDLoc &dl,
2979 MVT VT, SDNode *Node) {
2980 SDValue N0 = Node->getOperand(0);
2981 SDValue N1 = Node->getOperand(1);
2982 SDValue Imm = Node->getOperand(2);
2983 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2984 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2985
Craig Topperc8e183f2018-10-22 22:14:05 +00002986 // Try to fold a load. No need to check alignment.
Craig Topperd6564102018-04-27 22:15:33 +00002987 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Craig Topperc8e183f2018-10-22 22:14:05 +00002988 if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Craig Topperd6564102018-04-27 22:15:33 +00002989 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
Craig Topperc8e183f2018-10-22 22:14:05 +00002990 N1.getOperand(0) };
Craig Topperd6564102018-04-27 22:15:33 +00002991 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
2992 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2993 // Update the chain.
Craig Topperc8e183f2018-10-22 22:14:05 +00002994 ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
Craig Topperd6564102018-04-27 22:15:33 +00002995 // Record the mem-refs
Craig Topperc8e183f2018-10-22 22:14:05 +00002996 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
Craig Topperd6564102018-04-27 22:15:33 +00002997 return CNode;
2998 }
2999
3000 SDValue Ops[] = { N0, N1, Imm };
3001 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
3002 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3003 return CNode;
3004}
3005
3006// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
3007// to emit a second instruction after this one. This is needed since we have two
3008// copyToReg nodes glued before this and we need to continue that glue through.
3009MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
3010 bool MayFoldLoad, const SDLoc &dl,
3011 MVT VT, SDNode *Node,
3012 SDValue &InFlag) {
3013 SDValue N0 = Node->getOperand(0);
3014 SDValue N2 = Node->getOperand(2);
3015 SDValue Imm = Node->getOperand(4);
3016 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3017 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3018
Craig Topperc8e183f2018-10-22 22:14:05 +00003019 // Try to fold a load. No need to check alignment.
Craig Topperd6564102018-04-27 22:15:33 +00003020 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Craig Topperc8e183f2018-10-22 22:14:05 +00003021 if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Craig Topperd6564102018-04-27 22:15:33 +00003022 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
Craig Topperc8e183f2018-10-22 22:14:05 +00003023 N2.getOperand(0), InFlag };
Craig Topperd6564102018-04-27 22:15:33 +00003024 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
3025 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3026 InFlag = SDValue(CNode, 3);
3027 // Update the chain.
Craig Topperc8e183f2018-10-22 22:14:05 +00003028 ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
Craig Topperd6564102018-04-27 22:15:33 +00003029 // Record the mem-refs
Craig Topperc8e183f2018-10-22 22:14:05 +00003030 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
Craig Topperd6564102018-04-27 22:15:33 +00003031 return CNode;
3032 }
3033
3034 SDValue Ops[] = { N0, N2, Imm, InFlag };
3035 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
3036 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3037 InFlag = SDValue(CNode, 2);
3038 return CNode;
3039}
3040
Craig Topper538f8ab2018-08-22 19:39:09 +00003041bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
3042 EVT VT = N->getValueType(0);
3043
3044 // Only handle scalar shifts.
3045 if (VT.isVector())
3046 return false;
3047
3048 // Narrower shifts only mask to 5 bits in hardware.
3049 unsigned Size = VT == MVT::i64 ? 64 : 32;
3050
3051 SDValue OrigShiftAmt = N->getOperand(1);
3052 SDValue ShiftAmt = OrigShiftAmt;
3053 SDLoc DL(N);
3054
3055 // Skip over a truncate of the shift amount.
3056 if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
3057 ShiftAmt = ShiftAmt->getOperand(0);
3058
Roman Lebedev06e4db02018-10-23 13:19:31 +00003059 // This function is called after X86DAGToDAGISel::matchBitExtract(),
3060 // so we are not afraid that we might mess up BZHI/BEXTR pattern.
Craig Topper538f8ab2018-08-22 19:39:09 +00003061
3062 SDValue NewShiftAmt;
3063 if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
3064 SDValue Add0 = ShiftAmt->getOperand(0);
3065 SDValue Add1 = ShiftAmt->getOperand(1);
3066 // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
3067 // to avoid the ADD/SUB.
3068 if (isa<ConstantSDNode>(Add1) &&
3069 cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) {
3070 NewShiftAmt = Add0;
3071 // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
3072 // generate a NEG instead of a SUB of a constant.
3073 } else if (ShiftAmt->getOpcode() == ISD::SUB &&
3074 isa<ConstantSDNode>(Add0) &&
3075 cast<ConstantSDNode>(Add0)->getZExtValue() != 0 &&
3076 cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) {
3077 // Insert a negate op.
3078 // TODO: This isn't guaranteed to replace the sub if there is a logic cone
3079 // that uses it that's not a shift.
3080 EVT SubVT = ShiftAmt.getValueType();
3081 SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
3082 SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1);
3083 NewShiftAmt = Neg;
3084
3085 // Insert these operands into a valid topological order so they can
3086 // get selected independently.
3087 insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
3088 insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
3089 } else
3090 return false;
3091 } else
3092 return false;
3093
3094 if (NewShiftAmt.getValueType() != MVT::i8) {
3095 // Need to truncate the shift amount.
3096 NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
3097 // Add to a correct topological ordering.
3098 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3099 }
3100
3101 // Insert a new mask to keep the shift amount legal. This should be removed
3102 // by isel patterns.
3103 NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
3104 CurDAG->getConstant(Size - 1, DL, MVT::i8));
3105 // Place in a correct topological ordering.
3106 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3107
3108 SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
3109 NewShiftAmt);
3110 if (UpdatedNode != N) {
3111 // If we found an existing node, we should replace ourselves with that node
3112 // and wait for it to be selected after its other users.
3113 ReplaceNode(N, UpdatedNode);
3114 return true;
3115 }
3116
3117 // If the original shift amount is now dead, delete it so that we don't run
3118 // it through isel.
3119 if (OrigShiftAmt.getNode()->use_empty())
3120 CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
3121
3122 // Now that we've optimized the shift amount, defer to normal isel to get
3123 // load folding and legacy vs BMI2 selection without repeating it here.
3124 SelectCode(N);
3125 return true;
3126}
3127
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003128/// If the high bits of an 'and' operand are known zero, try setting the
3129/// high bits of an 'and' constant operand to produce a smaller encoding by
3130/// creating a small, sign-extended negative immediate rather than a large
3131/// positive one. This reverses a transform in SimplifyDemandedBits that
3132/// shrinks mask constants by clearing bits. There is also a possibility that
3133/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
3134/// case, just replace the 'and'. Return 'true' if the node is replaced.
3135bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
3136 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
3137 // have immediate operands.
3138 MVT VT = And->getSimpleValueType(0);
3139 if (VT != MVT::i32 && VT != MVT::i64)
3140 return false;
3141
3142 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
3143 if (!And1C)
3144 return false;
3145
Craig Topper57e06432018-02-05 16:54:07 +00003146 // Bail out if the mask constant is already negative. It's can't shrink more.
3147 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
3148 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
3149 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
3150 // are negative too.
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003151 APInt MaskVal = And1C->getAPIntValue();
3152 unsigned MaskLZ = MaskVal.countLeadingZeros();
Craig Topper57e06432018-02-05 16:54:07 +00003153 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003154 return false;
3155
Craig Topper57e06432018-02-05 16:54:07 +00003156 // Don't extend into the upper 32 bits of a 64 bit mask.
3157 if (VT == MVT::i64 && MaskLZ >= 32) {
3158 MaskLZ -= 32;
3159 MaskVal = MaskVal.trunc(32);
3160 }
3161
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003162 SDValue And0 = And->getOperand(0);
Craig Topper57e06432018-02-05 16:54:07 +00003163 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003164 APInt NegMaskVal = MaskVal | HighZeros;
3165
3166 // If a negative constant would not allow a smaller encoding, there's no need
3167 // to continue. Only change the constant when we know it's a win.
3168 unsigned MinWidth = NegMaskVal.getMinSignedBits();
3169 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
3170 return false;
3171
Craig Topper57e06432018-02-05 16:54:07 +00003172 // Extend masks if we truncated above.
3173 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
3174 NegMaskVal = NegMaskVal.zext(64);
3175 HighZeros = HighZeros.zext(64);
3176 }
3177
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003178 // The variable operand must be all zeros in the top bits to allow using the
3179 // new, negative constant as the mask.
3180 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
3181 return false;
3182
3183 // Check if the mask is -1. In that case, this is an unnecessary instruction
3184 // that escaped earlier analysis.
3185 if (NegMaskVal.isAllOnesValue()) {
3186 ReplaceNode(And, And0.getNode());
3187 return true;
3188 }
3189
3190 // A negative mask allows a smaller encoding. Create a new 'and' node.
3191 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
3192 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
3193 ReplaceNode(And, NewAnd.getNode());
3194 SelectCode(NewAnd.getNode());
3195 return true;
3196}
3197
Justin Bogner593741d2016-05-10 23:55:37 +00003198void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00003199 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00003200 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003201 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00003202
Dan Gohman17059682008-07-17 19:10:17 +00003203 if (Node->isMachineOpcode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003204 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00003205 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00003206 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00003207 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00003208
Evan Cheng10d27902006-01-06 20:36:21 +00003209 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00003210 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00003211 case ISD::BRIND: {
3212 if (Subtarget->isTargetNaCl())
3213 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
3214 // leave the instruction alone.
3215 break;
3216 if (Subtarget->isTarget64BitILP32()) {
3217 // Converts a 32-bit register to a 64-bit, zero-extended version of
3218 // it. This is needed because x86-64 can do many things, but jmp %r32
3219 // ain't one of them.
3220 const SDValue &Target = Node->getOperand(1);
3221 assert(Target.getSimpleValueType() == llvm::MVT::i32);
3222 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
3223 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
3224 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00003225 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00003226 SelectCode(ZextTarget.getNode());
3227 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00003228 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00003229 }
3230 break;
3231 }
Dan Gohman757eee82009-08-02 16:10:52 +00003232 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00003233 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00003234 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00003235
Craig Toppera7a12392018-08-03 07:01:10 +00003236 case ISD::BITCAST:
3237 // Just drop all 128/256/512-bit bitcasts.
3238 if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
3239 NVT == MVT::f128) {
3240 ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
3241 CurDAG->RemoveDeadNode(Node);
3242 return;
3243 }
3244 break;
3245
Craig Topper75370b92017-09-19 17:19:45 +00003246 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00003247 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00003248 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00003249 SDValue VSelect = CurDAG->getNode(
3250 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
3251 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00003252 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00003253 SelectCode(VSelect.getNode());
3254 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00003255 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00003256 }
Craig Topper3af251d2012-07-01 02:55:34 +00003257
Craig Topper538f8ab2018-08-22 19:39:09 +00003258 case ISD::SRL:
Roman Lebedev06e4db02018-10-23 13:19:31 +00003259 if (matchBitExtract(Node))
3260 return;
3261 LLVM_FALLTHROUGH;
Craig Topper538f8ab2018-08-22 19:39:09 +00003262 case ISD::SRA:
3263 case ISD::SHL:
3264 if (tryShiftAmountMod(Node))
3265 return;
3266 break;
3267
Tobias Grosser85508e82015-08-19 11:35:10 +00003268 case ISD::AND:
Craig Toppere0a99292018-10-16 22:29:36 +00003269 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
3270 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
3271 CurDAG->RemoveDeadNode(Node);
Craig Topperfb2ac892018-10-11 18:06:07 +00003272 return;
Craig Toppere0a99292018-10-16 22:29:36 +00003273 }
Roman Lebedev89880852018-10-22 14:12:44 +00003274 if (matchBitExtract(Node))
Roman Lebedev4225f4a2018-10-11 07:51:13 +00003275 return;
Sanjay Patel40aa8672018-08-23 15:58:07 +00003276 if (AndImmShrink && shrinkAndImmediate(Node))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00003277 return;
Craig Topper958106d2017-09-12 17:40:25 +00003278
3279 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003280 case ISD::OR:
3281 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00003282
Benjamin Kramer4c816242011-04-22 15:30:40 +00003283 // For operations of the form (x << C1) op C2, check if we can use a smaller
3284 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
3285 SDValue N0 = Node->getOperand(0);
3286 SDValue N1 = Node->getOperand(1);
3287
3288 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
3289 break;
3290
3291 // i8 is unshrinkable, i16 should be promoted to i32.
3292 if (NVT != MVT::i32 && NVT != MVT::i64)
3293 break;
3294
3295 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
3296 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3297 if (!Cst || !ShlCst)
3298 break;
3299
3300 int64_t Val = Cst->getSExtValue();
3301 uint64_t ShlVal = ShlCst->getZExtValue();
3302
3303 // Make sure that we don't change the operation by removing bits.
3304 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00003305 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
3306 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00003307 break;
3308
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003309 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00003310 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003311
3312 // Check the minimum bitwidth for the new constant.
3313 // TODO: AND32ri is the same as AND64ri32 with zext imm.
3314 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
3315 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
3316 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
3317 CstVT = MVT::i8;
3318 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
3319 CstVT = MVT::i32;
3320
3321 // Bail if there is no smaller encoding.
3322 if (NVT == CstVT)
3323 break;
3324
Craig Topper83e042a2013-08-15 05:57:07 +00003325 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00003326 default: llvm_unreachable("Unsupported VT!");
3327 case MVT::i32:
3328 assert(CstVT == MVT::i8);
3329 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003330 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003331
3332 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00003333 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00003334 case ISD::AND: Op = X86::AND32ri8; break;
3335 case ISD::OR: Op = X86::OR32ri8; break;
3336 case ISD::XOR: Op = X86::XOR32ri8; break;
3337 }
3338 break;
3339 case MVT::i64:
3340 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
3341 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003342 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003343
3344 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00003345 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00003346 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
3347 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
3348 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
3349 }
3350 break;
3351 }
3352
3353 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003354 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00003355 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003356 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00003357 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
3358 SDValue(New, 0));
3359 else
3360 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
3361 getI8Imm(ShlVal, dl));
3362 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003363 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00003364 case X86ISD::UMUL8:
3365 case X86ISD::SMUL8: {
3366 SDValue N0 = Node->getOperand(0);
3367 SDValue N1 = Node->getOperand(1);
3368
Craig Topper3efdb7c2018-06-11 20:50:58 +00003369 unsigned Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00003370
3371 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
3372 N0, SDValue()).getValue(1);
3373
3374 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
3375 SDValue Ops[] = {N1, InFlag};
3376 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
3377
Justin Bogner31d7da32016-05-11 21:13:17 +00003378 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00003379 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00003380 }
3381
Chris Lattner364bb0a2010-12-05 07:30:36 +00003382 case X86ISD::UMUL: {
3383 SDValue N0 = Node->getOperand(0);
3384 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00003385
Craig Topper3efdb7c2018-06-11 20:50:58 +00003386 unsigned LoReg, Opc;
Craig Topper83e042a2013-08-15 05:57:07 +00003387 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00003388 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00003389 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00003390 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
3391 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
3392 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00003393 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003394
Chris Lattner364bb0a2010-12-05 07:30:36 +00003395 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
3396 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00003397
Chris Lattner364bb0a2010-12-05 07:30:36 +00003398 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
3399 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00003400 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00003401
Justin Bognerfde9f2e2016-05-11 22:21:50 +00003402 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00003403 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00003404 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003405
Dan Gohman757eee82009-08-02 16:10:52 +00003406 case ISD::SMUL_LOHI:
3407 case ISD::UMUL_LOHI: {
3408 SDValue N0 = Node->getOperand(0);
3409 SDValue N1 = Node->getOperand(1);
3410
Craig Topper3efdb7c2018-06-11 20:50:58 +00003411 unsigned Opc, MOpc;
Dan Gohman757eee82009-08-02 16:10:52 +00003412 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00003413 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003414 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00003415 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003416 default: llvm_unreachable("Unsupported VT!");
Michael Liaof9f7b552012-09-26 08:22:37 +00003417 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
3418 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
3419 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
3420 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003421 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003422 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00003423 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003424 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003425 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
3426 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003427 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003428 }
Dan Gohman757eee82009-08-02 16:10:52 +00003429
Michael Liaof9f7b552012-09-26 08:22:37 +00003430 unsigned SrcReg, LoReg, HiReg;
3431 switch (Opc) {
3432 default: llvm_unreachable("Unknown MUL opcode!");
Michael Liaof9f7b552012-09-26 08:22:37 +00003433 case X86::IMUL32r:
3434 case X86::MUL32r:
3435 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
3436 break;
3437 case X86::IMUL64r:
3438 case X86::MUL64r:
3439 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
3440 break;
3441 case X86::MULX32rr:
3442 SrcReg = X86::EDX; LoReg = HiReg = 0;
3443 break;
3444 case X86::MULX64rr:
3445 SrcReg = X86::RDX; LoReg = HiReg = 0;
3446 break;
Dan Gohman757eee82009-08-02 16:10:52 +00003447 }
3448
3449 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003450 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003451 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00003452 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00003453 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00003454 if (foldedLoad)
3455 std::swap(N0, N1);
3456 }
3457
Michael Liaof9f7b552012-09-26 08:22:37 +00003458 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00003459 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00003460 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00003461
3462 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003463 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00003464 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00003465 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3466 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00003467 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
3468 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00003469 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003470 ResHi = SDValue(CNode, 0);
3471 ResLo = SDValue(CNode, 1);
3472 Chain = SDValue(CNode, 2);
3473 InFlag = SDValue(CNode, 3);
3474 } else {
3475 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00003476 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003477 Chain = SDValue(CNode, 0);
3478 InFlag = SDValue(CNode, 1);
3479 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00003480
Dan Gohman757eee82009-08-02 16:10:52 +00003481 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00003482 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00003483 // Record the mem-refs
Chandler Carruth66654b72018-08-14 23:30:32 +00003484 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
Dan Gohman757eee82009-08-02 16:10:52 +00003485 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00003486 SDValue Ops[] = { N1, InFlag };
3487 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
3488 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003489 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003490 ResHi = SDValue(CNode, 0);
3491 ResLo = SDValue(CNode, 1);
3492 InFlag = SDValue(CNode, 2);
3493 } else {
3494 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003495 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003496 InFlag = SDValue(CNode, 0);
3497 }
Dan Gohman757eee82009-08-02 16:10:52 +00003498 }
3499
3500 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003501 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003502 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003503 assert(LoReg && "Register for low half is not defined!");
3504 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
3505 InFlag);
3506 InFlag = ResLo.getValue(2);
3507 }
3508 ReplaceUses(SDValue(Node, 0), ResLo);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003509 LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
3510 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003511 }
3512 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003513 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003514 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003515 assert(HiReg && "Register for high half is not defined!");
3516 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
3517 InFlag);
3518 InFlag = ResHi.getValue(2);
3519 }
3520 ReplaceUses(SDValue(Node, 1), ResHi);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003521 LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
3522 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003523 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003524
Craig Topper6bed9de2017-09-09 05:57:20 +00003525 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003526 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003527 }
3528
3529 case ISD::SDIVREM:
Craig Topper5eea94e2018-10-21 21:07:27 +00003530 case ISD::UDIVREM: {
Dan Gohman757eee82009-08-02 16:10:52 +00003531 SDValue N0 = Node->getOperand(0);
3532 SDValue N1 = Node->getOperand(1);
3533
Craig Topper3efdb7c2018-06-11 20:50:58 +00003534 unsigned Opc, MOpc;
Craig Topper5eea94e2018-10-21 21:07:27 +00003535 bool isSigned = Opcode == ISD::SDIVREM;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003536 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00003537 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003538 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003539 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
3540 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
3541 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
3542 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003543 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003544 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00003545 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003546 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003547 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
3548 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
3549 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
3550 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003551 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003552 }
Dan Gohman757eee82009-08-02 16:10:52 +00003553
Chris Lattner518b0372009-12-23 01:45:04 +00003554 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003555 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00003556 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003557 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003558 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00003559 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00003560 SExtOpcode = X86::CBW;
3561 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003562 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00003563 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003564 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00003565 SExtOpcode = X86::CWD;
3566 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003567 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00003568 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003569 SExtOpcode = X86::CDQ;
3570 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003571 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00003572 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003573 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00003574 break;
3575 }
3576
Dan Gohman757eee82009-08-02 16:10:52 +00003577 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003578 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00003579 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00003580
Dan Gohman757eee82009-08-02 16:10:52 +00003581 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00003582 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003583 // Special case for div8, just use a move with zero extension to AX to
3584 // clear the upper 8 bits (AH).
Craig Topper99ad2a52018-09-30 17:47:18 +00003585 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
3586 MachineSDNode *Move;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003587 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003588 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
Craig Topper99ad2a52018-09-30 17:47:18 +00003589 Move = CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
3590 MVT::Other, Ops);
3591 Chain = SDValue(Move, 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003592 ReplaceUses(N0.getValue(1), Chain);
Craig Topper99ad2a52018-09-30 17:47:18 +00003593 // Record the mem-refs
3594 CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
Evan Cheng10d27902006-01-06 20:36:21 +00003595 } else {
Craig Topper99ad2a52018-09-30 17:47:18 +00003596 Move = CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0);
Dan Gohman757eee82009-08-02 16:10:52 +00003597 Chain = CurDAG->getEntryNode();
3598 }
Craig Topper99ad2a52018-09-30 17:47:18 +00003599 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, SDValue(Move, 0),
3600 SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00003601 InFlag = Chain.getValue(1);
3602 } else {
3603 InFlag =
3604 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
3605 LoReg, N0, SDValue()).getValue(1);
3606 if (isSigned && !signBitIsZero) {
3607 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00003608 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003609 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00003610 } else {
3611 // Zero out the high part, effectively zero extending the input.
Craig Topper6c3f1692018-10-31 21:53:24 +00003612 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00003613 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00003614 case MVT::i16:
3615 ClrNode =
3616 SDValue(CurDAG->getMachineNode(
3617 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003618 CurDAG->getTargetConstant(X86::sub_16bit, dl,
3619 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003620 0);
3621 break;
3622 case MVT::i32:
Craig Topper6c3f1692018-10-31 21:53:24 +00003623 break;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003624 case MVT::i64:
Craig Topper6c3f1692018-10-31 21:53:24 +00003625 ClrNode =
3626 SDValue(CurDAG->getMachineNode(
3627 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
3628 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
3629 CurDAG->getTargetConstant(X86::sub_32bit, dl,
3630 MVT::i32)),
3631 0);
Tim Northover64ec0ff2013-05-30 13:19:42 +00003632 break;
3633 default:
3634 llvm_unreachable("Unexpected division source");
3635 }
3636
Chris Lattner518b0372009-12-23 01:45:04 +00003637 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00003638 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00003639 }
Evan Cheng92e27972006-01-06 23:19:29 +00003640 }
Dan Gohmana1603612007-10-08 18:33:35 +00003641
Dan Gohman757eee82009-08-02 16:10:52 +00003642 if (foldedLoad) {
3643 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3644 InFlag };
Craig Topper61f81f92017-11-08 22:26:39 +00003645 MachineSDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00003646 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00003647 InFlag = SDValue(CNode, 1);
3648 // Update the chain.
3649 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
Craig Topper61f81f92017-11-08 22:26:39 +00003650 // Record the mem-refs
Chandler Carruth66654b72018-08-14 23:30:32 +00003651 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
Dan Gohman757eee82009-08-02 16:10:52 +00003652 } else {
3653 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003654 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003655 }
Evan Cheng92e27972006-01-06 23:19:29 +00003656
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003657 // Prevent use of AH in a REX instruction by explicitly copying it to
3658 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00003659 //
3660 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003661 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00003662 // the allocator and/or the backend get enhanced to be more robust in
3663 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003664 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
3665 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
3666 unsigned AHExtOpcode =
Craig Topperad7c6852018-03-20 05:00:20 +00003667 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003668
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003669 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
3670 MVT::Glue, AHCopy, InFlag);
3671 SDValue Result(RNode, 0);
3672 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003673
Craig Topper5eea94e2018-10-21 21:07:27 +00003674 Result =
3675 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
3676
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003677 ReplaceUses(SDValue(Node, 1), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003678 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3679 dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003680 }
Dan Gohman757eee82009-08-02 16:10:52 +00003681 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003682 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00003683 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3684 LoReg, NVT, InFlag);
3685 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003686 ReplaceUses(SDValue(Node, 0), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003687 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3688 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003689 }
3690 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003691 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003692 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3693 HiReg, NVT, InFlag);
3694 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003695 ReplaceUses(SDValue(Node, 1), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003696 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3697 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003698 }
Craig Topper6bed9de2017-09-09 05:57:20 +00003699 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003700 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003701 }
3702
Craig Topperb424faf2018-02-12 03:02:02 +00003703 case X86ISD::CMP: {
Dan Gohmanac33a902009-08-19 18:16:17 +00003704 SDValue N0 = Node->getOperand(0);
3705 SDValue N1 = Node->getOperand(1);
3706
Craig Topperf06a57f2018-10-01 21:35:26 +00003707 // Save the original VT of the compare.
3708 MVT CmpVT = N0.getSimpleValueType();
3709
Craig Toppere0a99292018-10-16 22:29:36 +00003710 // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
3711 // by a test instruction. The test should be removed later by
3712 // analyzeCompare if we are using only the zero flag.
3713 // TODO: Should we check the users and use the BEXTR flags directly?
3714 if (isNullConstant(N1) && N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
3715 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
3716 unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
3717 : X86::TEST32rr;
3718 SDValue BEXTR = SDValue(NewNode, 0);
3719 NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
3720 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
3721 CurDAG->RemoveDeadNode(Node);
3722 return;
3723 }
3724 }
3725
Craig Topperf06a57f2018-10-01 21:35:26 +00003726 // We can peek through truncates, but we need to be careful below.
3727 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003728 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00003729
Dan Gohmanac33a902009-08-19 18:16:17 +00003730 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
3731 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003732 // Look past the truncate if CMP is the only use of it.
Craig Topper3ccbd3f2018-02-12 03:02:01 +00003733 if (N0.getOpcode() == ISD::AND &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00003734 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00003735 N0.getValueType() != MVT::i8 &&
Craig Toppere0a99292018-10-16 22:29:36 +00003736 isNullConstant(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00003737 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00003738 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00003739 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00003740
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003741 MVT VT;
3742 int SubRegOp;
Craig Topper42cd8cd2018-10-01 21:35:28 +00003743 unsigned ROpc, MOpc;
Craig Topper2b587ad2018-10-01 17:10:45 +00003744
Craig Topperf06a57f2018-10-01 21:35:26 +00003745 // For each of these checks we need to be careful if the sign flag is
3746 // being used. It is only safe to use the sign flag in two conditions,
3747 // either the sign bit in the shrunken mask is zero or the final test
3748 // size is equal to the original compare size.
3749
Craig Topperfc53dc22017-08-25 05:04:34 +00003750 if (isUInt<8>(Mask) &&
Craig Topperf06a57f2018-10-01 21:35:26 +00003751 (!(Mask & 0x80) || CmpVT == MVT::i8 ||
3752 hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003753 // For example, convert "testl %eax, $8" to "testb %al, $8"
3754 VT = MVT::i8;
3755 SubRegOp = X86::sub_8bit;
Craig Topper42cd8cd2018-10-01 21:35:28 +00003756 ROpc = X86::TEST8ri;
3757 MOpc = X86::TEST8mi;
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003758 } else if (OptForMinSize && isUInt<16>(Mask) &&
Craig Topperf06a57f2018-10-01 21:35:26 +00003759 (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
3760 hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003761 // For example, "testl %eax, $32776" to "testw %ax, $32776".
3762 // NOTE: We only want to form TESTW instructions if optimizing for
3763 // min size. Otherwise we only save one byte and possibly get a length
3764 // changing prefix penalty in the decoders.
3765 VT = MVT::i16;
3766 SubRegOp = X86::sub_16bit;
Craig Topper42cd8cd2018-10-01 21:35:28 +00003767 ROpc = X86::TEST16ri;
3768 MOpc = X86::TEST16mi;
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003769 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
Craig Topperf06a57f2018-10-01 21:35:26 +00003770 ((!(Mask & 0x80000000) &&
3771 // Without minsize 16-bit Cmps can get here so we need to
3772 // be sure we calculate the correct sign flag if needed.
3773 (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
3774 CmpVT == MVT::i32 || hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003775 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3776 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
3777 // Otherwize, we find ourselves in a position where we have to do
3778 // promotion. If previous passes did not promote the and, we assume
3779 // they had a good reason not to and do not promote here.
3780 VT = MVT::i32;
3781 SubRegOp = X86::sub_32bit;
Craig Topper42cd8cd2018-10-01 21:35:28 +00003782 ROpc = X86::TEST32ri;
3783 MOpc = X86::TEST32mi;
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003784 } else {
3785 // No eligible transformation was found.
3786 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00003787 }
3788
Craig Topperf06a57f2018-10-01 21:35:26 +00003789 // FIXME: We should be able to fold loads here.
3790
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003791 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
3792 SDValue Reg = N0.getOperand(0);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003793
Craig Toppere0729342018-10-01 18:40:44 +00003794 // Emit a testl or testw.
Craig Topper42cd8cd2018-10-01 21:35:28 +00003795 MachineSDNode *NewNode;
3796 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3797 if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3798 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3799 Reg.getOperand(0) };
3800 NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
3801 // Update the chain.
3802 ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
3803 // Record the mem-refs
3804 CurDAG->setNodeMemRefs(NewNode,
3805 {cast<LoadSDNode>(Reg)->getMemOperand()});
3806 } else {
3807 // Extract the subregister if necessary.
3808 if (N0.getValueType() != VT)
3809 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
3810
3811 NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
3812 }
Craig Topperb424faf2018-02-12 03:02:02 +00003813 // Replace CMP with TEST.
Nirav Dave3264c1b2018-03-19 20:19:46 +00003814 ReplaceNode(Node, NewNode);
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003815 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003816 }
3817 break;
3818 }
Craig Topperd6564102018-04-27 22:15:33 +00003819 case X86ISD::PCMPISTR: {
3820 if (!Subtarget->hasSSE42())
3821 break;
3822
3823 bool NeedIndex = !SDValue(Node, 0).use_empty();
3824 bool NeedMask = !SDValue(Node, 1).use_empty();
3825 // We can't fold a load if we are going to make two instructions.
3826 bool MayFoldLoad = !NeedIndex || !NeedMask;
3827
3828 MachineSDNode *CNode;
3829 if (NeedMask) {
3830 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
3831 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
3832 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
3833 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3834 }
3835 if (NeedIndex || !NeedMask) {
3836 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
3837 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
3838 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
3839 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3840 }
3841
3842 // Connect the flag usage to the last instruction created.
Craig Topperabc307e2018-07-12 18:04:05 +00003843 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
Craig Topperd6564102018-04-27 22:15:33 +00003844 CurDAG->RemoveDeadNode(Node);
3845 return;
3846 }
3847 case X86ISD::PCMPESTR: {
3848 if (!Subtarget->hasSSE42())
3849 break;
3850
3851 // Copy the two implicit register inputs.
3852 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
3853 Node->getOperand(1),
3854 SDValue()).getValue(1);
3855 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
3856 Node->getOperand(3), InFlag).getValue(1);
3857
3858 bool NeedIndex = !SDValue(Node, 0).use_empty();
3859 bool NeedMask = !SDValue(Node, 1).use_empty();
3860 // We can't fold a load if we are going to make two instructions.
3861 bool MayFoldLoad = !NeedIndex || !NeedMask;
3862
3863 MachineSDNode *CNode;
3864 if (NeedMask) {
3865 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
3866 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
3867 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
3868 InFlag);
3869 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3870 }
3871 if (NeedIndex || !NeedMask) {
3872 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
3873 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
3874 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
3875 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3876 }
3877 // Connect the flag usage to the last instruction created.
3878 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
3879 CurDAG->RemoveDeadNode(Node);
3880 return;
3881 }
3882
Chandler Carruth03258f22017-08-25 02:04:03 +00003883 case ISD::STORE:
3884 if (foldLoadStoreIntoMemOperand(Node))
3885 return;
3886 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003887 }
3888
Justin Bogner593741d2016-05-10 23:55:37 +00003889 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003890}
3891
Chris Lattnerba1ed582006-06-08 18:03:49 +00003892bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003893SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003894 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003895 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003896 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003897 default:
3898 llvm_unreachable("Unexpected asm memory constraint");
3899 case InlineAsm::Constraint_i:
3900 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3901 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003902 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003903 case InlineAsm::Constraint_o: // offsetable ??
3904 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003905 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003906 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003907 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003908 return true;
3909 break;
3910 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003911
Evan Cheng2d487222006-08-26 01:05:16 +00003912 OutOps.push_back(Op0);
3913 OutOps.push_back(Op1);
3914 OutOps.push_back(Op2);
3915 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003916 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003917 return false;
3918}
3919
Sanjay Patelb5723d02015-10-13 15:12:27 +00003920/// This pass converts a legalized DAG into a X86-specific DAG,
3921/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003922FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003923 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003924 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003925}