blob: 4909d18d967e7dc60939eab63b4a7fdfbd4d7684 [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
Chris Lattner655e7df2005-11-16 01:54:32 +0000168 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000169 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000170 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Matt Morehouse9e658c92017-12-01 22:20:26 +0000171 OptForMinSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000172
Mehdi Amini117296c2016-10-01 02:56:57 +0000173 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000174 return "X86 DAG->DAG Instruction Selection";
175 }
176
Eric Christopher4f09c592014-05-22 01:53:26 +0000177 bool runOnMachineFunction(MachineFunction &MF) override {
178 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000179 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000180 SelectionDAGISel::runOnMachineFunction(MF);
181 return true;
182 }
183
Craig Topper2d9361e2014-03-09 07:44:38 +0000184 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000185
Craig Topper2d9361e2014-03-09 07:44:38 +0000186 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000187
Craig Topper2d9361e2014-03-09 07:44:38 +0000188 void PreprocessISelDAG() override;
Craig Toppere6913ec2018-03-16 17:13:42 +0000189 void PostprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000190
Chris Lattner655e7df2005-11-16 01:54:32 +0000191// Include the pieces autogenerated from the target description.
192#include "X86GenDAGISel.inc"
193
194 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000195 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000196
Sanjay Patel85030aa2015-10-13 16:23:00 +0000197 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
198 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
199 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
200 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Craig Topperc314f462017-11-13 17:53:59 +0000201 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000202 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000203 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000204 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000205 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
206 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000207 SDValue &Scale, SDValue &Index, SDValue &Disp,
208 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000209 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000210 SDValue &Scale, SDValue &Index, SDValue &Disp,
211 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000212 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
213 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000214 SDValue &Scale, SDValue &Index, SDValue &Disp,
215 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000216 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000217 SDValue &Scale, SDValue &Index, SDValue &Disp,
218 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000219 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000220 SDValue &Scale, SDValue &Index, SDValue &Disp,
221 SDValue &Segment);
Craig Topperb0e986f2018-06-17 16:29:46 +0000222 bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000223 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000224 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000225 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000226 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000227 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000228
Craig Topper78a77042017-11-08 20:17:33 +0000229 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000230 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000231 SDValue &Index, SDValue &Disp,
232 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000233
Craig Topperd6564102018-04-27 22:15:33 +0000234 // Convenience method where P is also root.
Craig Topper78a77042017-11-08 20:17:33 +0000235 bool tryFoldLoad(SDNode *P, SDValue N,
236 SDValue &Base, SDValue &Scale,
237 SDValue &Index, SDValue &Disp,
238 SDValue &Segment) {
239 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
240 }
241
Craig Topperd6564102018-04-27 22:15:33 +0000242 // Try to fold a vector load. This makes sure the load isn't non-temporal.
243 bool tryFoldVecLoad(SDNode *Root, SDNode *P, SDValue N,
244 SDValue &Base, SDValue &Scale,
245 SDValue &Index, SDValue &Disp,
246 SDValue &Segment);
247
Sanjay Patelb5723d02015-10-13 15:12:27 +0000248 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000249 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000250 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000251 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000252
Sanjay Patel85030aa2015-10-13 16:23:00 +0000253 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000254
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000255 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000256 SDValue &Base, SDValue &Scale,
257 SDValue &Index, SDValue &Disp,
258 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000259 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000260 ? CurDAG->getTargetFrameIndex(
261 AM.Base_FrameIndex,
262 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000263 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000264 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000265 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000266 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000267 // is 32-bit.
268 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000269 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000270 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000271 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000272 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000273 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000274 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000275 else if (AM.ES) {
276 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000277 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000278 } else if (AM.MCSym) {
279 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
280 assert(AM.SymbolFlags == 0 && "oo");
281 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000282 } else if (AM.JT != -1) {
283 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000284 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000285 } else if (AM.BlockAddr)
286 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
287 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000288 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000289 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000290
291 if (AM.Segment.getNode())
292 Segment = AM.Segment;
293 else
Owen Anderson9f944592009-08-11 20:47:22 +0000294 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000295 }
296
Michael Kuperstein243c0732015-08-11 14:10:58 +0000297 // Utility function to determine whether we should avoid selecting
298 // immediate forms of instructions for better code size or not.
299 // At a high level, we'd like to avoid such instructions when
300 // we have similar constants used within the same basic block
301 // that can be kept in a register.
302 //
303 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
304 uint32_t UseCount = 0;
305
306 // Do not want to hoist if we're not optimizing for size.
307 // TODO: We'd like to remove this restriction.
308 // See the comment in X86InstrInfo.td for more info.
309 if (!OptForSize)
310 return false;
311
312 // Walk all the users of the immediate.
313 for (SDNode::use_iterator UI = N->use_begin(),
314 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000315
Michael Kuperstein243c0732015-08-11 14:10:58 +0000316 SDNode *User = *UI;
317
318 // This user is already selected. Count it as a legitimate use and
319 // move on.
320 if (User->isMachineOpcode()) {
321 UseCount++;
322 continue;
323 }
324
325 // We want to count stores of immediates as real uses.
326 if (User->getOpcode() == ISD::STORE &&
327 User->getOperand(1).getNode() == N) {
328 UseCount++;
329 continue;
330 }
331
332 // We don't currently match users that have > 2 operands (except
333 // for stores, which are handled above)
334 // Those instruction won't match in ISEL, for now, and would
335 // be counted incorrectly.
336 // This may change in the future as we add additional instruction
337 // types.
338 if (User->getNumOperands() != 2)
339 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000340
Michael Kuperstein243c0732015-08-11 14:10:58 +0000341 // Immediates that are used for offsets as part of stack
342 // manipulation should be left alone. These are typically
343 // used to indicate SP offsets for argument passing and
344 // will get pulled into stores/pushes (implicitly).
345 if (User->getOpcode() == X86ISD::ADD ||
346 User->getOpcode() == ISD::ADD ||
347 User->getOpcode() == X86ISD::SUB ||
348 User->getOpcode() == ISD::SUB) {
349
350 // Find the other operand of the add/sub.
351 SDValue OtherOp = User->getOperand(0);
352 if (OtherOp.getNode() == N)
353 OtherOp = User->getOperand(1);
354
355 // Don't count if the other operand is SP.
356 RegisterSDNode *RegNode;
357 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
358 (RegNode = dyn_cast_or_null<RegisterSDNode>(
359 OtherOp->getOperand(1).getNode())))
360 if ((RegNode->getReg() == X86::ESP) ||
361 (RegNode->getReg() == X86::RSP))
362 continue;
363 }
364
365 // ... otherwise, count this and move on.
366 UseCount++;
367 }
368
369 // If we have more than 1 use, then recommend for hoisting.
370 return (UseCount > 1);
371 }
372
Sanjay Patelb5723d02015-10-13 15:12:27 +0000373 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000374 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000375 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000376 }
377
Sanjay Patelb5723d02015-10-13 15:12:27 +0000378 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000379 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000380 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000381 }
Evan Chengd49cc362006-02-10 22:24:32 +0000382
Craig Topper2b2d8c52018-02-15 19:57:35 +0000383 /// Return a target constant with the specified value, of type i64.
384 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
385 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
386 }
387
Craig Topper092c2f42017-09-23 05:34:07 +0000388 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
389 const SDLoc &DL) {
390 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
391 uint64_t Index = N->getConstantOperandVal(1);
392 MVT VecVT = N->getOperand(0).getSimpleValueType();
Craig Topper9563cab2017-10-08 01:33:42 +0000393 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000394 }
395
396 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
397 const SDLoc &DL) {
398 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
399 uint64_t Index = N->getConstantOperandVal(2);
400 MVT VecVT = N->getSimpleValueType(0);
Craig Topper9563cab2017-10-08 01:33:42 +0000401 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000402 }
403
Sanjay Patelb5723d02015-10-13 15:12:27 +0000404 /// Return an SDNode that returns the value of the global base register.
405 /// Output instructions required to initialize the global base register,
406 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000407 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000408
Sanjay Patelb5723d02015-10-13 15:12:27 +0000409 /// Return a reference to the TargetMachine, casted to the target-specific
410 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000411 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000412 return static_cast<const X86TargetMachine &>(TM);
413 }
414
Sanjay Patelb5723d02015-10-13 15:12:27 +0000415 /// Return a reference to the TargetInstrInfo, casted to the target-specific
416 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000417 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000418 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000419 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000420
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000421 /// Address-mode matching performs shift-of-and to and-of-shift
Adam Nemetff63a2d2014-10-03 20:00:34 +0000422 /// reassociation in order to expose more scaled addressing
423 /// opportunities.
424 bool ComplexPatternFuncMutatesDAG() const override {
425 return true;
426 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000427
428 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
429
430 /// Returns whether this is a relocatable immediate in the range
431 /// [-2^Width .. 2^Width-1].
432 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
433 if (auto *CN = dyn_cast<ConstantSDNode>(N))
434 return isInt<Width>(CN->getSExtValue());
435 return isSExtAbsoluteSymbolRef(Width, N);
436 }
Craig Topper4de6f582017-08-19 23:21:22 +0000437
438 // Indicates we should prefer to use a non-temporal load for this load.
439 bool useNonTemporalLoad(LoadSDNode *N) const {
440 if (!N->isNonTemporal())
441 return false;
442
443 unsigned StoreSize = N->getMemoryVT().getStoreSize();
444
445 if (N->getAlignment() < StoreSize)
446 return false;
447
448 switch (StoreSize) {
449 default: llvm_unreachable("Unsupported store size");
450 case 16:
451 return Subtarget->hasSSE41();
452 case 32:
453 return Subtarget->hasAVX2();
454 case 64:
455 return Subtarget->hasAVX512();
456 }
457 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000458
459 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000460 bool matchBEXTRFromAnd(SDNode *Node);
Sanjay Patel74a1eef2018-01-19 16:37:25 +0000461 bool shrinkAndImmediate(SDNode *N);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000462 bool isMaskZeroExtended(SDNode *N) const;
Craig Topper538f8ab2018-08-22 19:39:09 +0000463 bool tryShiftAmountMod(SDNode *N);
Craig Topperd6564102018-04-27 22:15:33 +0000464
465 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
466 const SDLoc &dl, MVT VT, SDNode *Node);
467 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
468 const SDLoc &dl, MVT VT, SDNode *Node,
469 SDValue &InFlag);
Chris Lattner655e7df2005-11-16 01:54:32 +0000470 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000471}
472
Evan Cheng72bb66a2006-08-08 00:31:00 +0000473
Craig Topperba3cc2e2017-09-25 18:43:13 +0000474// Returns true if this masked compare can be implemented legally with this
475// type.
476static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
Uriel Korachbb866862017-11-06 09:22:38 +0000477 unsigned Opcode = N->getOpcode();
Craig Topperc2696d52018-06-20 21:05:02 +0000478 if (Opcode == X86ISD::CMPM || Opcode == ISD::SETCC ||
Craig Topper48d5ed22018-02-28 08:14:28 +0000479 Opcode == X86ISD::CMPM_RND || Opcode == X86ISD::VFPCLASS) {
Craig Topperba3cc2e2017-09-25 18:43:13 +0000480 // We can get 256-bit 8 element types here without VLX being enabled. When
481 // this happens we will use 512-bit operations and the mask will not be
482 // zero extended.
Uriel Koracheb47d952017-11-06 08:32:45 +0000483 EVT OpVT = N->getOperand(0).getValueType();
Craig Topperd58c1652018-01-07 18:20:37 +0000484 if (OpVT.is256BitVector() || OpVT.is128BitVector())
Craig Topperba3cc2e2017-09-25 18:43:13 +0000485 return Subtarget->hasVLX();
486
487 return true;
488 }
Craig Topper48d5ed22018-02-28 08:14:28 +0000489 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
490 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
491 Opcode == X86ISD::FSETCCM_RND)
492 return true;
Craig Topperba3cc2e2017-09-25 18:43:13 +0000493
494 return false;
495}
496
497// Returns true if we can assume the writer of the mask has zero extended it
498// for us.
499bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
500 // If this is an AND, check if we have a compare on either side. As long as
501 // one side guarantees the mask is zero extended, the AND will preserve those
502 // zeros.
503 if (N->getOpcode() == ISD::AND)
504 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
505 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
506
507 return isLegalMaskCompare(N, Subtarget);
508}
509
Evan Cheng5e73ff22010-02-15 19:41:07 +0000510bool
511X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000512 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000513
Evan Cheng5e73ff22010-02-15 19:41:07 +0000514 if (!N.hasOneUse())
515 return false;
516
517 if (N.getOpcode() != ISD::LOAD)
518 return true;
519
520 // If N is a load, do additional profitability checks.
521 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000522 switch (U->getOpcode()) {
523 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000524 case X86ISD::ADD:
Craig Topper0fd5cde2018-09-06 22:41:44 +0000525 case X86ISD::ADC:
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000526 case X86ISD::SUB:
Craig Topper0fd5cde2018-09-06 22:41:44 +0000527 case X86ISD::SBB:
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000528 case X86ISD::AND:
529 case X86ISD::XOR:
530 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000531 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000532 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000533 case ISD::AND:
534 case ISD::OR:
535 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000536 SDValue Op1 = U->getOperand(1);
537
Evan Cheng83bdb382008-11-27 00:49:46 +0000538 // If the other operand is a 8-bit immediate we should fold the immediate
539 // instead. This reduces code size.
540 // e.g.
541 // movl 4(%esp), %eax
542 // addl $4, %eax
543 // vs.
544 // movl $4, %eax
545 // addl 4(%esp), %eax
546 // The former is 2 bytes shorter. In case where the increment is 1, then
547 // the saving can be 4 bytes (by using incl %eax).
Craig Topper7e42af82018-04-10 03:44:15 +0000548 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
Dan Gohman2293eb62009-03-14 02:07:16 +0000549 if (Imm->getAPIntValue().isSignedIntN(8))
550 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000551
Craig Topper7e42af82018-04-10 03:44:15 +0000552 // If this is a 64-bit AND with an immediate that fits in 32-bits,
553 // prefer using the smaller and over folding the load. This is needed to
554 // make sure immediates created by shrinkAndImmediate are always folded.
555 // Ideally we would narrow the load during DAG combine and get the
556 // best of both worlds.
557 if (U->getOpcode() == ISD::AND &&
558 Imm->getAPIntValue().getBitWidth() == 64 &&
559 Imm->getAPIntValue().isIntN(32))
560 return false;
561 }
562
Rafael Espindolabb834f02009-04-10 10:09:34 +0000563 // If the other operand is a TLS address, we should fold it instead.
564 // This produces
565 // movl %gs:0, %eax
566 // leal i@NTPOFF(%eax), %eax
567 // instead of
568 // movl $i@NTPOFF, %eax
569 // addl %gs:0, %eax
570 // if the block also has an access to a second TLS address this will save
571 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000572 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000573 if (Op1.getOpcode() == X86ISD::Wrapper) {
574 SDValue Val = Op1.getOperand(0);
575 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
576 return false;
577 }
Craig Topperab70f582018-06-28 00:47:41 +0000578
Craig Topper90317d12018-06-28 17:58:01 +0000579 // Don't fold load if this matches the BTS/BTR/BTC patterns.
580 // BTS: (or X, (shl 1, n))
581 // BTR: (and X, (rotl -2, n))
582 // BTC: (xor X, (shl 1, n))
583 if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
584 if (U->getOperand(0).getOpcode() == ISD::SHL &&
585 isOneConstant(U->getOperand(0).getOperand(0)))
586 return false;
587
588 if (U->getOperand(1).getOpcode() == ISD::SHL &&
589 isOneConstant(U->getOperand(1).getOperand(0)))
590 return false;
591 }
592 if (U->getOpcode() == ISD::AND) {
593 SDValue U0 = U->getOperand(0);
594 SDValue U1 = U->getOperand(1);
595 if (U0.getOpcode() == ISD::ROTL) {
596 auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
597 if (C && C->getSExtValue() == -2)
598 return false;
599 }
600
601 if (U1.getOpcode() == ISD::ROTL) {
602 auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
603 if (C && C->getSExtValue() == -2)
604 return false;
605 }
606 }
607
Craig Topperab70f582018-06-28 00:47:41 +0000608 break;
Evan Cheng83bdb382008-11-27 00:49:46 +0000609 }
Craig Topperab70f582018-06-28 00:47:41 +0000610 case ISD::SHL:
611 case ISD::SRA:
612 case ISD::SRL:
613 // Don't fold a load into a shift by immediate. The BMI2 instructions
614 // support folding a load, but not an immediate. The legacy instructions
615 // support folding an immediate, but can't fold a load. Folding an
616 // immediate is preferable to folding a load.
617 if (isa<ConstantSDNode>(U->getOperand(1)))
618 return false;
619
620 break;
Evan Cheng83bdb382008-11-27 00:49:46 +0000621 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000622 }
623
Craig Topper38b290f2018-07-11 18:09:04 +0000624 // Prevent folding a load if this can implemented with an insert_subreg or
625 // a move that implicitly zeroes.
Craig Topper08b81a52018-07-10 06:19:54 +0000626 if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
Craig Topper38b290f2018-07-11 18:09:04 +0000627 isNullConstant(Root->getOperand(2)) &&
628 (Root->getOperand(0).isUndef() ||
629 ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
Craig Topper08b81a52018-07-10 06:19:54 +0000630 return false;
631
Evan Cheng5e73ff22010-02-15 19:41:07 +0000632 return true;
633}
634
Sanjay Patelb5723d02015-10-13 15:12:27 +0000635/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000636/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000637static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
638 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000639 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000640 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000641 if (Chain.getNode() == Load.getNode())
642 Ops.push_back(Load.getOperand(0));
643 else {
644 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000645 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000646 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
647 if (Chain.getOperand(i).getNode() == Load.getNode())
648 Ops.push_back(Load.getOperand(0));
649 else
650 Ops.push_back(Chain.getOperand(i));
651 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000652 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000653 Ops.clear();
654 Ops.push_back(NewChain);
655 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000656 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000657 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000658 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000659 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000660
Evan Chengf00f1e52008-08-25 21:27:18 +0000661 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000662 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000663 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000664 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000665}
666
Sanjay Patelb5723d02015-10-13 15:12:27 +0000667/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000668/// moved below CALLSEQ_START and the chains leading up to the call.
669/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000670/// In the case of a tail call, there isn't a callseq node between the call
671/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000672static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000673 // The transformation is somewhat dangerous if the call's chain was glued to
674 // the call. After MoveBelowOrigChain the load is moved between the call and
675 // the chain, this can create a cycle if the load is not folded. So it is
676 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000677 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000678 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000679 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000680 if (!LD ||
681 LD->isVolatile() ||
682 LD->getAddressingMode() != ISD::UNINDEXED ||
683 LD->getExtensionType() != ISD::NON_EXTLOAD)
684 return false;
685
686 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000687 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000688 if (!Chain.hasOneUse())
689 return false;
690 Chain = Chain.getOperand(0);
691 }
Evan Chengd703df62010-03-14 03:48:46 +0000692
693 if (!Chain.getNumOperands())
694 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000695 // Since we are not checking for AA here, conservatively abort if the chain
696 // writes to memory. It's not safe to move the callee (a load) across a store.
697 if (isa<MemSDNode>(Chain.getNode()) &&
698 cast<MemSDNode>(Chain.getNode())->writeMem())
699 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000700 if (Chain.getOperand(0).getNode() == Callee.getNode())
701 return true;
702 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000703 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
704 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000705 return true;
706 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000707}
708
Chris Lattner8d637042010-03-02 23:12:51 +0000709void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000710 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Matthias Braunf1caa282017-12-15 22:22:58 +0000711 OptForSize = MF->getFunction().optForSize();
712 OptForMinSize = MF->getFunction().optForMinSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000713 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000714
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000715 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
716 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000717 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000718
Craig Topper7e910a92018-02-01 17:08:39 +0000719 // If this is a target specific AND node with no flag usages, turn it back
720 // into ISD::AND to enable test instruction matching.
721 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
722 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
723 N->getOperand(0), N->getOperand(1));
724 --I;
725 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
726 ++I;
727 CurDAG->DeleteNode(N);
Craig Topper880e34e2018-06-27 20:58:46 +0000728 continue;
Craig Topper7e910a92018-02-01 17:08:39 +0000729 }
730
Evan Chengd703df62010-03-14 03:48:46 +0000731 if (OptLevel != CodeGenOpt::None &&
Chandler Carruthc58f2162018-01-22 22:05:25 +0000732 // Only do this when the target can fold the load into the call or
733 // jmp.
Chandler Carruthae0cafe2018-08-23 06:06:38 +0000734 !Subtarget->useRetpolineIndirectCalls() &&
Craig Topper62c47a22017-08-29 05:14:27 +0000735 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000736 (N->getOpcode() == X86ISD::TC_RETURN &&
Evan Cheng847ad442012-10-05 01:48:22 +0000737 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000738 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000739 /// Also try moving call address load from outside callseq_start to just
740 /// before the call to allow it to be folded.
741 ///
742 /// [Load chain]
743 /// ^
744 /// |
745 /// [Load]
746 /// ^ ^
747 /// | |
748 /// / \--
749 /// / |
750 ///[CALLSEQ_START] |
751 /// ^ |
752 /// | |
753 /// [LOAD/C2Reg] |
754 /// | |
755 /// \ /
756 /// \ /
757 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000758 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000759 SDValue Chain = N->getOperand(0);
760 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000761 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000762 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000763 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000764 ++NumLoadMoved;
765 continue;
766 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000767
Chris Lattner8d637042010-03-02 23:12:51 +0000768 // Lower fpround and fpextend nodes that target the FP stack to be store and
769 // load to the stack. This is a gross hack. We would like to simply mark
770 // these as being illegal, but when we do that, legalize produces these when
771 // it expands calls, then expands these in the same legalize pass. We would
772 // like dag combine to be able to hack on these between the call expansion
773 // and the node legalization. As such this pass basically does "really
774 // late" legalization of these inline with the X86 isel pass.
775 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000776 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
777 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000778
Craig Topper83e042a2013-08-15 05:57:07 +0000779 MVT SrcVT = N->getOperand(0).getSimpleValueType();
780 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000781
782 // If any of the sources are vectors, no fp stack involved.
783 if (SrcVT.isVector() || DstVT.isVector())
784 continue;
785
786 // If the source and destination are SSE registers, then this is a legal
787 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000788 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000789 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000790 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
791 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000792 if (SrcIsSSE && DstIsSSE)
793 continue;
794
Chris Lattnerd587e582008-03-09 07:05:32 +0000795 if (!SrcIsSSE && !DstIsSSE) {
796 // If this is an FPStack extension, it is a noop.
797 if (N->getOpcode() == ISD::FP_EXTEND)
798 continue;
799 // If this is a value-preserving FPStack truncation, it is a noop.
800 if (N->getConstantOperandVal(1))
801 continue;
802 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000803
Chris Lattnera91f77e2008-01-24 08:07:48 +0000804 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
805 // FPStack has extload and truncstore. SSE can fold direct loads into other
806 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000807 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000808 if (N->getOpcode() == ISD::FP_ROUND)
809 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
810 else
811 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000812
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000813 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000814 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000815
Chris Lattnera91f77e2008-01-24 08:07:48 +0000816 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000817 SDValue Store =
818 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
819 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000820 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000821 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000822
823 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
824 // extload we created. This will cause general havok on the dag because
825 // anything below the conversion could be folded into other existing nodes.
826 // To avoid invalidating 'I', back it up to the convert node.
827 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000828 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000829
Chris Lattnera91f77e2008-01-24 08:07:48 +0000830 // Now that we did that, the node is dead. Increment the iterator to the
831 // next node to process, then delete N.
832 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000833 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000834 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000835}
836
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000837
Craig Toppere6913ec2018-03-16 17:13:42 +0000838void X86DAGToDAGISel::PostprocessISelDAG() {
839 // Skip peepholes at -O0.
840 if (TM.getOptLevel() == CodeGenOpt::None)
841 return;
842
843 // Attempt to remove vectors moves that were inserted to zero upper bits.
844
845 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
846 ++Position;
847
848 while (Position != CurDAG->allnodes_begin()) {
849 SDNode *N = &*--Position;
850 // Skip dead nodes and any non-machine opcodes.
851 if (N->use_empty() || !N->isMachineOpcode())
852 continue;
853
854 if (N->getMachineOpcode() != TargetOpcode::SUBREG_TO_REG)
855 continue;
856
857 unsigned SubRegIdx = N->getConstantOperandVal(2);
858 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
859 continue;
860
861 SDValue Move = N->getOperand(1);
862 if (!Move.isMachineOpcode())
863 continue;
864
865 // Make sure its one of the move opcodes we recognize.
866 switch (Move.getMachineOpcode()) {
867 default:
868 continue;
869 case X86::VMOVAPDrr: case X86::VMOVUPDrr:
870 case X86::VMOVAPSrr: case X86::VMOVUPSrr:
871 case X86::VMOVDQArr: case X86::VMOVDQUrr:
872 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr:
873 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr:
874 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr:
875 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr:
876 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr:
877 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
878 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
879 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr:
880 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr:
881 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
882 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
883 break;
884 }
885
886 SDValue In = Move.getOperand(0);
887 if (!In.isMachineOpcode() ||
888 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
889 continue;
890
Craig Toppera80352c2018-08-03 04:49:42 +0000891 // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
892 // the SHA instructions which use a legacy encoding.
893 uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
894 if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
895 (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
896 (TSFlags & X86II::EncodingMask) != X86II::XOP)
897 continue;
898
Craig Toppere6913ec2018-03-16 17:13:42 +0000899 // Producing instruction is another vector instruction. We can drop the
900 // move.
901 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
902
903 // If the move is now dead, delete it.
904 if (Move.getNode()->use_empty())
905 CurDAG->RemoveDeadNode(Move.getNode());
906 }
907}
908
909
Sanjay Patelb5723d02015-10-13 15:12:27 +0000910/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000911void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000912 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000913 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000914 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000915
916 TargetLowering::CallLoweringInfo CLI(*CurDAG);
917 CLI.setChain(CurDAG->getRoot())
918 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000919 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000920 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000921 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
922 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
923 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000924 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000925}
926
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000927void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000928 // If this is main, emit special code for main.
Matthias Braunf1caa282017-12-15 22:22:58 +0000929 const Function &F = MF->getFunction();
930 if (F.hasExternalLinkage() && F.getName() == "main")
931 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000932}
933
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000934static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000935 // On 64-bit platforms, we can run into an issue where a frame index
936 // includes a displacement that, when added to the explicit displacement,
937 // will overflow the displacement field. Assuming that the frame index
938 // displacement fits into a 31-bit integer (which is only slightly more
939 // aggressive than the current fundamental assumption that it fits into
940 // a 32-bit integer), a 31-bit disp should always be safe.
941 return isInt<31>(Val);
942}
943
Sanjay Patel85030aa2015-10-13 16:23:00 +0000944bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000945 X86ISelAddressMode &AM) {
Reid Kleckner537917d2018-05-21 21:03:19 +0000946 // If there's no offset to fold, we don't need to do any work.
947 if (Offset == 0)
948 return false;
949
Reid Kleckner9dad2272015-05-04 23:22:36 +0000950 // Cannot combine ExternalSymbol displacements with integer offsets.
Reid Kleckner537917d2018-05-21 21:03:19 +0000951 if (AM.ES || AM.MCSym)
Reid Kleckner9dad2272015-05-04 23:22:36 +0000952 return true;
Reid Kleckner537917d2018-05-21 21:03:19 +0000953
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000954 int64_t Val = AM.Disp + Offset;
955 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000956 if (Subtarget->is64Bit()) {
957 if (!X86::isOffsetSuitableForCodeModel(Val, M,
958 AM.hasSymbolicDisplacement()))
959 return true;
960 // In addition to the checks required for a register base, check that
961 // we do not try to use an unsafe Disp with a frame index.
962 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
963 !isDispSafeForFrameIndex(Val))
964 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000965 }
Eli Friedman344ec792011-07-13 21:29:53 +0000966 AM.Disp = Val;
967 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000968
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000969}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000970
Sanjay Patel85030aa2015-10-13 16:23:00 +0000971bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000972 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000973
Chris Lattner8a236b62010-09-22 04:39:11 +0000974 // load gs:0 -> GS segment register.
975 // load fs:0 -> FS segment register.
976 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000977 // This optimization is valid because the GNU TLS model defines that
978 // gs:0 (or fs:0 on X86-64) contains its own address.
979 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000981 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000982 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
983 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000984 switch (N->getPointerInfo().getAddrSpace()) {
985 case 256:
986 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
987 return false;
988 case 257:
989 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
990 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000991 // Address space 258 is not handled here, because it is not used to
992 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000993 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000994
Rafael Espindola3b2df102009-04-08 21:14:34 +0000995 return true;
996}
997
Sanjay Patelb5723d02015-10-13 15:12:27 +0000998/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
999/// mode. These wrap things that will resolve down into a symbol reference.
1000/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001001bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +00001002 // If the addressing mode already has a symbol as the displacement, we can
1003 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001004 if (AM.hasSymbolicDisplacement())
1005 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001006
Reid Kleckner537917d2018-05-21 21:03:19 +00001007 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1008
Reid Kleckner980c4df2018-07-23 21:14:35 +00001009 // We can't use an addressing mode in the 64-bit large code model. In the
1010 // medium code model, we use can use an mode when RIP wrappers are present.
1011 // That signifies access to globals that are known to be "near", such as the
1012 // GOT itself.
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001013 CodeModel::Model M = TM.getCodeModel();
Reid Kleckner980c4df2018-07-23 21:14:35 +00001014 if (Subtarget->is64Bit() &&
1015 (M == CodeModel::Large || (M == CodeModel::Medium && !IsRIPRel)))
Reid Kleckner537917d2018-05-21 21:03:19 +00001016 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001017
Reid Kleckner537917d2018-05-21 21:03:19 +00001018 // Base and index reg must be 0 in order to use %rip as base.
1019 if (IsRIPRel && AM.hasBaseOrIndexReg())
1020 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001021
Reid Kleckner537917d2018-05-21 21:03:19 +00001022 // Make a local copy in case we can't do this fold.
1023 X86ISelAddressMode Backup = AM;
1024
1025 int64_t Offset = 0;
1026 SDValue N0 = N.getOperand(0);
1027 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1028 AM.GV = G->getGlobal();
1029 AM.SymbolFlags = G->getTargetFlags();
1030 Offset = G->getOffset();
1031 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1032 AM.CP = CP->getConstVal();
1033 AM.Align = CP->getAlignment();
1034 AM.SymbolFlags = CP->getTargetFlags();
1035 Offset = CP->getOffset();
1036 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1037 AM.ES = S->getSymbol();
1038 AM.SymbolFlags = S->getTargetFlags();
1039 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1040 AM.MCSym = S->getMCSymbol();
1041 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1042 AM.JT = J->getIndex();
1043 AM.SymbolFlags = J->getTargetFlags();
1044 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1045 AM.BlockAddr = BA->getBlockAddress();
1046 AM.SymbolFlags = BA->getTargetFlags();
1047 Offset = BA->getOffset();
1048 } else
1049 llvm_unreachable("Unhandled symbol reference node.");
1050
1051 if (foldOffsetIntoAddress(Offset, AM)) {
1052 AM = Backup;
1053 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +00001054 }
1055
Reid Kleckner537917d2018-05-21 21:03:19 +00001056 if (IsRIPRel)
1057 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001058
Reid Kleckner537917d2018-05-21 21:03:19 +00001059 // Commit the changes now that we know this fold is safe.
1060 return false;
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001061}
1062
Sanjay Patelb5723d02015-10-13 15:12:27 +00001063/// Add the specified node to the specified addressing mode, returning true if
1064/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001065bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1066 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +00001067 return true;
1068
1069 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1070 // a smaller encoding and avoids a scaled-index.
1071 if (AM.Scale == 2 &&
1072 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001073 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001074 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +00001075 AM.Scale = 1;
1076 }
1077
Dan Gohman05046082009-08-20 18:23:44 +00001078 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1079 // because it has a smaller encoding.
1080 // TODO: Which other code models can use this?
1081 if (TM.getCodeModel() == CodeModel::Small &&
1082 Subtarget->is64Bit() &&
1083 AM.Scale == 1 &&
1084 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001085 AM.Base_Reg.getNode() == nullptr &&
1086 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +00001087 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +00001088 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001089 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +00001090
Dan Gohman824ab402009-07-22 23:26:55 +00001091 return false;
1092}
1093
Sanjay Patelefab8b02015-10-21 18:56:06 +00001094bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
1095 unsigned Depth) {
1096 // Add an artificial use to this node so that we can keep track of
1097 // it if it gets CSE'd with a different node.
1098 HandleSDNode Handle(N);
1099
1100 X86ISelAddressMode Backup = AM;
1101 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1102 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1103 return false;
1104 AM = Backup;
1105
1106 // Try again after commuting the operands.
1107 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
1108 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1109 return false;
1110 AM = Backup;
1111
1112 // If we couldn't fold both operands into the address at the same time,
1113 // see if we can just put each operand into a register and fold at least
1114 // the add.
1115 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1116 !AM.Base_Reg.getNode() &&
1117 !AM.IndexReg.getNode()) {
1118 N = Handle.getValue();
1119 AM.Base_Reg = N.getOperand(0);
1120 AM.IndexReg = N.getOperand(1);
1121 AM.Scale = 1;
1122 return false;
1123 }
1124 N = Handle.getValue();
1125 return true;
1126}
1127
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001128// Insert a node into the DAG at least before the Pos node's position. This
1129// will reposition the node as needed, and will assign it a node ID that is <=
1130// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1131// IDs! The selection DAG must no longer depend on their uniqueness when this
1132// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001133static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Nirav Dave8c5f47a2018-03-22 19:32:07 +00001134 if (N->getNodeId() == -1 ||
1135 (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1136 SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1137 DAG.RepositionNode(Pos->getIterator(), N.getNode());
1138 // Mark Node as invalid for pruning as after this it may be a successor to a
1139 // selected node but otherwise be in the same position of Pos.
1140 // Conservatively mark it with the same -abs(Id) to assure node id
1141 // invariant is preserved.
1142 N->setNodeId(Pos->getNodeId());
1143 SelectionDAGISel::InvalidateNodeId(N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001144 }
1145}
1146
Adam Nemet0c7caf42014-09-16 17:14:10 +00001147// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1148// safe. This allows us to convert the shift and and into an h-register
1149// extract and a scaled index. Returns false if the simplification is
1150// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001151static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1152 uint64_t Mask,
1153 SDValue Shift, SDValue X,
1154 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001155 if (Shift.getOpcode() != ISD::SRL ||
1156 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1157 !Shift.hasOneUse())
1158 return true;
1159
1160 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1161 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1162 Mask != (0xffu << ScaleLog))
1163 return true;
1164
Craig Topper83e042a2013-08-15 05:57:07 +00001165 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001166 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001167 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1168 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001169 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1170 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001171 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001172 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1173
Chandler Carrutheb21da02012-01-12 01:34:44 +00001174 // Insert the new nodes into the topological ordering. We must do this in
1175 // a valid topological ordering as nothing is going to go back and re-sort
1176 // these nodes. We continually insert before 'N' in sequence as this is
1177 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1178 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001179 insertDAGNode(DAG, N, Eight);
1180 insertDAGNode(DAG, N, Srl);
1181 insertDAGNode(DAG, N, NewMask);
1182 insertDAGNode(DAG, N, And);
1183 insertDAGNode(DAG, N, ShlCount);
1184 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001185 DAG.ReplaceAllUsesWith(N, Shl);
1186 AM.IndexReg = And;
1187 AM.Scale = (1 << ScaleLog);
1188 return false;
1189}
1190
Chandler Carruthaa01e662012-01-11 09:35:00 +00001191// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1192// allows us to fold the shift into this addressing mode. Returns false if the
1193// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001194static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1195 uint64_t Mask,
1196 SDValue Shift, SDValue X,
1197 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001198 if (Shift.getOpcode() != ISD::SHL ||
1199 !isa<ConstantSDNode>(Shift.getOperand(1)))
1200 return true;
1201
1202 // Not likely to be profitable if either the AND or SHIFT node has more
1203 // than one use (unless all uses are for address computation). Besides,
1204 // isel mechanism requires their node ids to be reused.
1205 if (!N.hasOneUse() || !Shift.hasOneUse())
1206 return true;
1207
1208 // Verify that the shift amount is something we can fold.
1209 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1210 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1211 return true;
1212
Craig Topper83e042a2013-08-15 05:57:07 +00001213 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001214 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001215 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001216 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1217 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1218
Chandler Carrutheb21da02012-01-12 01:34:44 +00001219 // Insert the new nodes into the topological ordering. We must do this in
1220 // a valid topological ordering as nothing is going to go back and re-sort
1221 // these nodes. We continually insert before 'N' in sequence as this is
1222 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1223 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001224 insertDAGNode(DAG, N, NewMask);
1225 insertDAGNode(DAG, N, NewAnd);
1226 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001227 DAG.ReplaceAllUsesWith(N, NewShift);
1228
1229 AM.Scale = 1 << ShiftAmt;
1230 AM.IndexReg = NewAnd;
1231 return false;
1232}
1233
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001234// Implement some heroics to detect shifts of masked values where the mask can
1235// be replaced by extending the shift and undoing that in the addressing mode
1236// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1237// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1238// the addressing mode. This results in code such as:
1239//
1240// int f(short *y, int *lookup_table) {
1241// ...
1242// return *y + lookup_table[*y >> 11];
1243// }
1244//
1245// Turning into:
1246// movzwl (%rdi), %eax
1247// movl %eax, %ecx
1248// shrl $11, %ecx
1249// addl (%rsi,%rcx,4), %eax
1250//
1251// Instead of:
1252// movzwl (%rdi), %eax
1253// movl %eax, %ecx
1254// shrl $9, %ecx
1255// andl $124, %rcx
1256// addl (%rsi,%rcx), %eax
1257//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001258// Note that this function assumes the mask is provided as a mask *after* the
1259// value is shifted. The input chain may or may not match that, but computing
1260// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001261static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1262 uint64_t Mask,
1263 SDValue Shift, SDValue X,
1264 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001265 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1266 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001267 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001268
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001269 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001270 unsigned MaskLZ = countLeadingZeros(Mask);
1271 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001272
1273 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001274 // from the trailing zeros of the mask.
1275 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001276
1277 // There is nothing we can do here unless the mask is removing some bits.
1278 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1279 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1280
1281 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001282 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001283
1284 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001285 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001286 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1287 if (MaskLZ < ScaleDown)
1288 return true;
1289 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001290
1291 // The final check is to ensure that any masked out high bits of X are
1292 // already known to be zero. Otherwise, the mask has a semantic impact
1293 // other than masking out a couple of low bits. Unfortunately, because of
1294 // the mask, zero extensions will be removed from operands in some cases.
1295 // This code works extra hard to look through extensions because we can
1296 // replace them with zero extensions cheaply if necessary.
1297 bool ReplacingAnyExtend = false;
1298 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001299 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1300 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001301 // Assume that we'll replace the any-extend with a zero-extend, and
1302 // narrow the search to the extended value.
1303 X = X.getOperand(0);
1304 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1305 ReplacingAnyExtend = true;
1306 }
Craig Topper83e042a2013-08-15 05:57:07 +00001307 APInt MaskedHighBits =
1308 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001309 KnownBits Known;
1310 DAG.computeKnownBits(X, Known);
1311 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001312
1313 // We've identified a pattern that can be transformed into a single shift
1314 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001315 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001316 if (ReplacingAnyExtend) {
1317 assert(X.getValueType() != VT);
1318 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001319 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001320 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001321 X = NewX;
1322 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001323 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001324 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001325 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001326 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001327 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001328
1329 // Insert the new nodes into the topological ordering. We must do this in
1330 // a valid topological ordering as nothing is going to go back and re-sort
1331 // these nodes. We continually insert before 'N' in sequence as this is
1332 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1333 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001334 insertDAGNode(DAG, N, NewSRLAmt);
1335 insertDAGNode(DAG, N, NewSRL);
1336 insertDAGNode(DAG, N, NewSHLAmt);
1337 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001338 DAG.ReplaceAllUsesWith(N, NewSHL);
1339
1340 AM.Scale = 1 << AMShiftAmt;
1341 AM.IndexReg = NewSRL;
1342 return false;
1343}
Matt Morehouse9e658c92017-12-01 22:20:26 +00001344
Sanjay Patel85030aa2015-10-13 16:23:00 +00001345bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001346 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001347 SDLoc dl(N);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001348 LLVM_DEBUG({
1349 dbgs() << "MatchAddress: ";
1350 AM.dump(CurDAG);
1351 });
Matt Morehouse9e658c92017-12-01 22:20:26 +00001352 // Limit recursion.
1353 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001354 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001355
Chris Lattnerfea81da2009-06-27 04:16:01 +00001356 // If this is already a %rip relative address, we can only merge immediates
1357 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001358 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001359 if (AM.isRIPRelative()) {
1360 // FIXME: JumpTable and ExternalSymbol address currently don't like
1361 // displacements. It isn't very important, but this should be fixed for
1362 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001363 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1364 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001365
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001366 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001367 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001368 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001369 return true;
1370 }
1371
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001372 switch (N.getOpcode()) {
1373 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001374 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001375 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001376 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1377 // Use the symbol and don't prefix it.
1378 AM.MCSym = ESNode->getMCSymbol();
1379 return false;
1380 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001381 break;
1382 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001383 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001384 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001385 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001386 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001387 break;
1388 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001389
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001390 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001391 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001392 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001393 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001394 break;
1395
Rafael Espindola3b2df102009-04-08 21:14:34 +00001396 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001397 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001398 return false;
1399 break;
1400
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001401 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001402 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001403 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001404 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001405 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001406 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001407 return false;
1408 }
1409 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001410
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001411 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001412 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001413 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001414
Simon Pilgrim7f032312017-05-12 13:08:45 +00001415 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001416 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001417 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1418 // that the base operand remains free for further matching. If
1419 // the base doesn't end up getting used, a post-processing step
1420 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001421 if (Val == 1 || Val == 2 || Val == 3) {
1422 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001423 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001424
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001425 // Okay, we know that we have a scale by now. However, if the scaled
1426 // value is an add of something and a constant, we can fold the
1427 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001428 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001429 AM.IndexReg = ShVal.getOperand(0);
1430 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001431 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001432 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001433 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001434 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001435
1436 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001437 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001438 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001439 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001440 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001441
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001442 case ISD::SRL: {
1443 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001444 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001445
1446 SDValue And = N.getOperand(0);
1447 if (And.getOpcode() != ISD::AND) break;
1448 SDValue X = And.getOperand(0);
1449
1450 // We only handle up to 64-bit values here as those are what matter for
1451 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001452 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001453
1454 // The mask used for the transform is expected to be post-shift, but we
1455 // found the shift first so just apply the shift to the mask before passing
1456 // it down.
1457 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1458 !isa<ConstantSDNode>(And.getOperand(1)))
1459 break;
1460 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1461
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001462 // Try to fold the mask and shift into the scale, and return false if we
1463 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001464 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001465 return false;
1466 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001467 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001468
Dan Gohmanbf474952007-10-22 20:22:24 +00001469 case ISD::SMUL_LOHI:
1470 case ISD::UMUL_LOHI:
1471 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001472 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001473 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001474 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001475 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001476 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001477 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001478 AM.Base_Reg.getNode() == nullptr &&
1479 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001480 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001481 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1482 CN->getZExtValue() == 9) {
1483 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001484
Simon Pilgrim7f032312017-05-12 13:08:45 +00001485 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001486 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001487
1488 // Okay, we know that we have a scale by now. However, if the scaled
1489 // value is an add of something and a constant, we can fold the
1490 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001491 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001492 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1493 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001494 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001495 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001496 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001497 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001498 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001499 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001500 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001501 }
1502
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001503 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001504 return false;
1505 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001506 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001507 break;
1508
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001509 case ISD::SUB: {
1510 // Given A-B, if A can be completely folded into the address and
1511 // the index field with the index field unused, use -B as the index.
1512 // This is a win if a has multiple parts that can be folded into
1513 // the address. Also, this saves a mov if the base register has
1514 // other uses, since it avoids a two-address sub instruction, however
1515 // it costs an additional mov if the index register has other uses.
1516
Dan Gohman99ba4da2010-06-18 01:24:29 +00001517 // Add an artificial use to this node so that we can keep track of
1518 // it if it gets CSE'd with a different node.
1519 HandleSDNode Handle(N);
1520
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001521 // Test if the LHS of the sub can be folded.
1522 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001523 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001524 AM = Backup;
1525 break;
1526 }
1527 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001528 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001529 AM = Backup;
1530 break;
1531 }
Evan Cheng68333f52010-03-17 23:58:35 +00001532
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001533 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001534 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001535 // If the RHS involves a register with multiple uses, this
1536 // transformation incurs an extra mov, due to the neg instruction
1537 // clobbering its operand.
1538 if (!RHS.getNode()->hasOneUse() ||
1539 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1540 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1541 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1542 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001543 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001544 ++Cost;
1545 // If the base is a register with multiple uses, this
1546 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001547 // FIXME: Don't rely on DELETED_NODEs.
1548 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1549 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001550 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001551 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1552 --Cost;
1553 // If the folded LHS was interesting, this transformation saves
1554 // address arithmetic.
1555 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1556 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1557 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1558 --Cost;
1559 // If it doesn't look like it may be an overall win, don't do it.
1560 if (Cost >= 0) {
1561 AM = Backup;
1562 break;
1563 }
1564
1565 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001566 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001567 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1568 AM.IndexReg = Neg;
1569 AM.Scale = 1;
1570
1571 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001572 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1573 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001574 return false;
1575 }
1576
Sanjay Patelefab8b02015-10-21 18:56:06 +00001577 case ISD::ADD:
1578 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001579 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001580 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001581
Sanjay Patel533c10c2015-11-09 23:31:38 +00001582 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001583 // We want to look through a transform in InstCombine and DAGCombiner that
1584 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001585 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001586 // An 'lea' can then be used to match the shift (multiply) and add:
1587 // and $1, %esi
1588 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001589 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1590 !matchAdd(N, AM, Depth))
1591 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001592 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001593
Evan Cheng827d30d2007-12-13 00:43:27 +00001594 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001595 // Perform some heroic transforms on an and of a constant-count shift
1596 // with a constant to enable use of the scaled offset field.
1597
Evan Cheng827d30d2007-12-13 00:43:27 +00001598 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001599 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001600
Chandler Carruthaa01e662012-01-11 09:35:00 +00001601 SDValue Shift = N.getOperand(0);
1602 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001603 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001604
1605 // We only handle up to 64-bit values here as those are what matter for
1606 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001607 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001608
Chandler Carruthb0049f42012-01-11 09:35:04 +00001609 if (!isa<ConstantSDNode>(N.getOperand(1)))
1610 break;
1611 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001612
Chandler Carruth51d30762012-01-11 08:48:20 +00001613 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001614 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001615 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001616
Chandler Carruth51d30762012-01-11 08:48:20 +00001617 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001618 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001619 return false;
1620
Chandler Carruthaa01e662012-01-11 09:35:00 +00001621 // Try to swap the mask and shift to place shifts which can be done as
1622 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001623 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001624 return false;
1625 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001626 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001627 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001628
Sanjay Patel85030aa2015-10-13 16:23:00 +00001629 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001630}
1631
Sanjay Patelb5723d02015-10-13 15:12:27 +00001632/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001633/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001634bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001635 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001636 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001637 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001638 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001639 AM.IndexReg = N;
1640 AM.Scale = 1;
1641 return false;
1642 }
1643
1644 // Otherwise, we cannot select it.
1645 return true;
1646 }
1647
1648 // Default, generate it as a register.
1649 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001650 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001651 return false;
1652}
1653
Craig Topperc314f462017-11-13 17:53:59 +00001654/// Helper for selectVectorAddr. Handles things that can be folded into a
1655/// gather scatter address. The index register and scale should have already
1656/// been handled.
1657bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
1658 // TODO: Support other operations.
1659 switch (N.getOpcode()) {
Craig Topperaf4eb172018-01-10 19:16:05 +00001660 case ISD::Constant: {
1661 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1662 if (!foldOffsetIntoAddress(Val, AM))
1663 return false;
1664 break;
1665 }
Craig Topperc314f462017-11-13 17:53:59 +00001666 case X86ISD::Wrapper:
1667 if (!matchWrapper(N, AM))
1668 return false;
1669 break;
1670 }
1671
1672 return matchAddressBase(N, AM);
1673}
1674
Craig Topperbb001c6d2017-11-10 19:26:04 +00001675bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1676 SDValue &Scale, SDValue &Index,
1677 SDValue &Disp, SDValue &Segment) {
Craig Topperc314f462017-11-13 17:53:59 +00001678 X86ISelAddressMode AM;
Craig Topperee740442017-11-22 08:10:54 +00001679 auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
1680 AM.IndexReg = Mgs->getIndex();
Craig Topperaf4eb172018-01-10 19:16:05 +00001681 AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
Craig Topperbb001c6d2017-11-10 19:26:04 +00001682
Craig Topperbb001c6d2017-11-10 19:26:04 +00001683 unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001684 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001685 if (AddrSpace == 256)
1686 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1687 if (AddrSpace == 257)
1688 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001689 if (AddrSpace == 258)
1690 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001691
Craig Topperaf4eb172018-01-10 19:16:05 +00001692 // Try to match into the base and displacement fields.
1693 if (matchVectorAddress(N, AM))
Craig Topperc314f462017-11-13 17:53:59 +00001694 return false;
1695
1696 MVT VT = N.getSimpleValueType();
1697 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1698 if (!AM.Base_Reg.getNode())
1699 AM.Base_Reg = CurDAG->getRegister(0, VT);
1700 }
1701
1702 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001703 return true;
1704}
1705
Sanjay Patelb5723d02015-10-13 15:12:27 +00001706/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001707/// It returns the operands which make up the maximal addressing mode it can
1708/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001709///
1710/// Parent is the parent node of the addr operand that is being matched. It
1711/// is always a load, store, atomic node, or null. It is only null when
1712/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001713bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001714 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001715 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001716 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001717
Chris Lattner8a236b62010-09-22 04:39:11 +00001718 if (Parent &&
1719 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1720 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001721 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001722 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001723 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1724 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1725 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001726 unsigned AddrSpace =
1727 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001728 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001729 if (AddrSpace == 256)
1730 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1731 if (AddrSpace == 257)
1732 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001733 if (AddrSpace == 258)
1734 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001735 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001736
Sanjay Patel85030aa2015-10-13 16:23:00 +00001737 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001738 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001739
Craig Topper83e042a2013-08-15 05:57:07 +00001740 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001741 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001742 if (!AM.Base_Reg.getNode())
1743 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001744 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001745
Gabor Greiff304a7a2008-08-28 21:40:38 +00001746 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001747 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001748
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001749 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001750 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001751}
1752
Craig Topper8078dd22017-08-21 16:04:04 +00001753// We can only fold a load if all nodes between it and the root node have a
1754// single use. If there are additional uses, we could end up duplicating the
1755// load.
Craig Topperb0e986f2018-06-17 16:29:46 +00001756static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) {
Craig Topper8078dd22017-08-21 16:04:04 +00001757 while (User != Root) {
1758 if (!User->hasOneUse())
1759 return false;
1760 User = *User->use_begin();
1761 }
1762
1763 return true;
1764}
1765
Sanjay Patelb5723d02015-10-13 15:12:27 +00001766/// Match a scalar SSE load. In particular, we want to match a load whose top
1767/// elements are either undef or zeros. The load flavor is derived from the
1768/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001769///
1770/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001771/// PatternChainNode: this is the matched node that has a chain input and
1772/// output.
Craig Topperb0e986f2018-06-17 16:29:46 +00001773bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001774 SDValue N, SDValue &Base,
1775 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001776 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001777 SDValue &PatternNodeWithChain) {
Craig Topperb0e986f2018-06-17 16:29:46 +00001778 if (!hasSingleUsesFromRoot(Root, Parent))
1779 return false;
1780
Craig Topper36ecce92016-12-12 07:57:24 +00001781 // We can allow a full vector load here since narrowing a load is ok.
1782 if (ISD::isNON_EXTLoad(N.getNode())) {
1783 PatternNodeWithChain = N;
1784 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001785 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001786 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1787 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1788 Segment);
1789 }
1790 }
1791
1792 // We can also match the special zero extended load opcode.
1793 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1794 PatternNodeWithChain = N;
1795 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001796 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001797 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1798 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1799 Segment);
1800 }
1801 }
1802
Craig Topper991d1ca2016-11-26 17:29:25 +00001803 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1804 // once. Otherwise the load might get duplicated and the chain output of the
1805 // duplicate load will not be observed by all dependencies.
1806 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001807 PatternNodeWithChain = N.getOperand(0);
1808 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001809 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001810 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001811 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001812 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1813 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001814 }
1815 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001816
1817 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001818 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001819 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001820 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001821 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001822 N.getOperand(0).getNode()->hasOneUse()) {
1823 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1824 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001825 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001826 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Craig Toppere266e122016-11-26 18:43:24 +00001827 // Okay, this is a zero extending load. Fold it.
1828 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1829 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1830 Segment);
1831 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001832 }
Craig Toppere266e122016-11-26 18:43:24 +00001833
Chris Lattner398195e2006-10-07 21:55:32 +00001834 return false;
1835}
1836
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001837
Sanjay Patel85030aa2015-10-13 16:23:00 +00001838bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001839 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1840 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001841 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001842 return false;
1843
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001844 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001845 return true;
1846 }
1847
1848 // In static codegen with small code model, we can get the address of a label
Simon Pilgrim3d141582018-06-06 10:52:10 +00001849 // into a register with 'movl'
1850 if (N->getOpcode() != X86ISD::Wrapper)
1851 return false;
1852
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001853 N = N.getOperand(0);
1854
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001855 // At least GNU as does not accept 'movl' for TPOFF relocations.
1856 // FIXME: We could use 'movl' when we know we are targeting MC.
1857 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001858 return false;
1859
1860 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001861 if (N->getOpcode() != ISD::TargetGlobalAddress)
1862 return TM.getCodeModel() == CodeModel::Small;
1863
1864 Optional<ConstantRange> CR =
1865 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1866 if (!CR)
1867 return TM.getCodeModel() == CodeModel::Small;
1868
1869 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001870}
1871
Sanjay Patel85030aa2015-10-13 16:23:00 +00001872bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001873 SDValue &Scale, SDValue &Index,
1874 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001875 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1876 SDLoc DL(N);
Matt Morehouse9e658c92017-12-01 22:20:26 +00001877
Sanjay Patel85030aa2015-10-13 16:23:00 +00001878 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001879 return false;
1880
Tim Northover6833e3f2013-06-10 20:43:49 +00001881 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1882 if (RN && RN->getReg() == 0)
1883 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001884 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001885 // Base could already be %rip, particularly in the x32 ABI.
1886 Base = SDValue(CurDAG->getMachineNode(
1887 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001888 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001889 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001890 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001891 0);
1892 }
1893
1894 RN = dyn_cast<RegisterSDNode>(Index);
1895 if (RN && RN->getReg() == 0)
1896 Index = CurDAG->getRegister(0, MVT::i64);
1897 else {
1898 assert(Index.getValueType() == MVT::i32 &&
1899 "Expect to be extending 32-bit registers for use in LEA");
1900 Index = SDValue(CurDAG->getMachineNode(
1901 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001902 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001903 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001904 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1905 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001906 0);
1907 }
1908
1909 return true;
1910}
1911
Sanjay Patelb5723d02015-10-13 15:12:27 +00001912/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001913/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001914bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001915 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001916 SDValue &Index, SDValue &Disp,
1917 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001918 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001919
Justin Bogner32ad24d2016-04-12 21:34:24 +00001920 // Save the DL and VT before calling matchAddress, it can invalidate N.
1921 SDLoc DL(N);
1922 MVT VT = N.getSimpleValueType();
1923
Rafael Espindolabb834f02009-04-10 10:09:34 +00001924 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1925 // segments.
1926 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001927 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001928 AM.Segment = T;
Matt Morehouse9e658c92017-12-01 22:20:26 +00001929 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001930 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001931 assert (T == AM.Segment);
1932 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001933
Evan Cheng77d86ff2006-02-25 10:09:08 +00001934 unsigned Complexity = 0;
1935 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001936 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001937 Complexity = 1;
1938 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001939 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001940 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1941 Complexity = 4;
1942
Gabor Greiff304a7a2008-08-28 21:40:38 +00001943 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001944 Complexity++;
1945 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001946 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001947
Chris Lattner3e1d9172007-03-20 06:08:29 +00001948 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1949 // a simple shift.
1950 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001951 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001952
1953 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001954 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001955 // optimal (especially for code size consideration). LEA is nice because of
1956 // its three-address nature. Tweak the cost function again when we can run
1957 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001958 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001959 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001960 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001961 Complexity = 4;
1962 else
1963 Complexity += 2;
1964 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001965
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001966 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001967 Complexity++;
1968
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001969 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001970 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001971 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001972
Justin Bogner32ad24d2016-04-12 21:34:24 +00001973 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001974 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001975}
1976
Sanjay Patelb5723d02015-10-13 15:12:27 +00001977/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001978bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001979 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001980 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001981 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1982 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001983
Chris Lattner7d2b0492009-06-20 20:38:48 +00001984 X86ISelAddressMode AM;
1985 AM.GV = GA->getGlobal();
1986 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001987 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001988 AM.SymbolFlags = GA->getTargetFlags();
1989
Owen Anderson9f944592009-08-11 20:47:22 +00001990 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001991 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001992 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001993 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001994 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001995 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001996
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001997 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001998 return true;
1999}
2000
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002001bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2002 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2003 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
2004 N.getValueType());
2005 return true;
2006 }
2007
Peter Collingbourne235c2752016-12-08 19:01:00 +00002008 // Keep track of the original value type and whether this value was
2009 // truncated. If we see a truncation from pointer type to VT that truncates
2010 // bits that are known to be zero, we can use a narrow reference.
2011 EVT VT = N.getValueType();
2012 bool WasTruncated = false;
2013 if (N.getOpcode() == ISD::TRUNCATE) {
2014 WasTruncated = true;
2015 N = N.getOperand(0);
2016 }
2017
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002018 if (N.getOpcode() != X86ISD::Wrapper)
2019 return false;
2020
Peter Collingbourne235c2752016-12-08 19:01:00 +00002021 // We can only use non-GlobalValues as immediates if they were not truncated,
2022 // as we do not have any range information. If we have a GlobalValue and the
2023 // address was not truncated, we can select it as an operand directly.
2024 unsigned Opc = N.getOperand(0)->getOpcode();
2025 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2026 Op = N.getOperand(0);
2027 // We can only select the operand directly if we didn't have to look past a
2028 // truncate.
2029 return !WasTruncated;
2030 }
2031
2032 // Check that the global's range fits into VT.
2033 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2034 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2035 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2036 return false;
2037
2038 // Okay, we can use a narrow reference.
2039 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2040 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00002041 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002042}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002043
Craig Topper78a77042017-11-08 20:17:33 +00002044bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002045 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00002046 SDValue &Index, SDValue &Disp,
2047 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00002048 if (!ISD::isNON_EXTLoad(N.getNode()) ||
Craig Topper78a77042017-11-08 20:17:33 +00002049 !IsProfitableToFold(N, P, Root) ||
2050 !IsLegalToFold(N, P, Root, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00002051 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002052
Sanjay Patel85030aa2015-10-13 16:23:00 +00002053 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00002054 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00002055}
2056
Craig Topperd6564102018-04-27 22:15:33 +00002057bool X86DAGToDAGISel::tryFoldVecLoad(SDNode *Root, SDNode *P, SDValue N,
2058 SDValue &Base, SDValue &Scale,
2059 SDValue &Index, SDValue &Disp,
2060 SDValue &Segment) {
2061 if (!ISD::isNON_EXTLoad(N.getNode()) ||
2062 useNonTemporalLoad(cast<LoadSDNode>(N)) ||
2063 !IsProfitableToFold(N, P, Root) ||
2064 !IsLegalToFold(N, P, Root, OptLevel))
2065 return false;
2066
2067 return selectAddr(N.getNode(),
2068 N.getOperand(1), Base, Scale, Index, Disp, Segment);
2069}
2070
Sanjay Patelb5723d02015-10-13 15:12:27 +00002071/// Return an SDNode that returns the value of the global base register.
2072/// Output instructions required to initialize the global base register,
2073/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00002074SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00002075 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00002076 auto &DL = MF->getDataLayout();
2077 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00002078}
2079
Peter Collingbourneef089bd2017-02-09 22:02:28 +00002080bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2081 if (N->getOpcode() == ISD::TRUNCATE)
2082 N = N->getOperand(0).getNode();
2083 if (N->getOpcode() != X86ISD::Wrapper)
2084 return false;
2085
2086 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2087 if (!GA)
2088 return false;
2089
2090 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2091 return CR && CR->getSignedMin().sge(-1ull << Width) &&
2092 CR->getSignedMax().slt(1ull << Width);
2093}
2094
Sanjay Patelb5723d02015-10-13 15:12:27 +00002095/// Test whether the given X86ISD::CMP node has any uses which require the SF
2096/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002097static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002098 // Examine each user of the node.
2099 for (SDNode::use_iterator UI = N->use_begin(),
2100 UE = N->use_end(); UI != UE; ++UI) {
2101 // Only examine CopyToReg uses.
2102 if (UI->getOpcode() != ISD::CopyToReg)
2103 return false;
2104 // Only examine CopyToReg uses that copy to EFLAGS.
2105 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
2106 X86::EFLAGS)
2107 return false;
2108 // Examine each user of the CopyToReg use.
2109 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2110 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2111 // Only examine the Flag result.
2112 if (FlagUI.getUse().getResNo() != 1) continue;
2113 // Anything unusual: assume conservatively.
2114 if (!FlagUI->isMachineOpcode()) return false;
2115 // Examine the opcode of the user.
2116 switch (FlagUI->getMachineOpcode()) {
2117 // These comparisons don't treat the most significant bit specially.
2118 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
2119 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
2120 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
2121 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00002122 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
2123 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002124 case X86::CMOVA16rr: case X86::CMOVA16rm:
2125 case X86::CMOVA32rr: case X86::CMOVA32rm:
2126 case X86::CMOVA64rr: case X86::CMOVA64rm:
2127 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
2128 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
2129 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
2130 case X86::CMOVB16rr: case X86::CMOVB16rm:
2131 case X86::CMOVB32rr: case X86::CMOVB32rm:
2132 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00002133 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
2134 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
2135 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002136 case X86::CMOVE16rr: case X86::CMOVE16rm:
2137 case X86::CMOVE32rr: case X86::CMOVE32rm:
2138 case X86::CMOVE64rr: case X86::CMOVE64rm:
2139 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
2140 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
2141 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
2142 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
2143 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2144 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2145 case X86::CMOVP16rr: case X86::CMOVP16rm:
2146 case X86::CMOVP32rr: case X86::CMOVP32rm:
2147 case X86::CMOVP64rr: case X86::CMOVP64rm:
2148 continue;
2149 // Anything else: assume conservatively.
2150 default: return false;
2151 }
2152 }
2153 }
2154 return true;
2155}
2156
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002157/// Test whether the given node which sets flags has any uses which require the
2158/// CF flag to be accurate.
2159static bool hasNoCarryFlagUses(SDNode *N) {
2160 // Examine each user of the node.
2161 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
2162 ++UI) {
2163 // Only check things that use the flags.
2164 if (UI.getUse().getResNo() != 1)
2165 continue;
2166 // Only examine CopyToReg uses.
2167 if (UI->getOpcode() != ISD::CopyToReg)
2168 return false;
2169 // Only examine CopyToReg uses that copy to EFLAGS.
2170 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2171 return false;
2172 // Examine each user of the CopyToReg use.
2173 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2174 FlagUI != FlagUE; ++FlagUI) {
2175 // Only examine the Flag result.
2176 if (FlagUI.getUse().getResNo() != 1)
2177 continue;
2178 // Anything unusual: assume conservatively.
2179 if (!FlagUI->isMachineOpcode())
2180 return false;
2181 // Examine the opcode of the user.
2182 switch (FlagUI->getMachineOpcode()) {
2183 // Comparisons which don't examine the CF flag.
2184 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2185 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2186 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2187 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2188 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2189 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2190 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2191 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2192 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2193 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2194 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2195 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2196 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2197 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2198 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2199 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2200 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2201 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2202 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2203 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2204 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2205 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2206 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2207 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2208 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2209 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2210 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2211 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2212 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2213 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2214 continue;
2215 // Anything else: assume conservatively.
2216 default:
2217 return false;
2218 }
2219 }
2220 }
2221 return true;
2222}
2223
Sanjay Patelb5723d02015-10-13 15:12:27 +00002224/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002225/// the {load; op; store} to modify transformation.
2226static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2227 SDValue StoredVal, SelectionDAG *CurDAG,
Craig Topper313d09a2018-09-07 16:27:55 +00002228 unsigned LoadOpNo,
Chandler Carruth96db3082017-08-25 02:06:36 +00002229 LoadSDNode *&LoadNode,
2230 SDValue &InputChain) {
Craig Topper13148562018-09-07 01:29:42 +00002231 // Is the stored value result 0 of the operation?
Joel Jones68d59e82012-03-29 05:45:48 +00002232 if (StoredVal.getResNo() != 0) return false;
2233
Craig Topper13148562018-09-07 01:29:42 +00002234 // Are there other uses of the operation other than the store?
Joel Jones68d59e82012-03-29 05:45:48 +00002235 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2236
Craig Topper13148562018-09-07 01:29:42 +00002237 // Is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002238 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002239 return false;
2240
Craig Topper313d09a2018-09-07 16:27:55 +00002241 SDValue Load = StoredVal->getOperand(LoadOpNo);
Evan Cheng3e869f02012-04-12 19:14:21 +00002242 // Is the stored value a non-extending and non-indexed load?
2243 if (!ISD::isNormalLoad(Load.getNode())) return false;
2244
2245 // Return LoadNode by reference.
2246 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002247
2248 // Is store the only read of the loaded value?
2249 if (!Load.hasOneUse())
2250 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002251
Evan Cheng3e869f02012-04-12 19:14:21 +00002252 // Is the address of the store the same as the load?
2253 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2254 LoadNode->getOffset() != StoreNode->getOffset())
2255 return false;
2256
Nirav Dave3264c1b2018-03-19 20:19:46 +00002257 bool FoundLoad = false;
2258 SmallVector<SDValue, 4> ChainOps;
2259 SmallVector<const SDNode *, 4> LoopWorklist;
2260 SmallPtrSet<const SDNode *, 16> Visited;
2261 const unsigned int Max = 1024;
2262
2263 // Visualization of Load-Op-Store fusion:
2264 // -------------------------
2265 // Legend:
2266 // *-lines = Chain operand dependencies.
2267 // |-lines = Normal operand dependencies.
2268 // Dependencies flow down and right. n-suffix references multiple nodes.
2269 //
2270 // C Xn C
2271 // * * *
2272 // * * *
2273 // Xn A-LD Yn TF Yn
2274 // * * \ | * |
2275 // * * \ | * |
2276 // * * \ | => A--LD_OP_ST
2277 // * * \| \
2278 // TF OP \
2279 // * | \ Zn
2280 // * | \
2281 // A-ST Zn
2282 //
2283
2284 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2285 // #2: Yn -> LD
2286 // #3: ST -> Zn
2287
2288 // Ensure the transform is safe by checking for the dual
2289 // dependencies to make sure we do not induce a loop.
2290
2291 // As LD is a predecessor to both OP and ST we can do this by checking:
2292 // a). if LD is a predecessor to a member of Xn or Yn.
2293 // b). if a Zn is a predecessor to ST.
2294
2295 // However, (b) can only occur through being a chain predecessor to
2296 // ST, which is the same as Zn being a member or predecessor of Xn,
2297 // which is a subset of LD being a predecessor of Xn. So it's
2298 // subsumed by check (a).
2299
Evan Cheng3e869f02012-04-12 19:14:21 +00002300 SDValue Chain = StoreNode->getChain();
2301
Nirav Dave3264c1b2018-03-19 20:19:46 +00002302 // Gather X elements in ChainOps.
Evan Cheng3e869f02012-04-12 19:14:21 +00002303 if (Chain == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002304 FoundLoad = true;
2305 ChainOps.push_back(Load.getOperand(0));
Nirav Dave0fab4172018-03-09 20:58:07 +00002306 } else if (Chain.getOpcode() == ISD::TokenFactor) {
Evan Cheng3e869f02012-04-12 19:14:21 +00002307 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2308 SDValue Op = Chain.getOperand(i);
2309 if (Op == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002310 FoundLoad = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002311 // Drop Load, but keep its chain. No cycle check necessary.
2312 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002313 continue;
2314 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002315 LoopWorklist.push_back(Op.getNode());
Evan Cheng3e869f02012-04-12 19:14:21 +00002316 ChainOps.push_back(Op);
2317 }
Nirav Daved668f692018-03-09 20:57:42 +00002318 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002319
2320 if (!FoundLoad)
Nirav Dave0fab4172018-03-09 20:58:07 +00002321 return false;
2322
Nirav Dave3264c1b2018-03-19 20:19:46 +00002323 // Worklist is currently Xn. Add Yn to worklist.
2324 for (SDValue Op : StoredVal->ops())
2325 if (Op.getNode() != LoadNode)
2326 LoopWorklist.push_back(Op.getNode());
2327
2328 // Check (a) if Load is a predecessor to Xn + Yn
2329 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2330 true))
2331 return false;
2332
2333 InputChain =
2334 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
Nirav Dave0fab4172018-03-09 20:58:07 +00002335 return true;
Nirav Dave042678b2018-03-10 02:16:15 +00002336}
Joel Jones68d59e82012-03-29 05:45:48 +00002337
Chandler Carruth4b611a82017-08-25 22:50:52 +00002338// Change a chain of {load; op; store} of the same value into a simple op
2339// through memory of that value, if the uses of the modified value and its
2340// address are suitable.
2341//
2342// The tablegen pattern memory operand pattern is currently not able to match
2343// the case where the EFLAGS on the original operation are used.
2344//
2345// To move this to tablegen, we'll need to improve tablegen to allow flags to
2346// be transferred from a node in the pattern to the result node, probably with
2347// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002348// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2349// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2350// (implicit EFLAGS)]>;
2351// but maybe need something like this
2352// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2353// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2354// (transferrable EFLAGS)]>;
2355//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002356// Until then, we manually fold these and instruction select the operation
2357// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002358bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2359 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2360 SDValue StoredVal = StoreNode->getOperand(1);
2361 unsigned Opc = StoredVal->getOpcode();
2362
Chandler Carruth4b611a82017-08-25 22:50:52 +00002363 // Before we try to select anything, make sure this is memory operand size
2364 // and opcode we can handle. Note that this must match the code below that
2365 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002366 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002367 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2368 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002369 return false;
Craig Topper313d09a2018-09-07 16:27:55 +00002370
2371 bool IsCommutable = false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002372 switch (Opc) {
2373 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002374 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002375 case X86ISD::INC:
2376 case X86ISD::DEC:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002377 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002378 case X86ISD::SBB:
Craig Topper313d09a2018-09-07 16:27:55 +00002379 break;
2380 case X86ISD::ADD:
2381 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002382 case X86ISD::AND:
2383 case X86ISD::OR:
2384 case X86ISD::XOR:
Craig Topper313d09a2018-09-07 16:27:55 +00002385 IsCommutable = true;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002386 break;
2387 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002388
Craig Topper313d09a2018-09-07 16:27:55 +00002389 unsigned LoadOpNo = 0;
Chandler Carruth03258f22017-08-25 02:04:03 +00002390 LoadSDNode *LoadNode = nullptr;
2391 SDValue InputChain;
Craig Topper313d09a2018-09-07 16:27:55 +00002392 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2393 LoadNode, InputChain)) {
2394 if (!IsCommutable)
2395 return false;
2396
2397 // This operation is commutable, try the other operand.
2398 LoadOpNo = 1;
2399 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2400 LoadNode, InputChain))
2401 return false;
2402 }
Chandler Carruth03258f22017-08-25 02:04:03 +00002403
2404 SDValue Base, Scale, Index, Disp, Segment;
2405 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2406 Segment))
2407 return false;
2408
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002409 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002410 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002411 switch (MemVT.getSimpleVT().SimpleTy) {
2412 case MVT::i64:
2413 return Opc64;
2414 case MVT::i32:
2415 return Opc32;
2416 case MVT::i16:
2417 return Opc16;
2418 case MVT::i8:
2419 return Opc8;
2420 default:
2421 llvm_unreachable("Invalid size!");
2422 }
2423 };
2424
2425 MachineSDNode *Result;
2426 switch (Opc) {
2427 case X86ISD::INC:
2428 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002429 unsigned NewOpc =
2430 Opc == X86ISD::INC
2431 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2432 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002433 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2434 Result =
2435 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2436 break;
2437 }
2438 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002439 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002440 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002441 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002442 case X86ISD::AND:
2443 case X86ISD::OR:
2444 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002445 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2446 switch (Opc) {
2447 case X86ISD::ADD:
2448 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2449 X86::ADD8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002450 case X86ISD::ADC:
2451 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2452 X86::ADC8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002453 case X86ISD::SUB:
2454 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2455 X86::SUB8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002456 case X86ISD::SBB:
2457 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2458 X86::SBB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002459 case X86ISD::AND:
2460 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2461 X86::AND8mr);
2462 case X86ISD::OR:
2463 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2464 case X86ISD::XOR:
2465 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2466 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002467 default:
2468 llvm_unreachable("Invalid opcode!");
2469 }
2470 };
2471 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2472 switch (Opc) {
2473 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002474 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002475 case X86ISD::ADC:
2476 return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002477 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002478 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002479 case X86ISD::SBB:
2480 return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002481 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002482 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002483 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002484 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002485 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002486 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002487 default:
2488 llvm_unreachable("Invalid opcode!");
2489 }
2490 };
2491 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2492 switch (Opc) {
2493 case X86ISD::ADD:
2494 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2495 X86::ADD8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002496 case X86ISD::ADC:
2497 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2498 X86::ADC8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002499 case X86ISD::SUB:
2500 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2501 X86::SUB8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002502 case X86ISD::SBB:
2503 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2504 X86::SBB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002505 case X86ISD::AND:
2506 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2507 X86::AND8mi);
2508 case X86ISD::OR:
2509 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2510 X86::OR8mi);
2511 case X86ISD::XOR:
2512 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2513 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002514 default:
2515 llvm_unreachable("Invalid opcode!");
2516 }
2517 };
2518
2519 unsigned NewOpc = SelectRegOpcode(Opc);
Craig Topper313d09a2018-09-07 16:27:55 +00002520 SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002521
2522 // See if the operand is a constant that we can fold into an immediate
2523 // operand.
2524 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2525 auto OperandV = OperandC->getAPIntValue();
2526
2527 // Check if we can shrink the operand enough to fit in an immediate (or
2528 // fit into a smaller immediate) by negating it and switching the
2529 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002530 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2531 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002532 (-OperandV).getMinSignedBits() <= 8) ||
2533 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2534 (-OperandV).getMinSignedBits() <= 32)) &&
2535 hasNoCarryFlagUses(StoredVal.getNode())) {
2536 OperandV = -OperandV;
2537 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2538 }
2539
2540 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2541 // the larger immediate operand.
2542 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2543 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2544 NewOpc = SelectImm8Opcode(Opc);
2545 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2546 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2547 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2548 NewOpc = SelectImmOpcode(Opc);
2549 }
2550 }
2551
Nirav Dave72d32f22018-01-19 15:37:57 +00002552 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2553 SDValue CopyTo =
2554 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2555 StoredVal.getOperand(2), SDValue());
2556
2557 const SDValue Ops[] = {Base, Scale, Index, Disp,
2558 Segment, Operand, CopyTo, CopyTo.getValue(1)};
2559 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2560 Ops);
2561 } else {
2562 const SDValue Ops[] = {Base, Scale, Index, Disp,
2563 Segment, Operand, InputChain};
2564 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2565 Ops);
2566 }
Chandler Carruth4b611a82017-08-25 22:50:52 +00002567 break;
2568 }
2569 default:
2570 llvm_unreachable("Invalid opcode!");
2571 }
2572
Chandler Carruth66654b72018-08-14 23:30:32 +00002573 MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
2574 LoadNode->getMemOperand()};
2575 CurDAG->setNodeMemRefs(Result, MemOps);
Chandler Carruth03258f22017-08-25 02:04:03 +00002576
Nirav Dave3264c1b2018-03-19 20:19:46 +00002577 // Update Load Chain uses as well.
2578 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
Chandler Carruth03258f22017-08-25 02:04:03 +00002579 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2580 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2581 CurDAG->RemoveDeadNode(Node);
2582 return true;
2583}
2584
Craig Topper958106d2017-09-12 17:40:25 +00002585// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2586bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2587 MVT NVT = Node->getSimpleValueType(0);
2588 SDLoc dl(Node);
2589
2590 SDValue N0 = Node->getOperand(0);
2591 SDValue N1 = Node->getOperand(1);
2592
Craig Topper17098292018-09-30 03:01:46 +00002593 // If we have TBM we can use an immediate for the control. If we have BMI
2594 // we should only do this if the BEXTR instruction is implemented well.
2595 // Otherwise moving the control into a register makes this more costly.
2596 // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
2597 // hoisting the move immediate would make it worthwhile with a less optimal
2598 // BEXTR?
2599 if (!Subtarget->hasTBM() &&
2600 !(Subtarget->hasBMI() && Subtarget->hasFastBEXTR()))
Craig Topper958106d2017-09-12 17:40:25 +00002601 return false;
2602
2603 // Must have a shift right.
2604 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2605 return false;
2606
2607 // Shift can't have additional users.
2608 if (!N0->hasOneUse())
2609 return false;
2610
2611 // Only supported for 32 and 64 bits.
2612 if (NVT != MVT::i32 && NVT != MVT::i64)
2613 return false;
2614
2615 // Shift amount and RHS of and must be constant.
2616 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2617 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2618 if (!MaskCst || !ShiftCst)
2619 return false;
2620
2621 // And RHS must be a mask.
2622 uint64_t Mask = MaskCst->getZExtValue();
2623 if (!isMask_64(Mask))
2624 return false;
2625
2626 uint64_t Shift = ShiftCst->getZExtValue();
2627 uint64_t MaskSize = countPopulation(Mask);
2628
2629 // Don't interfere with something that can be handled by extracting AH.
2630 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2631 if (Shift == 8 && MaskSize == 8)
2632 return false;
2633
2634 // Make sure we are only using bits that were in the original value, not
2635 // shifted in.
2636 if (Shift + MaskSize > NVT.getSizeInBits())
2637 return false;
2638
Craig Topper88939fe2018-02-12 21:18:11 +00002639 // Create a BEXTR node and run it through selection.
2640 SDValue C = CurDAG->getConstant(Shift | (MaskSize << 8), dl, NVT);
2641 SDValue New = CurDAG->getNode(X86ISD::BEXTR, dl, NVT,
2642 N0->getOperand(0), C);
2643 ReplaceNode(Node, New.getNode());
2644 SelectCode(New.getNode());
Craig Topper958106d2017-09-12 17:40:25 +00002645 return true;
2646}
2647
Craig Topperd6564102018-04-27 22:15:33 +00002648// Emit a PCMISTR(I/M) instruction.
2649MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
2650 bool MayFoldLoad, const SDLoc &dl,
2651 MVT VT, SDNode *Node) {
2652 SDValue N0 = Node->getOperand(0);
2653 SDValue N1 = Node->getOperand(1);
2654 SDValue Imm = Node->getOperand(2);
2655 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2656 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2657
2658 // If there is a load, it will be behind a bitcast. We don't need to check
2659 // alignment on this load.
2660 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2661 if (MayFoldLoad && N1->getOpcode() == ISD::BITCAST && N1->hasOneUse() &&
2662 tryFoldVecLoad(Node, N1.getNode(), N1.getOperand(0), Tmp0, Tmp1, Tmp2,
2663 Tmp3, Tmp4)) {
2664 SDValue Load = N1.getOperand(0);
2665 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
2666 Load.getOperand(0) };
2667 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
2668 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2669 // Update the chain.
2670 ReplaceUses(Load.getValue(1), SDValue(CNode, 2));
2671 // Record the mem-refs
Chandler Carruth66654b72018-08-14 23:30:32 +00002672 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(Load)->getMemOperand()});
Craig Topperd6564102018-04-27 22:15:33 +00002673 return CNode;
2674 }
2675
2676 SDValue Ops[] = { N0, N1, Imm };
2677 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
2678 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
2679 return CNode;
2680}
2681
2682// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
2683// to emit a second instruction after this one. This is needed since we have two
2684// copyToReg nodes glued before this and we need to continue that glue through.
2685MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
2686 bool MayFoldLoad, const SDLoc &dl,
2687 MVT VT, SDNode *Node,
2688 SDValue &InFlag) {
2689 SDValue N0 = Node->getOperand(0);
2690 SDValue N2 = Node->getOperand(2);
2691 SDValue Imm = Node->getOperand(4);
2692 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2693 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2694
2695 // If there is a load, it will be behind a bitcast. We don't need to check
2696 // alignment on this load.
2697 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2698 if (MayFoldLoad && N2->getOpcode() == ISD::BITCAST && N2->hasOneUse() &&
2699 tryFoldVecLoad(Node, N2.getNode(), N2.getOperand(0), Tmp0, Tmp1, Tmp2,
2700 Tmp3, Tmp4)) {
2701 SDValue Load = N2.getOperand(0);
2702 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
2703 Load.getOperand(0), InFlag };
2704 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
2705 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2706 InFlag = SDValue(CNode, 3);
2707 // Update the chain.
2708 ReplaceUses(Load.getValue(1), SDValue(CNode, 2));
2709 // Record the mem-refs
Chandler Carruth66654b72018-08-14 23:30:32 +00002710 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(Load)->getMemOperand()});
Craig Topperd6564102018-04-27 22:15:33 +00002711 return CNode;
2712 }
2713
2714 SDValue Ops[] = { N0, N2, Imm, InFlag };
2715 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
2716 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
2717 InFlag = SDValue(CNode, 2);
2718 return CNode;
2719}
2720
Craig Topper538f8ab2018-08-22 19:39:09 +00002721bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
2722 EVT VT = N->getValueType(0);
2723
2724 // Only handle scalar shifts.
2725 if (VT.isVector())
2726 return false;
2727
2728 // Narrower shifts only mask to 5 bits in hardware.
2729 unsigned Size = VT == MVT::i64 ? 64 : 32;
2730
2731 SDValue OrigShiftAmt = N->getOperand(1);
2732 SDValue ShiftAmt = OrigShiftAmt;
2733 SDLoc DL(N);
2734
2735 // Skip over a truncate of the shift amount.
2736 if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
2737 ShiftAmt = ShiftAmt->getOperand(0);
2738
2739 // Special case to avoid messing up a BZHI pattern.
2740 // Look for (srl (shl X, (size - y)), (size - y)
2741 if (Subtarget->hasBMI2() && (VT == MVT::i32 || VT == MVT::i64) &&
2742 N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL &&
2743 // Shift amounts the same?
2744 N->getOperand(1) == N->getOperand(0).getOperand(1) &&
2745 // Shift amounts size - y?
2746 ShiftAmt.getOpcode() == ISD::SUB &&
2747 isa<ConstantSDNode>(ShiftAmt.getOperand(0)) &&
2748 cast<ConstantSDNode>(ShiftAmt.getOperand(0))->getZExtValue() == Size)
2749 return false;
2750
2751 SDValue NewShiftAmt;
2752 if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
2753 SDValue Add0 = ShiftAmt->getOperand(0);
2754 SDValue Add1 = ShiftAmt->getOperand(1);
2755 // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
2756 // to avoid the ADD/SUB.
2757 if (isa<ConstantSDNode>(Add1) &&
2758 cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) {
2759 NewShiftAmt = Add0;
2760 // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
2761 // generate a NEG instead of a SUB of a constant.
2762 } else if (ShiftAmt->getOpcode() == ISD::SUB &&
2763 isa<ConstantSDNode>(Add0) &&
2764 cast<ConstantSDNode>(Add0)->getZExtValue() != 0 &&
2765 cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) {
2766 // Insert a negate op.
2767 // TODO: This isn't guaranteed to replace the sub if there is a logic cone
2768 // that uses it that's not a shift.
2769 EVT SubVT = ShiftAmt.getValueType();
2770 SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
2771 SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1);
2772 NewShiftAmt = Neg;
2773
2774 // Insert these operands into a valid topological order so they can
2775 // get selected independently.
2776 insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
2777 insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
2778 } else
2779 return false;
2780 } else
2781 return false;
2782
2783 if (NewShiftAmt.getValueType() != MVT::i8) {
2784 // Need to truncate the shift amount.
2785 NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
2786 // Add to a correct topological ordering.
2787 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
2788 }
2789
2790 // Insert a new mask to keep the shift amount legal. This should be removed
2791 // by isel patterns.
2792 NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
2793 CurDAG->getConstant(Size - 1, DL, MVT::i8));
2794 // Place in a correct topological ordering.
2795 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
2796
2797 SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2798 NewShiftAmt);
2799 if (UpdatedNode != N) {
2800 // If we found an existing node, we should replace ourselves with that node
2801 // and wait for it to be selected after its other users.
2802 ReplaceNode(N, UpdatedNode);
2803 return true;
2804 }
2805
2806 // If the original shift amount is now dead, delete it so that we don't run
2807 // it through isel.
2808 if (OrigShiftAmt.getNode()->use_empty())
2809 CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
2810
2811 // Now that we've optimized the shift amount, defer to normal isel to get
2812 // load folding and legacy vs BMI2 selection without repeating it here.
2813 SelectCode(N);
2814 return true;
2815}
2816
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002817/// If the high bits of an 'and' operand are known zero, try setting the
2818/// high bits of an 'and' constant operand to produce a smaller encoding by
2819/// creating a small, sign-extended negative immediate rather than a large
2820/// positive one. This reverses a transform in SimplifyDemandedBits that
2821/// shrinks mask constants by clearing bits. There is also a possibility that
2822/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
2823/// case, just replace the 'and'. Return 'true' if the node is replaced.
2824bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
2825 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
2826 // have immediate operands.
2827 MVT VT = And->getSimpleValueType(0);
2828 if (VT != MVT::i32 && VT != MVT::i64)
2829 return false;
2830
2831 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
2832 if (!And1C)
2833 return false;
2834
Craig Topper57e06432018-02-05 16:54:07 +00002835 // Bail out if the mask constant is already negative. It's can't shrink more.
2836 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
2837 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
2838 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
2839 // are negative too.
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002840 APInt MaskVal = And1C->getAPIntValue();
2841 unsigned MaskLZ = MaskVal.countLeadingZeros();
Craig Topper57e06432018-02-05 16:54:07 +00002842 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002843 return false;
2844
Craig Topper57e06432018-02-05 16:54:07 +00002845 // Don't extend into the upper 32 bits of a 64 bit mask.
2846 if (VT == MVT::i64 && MaskLZ >= 32) {
2847 MaskLZ -= 32;
2848 MaskVal = MaskVal.trunc(32);
2849 }
2850
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002851 SDValue And0 = And->getOperand(0);
Craig Topper57e06432018-02-05 16:54:07 +00002852 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002853 APInt NegMaskVal = MaskVal | HighZeros;
2854
2855 // If a negative constant would not allow a smaller encoding, there's no need
2856 // to continue. Only change the constant when we know it's a win.
2857 unsigned MinWidth = NegMaskVal.getMinSignedBits();
2858 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
2859 return false;
2860
Craig Topper57e06432018-02-05 16:54:07 +00002861 // Extend masks if we truncated above.
2862 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
2863 NegMaskVal = NegMaskVal.zext(64);
2864 HighZeros = HighZeros.zext(64);
2865 }
2866
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002867 // The variable operand must be all zeros in the top bits to allow using the
2868 // new, negative constant as the mask.
2869 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
2870 return false;
2871
2872 // Check if the mask is -1. In that case, this is an unnecessary instruction
2873 // that escaped earlier analysis.
2874 if (NegMaskVal.isAllOnesValue()) {
2875 ReplaceNode(And, And0.getNode());
2876 return true;
2877 }
2878
2879 // A negative mask allows a smaller encoding. Create a new 'and' node.
2880 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
2881 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
2882 ReplaceNode(And, NewAnd.getNode());
2883 SelectCode(NewAnd.getNode());
2884 return true;
2885}
2886
Justin Bogner593741d2016-05-10 23:55:37 +00002887void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002888 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002889 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002890 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002891
Dan Gohman17059682008-07-17 19:10:17 +00002892 if (Node->isMachineOpcode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002893 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002894 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002895 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002896 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002897
Evan Cheng10d27902006-01-06 20:36:21 +00002898 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002899 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002900 case ISD::BRIND: {
2901 if (Subtarget->isTargetNaCl())
2902 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2903 // leave the instruction alone.
2904 break;
2905 if (Subtarget->isTarget64BitILP32()) {
2906 // Converts a 32-bit register to a 64-bit, zero-extended version of
2907 // it. This is needed because x86-64 can do many things, but jmp %r32
2908 // ain't one of them.
2909 const SDValue &Target = Node->getOperand(1);
2910 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2911 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2912 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2913 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002914 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002915 SelectCode(ZextTarget.getNode());
2916 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002917 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002918 }
2919 break;
2920 }
Dan Gohman757eee82009-08-02 16:10:52 +00002921 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002922 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002923 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002924
Craig Toppera7a12392018-08-03 07:01:10 +00002925 case ISD::BITCAST:
2926 // Just drop all 128/256/512-bit bitcasts.
2927 if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
2928 NVT == MVT::f128) {
2929 ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
2930 CurDAG->RemoveDeadNode(Node);
2931 return;
2932 }
2933 break;
2934
Craig Topper75370b92017-09-19 17:19:45 +00002935 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002936 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002937 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002938 SDValue VSelect = CurDAG->getNode(
2939 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2940 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002941 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002942 SelectCode(VSelect.getNode());
2943 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002944 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002945 }
Craig Topper3af251d2012-07-01 02:55:34 +00002946
Craig Topper538f8ab2018-08-22 19:39:09 +00002947 case ISD::SRL:
2948 case ISD::SRA:
2949 case ISD::SHL:
2950 if (tryShiftAmountMod(Node))
2951 return;
2952 break;
2953
Tobias Grosser85508e82015-08-19 11:35:10 +00002954 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002955 if (matchBEXTRFromAnd(Node))
2956 return;
Sanjay Patel40aa8672018-08-23 15:58:07 +00002957 if (AndImmShrink && shrinkAndImmediate(Node))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002958 return;
Craig Topper958106d2017-09-12 17:40:25 +00002959
2960 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002961 case ISD::OR:
2962 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002963
Benjamin Kramer4c816242011-04-22 15:30:40 +00002964 // For operations of the form (x << C1) op C2, check if we can use a smaller
2965 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2966 SDValue N0 = Node->getOperand(0);
2967 SDValue N1 = Node->getOperand(1);
2968
2969 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2970 break;
2971
2972 // i8 is unshrinkable, i16 should be promoted to i32.
2973 if (NVT != MVT::i32 && NVT != MVT::i64)
2974 break;
2975
2976 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2977 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2978 if (!Cst || !ShlCst)
2979 break;
2980
2981 int64_t Val = Cst->getSExtValue();
2982 uint64_t ShlVal = ShlCst->getZExtValue();
2983
2984 // Make sure that we don't change the operation by removing bits.
2985 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002986 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2987 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002988 break;
2989
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002990 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002991 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002992
2993 // Check the minimum bitwidth for the new constant.
2994 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2995 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2996 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2997 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2998 CstVT = MVT::i8;
2999 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
3000 CstVT = MVT::i32;
3001
3002 // Bail if there is no smaller encoding.
3003 if (NVT == CstVT)
3004 break;
3005
Craig Topper83e042a2013-08-15 05:57:07 +00003006 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00003007 default: llvm_unreachable("Unsupported VT!");
3008 case MVT::i32:
3009 assert(CstVT == MVT::i8);
3010 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003011 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003012
3013 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00003014 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00003015 case ISD::AND: Op = X86::AND32ri8; break;
3016 case ISD::OR: Op = X86::OR32ri8; break;
3017 case ISD::XOR: Op = X86::XOR32ri8; break;
3018 }
3019 break;
3020 case MVT::i64:
3021 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
3022 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003023 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003024
3025 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00003026 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00003027 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
3028 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
3029 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
3030 }
3031 break;
3032 }
3033
3034 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003035 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00003036 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00003037 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00003038 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
3039 SDValue(New, 0));
3040 else
3041 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
3042 getI8Imm(ShlVal, dl));
3043 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00003044 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00003045 case X86ISD::UMUL8:
3046 case X86ISD::SMUL8: {
3047 SDValue N0 = Node->getOperand(0);
3048 SDValue N1 = Node->getOperand(1);
3049
Craig Topper3efdb7c2018-06-11 20:50:58 +00003050 unsigned Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00003051
3052 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
3053 N0, SDValue()).getValue(1);
3054
3055 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
3056 SDValue Ops[] = {N1, InFlag};
3057 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
3058
Justin Bogner31d7da32016-05-11 21:13:17 +00003059 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00003060 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00003061 }
3062
Chris Lattner364bb0a2010-12-05 07:30:36 +00003063 case X86ISD::UMUL: {
3064 SDValue N0 = Node->getOperand(0);
3065 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00003066
Craig Topper3efdb7c2018-06-11 20:50:58 +00003067 unsigned LoReg, Opc;
Craig Topper83e042a2013-08-15 05:57:07 +00003068 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00003069 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00003070 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00003071 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
3072 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
3073 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00003074 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003075
Chris Lattner364bb0a2010-12-05 07:30:36 +00003076 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
3077 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00003078
Chris Lattner364bb0a2010-12-05 07:30:36 +00003079 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
3080 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00003081 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00003082
Justin Bognerfde9f2e2016-05-11 22:21:50 +00003083 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00003084 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00003085 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003086
Dan Gohman757eee82009-08-02 16:10:52 +00003087 case ISD::SMUL_LOHI:
3088 case ISD::UMUL_LOHI: {
3089 SDValue N0 = Node->getOperand(0);
3090 SDValue N1 = Node->getOperand(1);
3091
Craig Topper3efdb7c2018-06-11 20:50:58 +00003092 unsigned Opc, MOpc;
Dan Gohman757eee82009-08-02 16:10:52 +00003093 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00003094 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003095 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00003096 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003097 default: llvm_unreachable("Unsupported VT!");
Michael Liaof9f7b552012-09-26 08:22:37 +00003098 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
3099 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
3100 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
3101 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003102 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003103 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00003104 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003105 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003106 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
3107 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003108 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003109 }
Dan Gohman757eee82009-08-02 16:10:52 +00003110
Michael Liaof9f7b552012-09-26 08:22:37 +00003111 unsigned SrcReg, LoReg, HiReg;
3112 switch (Opc) {
3113 default: llvm_unreachable("Unknown MUL opcode!");
Michael Liaof9f7b552012-09-26 08:22:37 +00003114 case X86::IMUL32r:
3115 case X86::MUL32r:
3116 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
3117 break;
3118 case X86::IMUL64r:
3119 case X86::MUL64r:
3120 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
3121 break;
3122 case X86::MULX32rr:
3123 SrcReg = X86::EDX; LoReg = HiReg = 0;
3124 break;
3125 case X86::MULX64rr:
3126 SrcReg = X86::RDX; LoReg = HiReg = 0;
3127 break;
Dan Gohman757eee82009-08-02 16:10:52 +00003128 }
3129
3130 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003131 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003132 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00003133 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00003134 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00003135 if (foldedLoad)
3136 std::swap(N0, N1);
3137 }
3138
Michael Liaof9f7b552012-09-26 08:22:37 +00003139 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00003140 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00003141 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00003142
3143 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003144 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00003145 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00003146 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3147 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00003148 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
3149 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00003150 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003151 ResHi = SDValue(CNode, 0);
3152 ResLo = SDValue(CNode, 1);
3153 Chain = SDValue(CNode, 2);
3154 InFlag = SDValue(CNode, 3);
3155 } else {
3156 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00003157 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003158 Chain = SDValue(CNode, 0);
3159 InFlag = SDValue(CNode, 1);
3160 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00003161
Dan Gohman757eee82009-08-02 16:10:52 +00003162 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00003163 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00003164 // Record the mem-refs
Chandler Carruth66654b72018-08-14 23:30:32 +00003165 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
Dan Gohman757eee82009-08-02 16:10:52 +00003166 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00003167 SDValue Ops[] = { N1, InFlag };
3168 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
3169 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003170 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003171 ResHi = SDValue(CNode, 0);
3172 ResLo = SDValue(CNode, 1);
3173 InFlag = SDValue(CNode, 2);
3174 } else {
3175 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003176 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003177 InFlag = SDValue(CNode, 0);
3178 }
Dan Gohman757eee82009-08-02 16:10:52 +00003179 }
3180
3181 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003182 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003183 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003184 assert(LoReg && "Register for low half is not defined!");
3185 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
3186 InFlag);
3187 InFlag = ResLo.getValue(2);
3188 }
3189 ReplaceUses(SDValue(Node, 0), ResLo);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003190 LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
3191 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003192 }
3193 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003194 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003195 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003196 assert(HiReg && "Register for high half is not defined!");
3197 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
3198 InFlag);
3199 InFlag = ResHi.getValue(2);
3200 }
3201 ReplaceUses(SDValue(Node, 1), ResHi);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003202 LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
3203 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003204 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003205
Craig Topper6bed9de2017-09-09 05:57:20 +00003206 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003207 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003208 }
3209
3210 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003211 case ISD::UDIVREM:
3212 case X86ISD::SDIVREM8_SEXT_HREG:
3213 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00003214 SDValue N0 = Node->getOperand(0);
3215 SDValue N1 = Node->getOperand(1);
3216
Craig Topper3efdb7c2018-06-11 20:50:58 +00003217 unsigned Opc, MOpc;
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003218 bool isSigned = (Opcode == ISD::SDIVREM ||
3219 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003220 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00003221 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003222 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003223 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
3224 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
3225 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
3226 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003227 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003228 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00003229 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003230 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003231 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
3232 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
3233 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
3234 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003235 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003236 }
Dan Gohman757eee82009-08-02 16:10:52 +00003237
Chris Lattner518b0372009-12-23 01:45:04 +00003238 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003239 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00003240 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003241 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003242 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00003243 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00003244 SExtOpcode = X86::CBW;
3245 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003246 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00003247 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003248 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00003249 SExtOpcode = X86::CWD;
3250 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003251 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00003252 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003253 SExtOpcode = X86::CDQ;
3254 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003255 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00003256 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003257 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00003258 break;
3259 }
3260
Dan Gohman757eee82009-08-02 16:10:52 +00003261 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003262 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00003263 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00003264
Dan Gohman757eee82009-08-02 16:10:52 +00003265 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00003266 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003267 // Special case for div8, just use a move with zero extension to AX to
3268 // clear the upper 8 bits (AH).
Craig Topper99ad2a52018-09-30 17:47:18 +00003269 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
3270 MachineSDNode *Move;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003271 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003272 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
Craig Topper99ad2a52018-09-30 17:47:18 +00003273 Move = CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
3274 MVT::Other, Ops);
3275 Chain = SDValue(Move, 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003276 ReplaceUses(N0.getValue(1), Chain);
Craig Topper99ad2a52018-09-30 17:47:18 +00003277 // Record the mem-refs
3278 CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
Evan Cheng10d27902006-01-06 20:36:21 +00003279 } else {
Craig Topper99ad2a52018-09-30 17:47:18 +00003280 Move = CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0);
Dan Gohman757eee82009-08-02 16:10:52 +00003281 Chain = CurDAG->getEntryNode();
3282 }
Craig Topper99ad2a52018-09-30 17:47:18 +00003283 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, SDValue(Move, 0),
3284 SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00003285 InFlag = Chain.getValue(1);
3286 } else {
3287 InFlag =
3288 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
3289 LoReg, N0, SDValue()).getValue(1);
3290 if (isSigned && !signBitIsZero) {
3291 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00003292 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003293 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00003294 } else {
3295 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00003296 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00003297 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00003298 case MVT::i16:
3299 ClrNode =
3300 SDValue(CurDAG->getMachineNode(
3301 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003302 CurDAG->getTargetConstant(X86::sub_16bit, dl,
3303 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003304 0);
3305 break;
3306 case MVT::i32:
3307 break;
3308 case MVT::i64:
3309 ClrNode =
3310 SDValue(CurDAG->getMachineNode(
3311 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003312 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
3313 CurDAG->getTargetConstant(X86::sub_32bit, dl,
3314 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003315 0);
3316 break;
3317 default:
3318 llvm_unreachable("Unexpected division source");
3319 }
3320
Chris Lattner518b0372009-12-23 01:45:04 +00003321 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00003322 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00003323 }
Evan Cheng92e27972006-01-06 23:19:29 +00003324 }
Dan Gohmana1603612007-10-08 18:33:35 +00003325
Dan Gohman757eee82009-08-02 16:10:52 +00003326 if (foldedLoad) {
3327 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3328 InFlag };
Craig Topper61f81f92017-11-08 22:26:39 +00003329 MachineSDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00003330 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00003331 InFlag = SDValue(CNode, 1);
3332 // Update the chain.
3333 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
Craig Topper61f81f92017-11-08 22:26:39 +00003334 // Record the mem-refs
Chandler Carruth66654b72018-08-14 23:30:32 +00003335 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
Dan Gohman757eee82009-08-02 16:10:52 +00003336 } else {
3337 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003338 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003339 }
Evan Cheng92e27972006-01-06 23:19:29 +00003340
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003341 // Prevent use of AH in a REX instruction by explicitly copying it to
3342 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00003343 //
3344 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003345 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00003346 // the allocator and/or the backend get enhanced to be more robust in
3347 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003348 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
3349 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
3350 unsigned AHExtOpcode =
Craig Topperad7c6852018-03-20 05:00:20 +00003351 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003352
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003353 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
3354 MVT::Glue, AHCopy, InFlag);
3355 SDValue Result(RNode, 0);
3356 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003357
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003358 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
3359 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
Craig Topperb8d7d4d2017-10-26 21:12:03 +00003360 assert(Node->getValueType(1) == MVT::i32 && "Unexpected result type!");
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003361 } else {
3362 Result =
3363 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
3364 }
3365 ReplaceUses(SDValue(Node, 1), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003366 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3367 dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003368 }
Dan Gohman757eee82009-08-02 16:10:52 +00003369 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003370 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00003371 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3372 LoReg, NVT, InFlag);
3373 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003374 ReplaceUses(SDValue(Node, 0), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003375 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3376 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003377 }
3378 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003379 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003380 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3381 HiReg, NVT, InFlag);
3382 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003383 ReplaceUses(SDValue(Node, 1), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003384 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3385 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003386 }
Craig Topper6bed9de2017-09-09 05:57:20 +00003387 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003388 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003389 }
3390
Craig Topperb424faf2018-02-12 03:02:02 +00003391 case X86ISD::CMP: {
Dan Gohmanac33a902009-08-19 18:16:17 +00003392 SDValue N0 = Node->getOperand(0);
3393 SDValue N1 = Node->getOperand(1);
3394
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003395 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00003396 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003397 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00003398
Dan Gohmanac33a902009-08-19 18:16:17 +00003399 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
3400 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003401 // Look past the truncate if CMP is the only use of it.
Craig Topper3ccbd3f2018-02-12 03:02:01 +00003402 if (N0.getOpcode() == ISD::AND &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00003403 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00003404 N0.getValueType() != MVT::i8 &&
3405 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00003406 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00003407 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00003408 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00003409
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003410 MVT VT;
3411 int SubRegOp;
3412 unsigned Op;
3413
Craig Topperfc53dc22017-08-25 05:04:34 +00003414 if (isUInt<8>(Mask) &&
3415 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003416 // For example, convert "testl %eax, $8" to "testb %al, $8"
3417 VT = MVT::i8;
3418 SubRegOp = X86::sub_8bit;
3419 Op = X86::TEST8ri;
3420 } else if (OptForMinSize && isUInt<16>(Mask) &&
3421 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3422 // For example, "testl %eax, $32776" to "testw %ax, $32776".
3423 // NOTE: We only want to form TESTW instructions if optimizing for
3424 // min size. Otherwise we only save one byte and possibly get a length
3425 // changing prefix penalty in the decoders.
3426 VT = MVT::i16;
3427 SubRegOp = X86::sub_16bit;
3428 Op = X86::TEST16ri;
3429 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
3430 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3431 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3432 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
3433 // Otherwize, we find ourselves in a position where we have to do
3434 // promotion. If previous passes did not promote the and, we assume
3435 // they had a good reason not to and do not promote here.
3436 VT = MVT::i32;
3437 SubRegOp = X86::sub_32bit;
3438 Op = X86::TEST32ri;
3439 } else {
3440 // No eligible transformation was found.
3441 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00003442 }
3443
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003444 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
3445 SDValue Reg = N0.getOperand(0);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003446
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003447 // Extract the subregister if necessary.
3448 if (N0.getValueType() != VT)
3449 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003450
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003451 // Emit a testl or testw.
3452 SDNode *NewNode = CurDAG->getMachineNode(Op, dl, MVT::i32, Reg, Imm);
Craig Topperb424faf2018-02-12 03:02:02 +00003453 // Replace CMP with TEST.
Nirav Dave3264c1b2018-03-19 20:19:46 +00003454 ReplaceNode(Node, NewNode);
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003455 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003456 }
3457 break;
3458 }
Craig Topperd6564102018-04-27 22:15:33 +00003459 case X86ISD::PCMPISTR: {
3460 if (!Subtarget->hasSSE42())
3461 break;
3462
3463 bool NeedIndex = !SDValue(Node, 0).use_empty();
3464 bool NeedMask = !SDValue(Node, 1).use_empty();
3465 // We can't fold a load if we are going to make two instructions.
3466 bool MayFoldLoad = !NeedIndex || !NeedMask;
3467
3468 MachineSDNode *CNode;
3469 if (NeedMask) {
3470 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
3471 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
3472 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
3473 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3474 }
3475 if (NeedIndex || !NeedMask) {
3476 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
3477 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
3478 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
3479 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3480 }
3481
3482 // Connect the flag usage to the last instruction created.
Craig Topperabc307e2018-07-12 18:04:05 +00003483 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
Craig Topperd6564102018-04-27 22:15:33 +00003484 CurDAG->RemoveDeadNode(Node);
3485 return;
3486 }
3487 case X86ISD::PCMPESTR: {
3488 if (!Subtarget->hasSSE42())
3489 break;
3490
3491 // Copy the two implicit register inputs.
3492 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
3493 Node->getOperand(1),
3494 SDValue()).getValue(1);
3495 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
3496 Node->getOperand(3), InFlag).getValue(1);
3497
3498 bool NeedIndex = !SDValue(Node, 0).use_empty();
3499 bool NeedMask = !SDValue(Node, 1).use_empty();
3500 // We can't fold a load if we are going to make two instructions.
3501 bool MayFoldLoad = !NeedIndex || !NeedMask;
3502
3503 MachineSDNode *CNode;
3504 if (NeedMask) {
3505 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
3506 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
3507 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
3508 InFlag);
3509 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3510 }
3511 if (NeedIndex || !NeedMask) {
3512 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
3513 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
3514 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
3515 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3516 }
3517 // Connect the flag usage to the last instruction created.
3518 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
3519 CurDAG->RemoveDeadNode(Node);
3520 return;
3521 }
3522
Chandler Carruth03258f22017-08-25 02:04:03 +00003523 case ISD::STORE:
3524 if (foldLoadStoreIntoMemOperand(Node))
3525 return;
3526 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003527 }
3528
Justin Bogner593741d2016-05-10 23:55:37 +00003529 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003530}
3531
Chris Lattnerba1ed582006-06-08 18:03:49 +00003532bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003533SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003534 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003535 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003536 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003537 default:
3538 llvm_unreachable("Unexpected asm memory constraint");
3539 case InlineAsm::Constraint_i:
3540 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3541 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003542 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003543 case InlineAsm::Constraint_o: // offsetable ??
3544 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003545 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003546 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003547 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003548 return true;
3549 break;
3550 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003551
Evan Cheng2d487222006-08-26 01:05:16 +00003552 OutOps.push_back(Op0);
3553 OutOps.push_back(Op1);
3554 OutOps.push_back(Op2);
3555 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003556 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003557 return false;
3558}
3559
Sanjay Patelb5723d02015-10-13 15:12:27 +00003560/// This pass converts a legalized DAG into a X86-specific DAG,
3561/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003562FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003563 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003564 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003565}