blob: f42e626a9c907136033c766cdfaf2aa541535a42 [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
Chris Lattner655e7df2005-11-16 01:54:32 +000044//===----------------------------------------------------------------------===//
45// Pattern Matcher Implementation
46//===----------------------------------------------------------------------===//
47
48namespace {
Sanjay Patelb5723d02015-10-13 15:12:27 +000049 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
50 /// numbers for the leaves of the matched tree.
Chris Lattner3f0f71b2005-11-19 02:11:08 +000051 struct X86ISelAddressMode {
52 enum {
53 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000054 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000055 } BaseType;
56
Dan Gohman0fd54fb2010-04-29 23:30:41 +000057 // This is really a union, discriminated by BaseType!
58 SDValue Base_Reg;
59 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000060
61 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000062 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000063 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000064 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000065 const GlobalValue *GV;
66 const Constant *CP;
67 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000068 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000069 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000070 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000071 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000072 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000073
74 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000075 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
76 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
77 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000078
79 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000080 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000081 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000082 }
Chad Rosier24c19d22012-08-01 18:39:17 +000083
Chris Lattnerfea81da2009-06-27 04:16:01 +000084 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000085 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000086 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000087 }
Chad Rosier24c19d22012-08-01 18:39:17 +000088
Sanjay Patelb5723d02015-10-13 15:12:27 +000089 /// Return true if this addressing mode is already RIP-relative.
Chris Lattnerfea81da2009-06-27 04:16:01 +000090 bool isRIPRelative() const {
91 if (BaseType != RegBase) return false;
92 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +000093 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +000094 return RegNode->getReg() == X86::RIP;
95 return false;
96 }
Chad Rosier24c19d22012-08-01 18:39:17 +000097
Chris Lattnerfea81da2009-06-27 04:16:01 +000098 void setBaseReg(SDValue Reg) {
99 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000100 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000101 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000102
Aaron Ballman615eb472017-10-15 14:32:27 +0000103#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Craig Topper25007c42018-03-16 21:10:07 +0000104 void dump(SelectionDAG *DAG = nullptr) {
David Greenedbdb1b22010-01-05 01:29:08 +0000105 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000106 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000107 if (Base_Reg.getNode())
Craig Topper25007c42018-03-16 21:10:07 +0000108 Base_Reg.getNode()->dump(DAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000109 else
Craig Toppereff84ed2017-12-22 17:18:10 +0000110 dbgs() << "nul\n";
111 if (BaseType == FrameIndexBase)
112 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
113 dbgs() << " Scale " << Scale << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000114 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000115 if (IndexReg.getNode())
Craig Topper25007c42018-03-16 21:10:07 +0000116 IndexReg.getNode()->dump(DAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000117 else
Craig Toppereff84ed2017-12-22 17:18:10 +0000118 dbgs() << "nul\n";
David Greenedbdb1b22010-01-05 01:29:08 +0000119 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000120 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000121 if (GV)
122 GV->dump();
123 else
David Greenedbdb1b22010-01-05 01:29:08 +0000124 dbgs() << "nul";
125 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000126 if (CP)
127 CP->dump();
128 else
David Greenedbdb1b22010-01-05 01:29:08 +0000129 dbgs() << "nul";
130 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000131 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000132 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000133 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000134 else
David Greenedbdb1b22010-01-05 01:29:08 +0000135 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000136 dbgs() << " MCSym ";
137 if (MCSym)
138 dbgs() << MCSym;
139 else
140 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000141 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000142 }
Manman Ren742534c2012-09-06 19:06:06 +0000143#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000144 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000145}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000146
147namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000148 //===--------------------------------------------------------------------===//
Sanjay Patelb5723d02015-10-13 15:12:27 +0000149 /// ISel - X86-specific code to select X86 machine instructions for
Chris Lattner655e7df2005-11-16 01:54:32 +0000150 /// SelectionDAG operations.
151 ///
Craig Topper26eec092014-03-31 06:22:15 +0000152 class X86DAGToDAGISel final : public SelectionDAGISel {
Sanjay Patelb5723d02015-10-13 15:12:27 +0000153 /// Keep a pointer to the X86Subtarget around so that we can
Chris Lattner655e7df2005-11-16 01:54:32 +0000154 /// make the right decision when generating code for different targets.
155 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000156
Sanjay Patelb5723d02015-10-13 15:12:27 +0000157 /// If true, selector should try to optimize for code size instead of
158 /// performance.
Evan Cheng7d6fa972008-09-26 23:41:32 +0000159 bool OptForSize;
160
Hans Wennborg4ae51192016-03-25 01:10:56 +0000161 /// If true, selector should try to optimize for minimum code size.
162 bool OptForMinSize;
163
Chris Lattner655e7df2005-11-16 01:54:32 +0000164 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000165 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000166 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Matt Morehouse9e658c92017-12-01 22:20:26 +0000167 OptForMinSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000168
Mehdi Amini117296c2016-10-01 02:56:57 +0000169 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000170 return "X86 DAG->DAG Instruction Selection";
171 }
172
Eric Christopher4f09c592014-05-22 01:53:26 +0000173 bool runOnMachineFunction(MachineFunction &MF) override {
174 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000175 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000176 SelectionDAGISel::runOnMachineFunction(MF);
177 return true;
178 }
179
Craig Topper2d9361e2014-03-09 07:44:38 +0000180 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000181
Craig Topper2d9361e2014-03-09 07:44:38 +0000182 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000183
Craig Topper2d9361e2014-03-09 07:44:38 +0000184 void PreprocessISelDAG() override;
Craig Toppere6913ec2018-03-16 17:13:42 +0000185 void PostprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000186
Chris Lattner655e7df2005-11-16 01:54:32 +0000187// Include the pieces autogenerated from the target description.
188#include "X86GenDAGISel.inc"
189
190 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000191 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000192
Sanjay Patel85030aa2015-10-13 16:23:00 +0000193 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
194 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
195 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
196 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Craig Topperc314f462017-11-13 17:53:59 +0000197 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000198 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000199 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000200 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000201 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
202 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000203 SDValue &Scale, SDValue &Index, SDValue &Disp,
204 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000205 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000206 SDValue &Scale, SDValue &Index, SDValue &Disp,
207 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000208 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
209 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000210 SDValue &Scale, SDValue &Index, SDValue &Disp,
211 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000212 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000213 SDValue &Scale, SDValue &Index, SDValue &Disp,
214 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000215 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000216 SDValue &Scale, SDValue &Index, SDValue &Disp,
217 SDValue &Segment);
Craig Topperb0e986f2018-06-17 16:29:46 +0000218 bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000219 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000220 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000221 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000222 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000223 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000224
Craig Topper78a77042017-11-08 20:17:33 +0000225 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000226 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000227 SDValue &Index, SDValue &Disp,
228 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000229
Craig Topperd6564102018-04-27 22:15:33 +0000230 // Convenience method where P is also root.
Craig Topper78a77042017-11-08 20:17:33 +0000231 bool tryFoldLoad(SDNode *P, SDValue N,
232 SDValue &Base, SDValue &Scale,
233 SDValue &Index, SDValue &Disp,
234 SDValue &Segment) {
235 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
236 }
237
Craig Topperd6564102018-04-27 22:15:33 +0000238 // Try to fold a vector load. This makes sure the load isn't non-temporal.
239 bool tryFoldVecLoad(SDNode *Root, SDNode *P, SDValue N,
240 SDValue &Base, SDValue &Scale,
241 SDValue &Index, SDValue &Disp,
242 SDValue &Segment);
243
Sanjay Patelb5723d02015-10-13 15:12:27 +0000244 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000245 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000246 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000247 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000248
Sanjay Patel85030aa2015-10-13 16:23:00 +0000249 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000250
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000251 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000252 SDValue &Base, SDValue &Scale,
253 SDValue &Index, SDValue &Disp,
254 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000255 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000256 ? CurDAG->getTargetFrameIndex(
257 AM.Base_FrameIndex,
258 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000259 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000260 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000261 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000262 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000263 // is 32-bit.
264 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000265 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000266 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000267 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000268 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000269 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000270 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000271 else if (AM.ES) {
272 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000273 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000274 } else if (AM.MCSym) {
275 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
276 assert(AM.SymbolFlags == 0 && "oo");
277 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000278 } else if (AM.JT != -1) {
279 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000280 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000281 } else if (AM.BlockAddr)
282 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
283 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000284 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000285 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000286
287 if (AM.Segment.getNode())
288 Segment = AM.Segment;
289 else
Owen Anderson9f944592009-08-11 20:47:22 +0000290 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000291 }
292
Michael Kuperstein243c0732015-08-11 14:10:58 +0000293 // Utility function to determine whether we should avoid selecting
294 // immediate forms of instructions for better code size or not.
295 // At a high level, we'd like to avoid such instructions when
296 // we have similar constants used within the same basic block
297 // that can be kept in a register.
298 //
299 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
300 uint32_t UseCount = 0;
301
302 // Do not want to hoist if we're not optimizing for size.
303 // TODO: We'd like to remove this restriction.
304 // See the comment in X86InstrInfo.td for more info.
305 if (!OptForSize)
306 return false;
307
308 // Walk all the users of the immediate.
309 for (SDNode::use_iterator UI = N->use_begin(),
310 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000311
Michael Kuperstein243c0732015-08-11 14:10:58 +0000312 SDNode *User = *UI;
313
314 // This user is already selected. Count it as a legitimate use and
315 // move on.
316 if (User->isMachineOpcode()) {
317 UseCount++;
318 continue;
319 }
320
321 // We want to count stores of immediates as real uses.
322 if (User->getOpcode() == ISD::STORE &&
323 User->getOperand(1).getNode() == N) {
324 UseCount++;
325 continue;
326 }
327
328 // We don't currently match users that have > 2 operands (except
329 // for stores, which are handled above)
330 // Those instruction won't match in ISEL, for now, and would
331 // be counted incorrectly.
332 // This may change in the future as we add additional instruction
333 // types.
334 if (User->getNumOperands() != 2)
335 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000336
Michael Kuperstein243c0732015-08-11 14:10:58 +0000337 // Immediates that are used for offsets as part of stack
338 // manipulation should be left alone. These are typically
339 // used to indicate SP offsets for argument passing and
340 // will get pulled into stores/pushes (implicitly).
341 if (User->getOpcode() == X86ISD::ADD ||
342 User->getOpcode() == ISD::ADD ||
343 User->getOpcode() == X86ISD::SUB ||
344 User->getOpcode() == ISD::SUB) {
345
346 // Find the other operand of the add/sub.
347 SDValue OtherOp = User->getOperand(0);
348 if (OtherOp.getNode() == N)
349 OtherOp = User->getOperand(1);
350
351 // Don't count if the other operand is SP.
352 RegisterSDNode *RegNode;
353 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
354 (RegNode = dyn_cast_or_null<RegisterSDNode>(
355 OtherOp->getOperand(1).getNode())))
356 if ((RegNode->getReg() == X86::ESP) ||
357 (RegNode->getReg() == X86::RSP))
358 continue;
359 }
360
361 // ... otherwise, count this and move on.
362 UseCount++;
363 }
364
365 // If we have more than 1 use, then recommend for hoisting.
366 return (UseCount > 1);
367 }
368
Sanjay Patelb5723d02015-10-13 15:12:27 +0000369 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000370 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000371 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000372 }
373
Sanjay Patelb5723d02015-10-13 15:12:27 +0000374 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000375 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000376 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000377 }
Evan Chengd49cc362006-02-10 22:24:32 +0000378
Craig Topper2b2d8c52018-02-15 19:57:35 +0000379 /// Return a target constant with the specified value, of type i64.
380 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
381 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
382 }
383
Craig Topper092c2f42017-09-23 05:34:07 +0000384 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
385 const SDLoc &DL) {
386 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
387 uint64_t Index = N->getConstantOperandVal(1);
388 MVT VecVT = N->getOperand(0).getSimpleValueType();
Craig Topper9563cab2017-10-08 01:33:42 +0000389 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000390 }
391
392 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
393 const SDLoc &DL) {
394 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
395 uint64_t Index = N->getConstantOperandVal(2);
396 MVT VecVT = N->getSimpleValueType(0);
Craig Topper9563cab2017-10-08 01:33:42 +0000397 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000398 }
399
Sanjay Patelb5723d02015-10-13 15:12:27 +0000400 /// Return an SDNode that returns the value of the global base register.
401 /// Output instructions required to initialize the global base register,
402 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000403 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000404
Sanjay Patelb5723d02015-10-13 15:12:27 +0000405 /// Return a reference to the TargetMachine, casted to the target-specific
406 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000407 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000408 return static_cast<const X86TargetMachine &>(TM);
409 }
410
Sanjay Patelb5723d02015-10-13 15:12:27 +0000411 /// Return a reference to the TargetInstrInfo, casted to the target-specific
412 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000413 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000414 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000415 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000416
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000417 /// Address-mode matching performs shift-of-and to and-of-shift
Adam Nemetff63a2d2014-10-03 20:00:34 +0000418 /// reassociation in order to expose more scaled addressing
419 /// opportunities.
420 bool ComplexPatternFuncMutatesDAG() const override {
421 return true;
422 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000423
424 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
425
426 /// Returns whether this is a relocatable immediate in the range
427 /// [-2^Width .. 2^Width-1].
428 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
429 if (auto *CN = dyn_cast<ConstantSDNode>(N))
430 return isInt<Width>(CN->getSExtValue());
431 return isSExtAbsoluteSymbolRef(Width, N);
432 }
Craig Topper4de6f582017-08-19 23:21:22 +0000433
434 // Indicates we should prefer to use a non-temporal load for this load.
435 bool useNonTemporalLoad(LoadSDNode *N) const {
436 if (!N->isNonTemporal())
437 return false;
438
439 unsigned StoreSize = N->getMemoryVT().getStoreSize();
440
441 if (N->getAlignment() < StoreSize)
442 return false;
443
444 switch (StoreSize) {
445 default: llvm_unreachable("Unsupported store size");
446 case 16:
447 return Subtarget->hasSSE41();
448 case 32:
449 return Subtarget->hasAVX2();
450 case 64:
451 return Subtarget->hasAVX512();
452 }
453 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000454
455 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000456 bool matchBEXTRFromAnd(SDNode *Node);
Sanjay Patel74a1eef2018-01-19 16:37:25 +0000457 bool shrinkAndImmediate(SDNode *N);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000458 bool isMaskZeroExtended(SDNode *N) const;
Craig Topperd6564102018-04-27 22:15:33 +0000459
460 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
461 const SDLoc &dl, MVT VT, SDNode *Node);
462 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
463 const SDLoc &dl, MVT VT, SDNode *Node,
464 SDValue &InFlag);
Chris Lattner655e7df2005-11-16 01:54:32 +0000465 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000466}
467
Evan Cheng72bb66a2006-08-08 00:31:00 +0000468
Craig Topperba3cc2e2017-09-25 18:43:13 +0000469// Returns true if this masked compare can be implemented legally with this
470// type.
471static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
Uriel Korachbb866862017-11-06 09:22:38 +0000472 unsigned Opcode = N->getOpcode();
Craig Topperc2696d52018-06-20 21:05:02 +0000473 if (Opcode == X86ISD::CMPM || Opcode == ISD::SETCC ||
Craig Topper48d5ed22018-02-28 08:14:28 +0000474 Opcode == X86ISD::CMPM_RND || Opcode == X86ISD::VFPCLASS) {
Craig Topperba3cc2e2017-09-25 18:43:13 +0000475 // We can get 256-bit 8 element types here without VLX being enabled. When
476 // this happens we will use 512-bit operations and the mask will not be
477 // zero extended.
Uriel Koracheb47d952017-11-06 08:32:45 +0000478 EVT OpVT = N->getOperand(0).getValueType();
Craig Topperd58c1652018-01-07 18:20:37 +0000479 if (OpVT.is256BitVector() || OpVT.is128BitVector())
Craig Topperba3cc2e2017-09-25 18:43:13 +0000480 return Subtarget->hasVLX();
481
482 return true;
483 }
Craig Topper48d5ed22018-02-28 08:14:28 +0000484 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
485 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
486 Opcode == X86ISD::FSETCCM_RND)
487 return true;
Craig Topperba3cc2e2017-09-25 18:43:13 +0000488
489 return false;
490}
491
492// Returns true if we can assume the writer of the mask has zero extended it
493// for us.
494bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
495 // If this is an AND, check if we have a compare on either side. As long as
496 // one side guarantees the mask is zero extended, the AND will preserve those
497 // zeros.
498 if (N->getOpcode() == ISD::AND)
499 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
500 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
501
502 return isLegalMaskCompare(N, Subtarget);
503}
504
Evan Cheng5e73ff22010-02-15 19:41:07 +0000505bool
506X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000507 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000508
Evan Cheng5e73ff22010-02-15 19:41:07 +0000509 if (!N.hasOneUse())
510 return false;
511
512 if (N.getOpcode() != ISD::LOAD)
513 return true;
514
515 // If N is a load, do additional profitability checks.
516 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000517 switch (U->getOpcode()) {
518 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000519 case X86ISD::ADD:
520 case X86ISD::SUB:
521 case X86ISD::AND:
522 case X86ISD::XOR:
523 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000524 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000525 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000526 case ISD::AND:
527 case ISD::OR:
528 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000529 SDValue Op1 = U->getOperand(1);
530
Evan Cheng83bdb382008-11-27 00:49:46 +0000531 // If the other operand is a 8-bit immediate we should fold the immediate
532 // instead. This reduces code size.
533 // e.g.
534 // movl 4(%esp), %eax
535 // addl $4, %eax
536 // vs.
537 // movl $4, %eax
538 // addl 4(%esp), %eax
539 // The former is 2 bytes shorter. In case where the increment is 1, then
540 // the saving can be 4 bytes (by using incl %eax).
Craig Topper7e42af82018-04-10 03:44:15 +0000541 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
Dan Gohman2293eb62009-03-14 02:07:16 +0000542 if (Imm->getAPIntValue().isSignedIntN(8))
543 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000544
Craig Topper7e42af82018-04-10 03:44:15 +0000545 // If this is a 64-bit AND with an immediate that fits in 32-bits,
546 // prefer using the smaller and over folding the load. This is needed to
547 // make sure immediates created by shrinkAndImmediate are always folded.
548 // Ideally we would narrow the load during DAG combine and get the
549 // best of both worlds.
550 if (U->getOpcode() == ISD::AND &&
551 Imm->getAPIntValue().getBitWidth() == 64 &&
552 Imm->getAPIntValue().isIntN(32))
553 return false;
554 }
555
Rafael Espindolabb834f02009-04-10 10:09:34 +0000556 // If the other operand is a TLS address, we should fold it instead.
557 // This produces
558 // movl %gs:0, %eax
559 // leal i@NTPOFF(%eax), %eax
560 // instead of
561 // movl $i@NTPOFF, %eax
562 // addl %gs:0, %eax
563 // if the block also has an access to a second TLS address this will save
564 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000565 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000566 if (Op1.getOpcode() == X86ISD::Wrapper) {
567 SDValue Val = Op1.getOperand(0);
568 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
569 return false;
570 }
Craig Topperab70f582018-06-28 00:47:41 +0000571
Craig Topper90317d12018-06-28 17:58:01 +0000572 // Don't fold load if this matches the BTS/BTR/BTC patterns.
573 // BTS: (or X, (shl 1, n))
574 // BTR: (and X, (rotl -2, n))
575 // BTC: (xor X, (shl 1, n))
576 if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
577 if (U->getOperand(0).getOpcode() == ISD::SHL &&
578 isOneConstant(U->getOperand(0).getOperand(0)))
579 return false;
580
581 if (U->getOperand(1).getOpcode() == ISD::SHL &&
582 isOneConstant(U->getOperand(1).getOperand(0)))
583 return false;
584 }
585 if (U->getOpcode() == ISD::AND) {
586 SDValue U0 = U->getOperand(0);
587 SDValue U1 = U->getOperand(1);
588 if (U0.getOpcode() == ISD::ROTL) {
589 auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
590 if (C && C->getSExtValue() == -2)
591 return false;
592 }
593
594 if (U1.getOpcode() == ISD::ROTL) {
595 auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
596 if (C && C->getSExtValue() == -2)
597 return false;
598 }
599 }
600
Craig Topperab70f582018-06-28 00:47:41 +0000601 break;
Evan Cheng83bdb382008-11-27 00:49:46 +0000602 }
Craig Topperab70f582018-06-28 00:47:41 +0000603 case ISD::SHL:
604 case ISD::SRA:
605 case ISD::SRL:
606 // Don't fold a load into a shift by immediate. The BMI2 instructions
607 // support folding a load, but not an immediate. The legacy instructions
608 // support folding an immediate, but can't fold a load. Folding an
609 // immediate is preferable to folding a load.
610 if (isa<ConstantSDNode>(U->getOperand(1)))
611 return false;
612
613 break;
Evan Cheng83bdb382008-11-27 00:49:46 +0000614 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000615 }
616
Craig Topper38b290f2018-07-11 18:09:04 +0000617 // Prevent folding a load if this can implemented with an insert_subreg or
618 // a move that implicitly zeroes.
Craig Topper08b81a52018-07-10 06:19:54 +0000619 if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
Craig Topper38b290f2018-07-11 18:09:04 +0000620 isNullConstant(Root->getOperand(2)) &&
621 (Root->getOperand(0).isUndef() ||
622 ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
Craig Topper08b81a52018-07-10 06:19:54 +0000623 return false;
624
Evan Cheng5e73ff22010-02-15 19:41:07 +0000625 return true;
626}
627
Sanjay Patelb5723d02015-10-13 15:12:27 +0000628/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000629/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000630static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
631 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000632 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000633 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000634 if (Chain.getNode() == Load.getNode())
635 Ops.push_back(Load.getOperand(0));
636 else {
637 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000638 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000639 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
640 if (Chain.getOperand(i).getNode() == Load.getNode())
641 Ops.push_back(Load.getOperand(0));
642 else
643 Ops.push_back(Chain.getOperand(i));
644 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000645 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000646 Ops.clear();
647 Ops.push_back(NewChain);
648 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000649 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000650 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000651 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000652 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000653
Evan Chengf00f1e52008-08-25 21:27:18 +0000654 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000655 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000656 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000657 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000658}
659
Sanjay Patelb5723d02015-10-13 15:12:27 +0000660/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000661/// moved below CALLSEQ_START and the chains leading up to the call.
662/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000663/// In the case of a tail call, there isn't a callseq node between the call
664/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000665static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000666 // The transformation is somewhat dangerous if the call's chain was glued to
667 // the call. After MoveBelowOrigChain the load is moved between the call and
668 // the chain, this can create a cycle if the load is not folded. So it is
669 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000670 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000671 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000672 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000673 if (!LD ||
674 LD->isVolatile() ||
675 LD->getAddressingMode() != ISD::UNINDEXED ||
676 LD->getExtensionType() != ISD::NON_EXTLOAD)
677 return false;
678
679 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000680 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000681 if (!Chain.hasOneUse())
682 return false;
683 Chain = Chain.getOperand(0);
684 }
Evan Chengd703df62010-03-14 03:48:46 +0000685
686 if (!Chain.getNumOperands())
687 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000688 // Since we are not checking for AA here, conservatively abort if the chain
689 // writes to memory. It's not safe to move the callee (a load) across a store.
690 if (isa<MemSDNode>(Chain.getNode()) &&
691 cast<MemSDNode>(Chain.getNode())->writeMem())
692 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000693 if (Chain.getOperand(0).getNode() == Callee.getNode())
694 return true;
695 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000696 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
697 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000698 return true;
699 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000700}
701
Chris Lattner8d637042010-03-02 23:12:51 +0000702void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000703 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Matthias Braunf1caa282017-12-15 22:22:58 +0000704 OptForSize = MF->getFunction().optForSize();
705 OptForMinSize = MF->getFunction().optForMinSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000706 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000707
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000708 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
709 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000710 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000711
Craig Topper7e910a92018-02-01 17:08:39 +0000712 // If this is a target specific AND node with no flag usages, turn it back
713 // into ISD::AND to enable test instruction matching.
714 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
715 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
716 N->getOperand(0), N->getOperand(1));
717 --I;
718 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
719 ++I;
720 CurDAG->DeleteNode(N);
Craig Topper880e34e2018-06-27 20:58:46 +0000721 continue;
Craig Topper7e910a92018-02-01 17:08:39 +0000722 }
723
Evan Chengd703df62010-03-14 03:48:46 +0000724 if (OptLevel != CodeGenOpt::None &&
Chandler Carruthc58f2162018-01-22 22:05:25 +0000725 // Only do this when the target can fold the load into the call or
726 // jmp.
727 !Subtarget->useRetpoline() &&
Craig Topper62c47a22017-08-29 05:14:27 +0000728 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000729 (N->getOpcode() == X86ISD::TC_RETURN &&
Evan Cheng847ad442012-10-05 01:48:22 +0000730 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000731 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000732 /// Also try moving call address load from outside callseq_start to just
733 /// before the call to allow it to be folded.
734 ///
735 /// [Load chain]
736 /// ^
737 /// |
738 /// [Load]
739 /// ^ ^
740 /// | |
741 /// / \--
742 /// / |
743 ///[CALLSEQ_START] |
744 /// ^ |
745 /// | |
746 /// [LOAD/C2Reg] |
747 /// | |
748 /// \ /
749 /// \ /
750 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000751 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000752 SDValue Chain = N->getOperand(0);
753 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000754 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000755 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000756 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000757 ++NumLoadMoved;
758 continue;
759 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000760
Chris Lattner8d637042010-03-02 23:12:51 +0000761 // Lower fpround and fpextend nodes that target the FP stack to be store and
762 // load to the stack. This is a gross hack. We would like to simply mark
763 // these as being illegal, but when we do that, legalize produces these when
764 // it expands calls, then expands these in the same legalize pass. We would
765 // like dag combine to be able to hack on these between the call expansion
766 // and the node legalization. As such this pass basically does "really
767 // late" legalization of these inline with the X86 isel pass.
768 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000769 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
770 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000771
Craig Topper83e042a2013-08-15 05:57:07 +0000772 MVT SrcVT = N->getOperand(0).getSimpleValueType();
773 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000774
775 // If any of the sources are vectors, no fp stack involved.
776 if (SrcVT.isVector() || DstVT.isVector())
777 continue;
778
779 // If the source and destination are SSE registers, then this is a legal
780 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000781 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000782 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000783 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
784 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000785 if (SrcIsSSE && DstIsSSE)
786 continue;
787
Chris Lattnerd587e582008-03-09 07:05:32 +0000788 if (!SrcIsSSE && !DstIsSSE) {
789 // If this is an FPStack extension, it is a noop.
790 if (N->getOpcode() == ISD::FP_EXTEND)
791 continue;
792 // If this is a value-preserving FPStack truncation, it is a noop.
793 if (N->getConstantOperandVal(1))
794 continue;
795 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000796
Chris Lattnera91f77e2008-01-24 08:07:48 +0000797 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
798 // FPStack has extload and truncstore. SSE can fold direct loads into other
799 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000800 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000801 if (N->getOpcode() == ISD::FP_ROUND)
802 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
803 else
804 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000805
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000806 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000807 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000808
Chris Lattnera91f77e2008-01-24 08:07:48 +0000809 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000810 SDValue Store =
811 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
812 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000813 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000814 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000815
816 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
817 // extload we created. This will cause general havok on the dag because
818 // anything below the conversion could be folded into other existing nodes.
819 // To avoid invalidating 'I', back it up to the convert node.
820 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000821 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000822
Chris Lattnera91f77e2008-01-24 08:07:48 +0000823 // Now that we did that, the node is dead. Increment the iterator to the
824 // next node to process, then delete N.
825 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000826 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000827 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000828}
829
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000830
Craig Toppere6913ec2018-03-16 17:13:42 +0000831void X86DAGToDAGISel::PostprocessISelDAG() {
832 // Skip peepholes at -O0.
833 if (TM.getOptLevel() == CodeGenOpt::None)
834 return;
835
836 // Attempt to remove vectors moves that were inserted to zero upper bits.
837
838 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
839 ++Position;
840
841 while (Position != CurDAG->allnodes_begin()) {
842 SDNode *N = &*--Position;
843 // Skip dead nodes and any non-machine opcodes.
844 if (N->use_empty() || !N->isMachineOpcode())
845 continue;
846
847 if (N->getMachineOpcode() != TargetOpcode::SUBREG_TO_REG)
848 continue;
849
850 unsigned SubRegIdx = N->getConstantOperandVal(2);
851 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
852 continue;
853
854 SDValue Move = N->getOperand(1);
855 if (!Move.isMachineOpcode())
856 continue;
857
858 // Make sure its one of the move opcodes we recognize.
859 switch (Move.getMachineOpcode()) {
860 default:
861 continue;
862 case X86::VMOVAPDrr: case X86::VMOVUPDrr:
863 case X86::VMOVAPSrr: case X86::VMOVUPSrr:
864 case X86::VMOVDQArr: case X86::VMOVDQUrr:
865 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr:
866 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr:
867 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr:
868 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr:
869 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr:
870 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
871 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
872 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr:
873 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr:
874 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
875 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
876 break;
877 }
878
879 SDValue In = Move.getOperand(0);
880 if (!In.isMachineOpcode() ||
881 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
882 continue;
883
884 // Producing instruction is another vector instruction. We can drop the
885 // move.
886 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
887
888 // If the move is now dead, delete it.
889 if (Move.getNode()->use_empty())
890 CurDAG->RemoveDeadNode(Move.getNode());
891 }
892}
893
894
Sanjay Patelb5723d02015-10-13 15:12:27 +0000895/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000896void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000897 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000898 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000899 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000900
901 TargetLowering::CallLoweringInfo CLI(*CurDAG);
902 CLI.setChain(CurDAG->getRoot())
903 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000904 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000905 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000906 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
907 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
908 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000909 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000910}
911
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000912void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000913 // If this is main, emit special code for main.
Matthias Braunf1caa282017-12-15 22:22:58 +0000914 const Function &F = MF->getFunction();
915 if (F.hasExternalLinkage() && F.getName() == "main")
916 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000917}
918
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000919static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000920 // On 64-bit platforms, we can run into an issue where a frame index
921 // includes a displacement that, when added to the explicit displacement,
922 // will overflow the displacement field. Assuming that the frame index
923 // displacement fits into a 31-bit integer (which is only slightly more
924 // aggressive than the current fundamental assumption that it fits into
925 // a 32-bit integer), a 31-bit disp should always be safe.
926 return isInt<31>(Val);
927}
928
Sanjay Patel85030aa2015-10-13 16:23:00 +0000929bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000930 X86ISelAddressMode &AM) {
Reid Kleckner537917d2018-05-21 21:03:19 +0000931 // If there's no offset to fold, we don't need to do any work.
932 if (Offset == 0)
933 return false;
934
Reid Kleckner9dad2272015-05-04 23:22:36 +0000935 // Cannot combine ExternalSymbol displacements with integer offsets.
Reid Kleckner537917d2018-05-21 21:03:19 +0000936 if (AM.ES || AM.MCSym)
Reid Kleckner9dad2272015-05-04 23:22:36 +0000937 return true;
Reid Kleckner537917d2018-05-21 21:03:19 +0000938
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000939 int64_t Val = AM.Disp + Offset;
940 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000941 if (Subtarget->is64Bit()) {
942 if (!X86::isOffsetSuitableForCodeModel(Val, M,
943 AM.hasSymbolicDisplacement()))
944 return true;
945 // In addition to the checks required for a register base, check that
946 // we do not try to use an unsafe Disp with a frame index.
947 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
948 !isDispSafeForFrameIndex(Val))
949 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000950 }
Eli Friedman344ec792011-07-13 21:29:53 +0000951 AM.Disp = Val;
952 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000953
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000954}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000955
Sanjay Patel85030aa2015-10-13 16:23:00 +0000956bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000957 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000958
Chris Lattner8a236b62010-09-22 04:39:11 +0000959 // load gs:0 -> GS segment register.
960 // load fs:0 -> FS segment register.
961 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000962 // This optimization is valid because the GNU TLS model defines that
963 // gs:0 (or fs:0 on X86-64) contains its own address.
964 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000965 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000966 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000967 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
968 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000969 switch (N->getPointerInfo().getAddrSpace()) {
970 case 256:
971 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
972 return false;
973 case 257:
974 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
975 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000976 // Address space 258 is not handled here, because it is not used to
977 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000978 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000979
Rafael Espindola3b2df102009-04-08 21:14:34 +0000980 return true;
981}
982
Sanjay Patelb5723d02015-10-13 15:12:27 +0000983/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
984/// mode. These wrap things that will resolve down into a symbol reference.
985/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000986bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000987 // If the addressing mode already has a symbol as the displacement, we can
988 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000989 if (AM.hasSymbolicDisplacement())
990 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000991
Reid Kleckner537917d2018-05-21 21:03:19 +0000992 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
993
Jonas Devlieghereb757fc32018-06-28 17:56:43 +0000994 // Only do this address mode folding for 64-bit if we're in the small code
995 // model.
996 // FIXME: But we can do GOTPCREL addressing in the medium code model.
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000997 CodeModel::Model M = TM.getCodeModel();
Jonas Devlieghereb757fc32018-06-28 17:56:43 +0000998 if (Subtarget->is64Bit() && M != CodeModel::Small && M != CodeModel::Kernel)
Reid Kleckner537917d2018-05-21 21:03:19 +0000999 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001000
Reid Kleckner537917d2018-05-21 21:03:19 +00001001 // Base and index reg must be 0 in order to use %rip as base.
1002 if (IsRIPRel && AM.hasBaseOrIndexReg())
1003 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001004
Reid Kleckner537917d2018-05-21 21:03:19 +00001005 // Make a local copy in case we can't do this fold.
1006 X86ISelAddressMode Backup = AM;
1007
1008 int64_t Offset = 0;
1009 SDValue N0 = N.getOperand(0);
1010 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1011 AM.GV = G->getGlobal();
1012 AM.SymbolFlags = G->getTargetFlags();
1013 Offset = G->getOffset();
1014 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1015 AM.CP = CP->getConstVal();
1016 AM.Align = CP->getAlignment();
1017 AM.SymbolFlags = CP->getTargetFlags();
1018 Offset = CP->getOffset();
1019 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1020 AM.ES = S->getSymbol();
1021 AM.SymbolFlags = S->getTargetFlags();
1022 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1023 AM.MCSym = S->getMCSymbol();
1024 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1025 AM.JT = J->getIndex();
1026 AM.SymbolFlags = J->getTargetFlags();
1027 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1028 AM.BlockAddr = BA->getBlockAddress();
1029 AM.SymbolFlags = BA->getTargetFlags();
1030 Offset = BA->getOffset();
1031 } else
1032 llvm_unreachable("Unhandled symbol reference node.");
1033
1034 if (foldOffsetIntoAddress(Offset, AM)) {
1035 AM = Backup;
1036 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +00001037 }
1038
Reid Kleckner537917d2018-05-21 21:03:19 +00001039 if (IsRIPRel)
1040 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001041
Reid Kleckner537917d2018-05-21 21:03:19 +00001042 // Commit the changes now that we know this fold is safe.
1043 return false;
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001044}
1045
Sanjay Patelb5723d02015-10-13 15:12:27 +00001046/// Add the specified node to the specified addressing mode, returning true if
1047/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001048bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1049 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +00001050 return true;
1051
1052 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1053 // a smaller encoding and avoids a scaled-index.
1054 if (AM.Scale == 2 &&
1055 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001056 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001057 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +00001058 AM.Scale = 1;
1059 }
1060
Dan Gohman05046082009-08-20 18:23:44 +00001061 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1062 // because it has a smaller encoding.
1063 // TODO: Which other code models can use this?
1064 if (TM.getCodeModel() == CodeModel::Small &&
1065 Subtarget->is64Bit() &&
1066 AM.Scale == 1 &&
1067 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001068 AM.Base_Reg.getNode() == nullptr &&
1069 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +00001070 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +00001071 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001072 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +00001073
Dan Gohman824ab402009-07-22 23:26:55 +00001074 return false;
1075}
1076
Sanjay Patelefab8b02015-10-21 18:56:06 +00001077bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
1078 unsigned Depth) {
1079 // Add an artificial use to this node so that we can keep track of
1080 // it if it gets CSE'd with a different node.
1081 HandleSDNode Handle(N);
1082
1083 X86ISelAddressMode Backup = AM;
1084 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1085 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1086 return false;
1087 AM = Backup;
1088
1089 // Try again after commuting the operands.
1090 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
1091 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1092 return false;
1093 AM = Backup;
1094
1095 // If we couldn't fold both operands into the address at the same time,
1096 // see if we can just put each operand into a register and fold at least
1097 // the add.
1098 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1099 !AM.Base_Reg.getNode() &&
1100 !AM.IndexReg.getNode()) {
1101 N = Handle.getValue();
1102 AM.Base_Reg = N.getOperand(0);
1103 AM.IndexReg = N.getOperand(1);
1104 AM.Scale = 1;
1105 return false;
1106 }
1107 N = Handle.getValue();
1108 return true;
1109}
1110
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001111// Insert a node into the DAG at least before the Pos node's position. This
1112// will reposition the node as needed, and will assign it a node ID that is <=
1113// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1114// IDs! The selection DAG must no longer depend on their uniqueness when this
1115// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001116static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Nirav Dave8c5f47a2018-03-22 19:32:07 +00001117 if (N->getNodeId() == -1 ||
1118 (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1119 SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1120 DAG.RepositionNode(Pos->getIterator(), N.getNode());
1121 // Mark Node as invalid for pruning as after this it may be a successor to a
1122 // selected node but otherwise be in the same position of Pos.
1123 // Conservatively mark it with the same -abs(Id) to assure node id
1124 // invariant is preserved.
1125 N->setNodeId(Pos->getNodeId());
1126 SelectionDAGISel::InvalidateNodeId(N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001127 }
1128}
1129
Adam Nemet0c7caf42014-09-16 17:14:10 +00001130// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1131// safe. This allows us to convert the shift and and into an h-register
1132// extract and a scaled index. Returns false if the simplification is
1133// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001134static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1135 uint64_t Mask,
1136 SDValue Shift, SDValue X,
1137 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001138 if (Shift.getOpcode() != ISD::SRL ||
1139 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1140 !Shift.hasOneUse())
1141 return true;
1142
1143 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1144 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1145 Mask != (0xffu << ScaleLog))
1146 return true;
1147
Craig Topper83e042a2013-08-15 05:57:07 +00001148 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001149 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001150 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1151 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001152 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1153 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001154 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001155 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1156
Chandler Carrutheb21da02012-01-12 01:34:44 +00001157 // Insert the new nodes into the topological ordering. We must do this in
1158 // a valid topological ordering as nothing is going to go back and re-sort
1159 // these nodes. We continually insert before 'N' in sequence as this is
1160 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1161 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001162 insertDAGNode(DAG, N, Eight);
1163 insertDAGNode(DAG, N, Srl);
1164 insertDAGNode(DAG, N, NewMask);
1165 insertDAGNode(DAG, N, And);
1166 insertDAGNode(DAG, N, ShlCount);
1167 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001168 DAG.ReplaceAllUsesWith(N, Shl);
1169 AM.IndexReg = And;
1170 AM.Scale = (1 << ScaleLog);
1171 return false;
1172}
1173
Chandler Carruthaa01e662012-01-11 09:35:00 +00001174// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1175// allows us to fold the shift into this addressing mode. Returns false if the
1176// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001177static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1178 uint64_t Mask,
1179 SDValue Shift, SDValue X,
1180 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001181 if (Shift.getOpcode() != ISD::SHL ||
1182 !isa<ConstantSDNode>(Shift.getOperand(1)))
1183 return true;
1184
1185 // Not likely to be profitable if either the AND or SHIFT node has more
1186 // than one use (unless all uses are for address computation). Besides,
1187 // isel mechanism requires their node ids to be reused.
1188 if (!N.hasOneUse() || !Shift.hasOneUse())
1189 return true;
1190
1191 // Verify that the shift amount is something we can fold.
1192 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1193 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1194 return true;
1195
Craig Topper83e042a2013-08-15 05:57:07 +00001196 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001197 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001198 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001199 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1200 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1201
Chandler Carrutheb21da02012-01-12 01:34:44 +00001202 // Insert the new nodes into the topological ordering. We must do this in
1203 // a valid topological ordering as nothing is going to go back and re-sort
1204 // these nodes. We continually insert before 'N' in sequence as this is
1205 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1206 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001207 insertDAGNode(DAG, N, NewMask);
1208 insertDAGNode(DAG, N, NewAnd);
1209 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001210 DAG.ReplaceAllUsesWith(N, NewShift);
1211
1212 AM.Scale = 1 << ShiftAmt;
1213 AM.IndexReg = NewAnd;
1214 return false;
1215}
1216
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001217// Implement some heroics to detect shifts of masked values where the mask can
1218// be replaced by extending the shift and undoing that in the addressing mode
1219// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1220// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1221// the addressing mode. This results in code such as:
1222//
1223// int f(short *y, int *lookup_table) {
1224// ...
1225// return *y + lookup_table[*y >> 11];
1226// }
1227//
1228// Turning into:
1229// movzwl (%rdi), %eax
1230// movl %eax, %ecx
1231// shrl $11, %ecx
1232// addl (%rsi,%rcx,4), %eax
1233//
1234// Instead of:
1235// movzwl (%rdi), %eax
1236// movl %eax, %ecx
1237// shrl $9, %ecx
1238// andl $124, %rcx
1239// addl (%rsi,%rcx), %eax
1240//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001241// Note that this function assumes the mask is provided as a mask *after* the
1242// value is shifted. The input chain may or may not match that, but computing
1243// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001244static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1245 uint64_t Mask,
1246 SDValue Shift, SDValue X,
1247 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001248 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1249 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001250 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001251
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001252 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001253 unsigned MaskLZ = countLeadingZeros(Mask);
1254 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001255
1256 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001257 // from the trailing zeros of the mask.
1258 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001259
1260 // There is nothing we can do here unless the mask is removing some bits.
1261 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1262 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1263
1264 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001265 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001266
1267 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001268 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001269 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1270 if (MaskLZ < ScaleDown)
1271 return true;
1272 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001273
1274 // The final check is to ensure that any masked out high bits of X are
1275 // already known to be zero. Otherwise, the mask has a semantic impact
1276 // other than masking out a couple of low bits. Unfortunately, because of
1277 // the mask, zero extensions will be removed from operands in some cases.
1278 // This code works extra hard to look through extensions because we can
1279 // replace them with zero extensions cheaply if necessary.
1280 bool ReplacingAnyExtend = false;
1281 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001282 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1283 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001284 // Assume that we'll replace the any-extend with a zero-extend, and
1285 // narrow the search to the extended value.
1286 X = X.getOperand(0);
1287 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1288 ReplacingAnyExtend = true;
1289 }
Craig Topper83e042a2013-08-15 05:57:07 +00001290 APInt MaskedHighBits =
1291 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001292 KnownBits Known;
1293 DAG.computeKnownBits(X, Known);
1294 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001295
1296 // We've identified a pattern that can be transformed into a single shift
1297 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001298 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001299 if (ReplacingAnyExtend) {
1300 assert(X.getValueType() != VT);
1301 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001302 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001303 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001304 X = NewX;
1305 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001306 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001307 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001308 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001309 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001310 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001311
1312 // Insert the new nodes into the topological ordering. We must do this in
1313 // a valid topological ordering as nothing is going to go back and re-sort
1314 // these nodes. We continually insert before 'N' in sequence as this is
1315 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1316 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001317 insertDAGNode(DAG, N, NewSRLAmt);
1318 insertDAGNode(DAG, N, NewSRL);
1319 insertDAGNode(DAG, N, NewSHLAmt);
1320 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001321 DAG.ReplaceAllUsesWith(N, NewSHL);
1322
1323 AM.Scale = 1 << AMShiftAmt;
1324 AM.IndexReg = NewSRL;
1325 return false;
1326}
Matt Morehouse9e658c92017-12-01 22:20:26 +00001327
Sanjay Patel85030aa2015-10-13 16:23:00 +00001328bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001329 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001330 SDLoc dl(N);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001331 LLVM_DEBUG({
1332 dbgs() << "MatchAddress: ";
1333 AM.dump(CurDAG);
1334 });
Matt Morehouse9e658c92017-12-01 22:20:26 +00001335 // Limit recursion.
1336 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001337 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001338
Chris Lattnerfea81da2009-06-27 04:16:01 +00001339 // If this is already a %rip relative address, we can only merge immediates
1340 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001341 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001342 if (AM.isRIPRelative()) {
1343 // FIXME: JumpTable and ExternalSymbol address currently don't like
1344 // displacements. It isn't very important, but this should be fixed for
1345 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001346 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1347 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001348
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001349 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001350 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001351 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001352 return true;
1353 }
1354
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001355 switch (N.getOpcode()) {
1356 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001357 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001358 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001359 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1360 // Use the symbol and don't prefix it.
1361 AM.MCSym = ESNode->getMCSymbol();
1362 return false;
1363 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001364 break;
1365 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001366 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001367 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001368 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001369 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001370 break;
1371 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001372
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001373 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001374 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001375 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001376 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001377 break;
1378
Rafael Espindola3b2df102009-04-08 21:14:34 +00001379 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001380 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001381 return false;
1382 break;
1383
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001384 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001385 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001386 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001387 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001388 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001389 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001390 return false;
1391 }
1392 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001393
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001394 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001395 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001396 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001397
Simon Pilgrim7f032312017-05-12 13:08:45 +00001398 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001399 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001400 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1401 // that the base operand remains free for further matching. If
1402 // the base doesn't end up getting used, a post-processing step
1403 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001404 if (Val == 1 || Val == 2 || Val == 3) {
1405 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001406 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001407
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001408 // Okay, we know that we have a scale by now. However, if the scaled
1409 // value is an add of something and a constant, we can fold the
1410 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001411 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001412 AM.IndexReg = ShVal.getOperand(0);
1413 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001414 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001415 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001416 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001417 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001418
1419 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001420 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001421 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001422 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001423 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001424
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001425 case ISD::SRL: {
1426 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001427 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001428
1429 SDValue And = N.getOperand(0);
1430 if (And.getOpcode() != ISD::AND) break;
1431 SDValue X = And.getOperand(0);
1432
1433 // We only handle up to 64-bit values here as those are what matter for
1434 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001435 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001436
1437 // The mask used for the transform is expected to be post-shift, but we
1438 // found the shift first so just apply the shift to the mask before passing
1439 // it down.
1440 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1441 !isa<ConstantSDNode>(And.getOperand(1)))
1442 break;
1443 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1444
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001445 // Try to fold the mask and shift into the scale, and return false if we
1446 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001447 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001448 return false;
1449 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001450 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001451
Dan Gohmanbf474952007-10-22 20:22:24 +00001452 case ISD::SMUL_LOHI:
1453 case ISD::UMUL_LOHI:
1454 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001455 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001456 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001457 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001458 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001459 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001460 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001461 AM.Base_Reg.getNode() == nullptr &&
1462 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001463 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001464 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1465 CN->getZExtValue() == 9) {
1466 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001467
Simon Pilgrim7f032312017-05-12 13:08:45 +00001468 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001469 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001470
1471 // Okay, we know that we have a scale by now. However, if the scaled
1472 // value is an add of something and a constant, we can fold the
1473 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001474 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001475 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1476 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001477 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001478 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001479 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001480 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001481 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001482 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001483 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001484 }
1485
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001486 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001487 return false;
1488 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001489 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001490 break;
1491
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001492 case ISD::SUB: {
1493 // Given A-B, if A can be completely folded into the address and
1494 // the index field with the index field unused, use -B as the index.
1495 // This is a win if a has multiple parts that can be folded into
1496 // the address. Also, this saves a mov if the base register has
1497 // other uses, since it avoids a two-address sub instruction, however
1498 // it costs an additional mov if the index register has other uses.
1499
Dan Gohman99ba4da2010-06-18 01:24:29 +00001500 // Add an artificial use to this node so that we can keep track of
1501 // it if it gets CSE'd with a different node.
1502 HandleSDNode Handle(N);
1503
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001504 // Test if the LHS of the sub can be folded.
1505 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001506 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001507 AM = Backup;
1508 break;
1509 }
1510 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001511 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001512 AM = Backup;
1513 break;
1514 }
Evan Cheng68333f52010-03-17 23:58:35 +00001515
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001516 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001517 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001518 // If the RHS involves a register with multiple uses, this
1519 // transformation incurs an extra mov, due to the neg instruction
1520 // clobbering its operand.
1521 if (!RHS.getNode()->hasOneUse() ||
1522 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1523 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1524 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1525 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001526 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001527 ++Cost;
1528 // If the base is a register with multiple uses, this
1529 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001530 // FIXME: Don't rely on DELETED_NODEs.
1531 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1532 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001533 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001534 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1535 --Cost;
1536 // If the folded LHS was interesting, this transformation saves
1537 // address arithmetic.
1538 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1539 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1540 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1541 --Cost;
1542 // If it doesn't look like it may be an overall win, don't do it.
1543 if (Cost >= 0) {
1544 AM = Backup;
1545 break;
1546 }
1547
1548 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001549 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001550 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1551 AM.IndexReg = Neg;
1552 AM.Scale = 1;
1553
1554 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001555 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1556 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001557 return false;
1558 }
1559
Sanjay Patelefab8b02015-10-21 18:56:06 +00001560 case ISD::ADD:
1561 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001562 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001563 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001564
Sanjay Patel533c10c2015-11-09 23:31:38 +00001565 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001566 // We want to look through a transform in InstCombine and DAGCombiner that
1567 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001568 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001569 // An 'lea' can then be used to match the shift (multiply) and add:
1570 // and $1, %esi
1571 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001572 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1573 !matchAdd(N, AM, Depth))
1574 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001575 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001576
Evan Cheng827d30d2007-12-13 00:43:27 +00001577 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001578 // Perform some heroic transforms on an and of a constant-count shift
1579 // with a constant to enable use of the scaled offset field.
1580
Evan Cheng827d30d2007-12-13 00:43:27 +00001581 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001582 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001583
Chandler Carruthaa01e662012-01-11 09:35:00 +00001584 SDValue Shift = N.getOperand(0);
1585 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001586 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001587
1588 // We only handle up to 64-bit values here as those are what matter for
1589 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001590 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001591
Chandler Carruthb0049f42012-01-11 09:35:04 +00001592 if (!isa<ConstantSDNode>(N.getOperand(1)))
1593 break;
1594 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001595
Chandler Carruth51d30762012-01-11 08:48:20 +00001596 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001597 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001598 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001599
Chandler Carruth51d30762012-01-11 08:48:20 +00001600 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001601 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001602 return false;
1603
Chandler Carruthaa01e662012-01-11 09:35:00 +00001604 // Try to swap the mask and shift to place shifts which can be done as
1605 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001606 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001607 return false;
1608 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001609 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001610 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001611
Sanjay Patel85030aa2015-10-13 16:23:00 +00001612 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001613}
1614
Sanjay Patelb5723d02015-10-13 15:12:27 +00001615/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001616/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001617bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001618 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001619 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001620 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001621 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001622 AM.IndexReg = N;
1623 AM.Scale = 1;
1624 return false;
1625 }
1626
1627 // Otherwise, we cannot select it.
1628 return true;
1629 }
1630
1631 // Default, generate it as a register.
1632 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001633 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001634 return false;
1635}
1636
Craig Topperc314f462017-11-13 17:53:59 +00001637/// Helper for selectVectorAddr. Handles things that can be folded into a
1638/// gather scatter address. The index register and scale should have already
1639/// been handled.
1640bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
1641 // TODO: Support other operations.
1642 switch (N.getOpcode()) {
Craig Topperaf4eb172018-01-10 19:16:05 +00001643 case ISD::Constant: {
1644 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1645 if (!foldOffsetIntoAddress(Val, AM))
1646 return false;
1647 break;
1648 }
Craig Topperc314f462017-11-13 17:53:59 +00001649 case X86ISD::Wrapper:
1650 if (!matchWrapper(N, AM))
1651 return false;
1652 break;
1653 }
1654
1655 return matchAddressBase(N, AM);
1656}
1657
Craig Topperbb001c6d2017-11-10 19:26:04 +00001658bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1659 SDValue &Scale, SDValue &Index,
1660 SDValue &Disp, SDValue &Segment) {
Craig Topperc314f462017-11-13 17:53:59 +00001661 X86ISelAddressMode AM;
Craig Topperee740442017-11-22 08:10:54 +00001662 auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
1663 AM.IndexReg = Mgs->getIndex();
Craig Topperaf4eb172018-01-10 19:16:05 +00001664 AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
Craig Topperbb001c6d2017-11-10 19:26:04 +00001665
Craig Topperbb001c6d2017-11-10 19:26:04 +00001666 unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001667 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001668 if (AddrSpace == 256)
1669 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1670 if (AddrSpace == 257)
1671 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001672 if (AddrSpace == 258)
1673 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001674
Craig Topperaf4eb172018-01-10 19:16:05 +00001675 // Try to match into the base and displacement fields.
1676 if (matchVectorAddress(N, AM))
Craig Topperc314f462017-11-13 17:53:59 +00001677 return false;
1678
1679 MVT VT = N.getSimpleValueType();
1680 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1681 if (!AM.Base_Reg.getNode())
1682 AM.Base_Reg = CurDAG->getRegister(0, VT);
1683 }
1684
1685 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001686 return true;
1687}
1688
Sanjay Patelb5723d02015-10-13 15:12:27 +00001689/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001690/// It returns the operands which make up the maximal addressing mode it can
1691/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001692///
1693/// Parent is the parent node of the addr operand that is being matched. It
1694/// is always a load, store, atomic node, or null. It is only null when
1695/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001696bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001697 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001698 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001699 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001700
Chris Lattner8a236b62010-09-22 04:39:11 +00001701 if (Parent &&
1702 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1703 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001704 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001705 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001706 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1707 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1708 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001709 unsigned AddrSpace =
1710 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001711 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001712 if (AddrSpace == 256)
1713 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1714 if (AddrSpace == 257)
1715 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001716 if (AddrSpace == 258)
1717 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001718 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001719
Sanjay Patel85030aa2015-10-13 16:23:00 +00001720 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001721 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001722
Craig Topper83e042a2013-08-15 05:57:07 +00001723 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001724 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001725 if (!AM.Base_Reg.getNode())
1726 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001727 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001728
Gabor Greiff304a7a2008-08-28 21:40:38 +00001729 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001730 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001731
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001732 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001733 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001734}
1735
Craig Topper8078dd22017-08-21 16:04:04 +00001736// We can only fold a load if all nodes between it and the root node have a
1737// single use. If there are additional uses, we could end up duplicating the
1738// load.
Craig Topperb0e986f2018-06-17 16:29:46 +00001739static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) {
Craig Topper8078dd22017-08-21 16:04:04 +00001740 while (User != Root) {
1741 if (!User->hasOneUse())
1742 return false;
1743 User = *User->use_begin();
1744 }
1745
1746 return true;
1747}
1748
Sanjay Patelb5723d02015-10-13 15:12:27 +00001749/// Match a scalar SSE load. In particular, we want to match a load whose top
1750/// elements are either undef or zeros. The load flavor is derived from the
1751/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001752///
1753/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001754/// PatternChainNode: this is the matched node that has a chain input and
1755/// output.
Craig Topperb0e986f2018-06-17 16:29:46 +00001756bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001757 SDValue N, SDValue &Base,
1758 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001759 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001760 SDValue &PatternNodeWithChain) {
Craig Topperb0e986f2018-06-17 16:29:46 +00001761 if (!hasSingleUsesFromRoot(Root, Parent))
1762 return false;
1763
Craig Topper36ecce92016-12-12 07:57:24 +00001764 // We can allow a full vector load here since narrowing a load is ok.
1765 if (ISD::isNON_EXTLoad(N.getNode())) {
1766 PatternNodeWithChain = N;
1767 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001768 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001769 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1770 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1771 Segment);
1772 }
1773 }
1774
1775 // We can also match the special zero extended load opcode.
1776 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1777 PatternNodeWithChain = N;
1778 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001779 IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001780 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1781 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1782 Segment);
1783 }
1784 }
1785
Craig Topper991d1ca2016-11-26 17:29:25 +00001786 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1787 // once. Otherwise the load might get duplicated and the chain output of the
1788 // duplicate load will not be observed by all dependencies.
1789 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001790 PatternNodeWithChain = N.getOperand(0);
1791 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001792 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001793 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001794 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001795 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1796 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001797 }
1798 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001799
1800 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001801 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001802 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001803 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001804 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001805 N.getOperand(0).getNode()->hasOneUse()) {
1806 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1807 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001808 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topperb0e986f2018-06-17 16:29:46 +00001809 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Craig Toppere266e122016-11-26 18:43:24 +00001810 // Okay, this is a zero extending load. Fold it.
1811 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1812 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1813 Segment);
1814 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001815 }
Craig Toppere266e122016-11-26 18:43:24 +00001816
Chris Lattner398195e2006-10-07 21:55:32 +00001817 return false;
1818}
1819
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001820
Sanjay Patel85030aa2015-10-13 16:23:00 +00001821bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001822 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1823 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001824 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001825 return false;
1826
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001827 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001828 return true;
1829 }
1830
1831 // In static codegen with small code model, we can get the address of a label
Simon Pilgrim3d141582018-06-06 10:52:10 +00001832 // into a register with 'movl'
1833 if (N->getOpcode() != X86ISD::Wrapper)
1834 return false;
1835
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001836 N = N.getOperand(0);
1837
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001838 // At least GNU as does not accept 'movl' for TPOFF relocations.
1839 // FIXME: We could use 'movl' when we know we are targeting MC.
1840 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001841 return false;
1842
1843 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001844 if (N->getOpcode() != ISD::TargetGlobalAddress)
1845 return TM.getCodeModel() == CodeModel::Small;
1846
1847 Optional<ConstantRange> CR =
1848 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1849 if (!CR)
1850 return TM.getCodeModel() == CodeModel::Small;
1851
1852 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001853}
1854
Sanjay Patel85030aa2015-10-13 16:23:00 +00001855bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001856 SDValue &Scale, SDValue &Index,
1857 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001858 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1859 SDLoc DL(N);
Matt Morehouse9e658c92017-12-01 22:20:26 +00001860
Sanjay Patel85030aa2015-10-13 16:23:00 +00001861 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001862 return false;
1863
Tim Northover6833e3f2013-06-10 20:43:49 +00001864 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1865 if (RN && RN->getReg() == 0)
1866 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001867 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001868 // Base could already be %rip, particularly in the x32 ABI.
1869 Base = SDValue(CurDAG->getMachineNode(
1870 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001871 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001872 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001873 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001874 0);
1875 }
1876
1877 RN = dyn_cast<RegisterSDNode>(Index);
1878 if (RN && RN->getReg() == 0)
1879 Index = CurDAG->getRegister(0, MVT::i64);
1880 else {
1881 assert(Index.getValueType() == MVT::i32 &&
1882 "Expect to be extending 32-bit registers for use in LEA");
1883 Index = SDValue(CurDAG->getMachineNode(
1884 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001885 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001886 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001887 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1888 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001889 0);
1890 }
1891
1892 return true;
1893}
1894
Sanjay Patelb5723d02015-10-13 15:12:27 +00001895/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001896/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001897bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001898 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001899 SDValue &Index, SDValue &Disp,
1900 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001901 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001902
Justin Bogner32ad24d2016-04-12 21:34:24 +00001903 // Save the DL and VT before calling matchAddress, it can invalidate N.
1904 SDLoc DL(N);
1905 MVT VT = N.getSimpleValueType();
1906
Rafael Espindolabb834f02009-04-10 10:09:34 +00001907 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1908 // segments.
1909 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001910 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001911 AM.Segment = T;
Matt Morehouse9e658c92017-12-01 22:20:26 +00001912 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001913 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001914 assert (T == AM.Segment);
1915 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001916
Evan Cheng77d86ff2006-02-25 10:09:08 +00001917 unsigned Complexity = 0;
1918 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001919 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001920 Complexity = 1;
1921 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001922 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001923 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1924 Complexity = 4;
1925
Gabor Greiff304a7a2008-08-28 21:40:38 +00001926 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001927 Complexity++;
1928 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001929 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001930
Chris Lattner3e1d9172007-03-20 06:08:29 +00001931 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1932 // a simple shift.
1933 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001934 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001935
1936 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001937 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001938 // optimal (especially for code size consideration). LEA is nice because of
1939 // its three-address nature. Tweak the cost function again when we can run
1940 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001941 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001942 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001943 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001944 Complexity = 4;
1945 else
1946 Complexity += 2;
1947 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001948
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001949 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001950 Complexity++;
1951
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001952 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001953 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001954 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001955
Justin Bogner32ad24d2016-04-12 21:34:24 +00001956 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001957 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001958}
1959
Sanjay Patelb5723d02015-10-13 15:12:27 +00001960/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001961bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001962 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001963 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001964 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1965 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001966
Chris Lattner7d2b0492009-06-20 20:38:48 +00001967 X86ISelAddressMode AM;
1968 AM.GV = GA->getGlobal();
1969 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001970 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001971 AM.SymbolFlags = GA->getTargetFlags();
1972
Owen Anderson9f944592009-08-11 20:47:22 +00001973 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001974 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001975 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001976 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001977 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001978 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001979
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001980 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001981 return true;
1982}
1983
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001984bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1985 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1986 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1987 N.getValueType());
1988 return true;
1989 }
1990
Peter Collingbourne235c2752016-12-08 19:01:00 +00001991 // Keep track of the original value type and whether this value was
1992 // truncated. If we see a truncation from pointer type to VT that truncates
1993 // bits that are known to be zero, we can use a narrow reference.
1994 EVT VT = N.getValueType();
1995 bool WasTruncated = false;
1996 if (N.getOpcode() == ISD::TRUNCATE) {
1997 WasTruncated = true;
1998 N = N.getOperand(0);
1999 }
2000
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002001 if (N.getOpcode() != X86ISD::Wrapper)
2002 return false;
2003
Peter Collingbourne235c2752016-12-08 19:01:00 +00002004 // We can only use non-GlobalValues as immediates if they were not truncated,
2005 // as we do not have any range information. If we have a GlobalValue and the
2006 // address was not truncated, we can select it as an operand directly.
2007 unsigned Opc = N.getOperand(0)->getOpcode();
2008 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2009 Op = N.getOperand(0);
2010 // We can only select the operand directly if we didn't have to look past a
2011 // truncate.
2012 return !WasTruncated;
2013 }
2014
2015 // Check that the global's range fits into VT.
2016 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2017 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2018 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2019 return false;
2020
2021 // Okay, we can use a narrow reference.
2022 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2023 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00002024 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002025}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002026
Craig Topper78a77042017-11-08 20:17:33 +00002027bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002028 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00002029 SDValue &Index, SDValue &Disp,
2030 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00002031 if (!ISD::isNON_EXTLoad(N.getNode()) ||
Craig Topper78a77042017-11-08 20:17:33 +00002032 !IsProfitableToFold(N, P, Root) ||
2033 !IsLegalToFold(N, P, Root, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00002034 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002035
Sanjay Patel85030aa2015-10-13 16:23:00 +00002036 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00002037 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00002038}
2039
Craig Topperd6564102018-04-27 22:15:33 +00002040bool X86DAGToDAGISel::tryFoldVecLoad(SDNode *Root, SDNode *P, SDValue N,
2041 SDValue &Base, SDValue &Scale,
2042 SDValue &Index, SDValue &Disp,
2043 SDValue &Segment) {
2044 if (!ISD::isNON_EXTLoad(N.getNode()) ||
2045 useNonTemporalLoad(cast<LoadSDNode>(N)) ||
2046 !IsProfitableToFold(N, P, Root) ||
2047 !IsLegalToFold(N, P, Root, OptLevel))
2048 return false;
2049
2050 return selectAddr(N.getNode(),
2051 N.getOperand(1), Base, Scale, Index, Disp, Segment);
2052}
2053
Sanjay Patelb5723d02015-10-13 15:12:27 +00002054/// Return an SDNode that returns the value of the global base register.
2055/// Output instructions required to initialize the global base register,
2056/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00002057SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00002058 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00002059 auto &DL = MF->getDataLayout();
2060 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00002061}
2062
Peter Collingbourneef089bd2017-02-09 22:02:28 +00002063bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2064 if (N->getOpcode() == ISD::TRUNCATE)
2065 N = N->getOperand(0).getNode();
2066 if (N->getOpcode() != X86ISD::Wrapper)
2067 return false;
2068
2069 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2070 if (!GA)
2071 return false;
2072
2073 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2074 return CR && CR->getSignedMin().sge(-1ull << Width) &&
2075 CR->getSignedMax().slt(1ull << Width);
2076}
2077
Sanjay Patelb5723d02015-10-13 15:12:27 +00002078/// Test whether the given X86ISD::CMP node has any uses which require the SF
2079/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002080static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002081 // Examine each user of the node.
2082 for (SDNode::use_iterator UI = N->use_begin(),
2083 UE = N->use_end(); UI != UE; ++UI) {
2084 // Only examine CopyToReg uses.
2085 if (UI->getOpcode() != ISD::CopyToReg)
2086 return false;
2087 // Only examine CopyToReg uses that copy to EFLAGS.
2088 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
2089 X86::EFLAGS)
2090 return false;
2091 // Examine each user of the CopyToReg use.
2092 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2093 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2094 // Only examine the Flag result.
2095 if (FlagUI.getUse().getResNo() != 1) continue;
2096 // Anything unusual: assume conservatively.
2097 if (!FlagUI->isMachineOpcode()) return false;
2098 // Examine the opcode of the user.
2099 switch (FlagUI->getMachineOpcode()) {
2100 // These comparisons don't treat the most significant bit specially.
2101 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
2102 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
2103 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
2104 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00002105 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
2106 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002107 case X86::CMOVA16rr: case X86::CMOVA16rm:
2108 case X86::CMOVA32rr: case X86::CMOVA32rm:
2109 case X86::CMOVA64rr: case X86::CMOVA64rm:
2110 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
2111 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
2112 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
2113 case X86::CMOVB16rr: case X86::CMOVB16rm:
2114 case X86::CMOVB32rr: case X86::CMOVB32rm:
2115 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00002116 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
2117 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
2118 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002119 case X86::CMOVE16rr: case X86::CMOVE16rm:
2120 case X86::CMOVE32rr: case X86::CMOVE32rm:
2121 case X86::CMOVE64rr: case X86::CMOVE64rm:
2122 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
2123 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
2124 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
2125 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
2126 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2127 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2128 case X86::CMOVP16rr: case X86::CMOVP16rm:
2129 case X86::CMOVP32rr: case X86::CMOVP32rm:
2130 case X86::CMOVP64rr: case X86::CMOVP64rm:
2131 continue;
2132 // Anything else: assume conservatively.
2133 default: return false;
2134 }
2135 }
2136 }
2137 return true;
2138}
2139
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002140/// Test whether the given node which sets flags has any uses which require the
2141/// CF flag to be accurate.
2142static bool hasNoCarryFlagUses(SDNode *N) {
2143 // Examine each user of the node.
2144 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
2145 ++UI) {
2146 // Only check things that use the flags.
2147 if (UI.getUse().getResNo() != 1)
2148 continue;
2149 // Only examine CopyToReg uses.
2150 if (UI->getOpcode() != ISD::CopyToReg)
2151 return false;
2152 // Only examine CopyToReg uses that copy to EFLAGS.
2153 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2154 return false;
2155 // Examine each user of the CopyToReg use.
2156 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2157 FlagUI != FlagUE; ++FlagUI) {
2158 // Only examine the Flag result.
2159 if (FlagUI.getUse().getResNo() != 1)
2160 continue;
2161 // Anything unusual: assume conservatively.
2162 if (!FlagUI->isMachineOpcode())
2163 return false;
2164 // Examine the opcode of the user.
2165 switch (FlagUI->getMachineOpcode()) {
2166 // Comparisons which don't examine the CF flag.
2167 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2168 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2169 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2170 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2171 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2172 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2173 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2174 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2175 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2176 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2177 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2178 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2179 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2180 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2181 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2182 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2183 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2184 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2185 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2186 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2187 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2188 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2189 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2190 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2191 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2192 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2193 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2194 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2195 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2196 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2197 continue;
2198 // Anything else: assume conservatively.
2199 default:
2200 return false;
2201 }
2202 }
2203 }
2204 return true;
2205}
2206
Sanjay Patelb5723d02015-10-13 15:12:27 +00002207/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002208/// the {load; op; store} to modify transformation.
2209static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2210 SDValue StoredVal, SelectionDAG *CurDAG,
2211 LoadSDNode *&LoadNode,
2212 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002213 // is the stored value result 0 of the load?
2214 if (StoredVal.getResNo() != 0) return false;
2215
2216 // are there other uses of the loaded value than the inc or dec?
2217 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2218
Joel Jones68d59e82012-03-29 05:45:48 +00002219 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002220 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002221 return false;
2222
Evan Cheng3e869f02012-04-12 19:14:21 +00002223 SDValue Load = StoredVal->getOperand(0);
2224 // Is the stored value a non-extending and non-indexed load?
2225 if (!ISD::isNormalLoad(Load.getNode())) return false;
2226
2227 // Return LoadNode by reference.
2228 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002229
2230 // Is store the only read of the loaded value?
2231 if (!Load.hasOneUse())
2232 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002233
Evan Cheng3e869f02012-04-12 19:14:21 +00002234 // Is the address of the store the same as the load?
2235 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2236 LoadNode->getOffset() != StoreNode->getOffset())
2237 return false;
2238
Nirav Dave3264c1b2018-03-19 20:19:46 +00002239 bool FoundLoad = false;
2240 SmallVector<SDValue, 4> ChainOps;
2241 SmallVector<const SDNode *, 4> LoopWorklist;
2242 SmallPtrSet<const SDNode *, 16> Visited;
2243 const unsigned int Max = 1024;
2244
2245 // Visualization of Load-Op-Store fusion:
2246 // -------------------------
2247 // Legend:
2248 // *-lines = Chain operand dependencies.
2249 // |-lines = Normal operand dependencies.
2250 // Dependencies flow down and right. n-suffix references multiple nodes.
2251 //
2252 // C Xn C
2253 // * * *
2254 // * * *
2255 // Xn A-LD Yn TF Yn
2256 // * * \ | * |
2257 // * * \ | * |
2258 // * * \ | => A--LD_OP_ST
2259 // * * \| \
2260 // TF OP \
2261 // * | \ Zn
2262 // * | \
2263 // A-ST Zn
2264 //
2265
2266 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2267 // #2: Yn -> LD
2268 // #3: ST -> Zn
2269
2270 // Ensure the transform is safe by checking for the dual
2271 // dependencies to make sure we do not induce a loop.
2272
2273 // As LD is a predecessor to both OP and ST we can do this by checking:
2274 // a). if LD is a predecessor to a member of Xn or Yn.
2275 // b). if a Zn is a predecessor to ST.
2276
2277 // However, (b) can only occur through being a chain predecessor to
2278 // ST, which is the same as Zn being a member or predecessor of Xn,
2279 // which is a subset of LD being a predecessor of Xn. So it's
2280 // subsumed by check (a).
2281
Evan Cheng3e869f02012-04-12 19:14:21 +00002282 SDValue Chain = StoreNode->getChain();
2283
Nirav Dave3264c1b2018-03-19 20:19:46 +00002284 // Gather X elements in ChainOps.
Evan Cheng3e869f02012-04-12 19:14:21 +00002285 if (Chain == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002286 FoundLoad = true;
2287 ChainOps.push_back(Load.getOperand(0));
Nirav Dave0fab4172018-03-09 20:58:07 +00002288 } else if (Chain.getOpcode() == ISD::TokenFactor) {
Evan Cheng3e869f02012-04-12 19:14:21 +00002289 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2290 SDValue Op = Chain.getOperand(i);
2291 if (Op == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002292 FoundLoad = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002293 // Drop Load, but keep its chain. No cycle check necessary.
2294 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002295 continue;
2296 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002297 LoopWorklist.push_back(Op.getNode());
Evan Cheng3e869f02012-04-12 19:14:21 +00002298 ChainOps.push_back(Op);
2299 }
Nirav Daved668f692018-03-09 20:57:42 +00002300 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002301
2302 if (!FoundLoad)
Nirav Dave0fab4172018-03-09 20:58:07 +00002303 return false;
2304
Nirav Dave3264c1b2018-03-19 20:19:46 +00002305 // Worklist is currently Xn. Add Yn to worklist.
2306 for (SDValue Op : StoredVal->ops())
2307 if (Op.getNode() != LoadNode)
2308 LoopWorklist.push_back(Op.getNode());
2309
2310 // Check (a) if Load is a predecessor to Xn + Yn
2311 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2312 true))
2313 return false;
2314
2315 InputChain =
2316 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
Nirav Dave0fab4172018-03-09 20:58:07 +00002317 return true;
Nirav Dave042678b2018-03-10 02:16:15 +00002318}
Joel Jones68d59e82012-03-29 05:45:48 +00002319
Chandler Carruth4b611a82017-08-25 22:50:52 +00002320// Change a chain of {load; op; store} of the same value into a simple op
2321// through memory of that value, if the uses of the modified value and its
2322// address are suitable.
2323//
2324// The tablegen pattern memory operand pattern is currently not able to match
2325// the case where the EFLAGS on the original operation are used.
2326//
2327// To move this to tablegen, we'll need to improve tablegen to allow flags to
2328// be transferred from a node in the pattern to the result node, probably with
2329// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002330// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2331// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2332// (implicit EFLAGS)]>;
2333// but maybe need something like this
2334// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2335// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2336// (transferrable EFLAGS)]>;
2337//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002338// Until then, we manually fold these and instruction select the operation
2339// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002340bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2341 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2342 SDValue StoredVal = StoreNode->getOperand(1);
2343 unsigned Opc = StoredVal->getOpcode();
2344
Chandler Carruth4b611a82017-08-25 22:50:52 +00002345 // Before we try to select anything, make sure this is memory operand size
2346 // and opcode we can handle. Note that this must match the code below that
2347 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002348 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002349 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2350 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002351 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002352 switch (Opc) {
2353 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002354 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002355 case X86ISD::INC:
2356 case X86ISD::DEC:
2357 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002358 case X86ISD::ADC:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002359 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002360 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002361 case X86ISD::AND:
2362 case X86ISD::OR:
2363 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002364 break;
2365 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002366
Chandler Carruth03258f22017-08-25 02:04:03 +00002367 LoadSDNode *LoadNode = nullptr;
2368 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002369 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2370 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002371 return false;
2372
2373 SDValue Base, Scale, Index, Disp, Segment;
2374 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2375 Segment))
2376 return false;
2377
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002378 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002379 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002380 switch (MemVT.getSimpleVT().SimpleTy) {
2381 case MVT::i64:
2382 return Opc64;
2383 case MVT::i32:
2384 return Opc32;
2385 case MVT::i16:
2386 return Opc16;
2387 case MVT::i8:
2388 return Opc8;
2389 default:
2390 llvm_unreachable("Invalid size!");
2391 }
2392 };
2393
2394 MachineSDNode *Result;
2395 switch (Opc) {
2396 case X86ISD::INC:
2397 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002398 unsigned NewOpc =
2399 Opc == X86ISD::INC
2400 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2401 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002402 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2403 Result =
2404 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2405 break;
2406 }
2407 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002408 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002409 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002410 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002411 case X86ISD::AND:
2412 case X86ISD::OR:
2413 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002414 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2415 switch (Opc) {
2416 case X86ISD::ADD:
2417 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2418 X86::ADD8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002419 case X86ISD::ADC:
2420 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2421 X86::ADC8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002422 case X86ISD::SUB:
2423 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2424 X86::SUB8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002425 case X86ISD::SBB:
2426 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2427 X86::SBB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002428 case X86ISD::AND:
2429 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2430 X86::AND8mr);
2431 case X86ISD::OR:
2432 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2433 case X86ISD::XOR:
2434 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2435 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002436 default:
2437 llvm_unreachable("Invalid opcode!");
2438 }
2439 };
2440 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2441 switch (Opc) {
2442 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002443 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002444 case X86ISD::ADC:
2445 return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002446 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002447 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002448 case X86ISD::SBB:
2449 return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002450 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002451 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002452 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002453 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002454 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002455 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002456 default:
2457 llvm_unreachable("Invalid opcode!");
2458 }
2459 };
2460 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2461 switch (Opc) {
2462 case X86ISD::ADD:
2463 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2464 X86::ADD8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002465 case X86ISD::ADC:
2466 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2467 X86::ADC8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002468 case X86ISD::SUB:
2469 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2470 X86::SUB8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002471 case X86ISD::SBB:
2472 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2473 X86::SBB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002474 case X86ISD::AND:
2475 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2476 X86::AND8mi);
2477 case X86ISD::OR:
2478 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2479 X86::OR8mi);
2480 case X86ISD::XOR:
2481 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2482 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002483 default:
2484 llvm_unreachable("Invalid opcode!");
2485 }
2486 };
2487
2488 unsigned NewOpc = SelectRegOpcode(Opc);
2489 SDValue Operand = StoredVal->getOperand(1);
2490
2491 // See if the operand is a constant that we can fold into an immediate
2492 // operand.
2493 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2494 auto OperandV = OperandC->getAPIntValue();
2495
2496 // Check if we can shrink the operand enough to fit in an immediate (or
2497 // fit into a smaller immediate) by negating it and switching the
2498 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002499 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2500 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002501 (-OperandV).getMinSignedBits() <= 8) ||
2502 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2503 (-OperandV).getMinSignedBits() <= 32)) &&
2504 hasNoCarryFlagUses(StoredVal.getNode())) {
2505 OperandV = -OperandV;
2506 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2507 }
2508
2509 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2510 // the larger immediate operand.
2511 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2512 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2513 NewOpc = SelectImm8Opcode(Opc);
2514 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2515 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2516 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2517 NewOpc = SelectImmOpcode(Opc);
2518 }
2519 }
2520
Nirav Dave72d32f22018-01-19 15:37:57 +00002521 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2522 SDValue CopyTo =
2523 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2524 StoredVal.getOperand(2), SDValue());
2525
2526 const SDValue Ops[] = {Base, Scale, Index, Disp,
2527 Segment, Operand, CopyTo, CopyTo.getValue(1)};
2528 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2529 Ops);
2530 } else {
2531 const SDValue Ops[] = {Base, Scale, Index, Disp,
2532 Segment, Operand, InputChain};
2533 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2534 Ops);
2535 }
Chandler Carruth4b611a82017-08-25 22:50:52 +00002536 break;
2537 }
2538 default:
2539 llvm_unreachable("Invalid opcode!");
2540 }
2541
Chandler Carruth03258f22017-08-25 02:04:03 +00002542 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2543 MemOp[0] = StoreNode->getMemOperand();
2544 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002545 Result->setMemRefs(MemOp, MemOp + 2);
2546
Nirav Dave3264c1b2018-03-19 20:19:46 +00002547 // Update Load Chain uses as well.
2548 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
Chandler Carruth03258f22017-08-25 02:04:03 +00002549 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2550 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2551 CurDAG->RemoveDeadNode(Node);
2552 return true;
2553}
2554
Craig Topper958106d2017-09-12 17:40:25 +00002555// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2556bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2557 MVT NVT = Node->getSimpleValueType(0);
2558 SDLoc dl(Node);
2559
2560 SDValue N0 = Node->getOperand(0);
2561 SDValue N1 = Node->getOperand(1);
2562
2563 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2564 return false;
2565
2566 // Must have a shift right.
2567 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2568 return false;
2569
2570 // Shift can't have additional users.
2571 if (!N0->hasOneUse())
2572 return false;
2573
2574 // Only supported for 32 and 64 bits.
2575 if (NVT != MVT::i32 && NVT != MVT::i64)
2576 return false;
2577
2578 // Shift amount and RHS of and must be constant.
2579 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2580 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2581 if (!MaskCst || !ShiftCst)
2582 return false;
2583
2584 // And RHS must be a mask.
2585 uint64_t Mask = MaskCst->getZExtValue();
2586 if (!isMask_64(Mask))
2587 return false;
2588
2589 uint64_t Shift = ShiftCst->getZExtValue();
2590 uint64_t MaskSize = countPopulation(Mask);
2591
2592 // Don't interfere with something that can be handled by extracting AH.
2593 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2594 if (Shift == 8 && MaskSize == 8)
2595 return false;
2596
2597 // Make sure we are only using bits that were in the original value, not
2598 // shifted in.
2599 if (Shift + MaskSize > NVT.getSizeInBits())
2600 return false;
2601
Craig Topper88939fe2018-02-12 21:18:11 +00002602 // Create a BEXTR node and run it through selection.
2603 SDValue C = CurDAG->getConstant(Shift | (MaskSize << 8), dl, NVT);
2604 SDValue New = CurDAG->getNode(X86ISD::BEXTR, dl, NVT,
2605 N0->getOperand(0), C);
2606 ReplaceNode(Node, New.getNode());
2607 SelectCode(New.getNode());
Craig Topper958106d2017-09-12 17:40:25 +00002608 return true;
2609}
2610
Craig Topperd6564102018-04-27 22:15:33 +00002611// Emit a PCMISTR(I/M) instruction.
2612MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
2613 bool MayFoldLoad, const SDLoc &dl,
2614 MVT VT, SDNode *Node) {
2615 SDValue N0 = Node->getOperand(0);
2616 SDValue N1 = Node->getOperand(1);
2617 SDValue Imm = Node->getOperand(2);
2618 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2619 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2620
2621 // If there is a load, it will be behind a bitcast. We don't need to check
2622 // alignment on this load.
2623 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2624 if (MayFoldLoad && N1->getOpcode() == ISD::BITCAST && N1->hasOneUse() &&
2625 tryFoldVecLoad(Node, N1.getNode(), N1.getOperand(0), Tmp0, Tmp1, Tmp2,
2626 Tmp3, Tmp4)) {
2627 SDValue Load = N1.getOperand(0);
2628 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
2629 Load.getOperand(0) };
2630 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
2631 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2632 // Update the chain.
2633 ReplaceUses(Load.getValue(1), SDValue(CNode, 2));
2634 // Record the mem-refs
2635 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2636 MemOp[0] = cast<LoadSDNode>(Load)->getMemOperand();
2637 CNode->setMemRefs(MemOp, MemOp + 1);
2638 return CNode;
2639 }
2640
2641 SDValue Ops[] = { N0, N1, Imm };
2642 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
2643 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
2644 return CNode;
2645}
2646
2647// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
2648// to emit a second instruction after this one. This is needed since we have two
2649// copyToReg nodes glued before this and we need to continue that glue through.
2650MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
2651 bool MayFoldLoad, const SDLoc &dl,
2652 MVT VT, SDNode *Node,
2653 SDValue &InFlag) {
2654 SDValue N0 = Node->getOperand(0);
2655 SDValue N2 = Node->getOperand(2);
2656 SDValue Imm = Node->getOperand(4);
2657 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2658 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2659
2660 // If there is a load, it will be behind a bitcast. We don't need to check
2661 // alignment on this load.
2662 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2663 if (MayFoldLoad && N2->getOpcode() == ISD::BITCAST && N2->hasOneUse() &&
2664 tryFoldVecLoad(Node, N2.getNode(), N2.getOperand(0), Tmp0, Tmp1, Tmp2,
2665 Tmp3, Tmp4)) {
2666 SDValue Load = N2.getOperand(0);
2667 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
2668 Load.getOperand(0), InFlag };
2669 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
2670 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2671 InFlag = SDValue(CNode, 3);
2672 // Update the chain.
2673 ReplaceUses(Load.getValue(1), SDValue(CNode, 2));
2674 // Record the mem-refs
2675 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2676 MemOp[0] = cast<LoadSDNode>(Load)->getMemOperand();
2677 CNode->setMemRefs(MemOp, MemOp + 1);
2678 return CNode;
2679 }
2680
2681 SDValue Ops[] = { N0, N2, Imm, InFlag };
2682 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
2683 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
2684 InFlag = SDValue(CNode, 2);
2685 return CNode;
2686}
2687
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002688/// If the high bits of an 'and' operand are known zero, try setting the
2689/// high bits of an 'and' constant operand to produce a smaller encoding by
2690/// creating a small, sign-extended negative immediate rather than a large
2691/// positive one. This reverses a transform in SimplifyDemandedBits that
2692/// shrinks mask constants by clearing bits. There is also a possibility that
2693/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
2694/// case, just replace the 'and'. Return 'true' if the node is replaced.
2695bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
2696 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
2697 // have immediate operands.
2698 MVT VT = And->getSimpleValueType(0);
2699 if (VT != MVT::i32 && VT != MVT::i64)
2700 return false;
2701
2702 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
2703 if (!And1C)
2704 return false;
2705
Craig Topper57e06432018-02-05 16:54:07 +00002706 // Bail out if the mask constant is already negative. It's can't shrink more.
2707 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
2708 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
2709 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
2710 // are negative too.
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002711 APInt MaskVal = And1C->getAPIntValue();
2712 unsigned MaskLZ = MaskVal.countLeadingZeros();
Craig Topper57e06432018-02-05 16:54:07 +00002713 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002714 return false;
2715
Craig Topper57e06432018-02-05 16:54:07 +00002716 // Don't extend into the upper 32 bits of a 64 bit mask.
2717 if (VT == MVT::i64 && MaskLZ >= 32) {
2718 MaskLZ -= 32;
2719 MaskVal = MaskVal.trunc(32);
2720 }
2721
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002722 SDValue And0 = And->getOperand(0);
Craig Topper57e06432018-02-05 16:54:07 +00002723 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002724 APInt NegMaskVal = MaskVal | HighZeros;
2725
2726 // If a negative constant would not allow a smaller encoding, there's no need
2727 // to continue. Only change the constant when we know it's a win.
2728 unsigned MinWidth = NegMaskVal.getMinSignedBits();
2729 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
2730 return false;
2731
Craig Topper57e06432018-02-05 16:54:07 +00002732 // Extend masks if we truncated above.
2733 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
2734 NegMaskVal = NegMaskVal.zext(64);
2735 HighZeros = HighZeros.zext(64);
2736 }
2737
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002738 // The variable operand must be all zeros in the top bits to allow using the
2739 // new, negative constant as the mask.
2740 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
2741 return false;
2742
2743 // Check if the mask is -1. In that case, this is an unnecessary instruction
2744 // that escaped earlier analysis.
2745 if (NegMaskVal.isAllOnesValue()) {
2746 ReplaceNode(And, And0.getNode());
2747 return true;
2748 }
2749
2750 // A negative mask allows a smaller encoding. Create a new 'and' node.
2751 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
2752 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
2753 ReplaceNode(And, NewAnd.getNode());
2754 SelectCode(NewAnd.getNode());
2755 return true;
2756}
2757
Justin Bogner593741d2016-05-10 23:55:37 +00002758void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002759 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002760 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002761 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002762
Dan Gohman17059682008-07-17 19:10:17 +00002763 if (Node->isMachineOpcode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002764 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002765 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002766 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002767 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002768
Evan Cheng10d27902006-01-06 20:36:21 +00002769 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002770 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002771 case ISD::BRIND: {
2772 if (Subtarget->isTargetNaCl())
2773 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2774 // leave the instruction alone.
2775 break;
2776 if (Subtarget->isTarget64BitILP32()) {
2777 // Converts a 32-bit register to a 64-bit, zero-extended version of
2778 // it. This is needed because x86-64 can do many things, but jmp %r32
2779 // ain't one of them.
2780 const SDValue &Target = Node->getOperand(1);
2781 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2782 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2783 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2784 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002785 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002786 SelectCode(ZextTarget.getNode());
2787 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002788 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002789 }
2790 break;
2791 }
Dan Gohman757eee82009-08-02 16:10:52 +00002792 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002793 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002794 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002795
Craig Topper75370b92017-09-19 17:19:45 +00002796 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002797 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002798 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002799 SDValue VSelect = CurDAG->getNode(
2800 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2801 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002802 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002803 SelectCode(VSelect.getNode());
2804 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002805 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002806 }
Craig Topper3af251d2012-07-01 02:55:34 +00002807
Tobias Grosser85508e82015-08-19 11:35:10 +00002808 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002809 if (matchBEXTRFromAnd(Node))
2810 return;
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002811 if (shrinkAndImmediate(Node))
2812 return;
Craig Topper958106d2017-09-12 17:40:25 +00002813
2814 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002815 case ISD::OR:
2816 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002817
Benjamin Kramer4c816242011-04-22 15:30:40 +00002818 // For operations of the form (x << C1) op C2, check if we can use a smaller
2819 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2820 SDValue N0 = Node->getOperand(0);
2821 SDValue N1 = Node->getOperand(1);
2822
2823 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2824 break;
2825
2826 // i8 is unshrinkable, i16 should be promoted to i32.
2827 if (NVT != MVT::i32 && NVT != MVT::i64)
2828 break;
2829
2830 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2831 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2832 if (!Cst || !ShlCst)
2833 break;
2834
2835 int64_t Val = Cst->getSExtValue();
2836 uint64_t ShlVal = ShlCst->getZExtValue();
2837
2838 // Make sure that we don't change the operation by removing bits.
2839 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002840 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2841 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002842 break;
2843
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002844 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002845 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002846
2847 // Check the minimum bitwidth for the new constant.
2848 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2849 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2850 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2851 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2852 CstVT = MVT::i8;
2853 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2854 CstVT = MVT::i32;
2855
2856 // Bail if there is no smaller encoding.
2857 if (NVT == CstVT)
2858 break;
2859
Craig Topper83e042a2013-08-15 05:57:07 +00002860 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002861 default: llvm_unreachable("Unsupported VT!");
2862 case MVT::i32:
2863 assert(CstVT == MVT::i8);
2864 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002865 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002866
2867 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002868 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002869 case ISD::AND: Op = X86::AND32ri8; break;
2870 case ISD::OR: Op = X86::OR32ri8; break;
2871 case ISD::XOR: Op = X86::XOR32ri8; break;
2872 }
2873 break;
2874 case MVT::i64:
2875 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2876 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002877 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002878
2879 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002880 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002881 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2882 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2883 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2884 }
2885 break;
2886 }
2887
2888 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002889 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002890 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002891 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002892 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2893 SDValue(New, 0));
2894 else
2895 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2896 getI8Imm(ShlVal, dl));
2897 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002898 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002899 case X86ISD::UMUL8:
2900 case X86ISD::SMUL8: {
2901 SDValue N0 = Node->getOperand(0);
2902 SDValue N1 = Node->getOperand(1);
2903
Craig Topper3efdb7c2018-06-11 20:50:58 +00002904 unsigned Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002905
2906 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2907 N0, SDValue()).getValue(1);
2908
2909 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2910 SDValue Ops[] = {N1, InFlag};
2911 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2912
Justin Bogner31d7da32016-05-11 21:13:17 +00002913 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002914 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002915 }
2916
Chris Lattner364bb0a2010-12-05 07:30:36 +00002917 case X86ISD::UMUL: {
2918 SDValue N0 = Node->getOperand(0);
2919 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002920
Craig Topper3efdb7c2018-06-11 20:50:58 +00002921 unsigned LoReg, Opc;
Craig Topper83e042a2013-08-15 05:57:07 +00002922 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002923 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00002924 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00002925 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2926 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2927 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002928 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002929
Chris Lattner364bb0a2010-12-05 07:30:36 +00002930 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2931 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002932
Chris Lattner364bb0a2010-12-05 07:30:36 +00002933 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2934 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002935 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002936
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002937 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002938 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002939 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002940
Dan Gohman757eee82009-08-02 16:10:52 +00002941 case ISD::SMUL_LOHI:
2942 case ISD::UMUL_LOHI: {
2943 SDValue N0 = Node->getOperand(0);
2944 SDValue N1 = Node->getOperand(1);
2945
Craig Topper3efdb7c2018-06-11 20:50:58 +00002946 unsigned Opc, MOpc;
Dan Gohman757eee82009-08-02 16:10:52 +00002947 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002948 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002949 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002950 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002951 default: llvm_unreachable("Unsupported VT!");
Michael Liaof9f7b552012-09-26 08:22:37 +00002952 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2953 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2954 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2955 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002956 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002957 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002958 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002959 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002960 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2961 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002962 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002963 }
Dan Gohman757eee82009-08-02 16:10:52 +00002964
Michael Liaof9f7b552012-09-26 08:22:37 +00002965 unsigned SrcReg, LoReg, HiReg;
2966 switch (Opc) {
2967 default: llvm_unreachable("Unknown MUL opcode!");
Michael Liaof9f7b552012-09-26 08:22:37 +00002968 case X86::IMUL32r:
2969 case X86::MUL32r:
2970 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2971 break;
2972 case X86::IMUL64r:
2973 case X86::MUL64r:
2974 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2975 break;
2976 case X86::MULX32rr:
2977 SrcReg = X86::EDX; LoReg = HiReg = 0;
2978 break;
2979 case X86::MULX64rr:
2980 SrcReg = X86::RDX; LoReg = HiReg = 0;
2981 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002982 }
2983
2984 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002985 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002986 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002987 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002988 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002989 if (foldedLoad)
2990 std::swap(N0, N1);
2991 }
2992
Michael Liaof9f7b552012-09-26 08:22:37 +00002993 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002994 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002995 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002996
2997 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002998 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002999 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00003000 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3001 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00003002 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
3003 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00003004 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003005 ResHi = SDValue(CNode, 0);
3006 ResLo = SDValue(CNode, 1);
3007 Chain = SDValue(CNode, 2);
3008 InFlag = SDValue(CNode, 3);
3009 } else {
3010 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00003011 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003012 Chain = SDValue(CNode, 0);
3013 InFlag = SDValue(CNode, 1);
3014 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00003015
Dan Gohman757eee82009-08-02 16:10:52 +00003016 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00003017 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00003018 // Record the mem-refs
Craig Topper55029d82017-11-08 22:26:37 +00003019 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3020 MemOp[0] = cast<LoadSDNode>(N1)->getMemOperand();
3021 CNode->setMemRefs(MemOp, MemOp + 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003022 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00003023 SDValue Ops[] = { N1, InFlag };
3024 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
3025 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003026 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003027 ResHi = SDValue(CNode, 0);
3028 ResLo = SDValue(CNode, 1);
3029 InFlag = SDValue(CNode, 2);
3030 } else {
3031 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003032 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003033 InFlag = SDValue(CNode, 0);
3034 }
Dan Gohman757eee82009-08-02 16:10:52 +00003035 }
3036
3037 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003038 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003039 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003040 assert(LoReg && "Register for low half is not defined!");
3041 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
3042 InFlag);
3043 InFlag = ResLo.getValue(2);
3044 }
3045 ReplaceUses(SDValue(Node, 0), ResLo);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003046 LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
3047 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003048 }
3049 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003050 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003051 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003052 assert(HiReg && "Register for high half is not defined!");
3053 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
3054 InFlag);
3055 InFlag = ResHi.getValue(2);
3056 }
3057 ReplaceUses(SDValue(Node, 1), ResHi);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003058 LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
3059 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003060 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003061
Craig Topper6bed9de2017-09-09 05:57:20 +00003062 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003063 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003064 }
3065
3066 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003067 case ISD::UDIVREM:
3068 case X86ISD::SDIVREM8_SEXT_HREG:
3069 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00003070 SDValue N0 = Node->getOperand(0);
3071 SDValue N1 = Node->getOperand(1);
3072
Craig Topper3efdb7c2018-06-11 20:50:58 +00003073 unsigned Opc, MOpc;
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003074 bool isSigned = (Opcode == ISD::SDIVREM ||
3075 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003076 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00003077 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003078 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003079 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
3080 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
3081 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
3082 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003083 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003084 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00003085 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003086 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003087 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
3088 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
3089 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
3090 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003091 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003092 }
Dan Gohman757eee82009-08-02 16:10:52 +00003093
Chris Lattner518b0372009-12-23 01:45:04 +00003094 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003095 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00003096 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003097 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003098 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00003099 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00003100 SExtOpcode = X86::CBW;
3101 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003102 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00003103 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003104 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00003105 SExtOpcode = X86::CWD;
3106 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003107 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00003108 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003109 SExtOpcode = X86::CDQ;
3110 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003111 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00003112 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003113 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00003114 break;
3115 }
3116
Dan Gohman757eee82009-08-02 16:10:52 +00003117 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003118 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00003119 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00003120
Dan Gohman757eee82009-08-02 16:10:52 +00003121 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00003122 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003123 // Special case for div8, just use a move with zero extension to AX to
3124 // clear the upper 8 bits (AH).
3125 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003126 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003127 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
3128 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00003129 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00003130 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003131 Chain = Move.getValue(1);
3132 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00003133 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00003134 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00003135 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00003136 Chain = CurDAG->getEntryNode();
3137 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00003138 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00003139 InFlag = Chain.getValue(1);
3140 } else {
3141 InFlag =
3142 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
3143 LoReg, N0, SDValue()).getValue(1);
3144 if (isSigned && !signBitIsZero) {
3145 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00003146 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003147 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00003148 } else {
3149 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00003150 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00003151 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00003152 case MVT::i16:
3153 ClrNode =
3154 SDValue(CurDAG->getMachineNode(
3155 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003156 CurDAG->getTargetConstant(X86::sub_16bit, dl,
3157 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003158 0);
3159 break;
3160 case MVT::i32:
3161 break;
3162 case MVT::i64:
3163 ClrNode =
3164 SDValue(CurDAG->getMachineNode(
3165 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003166 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
3167 CurDAG->getTargetConstant(X86::sub_32bit, dl,
3168 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003169 0);
3170 break;
3171 default:
3172 llvm_unreachable("Unexpected division source");
3173 }
3174
Chris Lattner518b0372009-12-23 01:45:04 +00003175 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00003176 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00003177 }
Evan Cheng92e27972006-01-06 23:19:29 +00003178 }
Dan Gohmana1603612007-10-08 18:33:35 +00003179
Dan Gohman757eee82009-08-02 16:10:52 +00003180 if (foldedLoad) {
3181 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3182 InFlag };
Craig Topper61f81f92017-11-08 22:26:39 +00003183 MachineSDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00003184 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00003185 InFlag = SDValue(CNode, 1);
3186 // Update the chain.
3187 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
Craig Topper61f81f92017-11-08 22:26:39 +00003188 // Record the mem-refs
3189 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3190 MemOp[0] = cast<LoadSDNode>(N1)->getMemOperand();
3191 CNode->setMemRefs(MemOp, MemOp + 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003192 } else {
3193 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003194 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003195 }
Evan Cheng92e27972006-01-06 23:19:29 +00003196
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003197 // Prevent use of AH in a REX instruction by explicitly copying it to
3198 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00003199 //
3200 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003201 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00003202 // the allocator and/or the backend get enhanced to be more robust in
3203 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003204 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
3205 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
3206 unsigned AHExtOpcode =
Craig Topperad7c6852018-03-20 05:00:20 +00003207 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003208
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003209 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
3210 MVT::Glue, AHCopy, InFlag);
3211 SDValue Result(RNode, 0);
3212 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003213
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003214 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
3215 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
Craig Topperb8d7d4d2017-10-26 21:12:03 +00003216 assert(Node->getValueType(1) == MVT::i32 && "Unexpected result type!");
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003217 } else {
3218 Result =
3219 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
3220 }
3221 ReplaceUses(SDValue(Node, 1), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003222 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3223 dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003224 }
Dan Gohman757eee82009-08-02 16:10:52 +00003225 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003226 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00003227 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3228 LoReg, NVT, InFlag);
3229 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003230 ReplaceUses(SDValue(Node, 0), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003231 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3232 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003233 }
3234 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003235 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003236 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3237 HiReg, NVT, InFlag);
3238 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003239 ReplaceUses(SDValue(Node, 1), Result);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003240 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3241 dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003242 }
Craig Topper6bed9de2017-09-09 05:57:20 +00003243 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003244 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003245 }
3246
Craig Topperb424faf2018-02-12 03:02:02 +00003247 case X86ISD::CMP: {
Dan Gohmanac33a902009-08-19 18:16:17 +00003248 SDValue N0 = Node->getOperand(0);
3249 SDValue N1 = Node->getOperand(1);
3250
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003251 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00003252 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003253 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00003254
Dan Gohmanac33a902009-08-19 18:16:17 +00003255 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
3256 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003257 // Look past the truncate if CMP is the only use of it.
Craig Topper3ccbd3f2018-02-12 03:02:01 +00003258 if (N0.getOpcode() == ISD::AND &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00003259 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00003260 N0.getValueType() != MVT::i8 &&
3261 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00003262 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00003263 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00003264 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00003265
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003266 MVT VT;
3267 int SubRegOp;
3268 unsigned Op;
3269
Craig Topperfc53dc22017-08-25 05:04:34 +00003270 if (isUInt<8>(Mask) &&
3271 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003272 // For example, convert "testl %eax, $8" to "testb %al, $8"
3273 VT = MVT::i8;
3274 SubRegOp = X86::sub_8bit;
3275 Op = X86::TEST8ri;
3276 } else if (OptForMinSize && isUInt<16>(Mask) &&
3277 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3278 // For example, "testl %eax, $32776" to "testw %ax, $32776".
3279 // NOTE: We only want to form TESTW instructions if optimizing for
3280 // min size. Otherwise we only save one byte and possibly get a length
3281 // changing prefix penalty in the decoders.
3282 VT = MVT::i16;
3283 SubRegOp = X86::sub_16bit;
3284 Op = X86::TEST16ri;
3285 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
3286 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3287 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3288 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
3289 // Otherwize, we find ourselves in a position where we have to do
3290 // promotion. If previous passes did not promote the and, we assume
3291 // they had a good reason not to and do not promote here.
3292 VT = MVT::i32;
3293 SubRegOp = X86::sub_32bit;
3294 Op = X86::TEST32ri;
3295 } else {
3296 // No eligible transformation was found.
3297 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00003298 }
3299
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003300 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
3301 SDValue Reg = N0.getOperand(0);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003302
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003303 // Extract the subregister if necessary.
3304 if (N0.getValueType() != VT)
3305 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003306
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003307 // Emit a testl or testw.
3308 SDNode *NewNode = CurDAG->getMachineNode(Op, dl, MVT::i32, Reg, Imm);
Craig Topperb424faf2018-02-12 03:02:02 +00003309 // Replace CMP with TEST.
Nirav Dave3264c1b2018-03-19 20:19:46 +00003310 ReplaceNode(Node, NewNode);
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003311 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003312 }
3313 break;
3314 }
Craig Topperd6564102018-04-27 22:15:33 +00003315 case X86ISD::PCMPISTR: {
3316 if (!Subtarget->hasSSE42())
3317 break;
3318
3319 bool NeedIndex = !SDValue(Node, 0).use_empty();
3320 bool NeedMask = !SDValue(Node, 1).use_empty();
3321 // We can't fold a load if we are going to make two instructions.
3322 bool MayFoldLoad = !NeedIndex || !NeedMask;
3323
3324 MachineSDNode *CNode;
3325 if (NeedMask) {
3326 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
3327 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
3328 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
3329 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3330 }
3331 if (NeedIndex || !NeedMask) {
3332 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
3333 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
3334 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
3335 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3336 }
3337
3338 // Connect the flag usage to the last instruction created.
Craig Topperabc307e2018-07-12 18:04:05 +00003339 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
Craig Topperd6564102018-04-27 22:15:33 +00003340 CurDAG->RemoveDeadNode(Node);
3341 return;
3342 }
3343 case X86ISD::PCMPESTR: {
3344 if (!Subtarget->hasSSE42())
3345 break;
3346
3347 // Copy the two implicit register inputs.
3348 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
3349 Node->getOperand(1),
3350 SDValue()).getValue(1);
3351 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
3352 Node->getOperand(3), InFlag).getValue(1);
3353
3354 bool NeedIndex = !SDValue(Node, 0).use_empty();
3355 bool NeedMask = !SDValue(Node, 1).use_empty();
3356 // We can't fold a load if we are going to make two instructions.
3357 bool MayFoldLoad = !NeedIndex || !NeedMask;
3358
3359 MachineSDNode *CNode;
3360 if (NeedMask) {
3361 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
3362 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
3363 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
3364 InFlag);
3365 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3366 }
3367 if (NeedIndex || !NeedMask) {
3368 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
3369 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
3370 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
3371 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3372 }
3373 // Connect the flag usage to the last instruction created.
3374 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
3375 CurDAG->RemoveDeadNode(Node);
3376 return;
3377 }
3378
Chandler Carruth03258f22017-08-25 02:04:03 +00003379 case ISD::STORE:
3380 if (foldLoadStoreIntoMemOperand(Node))
3381 return;
3382 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003383 }
3384
Justin Bogner593741d2016-05-10 23:55:37 +00003385 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003386}
3387
Chris Lattnerba1ed582006-06-08 18:03:49 +00003388bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003389SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003390 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003391 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003392 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003393 default:
3394 llvm_unreachable("Unexpected asm memory constraint");
3395 case InlineAsm::Constraint_i:
3396 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3397 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003398 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003399 case InlineAsm::Constraint_o: // offsetable ??
3400 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003401 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003402 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003403 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003404 return true;
3405 break;
3406 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003407
Evan Cheng2d487222006-08-26 01:05:16 +00003408 OutOps.push_back(Op0);
3409 OutOps.push_back(Op1);
3410 OutOps.push_back(Op2);
3411 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003412 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003413 return false;
3414}
3415
Sanjay Patelb5723d02015-10-13 15:12:27 +00003416/// This pass converts a legalized DAG into a X86-specific DAG,
3417/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003418FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003419 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003420 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003421}