blob: 5ee8ea6ec0386f93a6f7b5298127d28f5c31ab2c [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"
Peter Collingbourne235c2752016-12-08 19:01:00 +000024#include "llvm/IR/ConstantRange.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000025#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000029#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000030#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000031#include "llvm/Support/KnownBits.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000032#include "llvm/Support/MathExtras.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000036#include <stdint.h>
Chris Lattner655e7df2005-11-16 01:54:32 +000037using namespace llvm;
38
Chandler Carruth84e68b22014-04-22 02:41:26 +000039#define DEBUG_TYPE "x86-isel"
40
Chris Lattner1ef9cd42006-12-19 22:59:26 +000041STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
42
Chris Lattner655e7df2005-11-16 01:54:32 +000043//===----------------------------------------------------------------------===//
44// Pattern Matcher Implementation
45//===----------------------------------------------------------------------===//
46
47namespace {
Sanjay Patelb5723d02015-10-13 15:12:27 +000048 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
49 /// numbers for the leaves of the matched tree.
Chris Lattner3f0f71b2005-11-19 02:11:08 +000050 struct X86ISelAddressMode {
51 enum {
52 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000053 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000054 } BaseType;
55
Dan Gohman0fd54fb2010-04-29 23:30:41 +000056 // This is really a union, discriminated by BaseType!
57 SDValue Base_Reg;
58 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000059
60 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000061 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000062 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000063 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000064 const GlobalValue *GV;
65 const Constant *CP;
66 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000067 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000068 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000069 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000070 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000071 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000072
73 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000074 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
75 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
76 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000077
78 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000079 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000080 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000081 }
Chad Rosier24c19d22012-08-01 18:39:17 +000082
Chris Lattnerfea81da2009-06-27 04:16:01 +000083 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000084 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000085 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000086 }
Chad Rosier24c19d22012-08-01 18:39:17 +000087
Sanjay Patelb5723d02015-10-13 15:12:27 +000088 /// Return true if this addressing mode is already RIP-relative.
Chris Lattnerfea81da2009-06-27 04:16:01 +000089 bool isRIPRelative() const {
90 if (BaseType != RegBase) return false;
91 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +000092 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +000093 return RegNode->getReg() == X86::RIP;
94 return false;
95 }
Chad Rosier24c19d22012-08-01 18:39:17 +000096
Chris Lattnerfea81da2009-06-27 04:16:01 +000097 void setBaseReg(SDValue Reg) {
98 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +000099 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000100 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000101
Aaron Ballman615eb472017-10-15 14:32:27 +0000102#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Craig Topper25007c42018-03-16 21:10:07 +0000103 void dump(SelectionDAG *DAG = nullptr) {
David Greenedbdb1b22010-01-05 01:29:08 +0000104 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000105 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000106 if (Base_Reg.getNode())
Craig Topper25007c42018-03-16 21:10:07 +0000107 Base_Reg.getNode()->dump(DAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000108 else
Craig Toppereff84ed2017-12-22 17:18:10 +0000109 dbgs() << "nul\n";
110 if (BaseType == FrameIndexBase)
111 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
112 dbgs() << " Scale " << Scale << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000113 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000114 if (IndexReg.getNode())
Craig Topper25007c42018-03-16 21:10:07 +0000115 IndexReg.getNode()->dump(DAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000116 else
Craig Toppereff84ed2017-12-22 17:18:10 +0000117 dbgs() << "nul\n";
David Greenedbdb1b22010-01-05 01:29:08 +0000118 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000119 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000120 if (GV)
121 GV->dump();
122 else
David Greenedbdb1b22010-01-05 01:29:08 +0000123 dbgs() << "nul";
124 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000125 if (CP)
126 CP->dump();
127 else
David Greenedbdb1b22010-01-05 01:29:08 +0000128 dbgs() << "nul";
129 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000130 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000131 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000132 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000133 else
David Greenedbdb1b22010-01-05 01:29:08 +0000134 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000135 dbgs() << " MCSym ";
136 if (MCSym)
137 dbgs() << MCSym;
138 else
139 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000140 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000141 }
Manman Ren742534c2012-09-06 19:06:06 +0000142#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000143 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000144}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000145
146namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000147 //===--------------------------------------------------------------------===//
Sanjay Patelb5723d02015-10-13 15:12:27 +0000148 /// ISel - X86-specific code to select X86 machine instructions for
Chris Lattner655e7df2005-11-16 01:54:32 +0000149 /// SelectionDAG operations.
150 ///
Craig Topper26eec092014-03-31 06:22:15 +0000151 class X86DAGToDAGISel final : public SelectionDAGISel {
Sanjay Patelb5723d02015-10-13 15:12:27 +0000152 /// Keep a pointer to the X86Subtarget around so that we can
Chris Lattner655e7df2005-11-16 01:54:32 +0000153 /// make the right decision when generating code for different targets.
154 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000155
Sanjay Patelb5723d02015-10-13 15:12:27 +0000156 /// If true, selector should try to optimize for code size instead of
157 /// performance.
Evan Cheng7d6fa972008-09-26 23:41:32 +0000158 bool OptForSize;
159
Hans Wennborg4ae51192016-03-25 01:10:56 +0000160 /// If true, selector should try to optimize for minimum code size.
161 bool OptForMinSize;
162
Chris Lattner655e7df2005-11-16 01:54:32 +0000163 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000164 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000165 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Matt Morehouse9e658c92017-12-01 22:20:26 +0000166 OptForMinSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000167
Mehdi Amini117296c2016-10-01 02:56:57 +0000168 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000169 return "X86 DAG->DAG Instruction Selection";
170 }
171
Eric Christopher4f09c592014-05-22 01:53:26 +0000172 bool runOnMachineFunction(MachineFunction &MF) override {
173 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000174 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000175 SelectionDAGISel::runOnMachineFunction(MF);
176 return true;
177 }
178
Craig Topper2d9361e2014-03-09 07:44:38 +0000179 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000180
Craig Topper2d9361e2014-03-09 07:44:38 +0000181 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000182
Craig Topper2d9361e2014-03-09 07:44:38 +0000183 void PreprocessISelDAG() override;
Craig Toppere6913ec2018-03-16 17:13:42 +0000184 void PostprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000185
Chris Lattner655e7df2005-11-16 01:54:32 +0000186// Include the pieces autogenerated from the target description.
187#include "X86GenDAGISel.inc"
188
189 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000190 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000191
Sanjay Patel85030aa2015-10-13 16:23:00 +0000192 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
193 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
194 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
195 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Craig Topperc314f462017-11-13 17:53:59 +0000196 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000197 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000198 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000199 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000200 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000202 SDValue &Scale, SDValue &Index, SDValue &Disp,
203 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000204 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000205 SDValue &Scale, SDValue &Index, SDValue &Disp,
206 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000207 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
208 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000209 SDValue &Scale, SDValue &Index, SDValue &Disp,
210 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000211 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000212 SDValue &Scale, SDValue &Index, SDValue &Disp,
213 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000214 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000215 SDValue &Scale, SDValue &Index, SDValue &Disp,
216 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000217 bool selectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000218 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000219 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000220 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000221 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000222 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000223
Craig Topper78a77042017-11-08 20:17:33 +0000224 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000225 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000226 SDValue &Index, SDValue &Disp,
227 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000228
Craig Topperd6564102018-04-27 22:15:33 +0000229 // Convenience method where P is also root.
Craig Topper78a77042017-11-08 20:17:33 +0000230 bool tryFoldLoad(SDNode *P, SDValue N,
231 SDValue &Base, SDValue &Scale,
232 SDValue &Index, SDValue &Disp,
233 SDValue &Segment) {
234 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
235 }
236
Craig Topperd6564102018-04-27 22:15:33 +0000237 // Try to fold a vector load. This makes sure the load isn't non-temporal.
238 bool tryFoldVecLoad(SDNode *Root, SDNode *P, SDValue N,
239 SDValue &Base, SDValue &Scale,
240 SDValue &Index, SDValue &Disp,
241 SDValue &Segment);
242
Sanjay Patelb5723d02015-10-13 15:12:27 +0000243 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000244 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000245 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000246 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000247
Sanjay Patel85030aa2015-10-13 16:23:00 +0000248 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000249
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000250 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000251 SDValue &Base, SDValue &Scale,
252 SDValue &Index, SDValue &Disp,
253 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000254 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000255 ? CurDAG->getTargetFrameIndex(
256 AM.Base_FrameIndex,
257 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000258 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000259 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000260 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000261 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000262 // is 32-bit.
263 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000264 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000265 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000266 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000267 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000268 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000269 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000270 else if (AM.ES) {
271 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000272 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000273 } else if (AM.MCSym) {
274 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
275 assert(AM.SymbolFlags == 0 && "oo");
276 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000277 } else if (AM.JT != -1) {
278 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000279 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000280 } else if (AM.BlockAddr)
281 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
282 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000283 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000284 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000285
286 if (AM.Segment.getNode())
287 Segment = AM.Segment;
288 else
Owen Anderson9f944592009-08-11 20:47:22 +0000289 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000290 }
291
Michael Kuperstein243c0732015-08-11 14:10:58 +0000292 // Utility function to determine whether we should avoid selecting
293 // immediate forms of instructions for better code size or not.
294 // At a high level, we'd like to avoid such instructions when
295 // we have similar constants used within the same basic block
296 // that can be kept in a register.
297 //
298 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
299 uint32_t UseCount = 0;
300
301 // Do not want to hoist if we're not optimizing for size.
302 // TODO: We'd like to remove this restriction.
303 // See the comment in X86InstrInfo.td for more info.
304 if (!OptForSize)
305 return false;
306
307 // Walk all the users of the immediate.
308 for (SDNode::use_iterator UI = N->use_begin(),
309 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000310
Michael Kuperstein243c0732015-08-11 14:10:58 +0000311 SDNode *User = *UI;
312
313 // This user is already selected. Count it as a legitimate use and
314 // move on.
315 if (User->isMachineOpcode()) {
316 UseCount++;
317 continue;
318 }
319
320 // We want to count stores of immediates as real uses.
321 if (User->getOpcode() == ISD::STORE &&
322 User->getOperand(1).getNode() == N) {
323 UseCount++;
324 continue;
325 }
326
327 // We don't currently match users that have > 2 operands (except
328 // for stores, which are handled above)
329 // Those instruction won't match in ISEL, for now, and would
330 // be counted incorrectly.
331 // This may change in the future as we add additional instruction
332 // types.
333 if (User->getNumOperands() != 2)
334 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000335
Michael Kuperstein243c0732015-08-11 14:10:58 +0000336 // Immediates that are used for offsets as part of stack
337 // manipulation should be left alone. These are typically
338 // used to indicate SP offsets for argument passing and
339 // will get pulled into stores/pushes (implicitly).
340 if (User->getOpcode() == X86ISD::ADD ||
341 User->getOpcode() == ISD::ADD ||
342 User->getOpcode() == X86ISD::SUB ||
343 User->getOpcode() == ISD::SUB) {
344
345 // Find the other operand of the add/sub.
346 SDValue OtherOp = User->getOperand(0);
347 if (OtherOp.getNode() == N)
348 OtherOp = User->getOperand(1);
349
350 // Don't count if the other operand is SP.
351 RegisterSDNode *RegNode;
352 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
353 (RegNode = dyn_cast_or_null<RegisterSDNode>(
354 OtherOp->getOperand(1).getNode())))
355 if ((RegNode->getReg() == X86::ESP) ||
356 (RegNode->getReg() == X86::RSP))
357 continue;
358 }
359
360 // ... otherwise, count this and move on.
361 UseCount++;
362 }
363
364 // If we have more than 1 use, then recommend for hoisting.
365 return (UseCount > 1);
366 }
367
Sanjay Patelb5723d02015-10-13 15:12:27 +0000368 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000369 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000370 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000371 }
372
Sanjay Patelb5723d02015-10-13 15:12:27 +0000373 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000374 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000375 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000376 }
Evan Chengd49cc362006-02-10 22:24:32 +0000377
Craig Topper2b2d8c52018-02-15 19:57:35 +0000378 /// Return a target constant with the specified value, of type i64.
379 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
380 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
381 }
382
Craig Topper092c2f42017-09-23 05:34:07 +0000383 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
384 const SDLoc &DL) {
385 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
386 uint64_t Index = N->getConstantOperandVal(1);
387 MVT VecVT = N->getOperand(0).getSimpleValueType();
Craig Topper9563cab2017-10-08 01:33:42 +0000388 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000389 }
390
391 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
392 const SDLoc &DL) {
393 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
394 uint64_t Index = N->getConstantOperandVal(2);
395 MVT VecVT = N->getSimpleValueType(0);
Craig Topper9563cab2017-10-08 01:33:42 +0000396 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000397 }
398
Sanjay Patelb5723d02015-10-13 15:12:27 +0000399 /// Return an SDNode that returns the value of the global base register.
400 /// Output instructions required to initialize the global base register,
401 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000402 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000403
Sanjay Patelb5723d02015-10-13 15:12:27 +0000404 /// Return a reference to the TargetMachine, casted to the target-specific
405 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000406 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000407 return static_cast<const X86TargetMachine &>(TM);
408 }
409
Sanjay Patelb5723d02015-10-13 15:12:27 +0000410 /// Return a reference to the TargetInstrInfo, casted to the target-specific
411 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000412 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000413 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000414 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000415
416 /// \brief Address-mode matching performs shift-of-and to and-of-shift
417 /// reassociation in order to expose more scaled addressing
418 /// opportunities.
419 bool ComplexPatternFuncMutatesDAG() const override {
420 return true;
421 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000422
423 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
424
425 /// Returns whether this is a relocatable immediate in the range
426 /// [-2^Width .. 2^Width-1].
427 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
428 if (auto *CN = dyn_cast<ConstantSDNode>(N))
429 return isInt<Width>(CN->getSExtValue());
430 return isSExtAbsoluteSymbolRef(Width, N);
431 }
Craig Topper4de6f582017-08-19 23:21:22 +0000432
433 // Indicates we should prefer to use a non-temporal load for this load.
434 bool useNonTemporalLoad(LoadSDNode *N) const {
435 if (!N->isNonTemporal())
436 return false;
437
438 unsigned StoreSize = N->getMemoryVT().getStoreSize();
439
440 if (N->getAlignment() < StoreSize)
441 return false;
442
443 switch (StoreSize) {
444 default: llvm_unreachable("Unsupported store size");
445 case 16:
446 return Subtarget->hasSSE41();
447 case 32:
448 return Subtarget->hasAVX2();
449 case 64:
450 return Subtarget->hasAVX512();
451 }
452 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000453
454 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000455 bool matchBEXTRFromAnd(SDNode *Node);
Sanjay Patel74a1eef2018-01-19 16:37:25 +0000456 bool shrinkAndImmediate(SDNode *N);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000457 bool isMaskZeroExtended(SDNode *N) const;
Craig Topperd6564102018-04-27 22:15:33 +0000458
459 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
460 const SDLoc &dl, MVT VT, SDNode *Node);
461 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
462 const SDLoc &dl, MVT VT, SDNode *Node,
463 SDValue &InFlag);
Chris Lattner655e7df2005-11-16 01:54:32 +0000464 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000465}
466
Evan Cheng72bb66a2006-08-08 00:31:00 +0000467
Craig Topperba3cc2e2017-09-25 18:43:13 +0000468// Returns true if this masked compare can be implemented legally with this
469// type.
470static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
Uriel Korachbb866862017-11-06 09:22:38 +0000471 unsigned Opcode = N->getOpcode();
Craig Topper15d69732018-01-28 00:56:30 +0000472 if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMU ||
Craig Topper48d5ed22018-02-28 08:14:28 +0000473 Opcode == X86ISD::CMPM_RND || Opcode == X86ISD::VFPCLASS) {
Craig Topperba3cc2e2017-09-25 18:43:13 +0000474 // We can get 256-bit 8 element types here without VLX being enabled. When
475 // this happens we will use 512-bit operations and the mask will not be
476 // zero extended.
Uriel Koracheb47d952017-11-06 08:32:45 +0000477 EVT OpVT = N->getOperand(0).getValueType();
Craig Topperd58c1652018-01-07 18:20:37 +0000478 if (OpVT.is256BitVector() || OpVT.is128BitVector())
Craig Topperba3cc2e2017-09-25 18:43:13 +0000479 return Subtarget->hasVLX();
480
481 return true;
482 }
Craig Topper48d5ed22018-02-28 08:14:28 +0000483 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
484 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
485 Opcode == X86ISD::FSETCCM_RND)
486 return true;
Craig Topperba3cc2e2017-09-25 18:43:13 +0000487
488 return false;
489}
490
491// Returns true if we can assume the writer of the mask has zero extended it
492// for us.
493bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
494 // If this is an AND, check if we have a compare on either side. As long as
495 // one side guarantees the mask is zero extended, the AND will preserve those
496 // zeros.
497 if (N->getOpcode() == ISD::AND)
498 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
499 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
500
501 return isLegalMaskCompare(N, Subtarget);
502}
503
Evan Cheng5e73ff22010-02-15 19:41:07 +0000504bool
505X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000506 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000507
Evan Cheng5e73ff22010-02-15 19:41:07 +0000508 if (!N.hasOneUse())
509 return false;
510
511 if (N.getOpcode() != ISD::LOAD)
512 return true;
513
514 // If N is a load, do additional profitability checks.
515 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000516 switch (U->getOpcode()) {
517 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000518 case X86ISD::ADD:
519 case X86ISD::SUB:
520 case X86ISD::AND:
521 case X86ISD::XOR:
522 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000523 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000524 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000525 case ISD::AND:
526 case ISD::OR:
527 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000528 SDValue Op1 = U->getOperand(1);
529
Evan Cheng83bdb382008-11-27 00:49:46 +0000530 // If the other operand is a 8-bit immediate we should fold the immediate
531 // instead. This reduces code size.
532 // e.g.
533 // movl 4(%esp), %eax
534 // addl $4, %eax
535 // vs.
536 // movl $4, %eax
537 // addl 4(%esp), %eax
538 // The former is 2 bytes shorter. In case where the increment is 1, then
539 // the saving can be 4 bytes (by using incl %eax).
Craig Topper7e42af82018-04-10 03:44:15 +0000540 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
Dan Gohman2293eb62009-03-14 02:07:16 +0000541 if (Imm->getAPIntValue().isSignedIntN(8))
542 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000543
Craig Topper7e42af82018-04-10 03:44:15 +0000544 // If this is a 64-bit AND with an immediate that fits in 32-bits,
545 // prefer using the smaller and over folding the load. This is needed to
546 // make sure immediates created by shrinkAndImmediate are always folded.
547 // Ideally we would narrow the load during DAG combine and get the
548 // best of both worlds.
549 if (U->getOpcode() == ISD::AND &&
550 Imm->getAPIntValue().getBitWidth() == 64 &&
551 Imm->getAPIntValue().isIntN(32))
552 return false;
553 }
554
Rafael Espindolabb834f02009-04-10 10:09:34 +0000555 // If the other operand is a TLS address, we should fold it instead.
556 // This produces
557 // movl %gs:0, %eax
558 // leal i@NTPOFF(%eax), %eax
559 // instead of
560 // movl $i@NTPOFF, %eax
561 // addl %gs:0, %eax
562 // if the block also has an access to a second TLS address this will save
563 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000564 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000565 if (Op1.getOpcode() == X86ISD::Wrapper) {
566 SDValue Val = Op1.getOperand(0);
567 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
568 return false;
569 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000570 }
571 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000572 }
573
574 return true;
575}
576
Sanjay Patelb5723d02015-10-13 15:12:27 +0000577/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000578/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000579static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
580 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000581 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000582 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000583 if (Chain.getNode() == Load.getNode())
584 Ops.push_back(Load.getOperand(0));
585 else {
586 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000587 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000588 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
589 if (Chain.getOperand(i).getNode() == Load.getNode())
590 Ops.push_back(Load.getOperand(0));
591 else
592 Ops.push_back(Chain.getOperand(i));
593 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000594 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000595 Ops.clear();
596 Ops.push_back(NewChain);
597 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000598 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000599 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000600 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000601 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000602
Evan Chengf00f1e52008-08-25 21:27:18 +0000603 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000604 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000605 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000606 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000607}
608
Sanjay Patelb5723d02015-10-13 15:12:27 +0000609/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000610/// moved below CALLSEQ_START and the chains leading up to the call.
611/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000612/// In the case of a tail call, there isn't a callseq node between the call
613/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000614static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000615 // The transformation is somewhat dangerous if the call's chain was glued to
616 // the call. After MoveBelowOrigChain the load is moved between the call and
617 // the chain, this can create a cycle if the load is not folded. So it is
618 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000619 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000620 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000621 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000622 if (!LD ||
623 LD->isVolatile() ||
624 LD->getAddressingMode() != ISD::UNINDEXED ||
625 LD->getExtensionType() != ISD::NON_EXTLOAD)
626 return false;
627
628 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000629 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000630 if (!Chain.hasOneUse())
631 return false;
632 Chain = Chain.getOperand(0);
633 }
Evan Chengd703df62010-03-14 03:48:46 +0000634
635 if (!Chain.getNumOperands())
636 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000637 // Since we are not checking for AA here, conservatively abort if the chain
638 // writes to memory. It's not safe to move the callee (a load) across a store.
639 if (isa<MemSDNode>(Chain.getNode()) &&
640 cast<MemSDNode>(Chain.getNode())->writeMem())
641 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000642 if (Chain.getOperand(0).getNode() == Callee.getNode())
643 return true;
644 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000645 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
646 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000647 return true;
648 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000649}
650
Chris Lattner8d637042010-03-02 23:12:51 +0000651void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000652 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Matthias Braunf1caa282017-12-15 22:22:58 +0000653 OptForSize = MF->getFunction().optForSize();
654 OptForMinSize = MF->getFunction().optForMinSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000655 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000656
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000657 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
658 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000659 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000660
Craig Topper7e910a92018-02-01 17:08:39 +0000661 // If this is a target specific AND node with no flag usages, turn it back
662 // into ISD::AND to enable test instruction matching.
663 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
664 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
665 N->getOperand(0), N->getOperand(1));
666 --I;
667 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
668 ++I;
669 CurDAG->DeleteNode(N);
670 }
671
Evan Chengd703df62010-03-14 03:48:46 +0000672 if (OptLevel != CodeGenOpt::None &&
Chandler Carruthc58f2162018-01-22 22:05:25 +0000673 // Only do this when the target can fold the load into the call or
674 // jmp.
675 !Subtarget->useRetpoline() &&
Craig Topper62c47a22017-08-29 05:14:27 +0000676 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000677 (N->getOpcode() == X86ISD::TC_RETURN &&
Evan Cheng847ad442012-10-05 01:48:22 +0000678 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000679 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000680 /// Also try moving call address load from outside callseq_start to just
681 /// before the call to allow it to be folded.
682 ///
683 /// [Load chain]
684 /// ^
685 /// |
686 /// [Load]
687 /// ^ ^
688 /// | |
689 /// / \--
690 /// / |
691 ///[CALLSEQ_START] |
692 /// ^ |
693 /// | |
694 /// [LOAD/C2Reg] |
695 /// | |
696 /// \ /
697 /// \ /
698 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000699 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000700 SDValue Chain = N->getOperand(0);
701 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000702 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000703 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000704 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000705 ++NumLoadMoved;
706 continue;
707 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000708
Chris Lattner8d637042010-03-02 23:12:51 +0000709 // Lower fpround and fpextend nodes that target the FP stack to be store and
710 // load to the stack. This is a gross hack. We would like to simply mark
711 // these as being illegal, but when we do that, legalize produces these when
712 // it expands calls, then expands these in the same legalize pass. We would
713 // like dag combine to be able to hack on these between the call expansion
714 // and the node legalization. As such this pass basically does "really
715 // late" legalization of these inline with the X86 isel pass.
716 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000717 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
718 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000719
Craig Topper83e042a2013-08-15 05:57:07 +0000720 MVT SrcVT = N->getOperand(0).getSimpleValueType();
721 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000722
723 // If any of the sources are vectors, no fp stack involved.
724 if (SrcVT.isVector() || DstVT.isVector())
725 continue;
726
727 // If the source and destination are SSE registers, then this is a legal
728 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000729 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000730 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000731 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
732 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000733 if (SrcIsSSE && DstIsSSE)
734 continue;
735
Chris Lattnerd587e582008-03-09 07:05:32 +0000736 if (!SrcIsSSE && !DstIsSSE) {
737 // If this is an FPStack extension, it is a noop.
738 if (N->getOpcode() == ISD::FP_EXTEND)
739 continue;
740 // If this is a value-preserving FPStack truncation, it is a noop.
741 if (N->getConstantOperandVal(1))
742 continue;
743 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000744
Chris Lattnera91f77e2008-01-24 08:07:48 +0000745 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
746 // FPStack has extload and truncstore. SSE can fold direct loads into other
747 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000748 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000749 if (N->getOpcode() == ISD::FP_ROUND)
750 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
751 else
752 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000753
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000754 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000755 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000756
Chris Lattnera91f77e2008-01-24 08:07:48 +0000757 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000758 SDValue Store =
759 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
760 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000761 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000762 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000763
764 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
765 // extload we created. This will cause general havok on the dag because
766 // anything below the conversion could be folded into other existing nodes.
767 // To avoid invalidating 'I', back it up to the convert node.
768 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000769 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000770
Chris Lattnera91f77e2008-01-24 08:07:48 +0000771 // Now that we did that, the node is dead. Increment the iterator to the
772 // next node to process, then delete N.
773 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000774 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000775 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000776}
777
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000778
Craig Toppere6913ec2018-03-16 17:13:42 +0000779void X86DAGToDAGISel::PostprocessISelDAG() {
780 // Skip peepholes at -O0.
781 if (TM.getOptLevel() == CodeGenOpt::None)
782 return;
783
784 // Attempt to remove vectors moves that were inserted to zero upper bits.
785
786 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
787 ++Position;
788
789 while (Position != CurDAG->allnodes_begin()) {
790 SDNode *N = &*--Position;
791 // Skip dead nodes and any non-machine opcodes.
792 if (N->use_empty() || !N->isMachineOpcode())
793 continue;
794
795 if (N->getMachineOpcode() != TargetOpcode::SUBREG_TO_REG)
796 continue;
797
798 unsigned SubRegIdx = N->getConstantOperandVal(2);
799 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
800 continue;
801
802 SDValue Move = N->getOperand(1);
803 if (!Move.isMachineOpcode())
804 continue;
805
806 // Make sure its one of the move opcodes we recognize.
807 switch (Move.getMachineOpcode()) {
808 default:
809 continue;
810 case X86::VMOVAPDrr: case X86::VMOVUPDrr:
811 case X86::VMOVAPSrr: case X86::VMOVUPSrr:
812 case X86::VMOVDQArr: case X86::VMOVDQUrr:
813 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr:
814 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr:
815 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr:
816 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr:
817 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr:
818 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
819 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
820 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr:
821 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr:
822 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
823 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
824 break;
825 }
826
827 SDValue In = Move.getOperand(0);
828 if (!In.isMachineOpcode() ||
829 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
830 continue;
831
832 // Producing instruction is another vector instruction. We can drop the
833 // move.
834 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
835
836 // If the move is now dead, delete it.
837 if (Move.getNode()->use_empty())
838 CurDAG->RemoveDeadNode(Move.getNode());
839 }
840}
841
842
Sanjay Patelb5723d02015-10-13 15:12:27 +0000843/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000844void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000845 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000846 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000847 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000848
849 TargetLowering::CallLoweringInfo CLI(*CurDAG);
850 CLI.setChain(CurDAG->getRoot())
851 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000852 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000853 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000854 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
855 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
856 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000857 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000858}
859
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000860void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000861 // If this is main, emit special code for main.
Matthias Braunf1caa282017-12-15 22:22:58 +0000862 const Function &F = MF->getFunction();
863 if (F.hasExternalLinkage() && F.getName() == "main")
864 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000865}
866
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000867static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000868 // On 64-bit platforms, we can run into an issue where a frame index
869 // includes a displacement that, when added to the explicit displacement,
870 // will overflow the displacement field. Assuming that the frame index
871 // displacement fits into a 31-bit integer (which is only slightly more
872 // aggressive than the current fundamental assumption that it fits into
873 // a 32-bit integer), a 31-bit disp should always be safe.
874 return isInt<31>(Val);
875}
876
Sanjay Patel85030aa2015-10-13 16:23:00 +0000877bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000878 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000879 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000880 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000881 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000882 int64_t Val = AM.Disp + Offset;
883 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000884 if (Subtarget->is64Bit()) {
885 if (!X86::isOffsetSuitableForCodeModel(Val, M,
886 AM.hasSymbolicDisplacement()))
887 return true;
888 // In addition to the checks required for a register base, check that
889 // we do not try to use an unsafe Disp with a frame index.
890 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
891 !isDispSafeForFrameIndex(Val))
892 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000893 }
Eli Friedman344ec792011-07-13 21:29:53 +0000894 AM.Disp = Val;
895 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000896
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000897}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000898
Sanjay Patel85030aa2015-10-13 16:23:00 +0000899bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000900 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000901
Chris Lattner8a236b62010-09-22 04:39:11 +0000902 // load gs:0 -> GS segment register.
903 // load fs:0 -> FS segment register.
904 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000905 // This optimization is valid because the GNU TLS model defines that
906 // gs:0 (or fs:0 on X86-64) contains its own address.
907 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000908 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000909 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000910 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
911 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000912 switch (N->getPointerInfo().getAddrSpace()) {
913 case 256:
914 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
915 return false;
916 case 257:
917 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
918 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000919 // Address space 258 is not handled here, because it is not used to
920 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000921 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000922
Rafael Espindola3b2df102009-04-08 21:14:34 +0000923 return true;
924}
925
Sanjay Patelb5723d02015-10-13 15:12:27 +0000926/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
927/// mode. These wrap things that will resolve down into a symbol reference.
928/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000929bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000930 // If the addressing mode already has a symbol as the displacement, we can
931 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000932 if (AM.hasSymbolicDisplacement())
933 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000934
935 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000936 CodeModel::Model M = TM.getCodeModel();
937
Chris Lattnerfea81da2009-06-27 04:16:01 +0000938 // Handle X86-64 rip-relative addresses. We check this before checking direct
939 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000940 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000941 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
942 // they cannot be folded into immediate fields.
943 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000944 (M == CodeModel::Small || M == CodeModel::Kernel)) {
945 // Base and index reg must be 0 in order to use %rip as base.
946 if (AM.hasBaseOrIndexReg())
947 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000948 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000949 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000950 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000951 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000952 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000953 AM = Backup;
954 return true;
955 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000956 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000957 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000958 AM.CP = CP->getConstVal();
959 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000960 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000961 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000962 AM = Backup;
963 return true;
964 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000965 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
966 AM.ES = S->getSymbol();
967 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000968 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
969 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000970 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000971 AM.JT = J->getIndex();
972 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000973 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
974 X86ISelAddressMode Backup = AM;
975 AM.BlockAddr = BA->getBlockAddress();
976 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000977 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000978 AM = Backup;
979 return true;
980 }
981 } else
982 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000983
Chris Lattnerfea81da2009-06-27 04:16:01 +0000984 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000985 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000986 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000987 }
988
989 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000990 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
991 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000992 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000993 M == CodeModel::Small || M == CodeModel::Kernel) {
994 assert(N.getOpcode() != X86ISD::WrapperRIP &&
995 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000996 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
997 AM.GV = G->getGlobal();
998 AM.Disp += G->getOffset();
999 AM.SymbolFlags = G->getTargetFlags();
1000 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1001 AM.CP = CP->getConstVal();
1002 AM.Align = CP->getAlignment();
1003 AM.Disp += CP->getOffset();
1004 AM.SymbolFlags = CP->getTargetFlags();
1005 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1006 AM.ES = S->getSymbol();
1007 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +00001008 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1009 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +00001010 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +00001011 AM.JT = J->getIndex();
1012 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +00001013 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1014 AM.BlockAddr = BA->getBlockAddress();
1015 AM.Disp += BA->getOffset();
1016 AM.SymbolFlags = BA->getTargetFlags();
1017 } else
1018 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001019 return false;
1020 }
1021
1022 return true;
1023}
1024
Sanjay Patelb5723d02015-10-13 15:12:27 +00001025/// Add the specified node to the specified addressing mode, returning true if
1026/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001027bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1028 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +00001029 return true;
1030
1031 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1032 // a smaller encoding and avoids a scaled-index.
1033 if (AM.Scale == 2 &&
1034 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001035 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001036 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +00001037 AM.Scale = 1;
1038 }
1039
Dan Gohman05046082009-08-20 18:23:44 +00001040 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1041 // because it has a smaller encoding.
1042 // TODO: Which other code models can use this?
1043 if (TM.getCodeModel() == CodeModel::Small &&
1044 Subtarget->is64Bit() &&
1045 AM.Scale == 1 &&
1046 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001047 AM.Base_Reg.getNode() == nullptr &&
1048 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +00001049 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +00001050 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001051 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +00001052
Dan Gohman824ab402009-07-22 23:26:55 +00001053 return false;
1054}
1055
Sanjay Patelefab8b02015-10-21 18:56:06 +00001056bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
1057 unsigned Depth) {
1058 // Add an artificial use to this node so that we can keep track of
1059 // it if it gets CSE'd with a different node.
1060 HandleSDNode Handle(N);
1061
1062 X86ISelAddressMode Backup = AM;
1063 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1064 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1065 return false;
1066 AM = Backup;
1067
1068 // Try again after commuting the operands.
1069 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
1070 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1071 return false;
1072 AM = Backup;
1073
1074 // If we couldn't fold both operands into the address at the same time,
1075 // see if we can just put each operand into a register and fold at least
1076 // the add.
1077 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1078 !AM.Base_Reg.getNode() &&
1079 !AM.IndexReg.getNode()) {
1080 N = Handle.getValue();
1081 AM.Base_Reg = N.getOperand(0);
1082 AM.IndexReg = N.getOperand(1);
1083 AM.Scale = 1;
1084 return false;
1085 }
1086 N = Handle.getValue();
1087 return true;
1088}
1089
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001090// Insert a node into the DAG at least before the Pos node's position. This
1091// will reposition the node as needed, and will assign it a node ID that is <=
1092// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1093// IDs! The selection DAG must no longer depend on their uniqueness when this
1094// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001095static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Nirav Dave8c5f47a2018-03-22 19:32:07 +00001096 if (N->getNodeId() == -1 ||
1097 (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1098 SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1099 DAG.RepositionNode(Pos->getIterator(), N.getNode());
1100 // Mark Node as invalid for pruning as after this it may be a successor to a
1101 // selected node but otherwise be in the same position of Pos.
1102 // Conservatively mark it with the same -abs(Id) to assure node id
1103 // invariant is preserved.
1104 N->setNodeId(Pos->getNodeId());
1105 SelectionDAGISel::InvalidateNodeId(N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001106 }
1107}
1108
Adam Nemet0c7caf42014-09-16 17:14:10 +00001109// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1110// safe. This allows us to convert the shift and and into an h-register
1111// extract and a scaled index. Returns false if the simplification is
1112// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001113static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1114 uint64_t Mask,
1115 SDValue Shift, SDValue X,
1116 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001117 if (Shift.getOpcode() != ISD::SRL ||
1118 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1119 !Shift.hasOneUse())
1120 return true;
1121
1122 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1123 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1124 Mask != (0xffu << ScaleLog))
1125 return true;
1126
Craig Topper83e042a2013-08-15 05:57:07 +00001127 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001128 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001129 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1130 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001131 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1132 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001133 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001134 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1135
Chandler Carrutheb21da02012-01-12 01:34:44 +00001136 // Insert the new nodes into the topological ordering. We must do this in
1137 // a valid topological ordering as nothing is going to go back and re-sort
1138 // these nodes. We continually insert before 'N' in sequence as this is
1139 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1140 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001141 insertDAGNode(DAG, N, Eight);
1142 insertDAGNode(DAG, N, Srl);
1143 insertDAGNode(DAG, N, NewMask);
1144 insertDAGNode(DAG, N, And);
1145 insertDAGNode(DAG, N, ShlCount);
1146 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001147 DAG.ReplaceAllUsesWith(N, Shl);
1148 AM.IndexReg = And;
1149 AM.Scale = (1 << ScaleLog);
1150 return false;
1151}
1152
Chandler Carruthaa01e662012-01-11 09:35:00 +00001153// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1154// allows us to fold the shift into this addressing mode. Returns false if the
1155// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001156static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1157 uint64_t Mask,
1158 SDValue Shift, SDValue X,
1159 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001160 if (Shift.getOpcode() != ISD::SHL ||
1161 !isa<ConstantSDNode>(Shift.getOperand(1)))
1162 return true;
1163
1164 // Not likely to be profitable if either the AND or SHIFT node has more
1165 // than one use (unless all uses are for address computation). Besides,
1166 // isel mechanism requires their node ids to be reused.
1167 if (!N.hasOneUse() || !Shift.hasOneUse())
1168 return true;
1169
1170 // Verify that the shift amount is something we can fold.
1171 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1172 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1173 return true;
1174
Craig Topper83e042a2013-08-15 05:57:07 +00001175 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001176 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001177 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001178 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1179 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1180
Chandler Carrutheb21da02012-01-12 01:34:44 +00001181 // Insert the new nodes into the topological ordering. We must do this in
1182 // a valid topological ordering as nothing is going to go back and re-sort
1183 // these nodes. We continually insert before 'N' in sequence as this is
1184 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1185 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001186 insertDAGNode(DAG, N, NewMask);
1187 insertDAGNode(DAG, N, NewAnd);
1188 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001189 DAG.ReplaceAllUsesWith(N, NewShift);
1190
1191 AM.Scale = 1 << ShiftAmt;
1192 AM.IndexReg = NewAnd;
1193 return false;
1194}
1195
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001196// Implement some heroics to detect shifts of masked values where the mask can
1197// be replaced by extending the shift and undoing that in the addressing mode
1198// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1199// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1200// the addressing mode. This results in code such as:
1201//
1202// int f(short *y, int *lookup_table) {
1203// ...
1204// return *y + lookup_table[*y >> 11];
1205// }
1206//
1207// Turning into:
1208// movzwl (%rdi), %eax
1209// movl %eax, %ecx
1210// shrl $11, %ecx
1211// addl (%rsi,%rcx,4), %eax
1212//
1213// Instead of:
1214// movzwl (%rdi), %eax
1215// movl %eax, %ecx
1216// shrl $9, %ecx
1217// andl $124, %rcx
1218// addl (%rsi,%rcx), %eax
1219//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001220// Note that this function assumes the mask is provided as a mask *after* the
1221// value is shifted. The input chain may or may not match that, but computing
1222// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001223static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1224 uint64_t Mask,
1225 SDValue Shift, SDValue X,
1226 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001227 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1228 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001229 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001230
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001231 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001232 unsigned MaskLZ = countLeadingZeros(Mask);
1233 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001234
1235 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001236 // from the trailing zeros of the mask.
1237 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001238
1239 // There is nothing we can do here unless the mask is removing some bits.
1240 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1241 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1242
1243 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001244 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001245
1246 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001247 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001248 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1249 if (MaskLZ < ScaleDown)
1250 return true;
1251 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001252
1253 // The final check is to ensure that any masked out high bits of X are
1254 // already known to be zero. Otherwise, the mask has a semantic impact
1255 // other than masking out a couple of low bits. Unfortunately, because of
1256 // the mask, zero extensions will be removed from operands in some cases.
1257 // This code works extra hard to look through extensions because we can
1258 // replace them with zero extensions cheaply if necessary.
1259 bool ReplacingAnyExtend = false;
1260 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001261 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1262 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001263 // Assume that we'll replace the any-extend with a zero-extend, and
1264 // narrow the search to the extended value.
1265 X = X.getOperand(0);
1266 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1267 ReplacingAnyExtend = true;
1268 }
Craig Topper83e042a2013-08-15 05:57:07 +00001269 APInt MaskedHighBits =
1270 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001271 KnownBits Known;
1272 DAG.computeKnownBits(X, Known);
1273 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001274
1275 // We've identified a pattern that can be transformed into a single shift
1276 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001277 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001278 if (ReplacingAnyExtend) {
1279 assert(X.getValueType() != VT);
1280 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001281 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001282 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001283 X = NewX;
1284 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001285 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001286 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001287 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001288 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001289 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001290
1291 // Insert the new nodes into the topological ordering. We must do this in
1292 // a valid topological ordering as nothing is going to go back and re-sort
1293 // these nodes. We continually insert before 'N' in sequence as this is
1294 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1295 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001296 insertDAGNode(DAG, N, NewSRLAmt);
1297 insertDAGNode(DAG, N, NewSRL);
1298 insertDAGNode(DAG, N, NewSHLAmt);
1299 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001300 DAG.ReplaceAllUsesWith(N, NewSHL);
1301
1302 AM.Scale = 1 << AMShiftAmt;
1303 AM.IndexReg = NewSRL;
1304 return false;
1305}
Matt Morehouse9e658c92017-12-01 22:20:26 +00001306
Sanjay Patel85030aa2015-10-13 16:23:00 +00001307bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001308 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001309 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001310 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001311 dbgs() << "MatchAddress: ";
Craig Topper25007c42018-03-16 21:10:07 +00001312 AM.dump(CurDAG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001313 });
Matt Morehouse9e658c92017-12-01 22:20:26 +00001314 // Limit recursion.
1315 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001316 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001317
Chris Lattnerfea81da2009-06-27 04:16:01 +00001318 // If this is already a %rip relative address, we can only merge immediates
1319 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001320 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001321 if (AM.isRIPRelative()) {
1322 // FIXME: JumpTable and ExternalSymbol address currently don't like
1323 // displacements. It isn't very important, but this should be fixed for
1324 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001325 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1326 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001327
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001328 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001329 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001330 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001331 return true;
1332 }
1333
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001334 switch (N.getOpcode()) {
1335 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001336 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001337 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001338 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1339 // Use the symbol and don't prefix it.
1340 AM.MCSym = ESNode->getMCSymbol();
1341 return false;
1342 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001343 break;
1344 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001345 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001346 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001347 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001348 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001349 break;
1350 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001351
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001352 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001353 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001354 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001355 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001356 break;
1357
Rafael Espindola3b2df102009-04-08 21:14:34 +00001358 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001359 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001360 return false;
1361 break;
1362
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001363 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001364 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001365 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001366 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001367 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001368 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001369 return false;
1370 }
1371 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001372
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001373 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001374 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001375 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001376
Simon Pilgrim7f032312017-05-12 13:08:45 +00001377 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001378 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001379 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1380 // that the base operand remains free for further matching. If
1381 // the base doesn't end up getting used, a post-processing step
1382 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001383 if (Val == 1 || Val == 2 || Val == 3) {
1384 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001385 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001386
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001387 // Okay, we know that we have a scale by now. However, if the scaled
1388 // value is an add of something and a constant, we can fold the
1389 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001390 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001391 AM.IndexReg = ShVal.getOperand(0);
1392 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001393 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001394 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001395 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001396 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001397
1398 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001399 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001400 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001401 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001402 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001403
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001404 case ISD::SRL: {
1405 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001406 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001407
1408 SDValue And = N.getOperand(0);
1409 if (And.getOpcode() != ISD::AND) break;
1410 SDValue X = And.getOperand(0);
1411
1412 // We only handle up to 64-bit values here as those are what matter for
1413 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001414 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001415
1416 // The mask used for the transform is expected to be post-shift, but we
1417 // found the shift first so just apply the shift to the mask before passing
1418 // it down.
1419 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1420 !isa<ConstantSDNode>(And.getOperand(1)))
1421 break;
1422 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1423
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001424 // Try to fold the mask and shift into the scale, and return false if we
1425 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001426 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001427 return false;
1428 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001429 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001430
Dan Gohmanbf474952007-10-22 20:22:24 +00001431 case ISD::SMUL_LOHI:
1432 case ISD::UMUL_LOHI:
1433 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001434 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001435 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001436 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001437 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001438 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001439 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001440 AM.Base_Reg.getNode() == nullptr &&
1441 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001442 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001443 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1444 CN->getZExtValue() == 9) {
1445 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001446
Simon Pilgrim7f032312017-05-12 13:08:45 +00001447 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001448 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001449
1450 // Okay, we know that we have a scale by now. However, if the scaled
1451 // value is an add of something and a constant, we can fold the
1452 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001453 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001454 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1455 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001456 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001457 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001458 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001459 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001460 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001461 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001462 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001463 }
1464
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001465 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001466 return false;
1467 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001468 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001469 break;
1470
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001471 case ISD::SUB: {
1472 // Given A-B, if A can be completely folded into the address and
1473 // the index field with the index field unused, use -B as the index.
1474 // This is a win if a has multiple parts that can be folded into
1475 // the address. Also, this saves a mov if the base register has
1476 // other uses, since it avoids a two-address sub instruction, however
1477 // it costs an additional mov if the index register has other uses.
1478
Dan Gohman99ba4da2010-06-18 01:24:29 +00001479 // Add an artificial use to this node so that we can keep track of
1480 // it if it gets CSE'd with a different node.
1481 HandleSDNode Handle(N);
1482
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001483 // Test if the LHS of the sub can be folded.
1484 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001485 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001486 AM = Backup;
1487 break;
1488 }
1489 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001490 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001491 AM = Backup;
1492 break;
1493 }
Evan Cheng68333f52010-03-17 23:58:35 +00001494
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001495 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001496 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001497 // If the RHS involves a register with multiple uses, this
1498 // transformation incurs an extra mov, due to the neg instruction
1499 // clobbering its operand.
1500 if (!RHS.getNode()->hasOneUse() ||
1501 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1502 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1503 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1504 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001505 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001506 ++Cost;
1507 // If the base is a register with multiple uses, this
1508 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001509 // FIXME: Don't rely on DELETED_NODEs.
1510 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1511 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001512 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001513 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1514 --Cost;
1515 // If the folded LHS was interesting, this transformation saves
1516 // address arithmetic.
1517 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1518 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1519 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1520 --Cost;
1521 // If it doesn't look like it may be an overall win, don't do it.
1522 if (Cost >= 0) {
1523 AM = Backup;
1524 break;
1525 }
1526
1527 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001528 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001529 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1530 AM.IndexReg = Neg;
1531 AM.Scale = 1;
1532
1533 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001534 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1535 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001536 return false;
1537 }
1538
Sanjay Patelefab8b02015-10-21 18:56:06 +00001539 case ISD::ADD:
1540 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001541 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001542 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001543
Sanjay Patel533c10c2015-11-09 23:31:38 +00001544 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001545 // We want to look through a transform in InstCombine and DAGCombiner that
1546 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001547 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001548 // An 'lea' can then be used to match the shift (multiply) and add:
1549 // and $1, %esi
1550 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001551 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1552 !matchAdd(N, AM, Depth))
1553 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001554 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001555
Evan Cheng827d30d2007-12-13 00:43:27 +00001556 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001557 // Perform some heroic transforms on an and of a constant-count shift
1558 // with a constant to enable use of the scaled offset field.
1559
Evan Cheng827d30d2007-12-13 00:43:27 +00001560 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001561 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001562
Chandler Carruthaa01e662012-01-11 09:35:00 +00001563 SDValue Shift = N.getOperand(0);
1564 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001565 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001566
1567 // We only handle up to 64-bit values here as those are what matter for
1568 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001569 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001570
Chandler Carruthb0049f42012-01-11 09:35:04 +00001571 if (!isa<ConstantSDNode>(N.getOperand(1)))
1572 break;
1573 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001574
Chandler Carruth51d30762012-01-11 08:48:20 +00001575 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001576 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001577 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001578
Chandler Carruth51d30762012-01-11 08:48:20 +00001579 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001580 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001581 return false;
1582
Chandler Carruthaa01e662012-01-11 09:35:00 +00001583 // Try to swap the mask and shift to place shifts which can be done as
1584 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001585 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001586 return false;
1587 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001588 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001589 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001590
Sanjay Patel85030aa2015-10-13 16:23:00 +00001591 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001592}
1593
Sanjay Patelb5723d02015-10-13 15:12:27 +00001594/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001595/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001596bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001597 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001598 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001599 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001600 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001601 AM.IndexReg = N;
1602 AM.Scale = 1;
1603 return false;
1604 }
1605
1606 // Otherwise, we cannot select it.
1607 return true;
1608 }
1609
1610 // Default, generate it as a register.
1611 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001612 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001613 return false;
1614}
1615
Craig Topperc314f462017-11-13 17:53:59 +00001616/// Helper for selectVectorAddr. Handles things that can be folded into a
1617/// gather scatter address. The index register and scale should have already
1618/// been handled.
1619bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
1620 // TODO: Support other operations.
1621 switch (N.getOpcode()) {
Craig Topperaf4eb172018-01-10 19:16:05 +00001622 case ISD::Constant: {
1623 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1624 if (!foldOffsetIntoAddress(Val, AM))
1625 return false;
1626 break;
1627 }
Craig Topperc314f462017-11-13 17:53:59 +00001628 case X86ISD::Wrapper:
1629 if (!matchWrapper(N, AM))
1630 return false;
1631 break;
1632 }
1633
1634 return matchAddressBase(N, AM);
1635}
1636
Craig Topperbb001c6d2017-11-10 19:26:04 +00001637bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1638 SDValue &Scale, SDValue &Index,
1639 SDValue &Disp, SDValue &Segment) {
Craig Topperc314f462017-11-13 17:53:59 +00001640 X86ISelAddressMode AM;
Craig Topperee740442017-11-22 08:10:54 +00001641 auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
1642 AM.IndexReg = Mgs->getIndex();
Craig Topperaf4eb172018-01-10 19:16:05 +00001643 AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
Craig Topperbb001c6d2017-11-10 19:26:04 +00001644
Craig Topperbb001c6d2017-11-10 19:26:04 +00001645 unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001646 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001647 if (AddrSpace == 256)
1648 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1649 if (AddrSpace == 257)
1650 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001651 if (AddrSpace == 258)
1652 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001653
Craig Topperaf4eb172018-01-10 19:16:05 +00001654 // Try to match into the base and displacement fields.
1655 if (matchVectorAddress(N, AM))
Craig Topperc314f462017-11-13 17:53:59 +00001656 return false;
1657
1658 MVT VT = N.getSimpleValueType();
1659 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1660 if (!AM.Base_Reg.getNode())
1661 AM.Base_Reg = CurDAG->getRegister(0, VT);
1662 }
1663
1664 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001665 return true;
1666}
1667
Sanjay Patelb5723d02015-10-13 15:12:27 +00001668/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001669/// It returns the operands which make up the maximal addressing mode it can
1670/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001671///
1672/// Parent is the parent node of the addr operand that is being matched. It
1673/// is always a load, store, atomic node, or null. It is only null when
1674/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001675bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001676 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001677 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001678 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001679
Chris Lattner8a236b62010-09-22 04:39:11 +00001680 if (Parent &&
1681 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1682 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001683 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001684 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001685 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1686 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1687 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001688 unsigned AddrSpace =
1689 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001690 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001691 if (AddrSpace == 256)
1692 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1693 if (AddrSpace == 257)
1694 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001695 if (AddrSpace == 258)
1696 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001697 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001698
Sanjay Patel85030aa2015-10-13 16:23:00 +00001699 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001700 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001701
Craig Topper83e042a2013-08-15 05:57:07 +00001702 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001703 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001704 if (!AM.Base_Reg.getNode())
1705 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001706 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001707
Gabor Greiff304a7a2008-08-28 21:40:38 +00001708 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001709 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001710
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001711 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001712 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001713}
1714
Craig Topper8078dd22017-08-21 16:04:04 +00001715// We can only fold a load if all nodes between it and the root node have a
1716// single use. If there are additional uses, we could end up duplicating the
1717// load.
1718static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1719 SDNode *User = *N->use_begin();
1720 while (User != Root) {
1721 if (!User->hasOneUse())
1722 return false;
1723 User = *User->use_begin();
1724 }
1725
1726 return true;
1727}
1728
Sanjay Patelb5723d02015-10-13 15:12:27 +00001729/// Match a scalar SSE load. In particular, we want to match a load whose top
1730/// elements are either undef or zeros. The load flavor is derived from the
1731/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001732///
1733/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001734/// PatternChainNode: this is the matched node that has a chain input and
1735/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001736bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001737 SDValue N, SDValue &Base,
1738 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001739 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001740 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001741 // We can allow a full vector load here since narrowing a load is ok.
1742 if (ISD::isNON_EXTLoad(N.getNode())) {
1743 PatternNodeWithChain = N;
1744 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001745 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1746 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001747 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1748 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1749 Segment);
1750 }
1751 }
1752
1753 // We can also match the special zero extended load opcode.
1754 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1755 PatternNodeWithChain = N;
1756 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001757 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1758 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001759 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1760 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1761 Segment);
1762 }
1763 }
1764
Craig Topper991d1ca2016-11-26 17:29:25 +00001765 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1766 // once. Otherwise the load might get duplicated and the chain output of the
1767 // duplicate load will not be observed by all dependencies.
1768 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001769 PatternNodeWithChain = N.getOperand(0);
1770 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001771 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001772 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1773 hasSingleUsesFromRoot(Root, N.getNode())) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001774 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001775 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1776 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001777 }
1778 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001779
1780 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001781 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001782 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001783 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001784 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001785 N.getOperand(0).getNode()->hasOneUse()) {
1786 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1787 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001788 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001789 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1790 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Toppere266e122016-11-26 18:43:24 +00001791 // Okay, this is a zero extending load. Fold it.
1792 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1793 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1794 Segment);
1795 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001796 }
Craig Toppere266e122016-11-26 18:43:24 +00001797
Chris Lattner398195e2006-10-07 21:55:32 +00001798 return false;
1799}
1800
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001801
Sanjay Patel85030aa2015-10-13 16:23:00 +00001802bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001803 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1804 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001805 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001806 return false;
1807
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001808 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001809 return true;
1810 }
1811
1812 // In static codegen with small code model, we can get the address of a label
1813 // into a register with 'movl'. TableGen has already made sure we're looking
1814 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001815 assert(N->getOpcode() == X86ISD::Wrapper &&
1816 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001817 N = N.getOperand(0);
1818
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001819 // At least GNU as does not accept 'movl' for TPOFF relocations.
1820 // FIXME: We could use 'movl' when we know we are targeting MC.
1821 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001822 return false;
1823
1824 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001825 if (N->getOpcode() != ISD::TargetGlobalAddress)
1826 return TM.getCodeModel() == CodeModel::Small;
1827
1828 Optional<ConstantRange> CR =
1829 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1830 if (!CR)
1831 return TM.getCodeModel() == CodeModel::Small;
1832
1833 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001834}
1835
Sanjay Patel85030aa2015-10-13 16:23:00 +00001836bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001837 SDValue &Scale, SDValue &Index,
1838 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001839 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1840 SDLoc DL(N);
Matt Morehouse9e658c92017-12-01 22:20:26 +00001841
Sanjay Patel85030aa2015-10-13 16:23:00 +00001842 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001843 return false;
1844
Tim Northover6833e3f2013-06-10 20:43:49 +00001845 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1846 if (RN && RN->getReg() == 0)
1847 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001848 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001849 // Base could already be %rip, particularly in the x32 ABI.
1850 Base = SDValue(CurDAG->getMachineNode(
1851 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001852 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001853 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001854 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001855 0);
1856 }
1857
1858 RN = dyn_cast<RegisterSDNode>(Index);
1859 if (RN && RN->getReg() == 0)
1860 Index = CurDAG->getRegister(0, MVT::i64);
1861 else {
1862 assert(Index.getValueType() == MVT::i32 &&
1863 "Expect to be extending 32-bit registers for use in LEA");
1864 Index = SDValue(CurDAG->getMachineNode(
1865 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001866 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001867 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001868 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1869 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001870 0);
1871 }
1872
1873 return true;
1874}
1875
Sanjay Patelb5723d02015-10-13 15:12:27 +00001876/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001877/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001878bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001879 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001880 SDValue &Index, SDValue &Disp,
1881 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001882 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001883
Justin Bogner32ad24d2016-04-12 21:34:24 +00001884 // Save the DL and VT before calling matchAddress, it can invalidate N.
1885 SDLoc DL(N);
1886 MVT VT = N.getSimpleValueType();
1887
Rafael Espindolabb834f02009-04-10 10:09:34 +00001888 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1889 // segments.
1890 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001891 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001892 AM.Segment = T;
Matt Morehouse9e658c92017-12-01 22:20:26 +00001893 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001894 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001895 assert (T == AM.Segment);
1896 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001897
Evan Cheng77d86ff2006-02-25 10:09:08 +00001898 unsigned Complexity = 0;
1899 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001900 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001901 Complexity = 1;
1902 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001903 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001904 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1905 Complexity = 4;
1906
Gabor Greiff304a7a2008-08-28 21:40:38 +00001907 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001908 Complexity++;
1909 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001910 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001911
Chris Lattner3e1d9172007-03-20 06:08:29 +00001912 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1913 // a simple shift.
1914 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001915 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001916
1917 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001918 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001919 // optimal (especially for code size consideration). LEA is nice because of
1920 // its three-address nature. Tweak the cost function again when we can run
1921 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001922 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001923 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001924 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001925 Complexity = 4;
1926 else
1927 Complexity += 2;
1928 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001929
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001930 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001931 Complexity++;
1932
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001933 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001934 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001935 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001936
Justin Bogner32ad24d2016-04-12 21:34:24 +00001937 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001938 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001939}
1940
Sanjay Patelb5723d02015-10-13 15:12:27 +00001941/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001942bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001943 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001944 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001945 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1946 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001947
Chris Lattner7d2b0492009-06-20 20:38:48 +00001948 X86ISelAddressMode AM;
1949 AM.GV = GA->getGlobal();
1950 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001951 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001952 AM.SymbolFlags = GA->getTargetFlags();
1953
Owen Anderson9f944592009-08-11 20:47:22 +00001954 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001955 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001956 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001957 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001958 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001959 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001960
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001961 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001962 return true;
1963}
1964
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001965bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1966 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1967 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1968 N.getValueType());
1969 return true;
1970 }
1971
Peter Collingbourne235c2752016-12-08 19:01:00 +00001972 // Keep track of the original value type and whether this value was
1973 // truncated. If we see a truncation from pointer type to VT that truncates
1974 // bits that are known to be zero, we can use a narrow reference.
1975 EVT VT = N.getValueType();
1976 bool WasTruncated = false;
1977 if (N.getOpcode() == ISD::TRUNCATE) {
1978 WasTruncated = true;
1979 N = N.getOperand(0);
1980 }
1981
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001982 if (N.getOpcode() != X86ISD::Wrapper)
1983 return false;
1984
Peter Collingbourne235c2752016-12-08 19:01:00 +00001985 // We can only use non-GlobalValues as immediates if they were not truncated,
1986 // as we do not have any range information. If we have a GlobalValue and the
1987 // address was not truncated, we can select it as an operand directly.
1988 unsigned Opc = N.getOperand(0)->getOpcode();
1989 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1990 Op = N.getOperand(0);
1991 // We can only select the operand directly if we didn't have to look past a
1992 // truncate.
1993 return !WasTruncated;
1994 }
1995
1996 // Check that the global's range fits into VT.
1997 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1998 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1999 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2000 return false;
2001
2002 // Okay, we can use a narrow reference.
2003 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2004 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00002005 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00002006}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002007
Craig Topper78a77042017-11-08 20:17:33 +00002008bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002009 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00002010 SDValue &Index, SDValue &Disp,
2011 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00002012 if (!ISD::isNON_EXTLoad(N.getNode()) ||
Craig Topper78a77042017-11-08 20:17:33 +00002013 !IsProfitableToFold(N, P, Root) ||
2014 !IsLegalToFold(N, P, Root, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00002015 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002016
Sanjay Patel85030aa2015-10-13 16:23:00 +00002017 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00002018 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00002019}
2020
Craig Topperd6564102018-04-27 22:15:33 +00002021bool X86DAGToDAGISel::tryFoldVecLoad(SDNode *Root, SDNode *P, SDValue N,
2022 SDValue &Base, SDValue &Scale,
2023 SDValue &Index, SDValue &Disp,
2024 SDValue &Segment) {
2025 if (!ISD::isNON_EXTLoad(N.getNode()) ||
2026 useNonTemporalLoad(cast<LoadSDNode>(N)) ||
2027 !IsProfitableToFold(N, P, Root) ||
2028 !IsLegalToFold(N, P, Root, OptLevel))
2029 return false;
2030
2031 return selectAddr(N.getNode(),
2032 N.getOperand(1), Base, Scale, Index, Disp, Segment);
2033}
2034
Sanjay Patelb5723d02015-10-13 15:12:27 +00002035/// Return an SDNode that returns the value of the global base register.
2036/// Output instructions required to initialize the global base register,
2037/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00002038SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00002039 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00002040 auto &DL = MF->getDataLayout();
2041 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00002042}
2043
Peter Collingbourneef089bd2017-02-09 22:02:28 +00002044bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2045 if (N->getOpcode() == ISD::TRUNCATE)
2046 N = N->getOperand(0).getNode();
2047 if (N->getOpcode() != X86ISD::Wrapper)
2048 return false;
2049
2050 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2051 if (!GA)
2052 return false;
2053
2054 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2055 return CR && CR->getSignedMin().sge(-1ull << Width) &&
2056 CR->getSignedMax().slt(1ull << Width);
2057}
2058
Sanjay Patelb5723d02015-10-13 15:12:27 +00002059/// Test whether the given X86ISD::CMP node has any uses which require the SF
2060/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002061static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002062 // Examine each user of the node.
2063 for (SDNode::use_iterator UI = N->use_begin(),
2064 UE = N->use_end(); UI != UE; ++UI) {
2065 // Only examine CopyToReg uses.
2066 if (UI->getOpcode() != ISD::CopyToReg)
2067 return false;
2068 // Only examine CopyToReg uses that copy to EFLAGS.
2069 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
2070 X86::EFLAGS)
2071 return false;
2072 // Examine each user of the CopyToReg use.
2073 for (SDNode::use_iterator FlagUI = UI->use_begin(),
2074 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2075 // Only examine the Flag result.
2076 if (FlagUI.getUse().getResNo() != 1) continue;
2077 // Anything unusual: assume conservatively.
2078 if (!FlagUI->isMachineOpcode()) return false;
2079 // Examine the opcode of the user.
2080 switch (FlagUI->getMachineOpcode()) {
2081 // These comparisons don't treat the most significant bit specially.
2082 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
2083 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
2084 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
2085 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00002086 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
2087 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002088 case X86::CMOVA16rr: case X86::CMOVA16rm:
2089 case X86::CMOVA32rr: case X86::CMOVA32rm:
2090 case X86::CMOVA64rr: case X86::CMOVA64rm:
2091 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
2092 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
2093 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
2094 case X86::CMOVB16rr: case X86::CMOVB16rm:
2095 case X86::CMOVB32rr: case X86::CMOVB32rm:
2096 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00002097 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
2098 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
2099 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002100 case X86::CMOVE16rr: case X86::CMOVE16rm:
2101 case X86::CMOVE32rr: case X86::CMOVE32rm:
2102 case X86::CMOVE64rr: case X86::CMOVE64rm:
2103 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
2104 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
2105 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
2106 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
2107 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2108 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2109 case X86::CMOVP16rr: case X86::CMOVP16rm:
2110 case X86::CMOVP32rr: case X86::CMOVP32rm:
2111 case X86::CMOVP64rr: case X86::CMOVP64rm:
2112 continue;
2113 // Anything else: assume conservatively.
2114 default: return false;
2115 }
2116 }
2117 }
2118 return true;
2119}
2120
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002121/// Test whether the given node which sets flags has any uses which require the
2122/// CF flag to be accurate.
2123static bool hasNoCarryFlagUses(SDNode *N) {
2124 // Examine each user of the node.
2125 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
2126 ++UI) {
2127 // Only check things that use the flags.
2128 if (UI.getUse().getResNo() != 1)
2129 continue;
2130 // Only examine CopyToReg uses.
2131 if (UI->getOpcode() != ISD::CopyToReg)
2132 return false;
2133 // Only examine CopyToReg uses that copy to EFLAGS.
2134 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2135 return false;
2136 // Examine each user of the CopyToReg use.
2137 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2138 FlagUI != FlagUE; ++FlagUI) {
2139 // Only examine the Flag result.
2140 if (FlagUI.getUse().getResNo() != 1)
2141 continue;
2142 // Anything unusual: assume conservatively.
2143 if (!FlagUI->isMachineOpcode())
2144 return false;
2145 // Examine the opcode of the user.
2146 switch (FlagUI->getMachineOpcode()) {
2147 // Comparisons which don't examine the CF flag.
2148 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2149 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2150 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2151 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2152 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2153 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2154 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2155 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2156 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2157 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2158 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2159 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2160 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2161 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2162 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2163 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2164 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2165 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2166 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2167 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2168 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2169 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2170 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2171 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2172 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2173 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2174 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2175 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2176 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2177 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2178 continue;
2179 // Anything else: assume conservatively.
2180 default:
2181 return false;
2182 }
2183 }
2184 }
2185 return true;
2186}
2187
Sanjay Patelb5723d02015-10-13 15:12:27 +00002188/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002189/// the {load; op; store} to modify transformation.
2190static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2191 SDValue StoredVal, SelectionDAG *CurDAG,
2192 LoadSDNode *&LoadNode,
2193 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002194 // is the stored value result 0 of the load?
2195 if (StoredVal.getResNo() != 0) return false;
2196
2197 // are there other uses of the loaded value than the inc or dec?
2198 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2199
Joel Jones68d59e82012-03-29 05:45:48 +00002200 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002201 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002202 return false;
2203
Evan Cheng3e869f02012-04-12 19:14:21 +00002204 SDValue Load = StoredVal->getOperand(0);
2205 // Is the stored value a non-extending and non-indexed load?
2206 if (!ISD::isNormalLoad(Load.getNode())) return false;
2207
2208 // Return LoadNode by reference.
2209 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002210
2211 // Is store the only read of the loaded value?
2212 if (!Load.hasOneUse())
2213 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002214
Evan Cheng3e869f02012-04-12 19:14:21 +00002215 // Is the address of the store the same as the load?
2216 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2217 LoadNode->getOffset() != StoreNode->getOffset())
2218 return false;
2219
Nirav Dave3264c1b2018-03-19 20:19:46 +00002220 bool FoundLoad = false;
2221 SmallVector<SDValue, 4> ChainOps;
2222 SmallVector<const SDNode *, 4> LoopWorklist;
2223 SmallPtrSet<const SDNode *, 16> Visited;
2224 const unsigned int Max = 1024;
2225
2226 // Visualization of Load-Op-Store fusion:
2227 // -------------------------
2228 // Legend:
2229 // *-lines = Chain operand dependencies.
2230 // |-lines = Normal operand dependencies.
2231 // Dependencies flow down and right. n-suffix references multiple nodes.
2232 //
2233 // C Xn C
2234 // * * *
2235 // * * *
2236 // Xn A-LD Yn TF Yn
2237 // * * \ | * |
2238 // * * \ | * |
2239 // * * \ | => A--LD_OP_ST
2240 // * * \| \
2241 // TF OP \
2242 // * | \ Zn
2243 // * | \
2244 // A-ST Zn
2245 //
2246
2247 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2248 // #2: Yn -> LD
2249 // #3: ST -> Zn
2250
2251 // Ensure the transform is safe by checking for the dual
2252 // dependencies to make sure we do not induce a loop.
2253
2254 // As LD is a predecessor to both OP and ST we can do this by checking:
2255 // a). if LD is a predecessor to a member of Xn or Yn.
2256 // b). if a Zn is a predecessor to ST.
2257
2258 // However, (b) can only occur through being a chain predecessor to
2259 // ST, which is the same as Zn being a member or predecessor of Xn,
2260 // which is a subset of LD being a predecessor of Xn. So it's
2261 // subsumed by check (a).
2262
Evan Cheng3e869f02012-04-12 19:14:21 +00002263 SDValue Chain = StoreNode->getChain();
2264
Nirav Dave3264c1b2018-03-19 20:19:46 +00002265 // Gather X elements in ChainOps.
Evan Cheng3e869f02012-04-12 19:14:21 +00002266 if (Chain == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002267 FoundLoad = true;
2268 ChainOps.push_back(Load.getOperand(0));
Nirav Dave0fab4172018-03-09 20:58:07 +00002269 } else if (Chain.getOpcode() == ISD::TokenFactor) {
Evan Cheng3e869f02012-04-12 19:14:21 +00002270 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2271 SDValue Op = Chain.getOperand(i);
2272 if (Op == Load.getValue(1)) {
Nirav Dave3264c1b2018-03-19 20:19:46 +00002273 FoundLoad = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002274 // Drop Load, but keep its chain. No cycle check necessary.
2275 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002276 continue;
2277 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002278 LoopWorklist.push_back(Op.getNode());
Evan Cheng3e869f02012-04-12 19:14:21 +00002279 ChainOps.push_back(Op);
2280 }
Nirav Daved668f692018-03-09 20:57:42 +00002281 }
Nirav Dave3264c1b2018-03-19 20:19:46 +00002282
2283 if (!FoundLoad)
Nirav Dave0fab4172018-03-09 20:58:07 +00002284 return false;
2285
Nirav Dave3264c1b2018-03-19 20:19:46 +00002286 // Worklist is currently Xn. Add Yn to worklist.
2287 for (SDValue Op : StoredVal->ops())
2288 if (Op.getNode() != LoadNode)
2289 LoopWorklist.push_back(Op.getNode());
2290
2291 // Check (a) if Load is a predecessor to Xn + Yn
2292 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2293 true))
2294 return false;
2295
2296 InputChain =
2297 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
Nirav Dave0fab4172018-03-09 20:58:07 +00002298 return true;
Nirav Dave042678b2018-03-10 02:16:15 +00002299}
Joel Jones68d59e82012-03-29 05:45:48 +00002300
Chandler Carruth4b611a82017-08-25 22:50:52 +00002301// Change a chain of {load; op; store} of the same value into a simple op
2302// through memory of that value, if the uses of the modified value and its
2303// address are suitable.
2304//
2305// The tablegen pattern memory operand pattern is currently not able to match
2306// the case where the EFLAGS on the original operation are used.
2307//
2308// To move this to tablegen, we'll need to improve tablegen to allow flags to
2309// be transferred from a node in the pattern to the result node, probably with
2310// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002311// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2312// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2313// (implicit EFLAGS)]>;
2314// but maybe need something like this
2315// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2316// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2317// (transferrable EFLAGS)]>;
2318//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002319// Until then, we manually fold these and instruction select the operation
2320// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002321bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2322 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2323 SDValue StoredVal = StoreNode->getOperand(1);
2324 unsigned Opc = StoredVal->getOpcode();
2325
Chandler Carruth4b611a82017-08-25 22:50:52 +00002326 // Before we try to select anything, make sure this is memory operand size
2327 // and opcode we can handle. Note that this must match the code below that
2328 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002329 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002330 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2331 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002332 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002333 switch (Opc) {
2334 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002335 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002336 case X86ISD::INC:
2337 case X86ISD::DEC:
2338 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002339 case X86ISD::ADC:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002340 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002341 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002342 case X86ISD::AND:
2343 case X86ISD::OR:
2344 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002345 break;
2346 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002347
Chandler Carruth03258f22017-08-25 02:04:03 +00002348 LoadSDNode *LoadNode = nullptr;
2349 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002350 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2351 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002352 return false;
2353
2354 SDValue Base, Scale, Index, Disp, Segment;
2355 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2356 Segment))
2357 return false;
2358
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002359 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002360 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002361 switch (MemVT.getSimpleVT().SimpleTy) {
2362 case MVT::i64:
2363 return Opc64;
2364 case MVT::i32:
2365 return Opc32;
2366 case MVT::i16:
2367 return Opc16;
2368 case MVT::i8:
2369 return Opc8;
2370 default:
2371 llvm_unreachable("Invalid size!");
2372 }
2373 };
2374
2375 MachineSDNode *Result;
2376 switch (Opc) {
2377 case X86ISD::INC:
2378 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002379 unsigned NewOpc =
2380 Opc == X86ISD::INC
2381 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2382 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002383 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2384 Result =
2385 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2386 break;
2387 }
2388 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002389 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002390 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002391 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002392 case X86ISD::AND:
2393 case X86ISD::OR:
2394 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002395 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2396 switch (Opc) {
2397 case X86ISD::ADD:
2398 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2399 X86::ADD8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002400 case X86ISD::ADC:
2401 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2402 X86::ADC8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002403 case X86ISD::SUB:
2404 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2405 X86::SUB8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002406 case X86ISD::SBB:
2407 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2408 X86::SBB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002409 case X86ISD::AND:
2410 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2411 X86::AND8mr);
2412 case X86ISD::OR:
2413 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2414 case X86ISD::XOR:
2415 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2416 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002417 default:
2418 llvm_unreachable("Invalid opcode!");
2419 }
2420 };
2421 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2422 switch (Opc) {
2423 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002424 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002425 case X86ISD::ADC:
2426 return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002427 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002428 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002429 case X86ISD::SBB:
2430 return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002431 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002432 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002433 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002434 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002435 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002436 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002437 default:
2438 llvm_unreachable("Invalid opcode!");
2439 }
2440 };
2441 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2442 switch (Opc) {
2443 case X86ISD::ADD:
2444 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2445 X86::ADD8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002446 case X86ISD::ADC:
2447 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2448 X86::ADC8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002449 case X86ISD::SUB:
2450 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2451 X86::SUB8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002452 case X86ISD::SBB:
2453 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2454 X86::SBB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002455 case X86ISD::AND:
2456 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2457 X86::AND8mi);
2458 case X86ISD::OR:
2459 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2460 X86::OR8mi);
2461 case X86ISD::XOR:
2462 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2463 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002464 default:
2465 llvm_unreachable("Invalid opcode!");
2466 }
2467 };
2468
2469 unsigned NewOpc = SelectRegOpcode(Opc);
2470 SDValue Operand = StoredVal->getOperand(1);
2471
2472 // See if the operand is a constant that we can fold into an immediate
2473 // operand.
2474 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2475 auto OperandV = OperandC->getAPIntValue();
2476
2477 // Check if we can shrink the operand enough to fit in an immediate (or
2478 // fit into a smaller immediate) by negating it and switching the
2479 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002480 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2481 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002482 (-OperandV).getMinSignedBits() <= 8) ||
2483 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2484 (-OperandV).getMinSignedBits() <= 32)) &&
2485 hasNoCarryFlagUses(StoredVal.getNode())) {
2486 OperandV = -OperandV;
2487 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2488 }
2489
2490 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2491 // the larger immediate operand.
2492 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2493 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2494 NewOpc = SelectImm8Opcode(Opc);
2495 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2496 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2497 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2498 NewOpc = SelectImmOpcode(Opc);
2499 }
2500 }
2501
Nirav Dave72d32f22018-01-19 15:37:57 +00002502 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2503 SDValue CopyTo =
2504 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2505 StoredVal.getOperand(2), SDValue());
2506
2507 const SDValue Ops[] = {Base, Scale, Index, Disp,
2508 Segment, Operand, CopyTo, CopyTo.getValue(1)};
2509 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2510 Ops);
2511 } else {
2512 const SDValue Ops[] = {Base, Scale, Index, Disp,
2513 Segment, Operand, InputChain};
2514 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2515 Ops);
2516 }
Chandler Carruth4b611a82017-08-25 22:50:52 +00002517 break;
2518 }
2519 default:
2520 llvm_unreachable("Invalid opcode!");
2521 }
2522
Chandler Carruth03258f22017-08-25 02:04:03 +00002523 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2524 MemOp[0] = StoreNode->getMemOperand();
2525 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002526 Result->setMemRefs(MemOp, MemOp + 2);
2527
Nirav Dave3264c1b2018-03-19 20:19:46 +00002528 // Update Load Chain uses as well.
2529 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
Chandler Carruth03258f22017-08-25 02:04:03 +00002530 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2531 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2532 CurDAG->RemoveDeadNode(Node);
2533 return true;
2534}
2535
Craig Topper958106d2017-09-12 17:40:25 +00002536// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2537bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2538 MVT NVT = Node->getSimpleValueType(0);
2539 SDLoc dl(Node);
2540
2541 SDValue N0 = Node->getOperand(0);
2542 SDValue N1 = Node->getOperand(1);
2543
2544 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2545 return false;
2546
2547 // Must have a shift right.
2548 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2549 return false;
2550
2551 // Shift can't have additional users.
2552 if (!N0->hasOneUse())
2553 return false;
2554
2555 // Only supported for 32 and 64 bits.
2556 if (NVT != MVT::i32 && NVT != MVT::i64)
2557 return false;
2558
2559 // Shift amount and RHS of and must be constant.
2560 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2561 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2562 if (!MaskCst || !ShiftCst)
2563 return false;
2564
2565 // And RHS must be a mask.
2566 uint64_t Mask = MaskCst->getZExtValue();
2567 if (!isMask_64(Mask))
2568 return false;
2569
2570 uint64_t Shift = ShiftCst->getZExtValue();
2571 uint64_t MaskSize = countPopulation(Mask);
2572
2573 // Don't interfere with something that can be handled by extracting AH.
2574 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2575 if (Shift == 8 && MaskSize == 8)
2576 return false;
2577
2578 // Make sure we are only using bits that were in the original value, not
2579 // shifted in.
2580 if (Shift + MaskSize > NVT.getSizeInBits())
2581 return false;
2582
Craig Topper88939fe2018-02-12 21:18:11 +00002583 // Create a BEXTR node and run it through selection.
2584 SDValue C = CurDAG->getConstant(Shift | (MaskSize << 8), dl, NVT);
2585 SDValue New = CurDAG->getNode(X86ISD::BEXTR, dl, NVT,
2586 N0->getOperand(0), C);
2587 ReplaceNode(Node, New.getNode());
2588 SelectCode(New.getNode());
Craig Topper958106d2017-09-12 17:40:25 +00002589 return true;
2590}
2591
Craig Topperd6564102018-04-27 22:15:33 +00002592// Emit a PCMISTR(I/M) instruction.
2593MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
2594 bool MayFoldLoad, const SDLoc &dl,
2595 MVT VT, SDNode *Node) {
2596 SDValue N0 = Node->getOperand(0);
2597 SDValue N1 = Node->getOperand(1);
2598 SDValue Imm = Node->getOperand(2);
2599 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2600 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2601
2602 // If there is a load, it will be behind a bitcast. We don't need to check
2603 // alignment on this load.
2604 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2605 if (MayFoldLoad && N1->getOpcode() == ISD::BITCAST && N1->hasOneUse() &&
2606 tryFoldVecLoad(Node, N1.getNode(), N1.getOperand(0), Tmp0, Tmp1, Tmp2,
2607 Tmp3, Tmp4)) {
2608 SDValue Load = N1.getOperand(0);
2609 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
2610 Load.getOperand(0) };
2611 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
2612 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2613 // Update the chain.
2614 ReplaceUses(Load.getValue(1), SDValue(CNode, 2));
2615 // Record the mem-refs
2616 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2617 MemOp[0] = cast<LoadSDNode>(Load)->getMemOperand();
2618 CNode->setMemRefs(MemOp, MemOp + 1);
2619 return CNode;
2620 }
2621
2622 SDValue Ops[] = { N0, N1, Imm };
2623 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
2624 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
2625 return CNode;
2626}
2627
2628// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
2629// to emit a second instruction after this one. This is needed since we have two
2630// copyToReg nodes glued before this and we need to continue that glue through.
2631MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
2632 bool MayFoldLoad, const SDLoc &dl,
2633 MVT VT, SDNode *Node,
2634 SDValue &InFlag) {
2635 SDValue N0 = Node->getOperand(0);
2636 SDValue N2 = Node->getOperand(2);
2637 SDValue Imm = Node->getOperand(4);
2638 const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
2639 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
2640
2641 // If there is a load, it will be behind a bitcast. We don't need to check
2642 // alignment on this load.
2643 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2644 if (MayFoldLoad && N2->getOpcode() == ISD::BITCAST && N2->hasOneUse() &&
2645 tryFoldVecLoad(Node, N2.getNode(), N2.getOperand(0), Tmp0, Tmp1, Tmp2,
2646 Tmp3, Tmp4)) {
2647 SDValue Load = N2.getOperand(0);
2648 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
2649 Load.getOperand(0), InFlag };
2650 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
2651 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2652 InFlag = SDValue(CNode, 3);
2653 // Update the chain.
2654 ReplaceUses(Load.getValue(1), SDValue(CNode, 2));
2655 // Record the mem-refs
2656 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2657 MemOp[0] = cast<LoadSDNode>(Load)->getMemOperand();
2658 CNode->setMemRefs(MemOp, MemOp + 1);
2659 return CNode;
2660 }
2661
2662 SDValue Ops[] = { N0, N2, Imm, InFlag };
2663 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
2664 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
2665 InFlag = SDValue(CNode, 2);
2666 return CNode;
2667}
2668
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002669/// If the high bits of an 'and' operand are known zero, try setting the
2670/// high bits of an 'and' constant operand to produce a smaller encoding by
2671/// creating a small, sign-extended negative immediate rather than a large
2672/// positive one. This reverses a transform in SimplifyDemandedBits that
2673/// shrinks mask constants by clearing bits. There is also a possibility that
2674/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
2675/// case, just replace the 'and'. Return 'true' if the node is replaced.
2676bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
2677 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
2678 // have immediate operands.
2679 MVT VT = And->getSimpleValueType(0);
2680 if (VT != MVT::i32 && VT != MVT::i64)
2681 return false;
2682
2683 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
2684 if (!And1C)
2685 return false;
2686
Craig Topper57e06432018-02-05 16:54:07 +00002687 // Bail out if the mask constant is already negative. It's can't shrink more.
2688 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
2689 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
2690 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
2691 // are negative too.
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002692 APInt MaskVal = And1C->getAPIntValue();
2693 unsigned MaskLZ = MaskVal.countLeadingZeros();
Craig Topper57e06432018-02-05 16:54:07 +00002694 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002695 return false;
2696
Craig Topper57e06432018-02-05 16:54:07 +00002697 // Don't extend into the upper 32 bits of a 64 bit mask.
2698 if (VT == MVT::i64 && MaskLZ >= 32) {
2699 MaskLZ -= 32;
2700 MaskVal = MaskVal.trunc(32);
2701 }
2702
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002703 SDValue And0 = And->getOperand(0);
Craig Topper57e06432018-02-05 16:54:07 +00002704 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002705 APInt NegMaskVal = MaskVal | HighZeros;
2706
2707 // If a negative constant would not allow a smaller encoding, there's no need
2708 // to continue. Only change the constant when we know it's a win.
2709 unsigned MinWidth = NegMaskVal.getMinSignedBits();
2710 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
2711 return false;
2712
Craig Topper57e06432018-02-05 16:54:07 +00002713 // Extend masks if we truncated above.
2714 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
2715 NegMaskVal = NegMaskVal.zext(64);
2716 HighZeros = HighZeros.zext(64);
2717 }
2718
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002719 // The variable operand must be all zeros in the top bits to allow using the
2720 // new, negative constant as the mask.
2721 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
2722 return false;
2723
2724 // Check if the mask is -1. In that case, this is an unnecessary instruction
2725 // that escaped earlier analysis.
2726 if (NegMaskVal.isAllOnesValue()) {
2727 ReplaceNode(And, And0.getNode());
2728 return true;
2729 }
2730
2731 // A negative mask allows a smaller encoding. Create a new 'and' node.
2732 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
2733 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
2734 ReplaceNode(And, NewAnd.getNode());
2735 SelectCode(NewAnd.getNode());
2736 return true;
2737}
2738
Justin Bogner593741d2016-05-10 23:55:37 +00002739void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002740 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002741 unsigned Opc, MOpc;
2742 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002743 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002744
Dan Gohman17059682008-07-17 19:10:17 +00002745 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002746 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002747 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002748 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002749 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002750
Evan Cheng10d27902006-01-06 20:36:21 +00002751 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002752 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002753 case ISD::BRIND: {
2754 if (Subtarget->isTargetNaCl())
2755 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2756 // leave the instruction alone.
2757 break;
2758 if (Subtarget->isTarget64BitILP32()) {
2759 // Converts a 32-bit register to a 64-bit, zero-extended version of
2760 // it. This is needed because x86-64 can do many things, but jmp %r32
2761 // ain't one of them.
2762 const SDValue &Target = Node->getOperand(1);
2763 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2764 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2765 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2766 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002767 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002768 SelectCode(ZextTarget.getNode());
2769 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002770 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002771 }
2772 break;
2773 }
Dan Gohman757eee82009-08-02 16:10:52 +00002774 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002775 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002776 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002777
Craig Topper75370b92017-09-19 17:19:45 +00002778 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002779 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002780 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002781 SDValue VSelect = CurDAG->getNode(
2782 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2783 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002784 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002785 SelectCode(VSelect.getNode());
2786 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002787 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002788 }
Craig Topper3af251d2012-07-01 02:55:34 +00002789
Tobias Grosser85508e82015-08-19 11:35:10 +00002790 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002791 if (matchBEXTRFromAnd(Node))
2792 return;
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002793 if (shrinkAndImmediate(Node))
2794 return;
Craig Topper958106d2017-09-12 17:40:25 +00002795
2796 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002797 case ISD::OR:
2798 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002799
Benjamin Kramer4c816242011-04-22 15:30:40 +00002800 // For operations of the form (x << C1) op C2, check if we can use a smaller
2801 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2802 SDValue N0 = Node->getOperand(0);
2803 SDValue N1 = Node->getOperand(1);
2804
2805 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2806 break;
2807
2808 // i8 is unshrinkable, i16 should be promoted to i32.
2809 if (NVT != MVT::i32 && NVT != MVT::i64)
2810 break;
2811
2812 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2813 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2814 if (!Cst || !ShlCst)
2815 break;
2816
2817 int64_t Val = Cst->getSExtValue();
2818 uint64_t ShlVal = ShlCst->getZExtValue();
2819
2820 // Make sure that we don't change the operation by removing bits.
2821 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002822 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2823 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002824 break;
2825
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002826 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002827 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002828
2829 // Check the minimum bitwidth for the new constant.
2830 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2831 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2832 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2833 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2834 CstVT = MVT::i8;
2835 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2836 CstVT = MVT::i32;
2837
2838 // Bail if there is no smaller encoding.
2839 if (NVT == CstVT)
2840 break;
2841
Craig Topper83e042a2013-08-15 05:57:07 +00002842 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002843 default: llvm_unreachable("Unsupported VT!");
2844 case MVT::i32:
2845 assert(CstVT == MVT::i8);
2846 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002847 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002848
2849 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002850 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002851 case ISD::AND: Op = X86::AND32ri8; break;
2852 case ISD::OR: Op = X86::OR32ri8; break;
2853 case ISD::XOR: Op = X86::XOR32ri8; break;
2854 }
2855 break;
2856 case MVT::i64:
2857 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2858 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002859 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002860
2861 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002862 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002863 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2864 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2865 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2866 }
2867 break;
2868 }
2869
2870 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002871 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002872 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002873 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002874 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2875 SDValue(New, 0));
2876 else
2877 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2878 getI8Imm(ShlVal, dl));
2879 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002880 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002881 case X86ISD::UMUL8:
2882 case X86ISD::SMUL8: {
2883 SDValue N0 = Node->getOperand(0);
2884 SDValue N1 = Node->getOperand(1);
2885
2886 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2887
2888 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2889 N0, SDValue()).getValue(1);
2890
2891 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2892 SDValue Ops[] = {N1, InFlag};
2893 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2894
Justin Bogner31d7da32016-05-11 21:13:17 +00002895 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002896 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002897 }
2898
Chris Lattner364bb0a2010-12-05 07:30:36 +00002899 case X86ISD::UMUL: {
2900 SDValue N0 = Node->getOperand(0);
2901 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002902
Ted Kremenekb5241b22011-01-14 22:34:13 +00002903 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002904 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002905 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00002906 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00002907 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2908 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2909 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002910 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002911
Chris Lattner364bb0a2010-12-05 07:30:36 +00002912 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2913 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002914
Chris Lattner364bb0a2010-12-05 07:30:36 +00002915 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2916 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002917 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002918
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002919 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002920 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002921 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002922
Dan Gohman757eee82009-08-02 16:10:52 +00002923 case ISD::SMUL_LOHI:
2924 case ISD::UMUL_LOHI: {
2925 SDValue N0 = Node->getOperand(0);
2926 SDValue N1 = Node->getOperand(1);
2927
2928 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002929 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002930 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002931 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002932 default: llvm_unreachable("Unsupported VT!");
Michael Liaof9f7b552012-09-26 08:22:37 +00002933 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2934 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2935 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2936 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002937 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002938 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002939 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002940 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002941 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2942 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002943 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002944 }
Dan Gohman757eee82009-08-02 16:10:52 +00002945
Michael Liaof9f7b552012-09-26 08:22:37 +00002946 unsigned SrcReg, LoReg, HiReg;
2947 switch (Opc) {
2948 default: llvm_unreachable("Unknown MUL opcode!");
Michael Liaof9f7b552012-09-26 08:22:37 +00002949 case X86::IMUL32r:
2950 case X86::MUL32r:
2951 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2952 break;
2953 case X86::IMUL64r:
2954 case X86::MUL64r:
2955 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2956 break;
2957 case X86::MULX32rr:
2958 SrcReg = X86::EDX; LoReg = HiReg = 0;
2959 break;
2960 case X86::MULX64rr:
2961 SrcReg = X86::RDX; LoReg = HiReg = 0;
2962 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002963 }
2964
2965 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002966 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002967 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002968 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002969 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002970 if (foldedLoad)
2971 std::swap(N0, N1);
2972 }
2973
Michael Liaof9f7b552012-09-26 08:22:37 +00002974 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002975 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002976 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002977
2978 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002979 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002980 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002981 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2982 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002983 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2984 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002985 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002986 ResHi = SDValue(CNode, 0);
2987 ResLo = SDValue(CNode, 1);
2988 Chain = SDValue(CNode, 2);
2989 InFlag = SDValue(CNode, 3);
2990 } else {
2991 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002992 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002993 Chain = SDValue(CNode, 0);
2994 InFlag = SDValue(CNode, 1);
2995 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002996
Dan Gohman757eee82009-08-02 16:10:52 +00002997 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002998 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002999 // Record the mem-refs
Craig Topper55029d82017-11-08 22:26:37 +00003000 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3001 MemOp[0] = cast<LoadSDNode>(N1)->getMemOperand();
3002 CNode->setMemRefs(MemOp, MemOp + 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003003 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00003004 SDValue Ops[] = { N1, InFlag };
3005 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
3006 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003007 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003008 ResHi = SDValue(CNode, 0);
3009 ResLo = SDValue(CNode, 1);
3010 InFlag = SDValue(CNode, 2);
3011 } else {
3012 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00003013 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00003014 InFlag = SDValue(CNode, 0);
3015 }
Dan Gohman757eee82009-08-02 16:10:52 +00003016 }
3017
3018 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003019 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003020 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003021 assert(LoReg && "Register for low half is not defined!");
3022 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
3023 InFlag);
3024 InFlag = ResLo.getValue(2);
3025 }
3026 ReplaceUses(SDValue(Node, 0), ResLo);
3027 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003028 }
3029 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003030 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00003031 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00003032 assert(HiReg && "Register for high half is not defined!");
3033 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
3034 InFlag);
3035 InFlag = ResHi.getValue(2);
3036 }
3037 ReplaceUses(SDValue(Node, 1), ResHi);
3038 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003039 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003040
Craig Topper6bed9de2017-09-09 05:57:20 +00003041 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003042 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003043 }
3044
3045 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003046 case ISD::UDIVREM:
3047 case X86ISD::SDIVREM8_SEXT_HREG:
3048 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00003049 SDValue N0 = Node->getOperand(0);
3050 SDValue N1 = Node->getOperand(1);
3051
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003052 bool isSigned = (Opcode == ISD::SDIVREM ||
3053 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003054 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00003055 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003056 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003057 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
3058 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
3059 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
3060 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003061 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003062 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00003063 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003064 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003065 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
3066 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
3067 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
3068 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00003069 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00003070 }
Dan Gohman757eee82009-08-02 16:10:52 +00003071
Chris Lattner518b0372009-12-23 01:45:04 +00003072 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003073 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00003074 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00003075 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00003076 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00003077 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00003078 SExtOpcode = X86::CBW;
3079 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003080 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00003081 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00003082 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00003083 SExtOpcode = X86::CWD;
3084 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003085 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00003086 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003087 SExtOpcode = X86::CDQ;
3088 break;
Owen Anderson9f944592009-08-11 20:47:22 +00003089 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00003090 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00003091 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00003092 break;
3093 }
3094
Dan Gohman757eee82009-08-02 16:10:52 +00003095 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003096 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00003097 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00003098
Dan Gohman757eee82009-08-02 16:10:52 +00003099 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00003100 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003101 // Special case for div8, just use a move with zero extension to AX to
3102 // clear the upper 8 bits (AH).
3103 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00003104 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00003105 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
3106 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00003107 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00003108 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003109 Chain = Move.getValue(1);
3110 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00003111 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00003112 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00003113 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00003114 Chain = CurDAG->getEntryNode();
3115 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00003116 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00003117 InFlag = Chain.getValue(1);
3118 } else {
3119 InFlag =
3120 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
3121 LoReg, N0, SDValue()).getValue(1);
3122 if (isSigned && !signBitIsZero) {
3123 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00003124 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003125 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00003126 } else {
3127 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00003128 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00003129 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00003130 case MVT::i16:
3131 ClrNode =
3132 SDValue(CurDAG->getMachineNode(
3133 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003134 CurDAG->getTargetConstant(X86::sub_16bit, dl,
3135 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003136 0);
3137 break;
3138 case MVT::i32:
3139 break;
3140 case MVT::i64:
3141 ClrNode =
3142 SDValue(CurDAG->getMachineNode(
3143 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003144 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
3145 CurDAG->getTargetConstant(X86::sub_32bit, dl,
3146 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00003147 0);
3148 break;
3149 default:
3150 llvm_unreachable("Unexpected division source");
3151 }
3152
Chris Lattner518b0372009-12-23 01:45:04 +00003153 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00003154 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00003155 }
Evan Cheng92e27972006-01-06 23:19:29 +00003156 }
Dan Gohmana1603612007-10-08 18:33:35 +00003157
Dan Gohman757eee82009-08-02 16:10:52 +00003158 if (foldedLoad) {
3159 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3160 InFlag };
Craig Topper61f81f92017-11-08 22:26:39 +00003161 MachineSDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00003162 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00003163 InFlag = SDValue(CNode, 1);
3164 // Update the chain.
3165 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
Craig Topper61f81f92017-11-08 22:26:39 +00003166 // Record the mem-refs
3167 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3168 MemOp[0] = cast<LoadSDNode>(N1)->getMemOperand();
3169 CNode->setMemRefs(MemOp, MemOp + 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003170 } else {
3171 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003172 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003173 }
Evan Cheng92e27972006-01-06 23:19:29 +00003174
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003175 // Prevent use of AH in a REX instruction by explicitly copying it to
3176 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00003177 //
3178 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003179 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00003180 // the allocator and/or the backend get enhanced to be more robust in
3181 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003182 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
3183 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
3184 unsigned AHExtOpcode =
Craig Topperad7c6852018-03-20 05:00:20 +00003185 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003186
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003187 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
3188 MVT::Glue, AHCopy, InFlag);
3189 SDValue Result(RNode, 0);
3190 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003191
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003192 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
3193 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
Craig Topperb8d7d4d2017-10-26 21:12:03 +00003194 assert(Node->getValueType(1) == MVT::i32 && "Unexpected result type!");
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003195 } else {
3196 Result =
3197 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
3198 }
3199 ReplaceUses(SDValue(Node, 1), Result);
3200 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003201 }
Dan Gohman757eee82009-08-02 16:10:52 +00003202 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003203 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00003204 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3205 LoReg, NVT, InFlag);
3206 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003207 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00003208 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003209 }
3210 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003211 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003212 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3213 HiReg, NVT, InFlag);
3214 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003215 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00003216 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003217 }
Craig Topper6bed9de2017-09-09 05:57:20 +00003218 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003219 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003220 }
3221
Craig Topperb424faf2018-02-12 03:02:02 +00003222 case X86ISD::CMP: {
Dan Gohmanac33a902009-08-19 18:16:17 +00003223 SDValue N0 = Node->getOperand(0);
3224 SDValue N1 = Node->getOperand(1);
3225
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003226 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00003227 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003228 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00003229
Dan Gohmanac33a902009-08-19 18:16:17 +00003230 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
3231 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003232 // Look past the truncate if CMP is the only use of it.
Craig Topper3ccbd3f2018-02-12 03:02:01 +00003233 if (N0.getOpcode() == ISD::AND &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00003234 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00003235 N0.getValueType() != MVT::i8 &&
3236 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00003237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00003238 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00003239 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00003240
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003241 MVT VT;
3242 int SubRegOp;
3243 unsigned Op;
3244
Craig Topperfc53dc22017-08-25 05:04:34 +00003245 if (isUInt<8>(Mask) &&
3246 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003247 // For example, convert "testl %eax, $8" to "testb %al, $8"
3248 VT = MVT::i8;
3249 SubRegOp = X86::sub_8bit;
3250 Op = X86::TEST8ri;
3251 } else if (OptForMinSize && isUInt<16>(Mask) &&
3252 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3253 // For example, "testl %eax, $32776" to "testw %ax, $32776".
3254 // NOTE: We only want to form TESTW instructions if optimizing for
3255 // min size. Otherwise we only save one byte and possibly get a length
3256 // changing prefix penalty in the decoders.
3257 VT = MVT::i16;
3258 SubRegOp = X86::sub_16bit;
3259 Op = X86::TEST16ri;
3260 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
3261 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3262 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3263 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
3264 // Otherwize, we find ourselves in a position where we have to do
3265 // promotion. If previous passes did not promote the and, we assume
3266 // they had a good reason not to and do not promote here.
3267 VT = MVT::i32;
3268 SubRegOp = X86::sub_32bit;
3269 Op = X86::TEST32ri;
3270 } else {
3271 // No eligible transformation was found.
3272 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00003273 }
3274
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003275 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
3276 SDValue Reg = N0.getOperand(0);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003277
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003278 // Extract the subregister if necessary.
3279 if (N0.getValueType() != VT)
3280 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003281
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003282 // Emit a testl or testw.
3283 SDNode *NewNode = CurDAG->getMachineNode(Op, dl, MVT::i32, Reg, Imm);
Craig Topperb424faf2018-02-12 03:02:02 +00003284 // Replace CMP with TEST.
Nirav Dave3264c1b2018-03-19 20:19:46 +00003285 ReplaceNode(Node, NewNode);
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003286 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003287 }
3288 break;
3289 }
Craig Topperd6564102018-04-27 22:15:33 +00003290 case X86ISD::PCMPISTR: {
3291 if (!Subtarget->hasSSE42())
3292 break;
3293
3294 bool NeedIndex = !SDValue(Node, 0).use_empty();
3295 bool NeedMask = !SDValue(Node, 1).use_empty();
3296 // We can't fold a load if we are going to make two instructions.
3297 bool MayFoldLoad = !NeedIndex || !NeedMask;
3298
3299 MachineSDNode *CNode;
3300 if (NeedMask) {
3301 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
3302 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
3303 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
3304 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3305 }
3306 if (NeedIndex || !NeedMask) {
3307 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
3308 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
3309 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
3310 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3311 }
3312
3313 // Connect the flag usage to the last instruction created.
3314 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 0));
3315 CurDAG->RemoveDeadNode(Node);
3316 return;
3317 }
3318 case X86ISD::PCMPESTR: {
3319 if (!Subtarget->hasSSE42())
3320 break;
3321
3322 // Copy the two implicit register inputs.
3323 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
3324 Node->getOperand(1),
3325 SDValue()).getValue(1);
3326 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
3327 Node->getOperand(3), InFlag).getValue(1);
3328
3329 bool NeedIndex = !SDValue(Node, 0).use_empty();
3330 bool NeedMask = !SDValue(Node, 1).use_empty();
3331 // We can't fold a load if we are going to make two instructions.
3332 bool MayFoldLoad = !NeedIndex || !NeedMask;
3333
3334 MachineSDNode *CNode;
3335 if (NeedMask) {
3336 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
3337 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
3338 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
3339 InFlag);
3340 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3341 }
3342 if (NeedIndex || !NeedMask) {
3343 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
3344 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
3345 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
3346 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3347 }
3348 // Connect the flag usage to the last instruction created.
3349 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
3350 CurDAG->RemoveDeadNode(Node);
3351 return;
3352 }
3353
Chandler Carruth03258f22017-08-25 02:04:03 +00003354 case ISD::STORE:
3355 if (foldLoadStoreIntoMemOperand(Node))
3356 return;
3357 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003358 }
3359
Justin Bogner593741d2016-05-10 23:55:37 +00003360 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003361}
3362
Chris Lattnerba1ed582006-06-08 18:03:49 +00003363bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003364SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003365 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003366 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003367 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003368 default:
3369 llvm_unreachable("Unexpected asm memory constraint");
3370 case InlineAsm::Constraint_i:
3371 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3372 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003373 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003374 case InlineAsm::Constraint_o: // offsetable ??
3375 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003376 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003377 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003378 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003379 return true;
3380 break;
3381 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003382
Evan Cheng2d487222006-08-26 01:05:16 +00003383 OutOps.push_back(Op0);
3384 OutOps.push_back(Op1);
3385 OutOps.push_back(Op2);
3386 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003387 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003388 return false;
3389}
3390
Sanjay Patelb5723d02015-10-13 15:12:27 +00003391/// This pass converts a legalized DAG into a X86-specific DAG,
3392/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003393FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003394 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003395 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003396}