blob: ebcd15230b97254235bb62c8c7b4793698dfb62c [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)
Dale Johannesendafdbf72008-08-11 23:46:25 +0000103 void dump() {
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())
Chad Rosier24c19d22012-08-01 18:39:17 +0000107 Base_Reg.getNode()->dump();
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())
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000115 IndexReg.getNode()->dump();
116 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;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000184
Chris Lattner655e7df2005-11-16 01:54:32 +0000185// Include the pieces autogenerated from the target description.
186#include "X86GenDAGISel.inc"
187
188 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000189 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000190
Sanjay Patel85030aa2015-10-13 16:23:00 +0000191 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
192 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
193 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
194 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Craig Topperc314f462017-11-13 17:53:59 +0000195 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000196 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000197 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000198 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000199 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
200 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000201 SDValue &Scale, SDValue &Index, SDValue &Disp,
202 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000203 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000204 SDValue &Scale, SDValue &Index, SDValue &Disp,
205 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000206 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
207 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000208 SDValue &Scale, SDValue &Index, SDValue &Disp,
209 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000210 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000211 SDValue &Scale, SDValue &Index, SDValue &Disp,
212 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000213 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000214 SDValue &Scale, SDValue &Index, SDValue &Disp,
215 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000216 bool selectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000217 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000219 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000220 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000221 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000222
Craig Topper78a77042017-11-08 20:17:33 +0000223 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000224 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000225 SDValue &Index, SDValue &Disp,
226 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000227
Craig Topper78a77042017-11-08 20:17:33 +0000228 // Convience method where P is also root.
229 bool tryFoldLoad(SDNode *P, SDValue N,
230 SDValue &Base, SDValue &Scale,
231 SDValue &Index, SDValue &Disp,
232 SDValue &Segment) {
233 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
234 }
235
Sanjay Patelb5723d02015-10-13 15:12:27 +0000236 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000237 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000238 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000239 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000240
Sanjay Patel85030aa2015-10-13 16:23:00 +0000241 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000242
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000243 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000244 SDValue &Base, SDValue &Scale,
245 SDValue &Index, SDValue &Disp,
246 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000247 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000248 ? CurDAG->getTargetFrameIndex(
249 AM.Base_FrameIndex,
250 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000251 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000252 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000253 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000254 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000255 // is 32-bit.
256 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000257 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000258 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000259 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000260 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000261 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000262 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000263 else if (AM.ES) {
264 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000265 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000266 } else if (AM.MCSym) {
267 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
268 assert(AM.SymbolFlags == 0 && "oo");
269 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000270 } else if (AM.JT != -1) {
271 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000272 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000273 } else if (AM.BlockAddr)
274 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
275 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000276 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000277 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000278
279 if (AM.Segment.getNode())
280 Segment = AM.Segment;
281 else
Owen Anderson9f944592009-08-11 20:47:22 +0000282 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000283 }
284
Michael Kuperstein243c0732015-08-11 14:10:58 +0000285 // Utility function to determine whether we should avoid selecting
286 // immediate forms of instructions for better code size or not.
287 // At a high level, we'd like to avoid such instructions when
288 // we have similar constants used within the same basic block
289 // that can be kept in a register.
290 //
291 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
292 uint32_t UseCount = 0;
293
294 // Do not want to hoist if we're not optimizing for size.
295 // TODO: We'd like to remove this restriction.
296 // See the comment in X86InstrInfo.td for more info.
297 if (!OptForSize)
298 return false;
299
300 // Walk all the users of the immediate.
301 for (SDNode::use_iterator UI = N->use_begin(),
302 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000303
Michael Kuperstein243c0732015-08-11 14:10:58 +0000304 SDNode *User = *UI;
305
306 // This user is already selected. Count it as a legitimate use and
307 // move on.
308 if (User->isMachineOpcode()) {
309 UseCount++;
310 continue;
311 }
312
313 // We want to count stores of immediates as real uses.
314 if (User->getOpcode() == ISD::STORE &&
315 User->getOperand(1).getNode() == N) {
316 UseCount++;
317 continue;
318 }
319
320 // We don't currently match users that have > 2 operands (except
321 // for stores, which are handled above)
322 // Those instruction won't match in ISEL, for now, and would
323 // be counted incorrectly.
324 // This may change in the future as we add additional instruction
325 // types.
326 if (User->getNumOperands() != 2)
327 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000328
Michael Kuperstein243c0732015-08-11 14:10:58 +0000329 // Immediates that are used for offsets as part of stack
330 // manipulation should be left alone. These are typically
331 // used to indicate SP offsets for argument passing and
332 // will get pulled into stores/pushes (implicitly).
333 if (User->getOpcode() == X86ISD::ADD ||
334 User->getOpcode() == ISD::ADD ||
335 User->getOpcode() == X86ISD::SUB ||
336 User->getOpcode() == ISD::SUB) {
337
338 // Find the other operand of the add/sub.
339 SDValue OtherOp = User->getOperand(0);
340 if (OtherOp.getNode() == N)
341 OtherOp = User->getOperand(1);
342
343 // Don't count if the other operand is SP.
344 RegisterSDNode *RegNode;
345 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
346 (RegNode = dyn_cast_or_null<RegisterSDNode>(
347 OtherOp->getOperand(1).getNode())))
348 if ((RegNode->getReg() == X86::ESP) ||
349 (RegNode->getReg() == X86::RSP))
350 continue;
351 }
352
353 // ... otherwise, count this and move on.
354 UseCount++;
355 }
356
357 // If we have more than 1 use, then recommend for hoisting.
358 return (UseCount > 1);
359 }
360
Sanjay Patelb5723d02015-10-13 15:12:27 +0000361 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000362 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000363 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000364 }
365
Sanjay Patelb5723d02015-10-13 15:12:27 +0000366 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000367 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000368 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000369 }
Evan Chengd49cc362006-02-10 22:24:32 +0000370
Craig Topper2b2d8c52018-02-15 19:57:35 +0000371 /// Return a target constant with the specified value, of type i64.
372 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
373 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
374 }
375
Craig Topper092c2f42017-09-23 05:34:07 +0000376 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
377 const SDLoc &DL) {
378 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
379 uint64_t Index = N->getConstantOperandVal(1);
380 MVT VecVT = N->getOperand(0).getSimpleValueType();
Craig Topper9563cab2017-10-08 01:33:42 +0000381 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000382 }
383
384 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
385 const SDLoc &DL) {
386 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
387 uint64_t Index = N->getConstantOperandVal(2);
388 MVT VecVT = N->getSimpleValueType(0);
Craig Topper9563cab2017-10-08 01:33:42 +0000389 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000390 }
391
Sanjay Patelb5723d02015-10-13 15:12:27 +0000392 /// Return an SDNode that returns the value of the global base register.
393 /// Output instructions required to initialize the global base register,
394 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000395 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000396
Sanjay Patelb5723d02015-10-13 15:12:27 +0000397 /// Return a reference to the TargetMachine, casted to the target-specific
398 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000399 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000400 return static_cast<const X86TargetMachine &>(TM);
401 }
402
Sanjay Patelb5723d02015-10-13 15:12:27 +0000403 /// Return a reference to the TargetInstrInfo, casted to the target-specific
404 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000405 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000406 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000407 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000408
409 /// \brief Address-mode matching performs shift-of-and to and-of-shift
410 /// reassociation in order to expose more scaled addressing
411 /// opportunities.
412 bool ComplexPatternFuncMutatesDAG() const override {
413 return true;
414 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000415
416 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
417
418 /// Returns whether this is a relocatable immediate in the range
419 /// [-2^Width .. 2^Width-1].
420 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
421 if (auto *CN = dyn_cast<ConstantSDNode>(N))
422 return isInt<Width>(CN->getSExtValue());
423 return isSExtAbsoluteSymbolRef(Width, N);
424 }
Craig Topper4de6f582017-08-19 23:21:22 +0000425
426 // Indicates we should prefer to use a non-temporal load for this load.
427 bool useNonTemporalLoad(LoadSDNode *N) const {
428 if (!N->isNonTemporal())
429 return false;
430
431 unsigned StoreSize = N->getMemoryVT().getStoreSize();
432
433 if (N->getAlignment() < StoreSize)
434 return false;
435
436 switch (StoreSize) {
437 default: llvm_unreachable("Unsupported store size");
438 case 16:
439 return Subtarget->hasSSE41();
440 case 32:
441 return Subtarget->hasAVX2();
442 case 64:
443 return Subtarget->hasAVX512();
444 }
445 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000446
447 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000448 bool matchBEXTRFromAnd(SDNode *Node);
Sanjay Patel74a1eef2018-01-19 16:37:25 +0000449 bool shrinkAndImmediate(SDNode *N);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000450 bool isMaskZeroExtended(SDNode *N) const;
Chris Lattner655e7df2005-11-16 01:54:32 +0000451 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000452}
453
Evan Cheng72bb66a2006-08-08 00:31:00 +0000454
Craig Topperba3cc2e2017-09-25 18:43:13 +0000455// Returns true if this masked compare can be implemented legally with this
456// type.
457static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
Uriel Korachbb866862017-11-06 09:22:38 +0000458 unsigned Opcode = N->getOpcode();
Craig Topper15d69732018-01-28 00:56:30 +0000459 if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMU ||
Craig Topper48d5ed22018-02-28 08:14:28 +0000460 Opcode == X86ISD::CMPM_RND || Opcode == X86ISD::VFPCLASS) {
Craig Topperba3cc2e2017-09-25 18:43:13 +0000461 // We can get 256-bit 8 element types here without VLX being enabled. When
462 // this happens we will use 512-bit operations and the mask will not be
463 // zero extended.
Uriel Koracheb47d952017-11-06 08:32:45 +0000464 EVT OpVT = N->getOperand(0).getValueType();
Craig Topperd58c1652018-01-07 18:20:37 +0000465 if (OpVT.is256BitVector() || OpVT.is128BitVector())
Craig Topperba3cc2e2017-09-25 18:43:13 +0000466 return Subtarget->hasVLX();
467
468 return true;
469 }
Craig Topper48d5ed22018-02-28 08:14:28 +0000470 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
471 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
472 Opcode == X86ISD::FSETCCM_RND)
473 return true;
Craig Topperba3cc2e2017-09-25 18:43:13 +0000474
475 return false;
476}
477
478// Returns true if we can assume the writer of the mask has zero extended it
479// for us.
480bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
481 // If this is an AND, check if we have a compare on either side. As long as
482 // one side guarantees the mask is zero extended, the AND will preserve those
483 // zeros.
484 if (N->getOpcode() == ISD::AND)
485 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
486 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
487
488 return isLegalMaskCompare(N, Subtarget);
489}
490
Evan Cheng5e73ff22010-02-15 19:41:07 +0000491bool
492X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000493 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000494
Evan Cheng5e73ff22010-02-15 19:41:07 +0000495 if (!N.hasOneUse())
496 return false;
497
498 if (N.getOpcode() != ISD::LOAD)
499 return true;
500
501 // If N is a load, do additional profitability checks.
502 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000503 switch (U->getOpcode()) {
504 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000505 case X86ISD::ADD:
506 case X86ISD::SUB:
507 case X86ISD::AND:
508 case X86ISD::XOR:
509 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000510 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000511 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000512 case ISD::AND:
513 case ISD::OR:
514 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000515 SDValue Op1 = U->getOperand(1);
516
Evan Cheng83bdb382008-11-27 00:49:46 +0000517 // If the other operand is a 8-bit immediate we should fold the immediate
518 // instead. This reduces code size.
519 // e.g.
520 // movl 4(%esp), %eax
521 // addl $4, %eax
522 // vs.
523 // movl $4, %eax
524 // addl 4(%esp), %eax
525 // The former is 2 bytes shorter. In case where the increment is 1, then
526 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000527 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000528 if (Imm->getAPIntValue().isSignedIntN(8))
529 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000530
531 // If the other operand is a TLS address, we should fold it instead.
532 // This produces
533 // movl %gs:0, %eax
534 // leal i@NTPOFF(%eax), %eax
535 // instead of
536 // movl $i@NTPOFF, %eax
537 // addl %gs:0, %eax
538 // if the block also has an access to a second TLS address this will save
539 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000540 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000541 if (Op1.getOpcode() == X86ISD::Wrapper) {
542 SDValue Val = Op1.getOperand(0);
543 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
544 return false;
545 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000546 }
547 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000548 }
549
550 return true;
551}
552
Sanjay Patelb5723d02015-10-13 15:12:27 +0000553/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000554/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000555static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
556 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000557 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000558 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000559 if (Chain.getNode() == Load.getNode())
560 Ops.push_back(Load.getOperand(0));
561 else {
562 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000563 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000564 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
565 if (Chain.getOperand(i).getNode() == Load.getNode())
566 Ops.push_back(Load.getOperand(0));
567 else
568 Ops.push_back(Chain.getOperand(i));
569 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000570 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000571 Ops.clear();
572 Ops.push_back(NewChain);
573 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000574 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000575 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000576 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000577 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000578
Evan Chengf00f1e52008-08-25 21:27:18 +0000579 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000580 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000581 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000582 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000583}
584
Sanjay Patelb5723d02015-10-13 15:12:27 +0000585/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000586/// moved below CALLSEQ_START and the chains leading up to the call.
587/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000588/// In the case of a tail call, there isn't a callseq node between the call
589/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000590static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000591 // The transformation is somewhat dangerous if the call's chain was glued to
592 // the call. After MoveBelowOrigChain the load is moved between the call and
593 // the chain, this can create a cycle if the load is not folded. So it is
594 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000595 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000596 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000597 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000598 if (!LD ||
599 LD->isVolatile() ||
600 LD->getAddressingMode() != ISD::UNINDEXED ||
601 LD->getExtensionType() != ISD::NON_EXTLOAD)
602 return false;
603
604 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000605 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000606 if (!Chain.hasOneUse())
607 return false;
608 Chain = Chain.getOperand(0);
609 }
Evan Chengd703df62010-03-14 03:48:46 +0000610
611 if (!Chain.getNumOperands())
612 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000613 // Since we are not checking for AA here, conservatively abort if the chain
614 // writes to memory. It's not safe to move the callee (a load) across a store.
615 if (isa<MemSDNode>(Chain.getNode()) &&
616 cast<MemSDNode>(Chain.getNode())->writeMem())
617 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000618 if (Chain.getOperand(0).getNode() == Callee.getNode())
619 return true;
620 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000621 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
622 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000623 return true;
624 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000625}
626
Chris Lattner8d637042010-03-02 23:12:51 +0000627void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000628 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Matthias Braunf1caa282017-12-15 22:22:58 +0000629 OptForSize = MF->getFunction().optForSize();
630 OptForMinSize = MF->getFunction().optForMinSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000631 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000632
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000633 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
634 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000635 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000636
Craig Topper7e910a92018-02-01 17:08:39 +0000637 // If this is a target specific AND node with no flag usages, turn it back
638 // into ISD::AND to enable test instruction matching.
639 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
640 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
641 N->getOperand(0), N->getOperand(1));
642 --I;
643 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
644 ++I;
645 CurDAG->DeleteNode(N);
646 }
647
Evan Chengd703df62010-03-14 03:48:46 +0000648 if (OptLevel != CodeGenOpt::None &&
Chandler Carruthc58f2162018-01-22 22:05:25 +0000649 // Only do this when the target can fold the load into the call or
650 // jmp.
651 !Subtarget->useRetpoline() &&
Craig Topper62c47a22017-08-29 05:14:27 +0000652 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000653 (N->getOpcode() == X86ISD::TC_RETURN &&
Evan Cheng847ad442012-10-05 01:48:22 +0000654 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000655 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000656 /// Also try moving call address load from outside callseq_start to just
657 /// before the call to allow it to be folded.
658 ///
659 /// [Load chain]
660 /// ^
661 /// |
662 /// [Load]
663 /// ^ ^
664 /// | |
665 /// / \--
666 /// / |
667 ///[CALLSEQ_START] |
668 /// ^ |
669 /// | |
670 /// [LOAD/C2Reg] |
671 /// | |
672 /// \ /
673 /// \ /
674 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000675 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000676 SDValue Chain = N->getOperand(0);
677 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000678 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000679 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000680 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000681 ++NumLoadMoved;
682 continue;
683 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000684
Chris Lattner8d637042010-03-02 23:12:51 +0000685 // Lower fpround and fpextend nodes that target the FP stack to be store and
686 // load to the stack. This is a gross hack. We would like to simply mark
687 // these as being illegal, but when we do that, legalize produces these when
688 // it expands calls, then expands these in the same legalize pass. We would
689 // like dag combine to be able to hack on these between the call expansion
690 // and the node legalization. As such this pass basically does "really
691 // late" legalization of these inline with the X86 isel pass.
692 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000693 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
694 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000695
Craig Topper83e042a2013-08-15 05:57:07 +0000696 MVT SrcVT = N->getOperand(0).getSimpleValueType();
697 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000698
699 // If any of the sources are vectors, no fp stack involved.
700 if (SrcVT.isVector() || DstVT.isVector())
701 continue;
702
703 // If the source and destination are SSE registers, then this is a legal
704 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000705 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000706 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000707 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
708 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000709 if (SrcIsSSE && DstIsSSE)
710 continue;
711
Chris Lattnerd587e582008-03-09 07:05:32 +0000712 if (!SrcIsSSE && !DstIsSSE) {
713 // If this is an FPStack extension, it is a noop.
714 if (N->getOpcode() == ISD::FP_EXTEND)
715 continue;
716 // If this is a value-preserving FPStack truncation, it is a noop.
717 if (N->getConstantOperandVal(1))
718 continue;
719 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000720
Chris Lattnera91f77e2008-01-24 08:07:48 +0000721 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
722 // FPStack has extload and truncstore. SSE can fold direct loads into other
723 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000724 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000725 if (N->getOpcode() == ISD::FP_ROUND)
726 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
727 else
728 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000729
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000730 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000731 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000732
Chris Lattnera91f77e2008-01-24 08:07:48 +0000733 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000734 SDValue Store =
735 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
736 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000737 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000738 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000739
740 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
741 // extload we created. This will cause general havok on the dag because
742 // anything below the conversion could be folded into other existing nodes.
743 // To avoid invalidating 'I', back it up to the convert node.
744 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000745 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000746
Chris Lattnera91f77e2008-01-24 08:07:48 +0000747 // Now that we did that, the node is dead. Increment the iterator to the
748 // next node to process, then delete N.
749 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000750 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000751 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000752}
753
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000754
Sanjay Patelb5723d02015-10-13 15:12:27 +0000755/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000756void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000757 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000758 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000759 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000760
761 TargetLowering::CallLoweringInfo CLI(*CurDAG);
762 CLI.setChain(CurDAG->getRoot())
763 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000764 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000765 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000766 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
767 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
768 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000769 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000770}
771
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000772void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000773 // If this is main, emit special code for main.
Matthias Braunf1caa282017-12-15 22:22:58 +0000774 const Function &F = MF->getFunction();
775 if (F.hasExternalLinkage() && F.getName() == "main")
776 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000777}
778
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000779static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000780 // On 64-bit platforms, we can run into an issue where a frame index
781 // includes a displacement that, when added to the explicit displacement,
782 // will overflow the displacement field. Assuming that the frame index
783 // displacement fits into a 31-bit integer (which is only slightly more
784 // aggressive than the current fundamental assumption that it fits into
785 // a 32-bit integer), a 31-bit disp should always be safe.
786 return isInt<31>(Val);
787}
788
Sanjay Patel85030aa2015-10-13 16:23:00 +0000789bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000790 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000791 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000792 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000793 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000794 int64_t Val = AM.Disp + Offset;
795 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000796 if (Subtarget->is64Bit()) {
797 if (!X86::isOffsetSuitableForCodeModel(Val, M,
798 AM.hasSymbolicDisplacement()))
799 return true;
800 // In addition to the checks required for a register base, check that
801 // we do not try to use an unsafe Disp with a frame index.
802 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
803 !isDispSafeForFrameIndex(Val))
804 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000805 }
Eli Friedman344ec792011-07-13 21:29:53 +0000806 AM.Disp = Val;
807 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000808
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000809}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000810
Sanjay Patel85030aa2015-10-13 16:23:00 +0000811bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000812 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000813
Chris Lattner8a236b62010-09-22 04:39:11 +0000814 // load gs:0 -> GS segment register.
815 // load fs:0 -> FS segment register.
816 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000817 // This optimization is valid because the GNU TLS model defines that
818 // gs:0 (or fs:0 on X86-64) contains its own address.
819 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000821 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000822 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
823 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000824 switch (N->getPointerInfo().getAddrSpace()) {
825 case 256:
826 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
827 return false;
828 case 257:
829 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
830 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000831 // Address space 258 is not handled here, because it is not used to
832 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000833 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000834
Rafael Espindola3b2df102009-04-08 21:14:34 +0000835 return true;
836}
837
Sanjay Patelb5723d02015-10-13 15:12:27 +0000838/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
839/// mode. These wrap things that will resolve down into a symbol reference.
840/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000841bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000842 // If the addressing mode already has a symbol as the displacement, we can
843 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000844 if (AM.hasSymbolicDisplacement())
845 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000846
847 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000848 CodeModel::Model M = TM.getCodeModel();
849
Chris Lattnerfea81da2009-06-27 04:16:01 +0000850 // Handle X86-64 rip-relative addresses. We check this before checking direct
851 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000852 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000853 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
854 // they cannot be folded into immediate fields.
855 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000856 (M == CodeModel::Small || M == CodeModel::Kernel)) {
857 // Base and index reg must be 0 in order to use %rip as base.
858 if (AM.hasBaseOrIndexReg())
859 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000860 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000861 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000862 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000863 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000864 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000865 AM = Backup;
866 return true;
867 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000868 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000869 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000870 AM.CP = CP->getConstVal();
871 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000872 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000873 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000874 AM = Backup;
875 return true;
876 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000877 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
878 AM.ES = S->getSymbol();
879 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000880 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
881 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000882 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000883 AM.JT = J->getIndex();
884 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000885 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
886 X86ISelAddressMode Backup = AM;
887 AM.BlockAddr = BA->getBlockAddress();
888 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000889 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000890 AM = Backup;
891 return true;
892 }
893 } else
894 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000895
Chris Lattnerfea81da2009-06-27 04:16:01 +0000896 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000897 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000898 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000899 }
900
901 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000902 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
903 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000904 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000905 M == CodeModel::Small || M == CodeModel::Kernel) {
906 assert(N.getOpcode() != X86ISD::WrapperRIP &&
907 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000908 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
909 AM.GV = G->getGlobal();
910 AM.Disp += G->getOffset();
911 AM.SymbolFlags = G->getTargetFlags();
912 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
913 AM.CP = CP->getConstVal();
914 AM.Align = CP->getAlignment();
915 AM.Disp += CP->getOffset();
916 AM.SymbolFlags = CP->getTargetFlags();
917 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
918 AM.ES = S->getSymbol();
919 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000920 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
921 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000922 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000923 AM.JT = J->getIndex();
924 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000925 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
926 AM.BlockAddr = BA->getBlockAddress();
927 AM.Disp += BA->getOffset();
928 AM.SymbolFlags = BA->getTargetFlags();
929 } else
930 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000931 return false;
932 }
933
934 return true;
935}
936
Sanjay Patelb5723d02015-10-13 15:12:27 +0000937/// Add the specified node to the specified addressing mode, returning true if
938/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000939bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
940 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000941 return true;
942
943 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
944 // a smaller encoding and avoids a scaled-index.
945 if (AM.Scale == 2 &&
946 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000947 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000948 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000949 AM.Scale = 1;
950 }
951
Dan Gohman05046082009-08-20 18:23:44 +0000952 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
953 // because it has a smaller encoding.
954 // TODO: Which other code models can use this?
955 if (TM.getCodeModel() == CodeModel::Small &&
956 Subtarget->is64Bit() &&
957 AM.Scale == 1 &&
958 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000959 AM.Base_Reg.getNode() == nullptr &&
960 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000961 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000962 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000963 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000964
Dan Gohman824ab402009-07-22 23:26:55 +0000965 return false;
966}
967
Sanjay Patelefab8b02015-10-21 18:56:06 +0000968bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
969 unsigned Depth) {
970 // Add an artificial use to this node so that we can keep track of
971 // it if it gets CSE'd with a different node.
972 HandleSDNode Handle(N);
973
974 X86ISelAddressMode Backup = AM;
975 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
976 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
977 return false;
978 AM = Backup;
979
980 // Try again after commuting the operands.
981 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
982 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
983 return false;
984 AM = Backup;
985
986 // If we couldn't fold both operands into the address at the same time,
987 // see if we can just put each operand into a register and fold at least
988 // the add.
989 if (AM.BaseType == X86ISelAddressMode::RegBase &&
990 !AM.Base_Reg.getNode() &&
991 !AM.IndexReg.getNode()) {
992 N = Handle.getValue();
993 AM.Base_Reg = N.getOperand(0);
994 AM.IndexReg = N.getOperand(1);
995 AM.Scale = 1;
996 return false;
997 }
998 N = Handle.getValue();
999 return true;
1000}
1001
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001002// Insert a node into the DAG at least before the Pos node's position. This
1003// will reposition the node as needed, and will assign it a node ID that is <=
1004// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1005// IDs! The selection DAG must no longer depend on their uniqueness when this
1006// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001007static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001008 if (N.getNode()->getNodeId() == -1 ||
1009 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +00001010 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +00001011 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
1012 }
1013}
1014
Adam Nemet0c7caf42014-09-16 17:14:10 +00001015// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1016// safe. This allows us to convert the shift and and into an h-register
1017// extract and a scaled index. Returns false if the simplification is
1018// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001019static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1020 uint64_t Mask,
1021 SDValue Shift, SDValue X,
1022 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001023 if (Shift.getOpcode() != ISD::SRL ||
1024 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1025 !Shift.hasOneUse())
1026 return true;
1027
1028 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1029 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1030 Mask != (0xffu << ScaleLog))
1031 return true;
1032
Craig Topper83e042a2013-08-15 05:57:07 +00001033 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001034 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001035 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1036 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001037 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1038 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001039 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001040 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1041
Chandler Carrutheb21da02012-01-12 01:34:44 +00001042 // Insert the new nodes into the topological ordering. We must do this in
1043 // a valid topological ordering as nothing is going to go back and re-sort
1044 // these nodes. We continually insert before 'N' in sequence as this is
1045 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1046 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001047 insertDAGNode(DAG, N, Eight);
1048 insertDAGNode(DAG, N, Srl);
1049 insertDAGNode(DAG, N, NewMask);
1050 insertDAGNode(DAG, N, And);
1051 insertDAGNode(DAG, N, ShlCount);
1052 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001053 DAG.ReplaceAllUsesWith(N, Shl);
1054 AM.IndexReg = And;
1055 AM.Scale = (1 << ScaleLog);
1056 return false;
1057}
1058
Chandler Carruthaa01e662012-01-11 09:35:00 +00001059// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1060// allows us to fold the shift into this addressing mode. Returns false if the
1061// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001062static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1063 uint64_t Mask,
1064 SDValue Shift, SDValue X,
1065 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001066 if (Shift.getOpcode() != ISD::SHL ||
1067 !isa<ConstantSDNode>(Shift.getOperand(1)))
1068 return true;
1069
1070 // Not likely to be profitable if either the AND or SHIFT node has more
1071 // than one use (unless all uses are for address computation). Besides,
1072 // isel mechanism requires their node ids to be reused.
1073 if (!N.hasOneUse() || !Shift.hasOneUse())
1074 return true;
1075
1076 // Verify that the shift amount is something we can fold.
1077 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1078 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1079 return true;
1080
Craig Topper83e042a2013-08-15 05:57:07 +00001081 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001082 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001083 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001084 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1085 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1086
Chandler Carrutheb21da02012-01-12 01:34:44 +00001087 // Insert the new nodes into the topological ordering. We must do this in
1088 // a valid topological ordering as nothing is going to go back and re-sort
1089 // these nodes. We continually insert before 'N' in sequence as this is
1090 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1091 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001092 insertDAGNode(DAG, N, NewMask);
1093 insertDAGNode(DAG, N, NewAnd);
1094 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001095 DAG.ReplaceAllUsesWith(N, NewShift);
1096
1097 AM.Scale = 1 << ShiftAmt;
1098 AM.IndexReg = NewAnd;
1099 return false;
1100}
1101
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001102// Implement some heroics to detect shifts of masked values where the mask can
1103// be replaced by extending the shift and undoing that in the addressing mode
1104// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1105// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1106// the addressing mode. This results in code such as:
1107//
1108// int f(short *y, int *lookup_table) {
1109// ...
1110// return *y + lookup_table[*y >> 11];
1111// }
1112//
1113// Turning into:
1114// movzwl (%rdi), %eax
1115// movl %eax, %ecx
1116// shrl $11, %ecx
1117// addl (%rsi,%rcx,4), %eax
1118//
1119// Instead of:
1120// movzwl (%rdi), %eax
1121// movl %eax, %ecx
1122// shrl $9, %ecx
1123// andl $124, %rcx
1124// addl (%rsi,%rcx), %eax
1125//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001126// Note that this function assumes the mask is provided as a mask *after* the
1127// value is shifted. The input chain may or may not match that, but computing
1128// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001129static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1130 uint64_t Mask,
1131 SDValue Shift, SDValue X,
1132 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001133 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1134 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001135 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001136
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001137 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001138 unsigned MaskLZ = countLeadingZeros(Mask);
1139 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001140
1141 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001142 // from the trailing zeros of the mask.
1143 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001144
1145 // There is nothing we can do here unless the mask is removing some bits.
1146 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1147 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1148
1149 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001150 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001151
1152 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001153 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001154 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1155 if (MaskLZ < ScaleDown)
1156 return true;
1157 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001158
1159 // The final check is to ensure that any masked out high bits of X are
1160 // already known to be zero. Otherwise, the mask has a semantic impact
1161 // other than masking out a couple of low bits. Unfortunately, because of
1162 // the mask, zero extensions will be removed from operands in some cases.
1163 // This code works extra hard to look through extensions because we can
1164 // replace them with zero extensions cheaply if necessary.
1165 bool ReplacingAnyExtend = false;
1166 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001167 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1168 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001169 // Assume that we'll replace the any-extend with a zero-extend, and
1170 // narrow the search to the extended value.
1171 X = X.getOperand(0);
1172 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1173 ReplacingAnyExtend = true;
1174 }
Craig Topper83e042a2013-08-15 05:57:07 +00001175 APInt MaskedHighBits =
1176 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001177 KnownBits Known;
1178 DAG.computeKnownBits(X, Known);
1179 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001180
1181 // We've identified a pattern that can be transformed into a single shift
1182 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001183 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001184 if (ReplacingAnyExtend) {
1185 assert(X.getValueType() != VT);
1186 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001187 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001188 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001189 X = NewX;
1190 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001191 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001192 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001193 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001194 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001195 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001196
1197 // Insert the new nodes into the topological ordering. We must do this in
1198 // a valid topological ordering as nothing is going to go back and re-sort
1199 // these nodes. We continually insert before 'N' in sequence as this is
1200 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1201 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001202 insertDAGNode(DAG, N, NewSRLAmt);
1203 insertDAGNode(DAG, N, NewSRL);
1204 insertDAGNode(DAG, N, NewSHLAmt);
1205 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001206 DAG.ReplaceAllUsesWith(N, NewSHL);
1207
1208 AM.Scale = 1 << AMShiftAmt;
1209 AM.IndexReg = NewSRL;
1210 return false;
1211}
Matt Morehouse9e658c92017-12-01 22:20:26 +00001212
Sanjay Patel85030aa2015-10-13 16:23:00 +00001213bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001214 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001215 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001216 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001217 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001218 AM.dump();
1219 });
Matt Morehouse9e658c92017-12-01 22:20:26 +00001220 // Limit recursion.
1221 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001222 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001223
Chris Lattnerfea81da2009-06-27 04:16:01 +00001224 // If this is already a %rip relative address, we can only merge immediates
1225 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001226 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001227 if (AM.isRIPRelative()) {
1228 // FIXME: JumpTable and ExternalSymbol address currently don't like
1229 // displacements. It isn't very important, but this should be fixed for
1230 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001231 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1232 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001233
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001234 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001235 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001236 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001237 return true;
1238 }
1239
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001240 switch (N.getOpcode()) {
1241 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001242 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001243 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001244 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1245 // Use the symbol and don't prefix it.
1246 AM.MCSym = ESNode->getMCSymbol();
1247 return false;
1248 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001249 break;
1250 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001251 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001252 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001253 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001254 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001255 break;
1256 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001257
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001258 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001259 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001260 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001261 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001262 break;
1263
Rafael Espindola3b2df102009-04-08 21:14:34 +00001264 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001265 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001266 return false;
1267 break;
1268
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001269 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001270 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001271 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001272 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001273 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001274 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001275 return false;
1276 }
1277 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001278
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001279 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001280 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001281 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001282
Simon Pilgrim7f032312017-05-12 13:08:45 +00001283 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001284 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001285 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1286 // that the base operand remains free for further matching. If
1287 // the base doesn't end up getting used, a post-processing step
1288 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001289 if (Val == 1 || Val == 2 || Val == 3) {
1290 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001291 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001292
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001293 // Okay, we know that we have a scale by now. However, if the scaled
1294 // value is an add of something and a constant, we can fold the
1295 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001296 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001297 AM.IndexReg = ShVal.getOperand(0);
1298 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001299 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001300 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001301 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001302 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001303
1304 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001305 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001306 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001307 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001308 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001309
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001310 case ISD::SRL: {
1311 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001312 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001313
1314 SDValue And = N.getOperand(0);
1315 if (And.getOpcode() != ISD::AND) break;
1316 SDValue X = And.getOperand(0);
1317
1318 // We only handle up to 64-bit values here as those are what matter for
1319 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001320 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001321
1322 // The mask used for the transform is expected to be post-shift, but we
1323 // found the shift first so just apply the shift to the mask before passing
1324 // it down.
1325 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1326 !isa<ConstantSDNode>(And.getOperand(1)))
1327 break;
1328 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1329
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001330 // Try to fold the mask and shift into the scale, and return false if we
1331 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001332 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001333 return false;
1334 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001335 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001336
Dan Gohmanbf474952007-10-22 20:22:24 +00001337 case ISD::SMUL_LOHI:
1338 case ISD::UMUL_LOHI:
1339 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001340 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001341 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001342 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001343 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001344 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001345 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001346 AM.Base_Reg.getNode() == nullptr &&
1347 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001348 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001349 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1350 CN->getZExtValue() == 9) {
1351 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001352
Simon Pilgrim7f032312017-05-12 13:08:45 +00001353 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001354 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001355
1356 // Okay, we know that we have a scale by now. However, if the scaled
1357 // value is an add of something and a constant, we can fold the
1358 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001359 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001360 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1361 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001362 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001363 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001364 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001365 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001366 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001367 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001368 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001369 }
1370
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001371 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001372 return false;
1373 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001374 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001375 break;
1376
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001377 case ISD::SUB: {
1378 // Given A-B, if A can be completely folded into the address and
1379 // the index field with the index field unused, use -B as the index.
1380 // This is a win if a has multiple parts that can be folded into
1381 // the address. Also, this saves a mov if the base register has
1382 // other uses, since it avoids a two-address sub instruction, however
1383 // it costs an additional mov if the index register has other uses.
1384
Dan Gohman99ba4da2010-06-18 01:24:29 +00001385 // Add an artificial use to this node so that we can keep track of
1386 // it if it gets CSE'd with a different node.
1387 HandleSDNode Handle(N);
1388
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001389 // Test if the LHS of the sub can be folded.
1390 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001391 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001392 AM = Backup;
1393 break;
1394 }
1395 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001396 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001397 AM = Backup;
1398 break;
1399 }
Evan Cheng68333f52010-03-17 23:58:35 +00001400
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001401 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001402 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001403 // If the RHS involves a register with multiple uses, this
1404 // transformation incurs an extra mov, due to the neg instruction
1405 // clobbering its operand.
1406 if (!RHS.getNode()->hasOneUse() ||
1407 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1408 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1409 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1410 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001411 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001412 ++Cost;
1413 // If the base is a register with multiple uses, this
1414 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001415 // FIXME: Don't rely on DELETED_NODEs.
1416 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1417 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001418 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001419 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1420 --Cost;
1421 // If the folded LHS was interesting, this transformation saves
1422 // address arithmetic.
1423 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1424 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1425 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1426 --Cost;
1427 // If it doesn't look like it may be an overall win, don't do it.
1428 if (Cost >= 0) {
1429 AM = Backup;
1430 break;
1431 }
1432
1433 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001434 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001435 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1436 AM.IndexReg = Neg;
1437 AM.Scale = 1;
1438
1439 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001440 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1441 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001442 return false;
1443 }
1444
Sanjay Patelefab8b02015-10-21 18:56:06 +00001445 case ISD::ADD:
1446 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001447 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001448 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001449
Sanjay Patel533c10c2015-11-09 23:31:38 +00001450 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001451 // We want to look through a transform in InstCombine and DAGCombiner that
1452 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001453 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001454 // An 'lea' can then be used to match the shift (multiply) and add:
1455 // and $1, %esi
1456 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001457 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1458 !matchAdd(N, AM, Depth))
1459 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001460 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001461
Evan Cheng827d30d2007-12-13 00:43:27 +00001462 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001463 // Perform some heroic transforms on an and of a constant-count shift
1464 // with a constant to enable use of the scaled offset field.
1465
Evan Cheng827d30d2007-12-13 00:43:27 +00001466 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001467 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001468
Chandler Carruthaa01e662012-01-11 09:35:00 +00001469 SDValue Shift = N.getOperand(0);
1470 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001471 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001472
1473 // We only handle up to 64-bit values here as those are what matter for
1474 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001475 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001476
Chandler Carruthb0049f42012-01-11 09:35:04 +00001477 if (!isa<ConstantSDNode>(N.getOperand(1)))
1478 break;
1479 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001480
Chandler Carruth51d30762012-01-11 08:48:20 +00001481 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001482 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001483 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001484
Chandler Carruth51d30762012-01-11 08:48:20 +00001485 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001486 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001487 return false;
1488
Chandler Carruthaa01e662012-01-11 09:35:00 +00001489 // Try to swap the mask and shift to place shifts which can be done as
1490 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001491 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001492 return false;
1493 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001494 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001495 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001496
Sanjay Patel85030aa2015-10-13 16:23:00 +00001497 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001498}
1499
Sanjay Patelb5723d02015-10-13 15:12:27 +00001500/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001501/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001502bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001503 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001504 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001505 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001506 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001507 AM.IndexReg = N;
1508 AM.Scale = 1;
1509 return false;
1510 }
1511
1512 // Otherwise, we cannot select it.
1513 return true;
1514 }
1515
1516 // Default, generate it as a register.
1517 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001518 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001519 return false;
1520}
1521
Craig Topperc314f462017-11-13 17:53:59 +00001522/// Helper for selectVectorAddr. Handles things that can be folded into a
1523/// gather scatter address. The index register and scale should have already
1524/// been handled.
1525bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
1526 // TODO: Support other operations.
1527 switch (N.getOpcode()) {
Craig Topperaf4eb172018-01-10 19:16:05 +00001528 case ISD::Constant: {
1529 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1530 if (!foldOffsetIntoAddress(Val, AM))
1531 return false;
1532 break;
1533 }
Craig Topperc314f462017-11-13 17:53:59 +00001534 case X86ISD::Wrapper:
1535 if (!matchWrapper(N, AM))
1536 return false;
1537 break;
1538 }
1539
1540 return matchAddressBase(N, AM);
1541}
1542
Craig Topperbb001c6d2017-11-10 19:26:04 +00001543bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1544 SDValue &Scale, SDValue &Index,
1545 SDValue &Disp, SDValue &Segment) {
Craig Topperc314f462017-11-13 17:53:59 +00001546 X86ISelAddressMode AM;
Craig Topperee740442017-11-22 08:10:54 +00001547 auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
1548 AM.IndexReg = Mgs->getIndex();
Craig Topperaf4eb172018-01-10 19:16:05 +00001549 AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
Craig Topperbb001c6d2017-11-10 19:26:04 +00001550
Craig Topperbb001c6d2017-11-10 19:26:04 +00001551 unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001552 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001553 if (AddrSpace == 256)
1554 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1555 if (AddrSpace == 257)
1556 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001557 if (AddrSpace == 258)
1558 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001559
Craig Topperaf4eb172018-01-10 19:16:05 +00001560 // Try to match into the base and displacement fields.
1561 if (matchVectorAddress(N, AM))
Craig Topperc314f462017-11-13 17:53:59 +00001562 return false;
1563
1564 MVT VT = N.getSimpleValueType();
1565 if (AM.BaseType == X86ISelAddressMode::RegBase) {
1566 if (!AM.Base_Reg.getNode())
1567 AM.Base_Reg = CurDAG->getRegister(0, VT);
1568 }
1569
1570 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001571 return true;
1572}
1573
Sanjay Patelb5723d02015-10-13 15:12:27 +00001574/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001575/// It returns the operands which make up the maximal addressing mode it can
1576/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001577///
1578/// Parent is the parent node of the addr operand that is being matched. It
1579/// is always a load, store, atomic node, or null. It is only null when
1580/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001581bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001582 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001583 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001584 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001585
Chris Lattner8a236b62010-09-22 04:39:11 +00001586 if (Parent &&
1587 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1588 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001589 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001590 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001591 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1592 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1593 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001594 unsigned AddrSpace =
1595 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001596 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001597 if (AddrSpace == 256)
1598 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1599 if (AddrSpace == 257)
1600 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001601 if (AddrSpace == 258)
1602 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001603 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001604
Sanjay Patel85030aa2015-10-13 16:23:00 +00001605 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001606 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001607
Craig Topper83e042a2013-08-15 05:57:07 +00001608 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001609 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001610 if (!AM.Base_Reg.getNode())
1611 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001612 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001613
Gabor Greiff304a7a2008-08-28 21:40:38 +00001614 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001615 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001616
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001617 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001618 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001619}
1620
Craig Topper8078dd22017-08-21 16:04:04 +00001621// We can only fold a load if all nodes between it and the root node have a
1622// single use. If there are additional uses, we could end up duplicating the
1623// load.
1624static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1625 SDNode *User = *N->use_begin();
1626 while (User != Root) {
1627 if (!User->hasOneUse())
1628 return false;
1629 User = *User->use_begin();
1630 }
1631
1632 return true;
1633}
1634
Sanjay Patelb5723d02015-10-13 15:12:27 +00001635/// Match a scalar SSE load. In particular, we want to match a load whose top
1636/// elements are either undef or zeros. The load flavor is derived from the
1637/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001638///
1639/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001640/// PatternChainNode: this is the matched node that has a chain input and
1641/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001642bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001643 SDValue N, SDValue &Base,
1644 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001645 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001646 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001647 // We can allow a full vector load here since narrowing a load is ok.
1648 if (ISD::isNON_EXTLoad(N.getNode())) {
1649 PatternNodeWithChain = N;
1650 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001651 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1652 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001653 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1654 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1655 Segment);
1656 }
1657 }
1658
1659 // We can also match the special zero extended load opcode.
1660 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1661 PatternNodeWithChain = N;
1662 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001663 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1664 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001665 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1666 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1667 Segment);
1668 }
1669 }
1670
Craig Topper991d1ca2016-11-26 17:29:25 +00001671 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1672 // once. Otherwise the load might get duplicated and the chain output of the
1673 // duplicate load will not be observed by all dependencies.
1674 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001675 PatternNodeWithChain = N.getOperand(0);
1676 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001677 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001678 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1679 hasSingleUsesFromRoot(Root, N.getNode())) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001680 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001681 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1682 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001683 }
1684 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001685
1686 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001687 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001688 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001689 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001690 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001691 N.getOperand(0).getNode()->hasOneUse()) {
1692 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1693 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001694 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001695 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1696 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Toppere266e122016-11-26 18:43:24 +00001697 // Okay, this is a zero extending load. Fold it.
1698 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1699 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1700 Segment);
1701 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001702 }
Craig Toppere266e122016-11-26 18:43:24 +00001703
Chris Lattner398195e2006-10-07 21:55:32 +00001704 return false;
1705}
1706
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001707
Sanjay Patel85030aa2015-10-13 16:23:00 +00001708bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001709 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1710 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001711 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001712 return false;
1713
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001714 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001715 return true;
1716 }
1717
1718 // In static codegen with small code model, we can get the address of a label
1719 // into a register with 'movl'. TableGen has already made sure we're looking
1720 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001721 assert(N->getOpcode() == X86ISD::Wrapper &&
1722 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001723 N = N.getOperand(0);
1724
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001725 // At least GNU as does not accept 'movl' for TPOFF relocations.
1726 // FIXME: We could use 'movl' when we know we are targeting MC.
1727 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001728 return false;
1729
1730 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001731 if (N->getOpcode() != ISD::TargetGlobalAddress)
1732 return TM.getCodeModel() == CodeModel::Small;
1733
1734 Optional<ConstantRange> CR =
1735 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1736 if (!CR)
1737 return TM.getCodeModel() == CodeModel::Small;
1738
1739 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001740}
1741
Sanjay Patel85030aa2015-10-13 16:23:00 +00001742bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001743 SDValue &Scale, SDValue &Index,
1744 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001745 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1746 SDLoc DL(N);
Matt Morehouse9e658c92017-12-01 22:20:26 +00001747
Sanjay Patel85030aa2015-10-13 16:23:00 +00001748 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001749 return false;
1750
Tim Northover6833e3f2013-06-10 20:43:49 +00001751 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1752 if (RN && RN->getReg() == 0)
1753 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001754 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001755 // Base could already be %rip, particularly in the x32 ABI.
1756 Base = SDValue(CurDAG->getMachineNode(
1757 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001758 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001759 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001760 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001761 0);
1762 }
1763
1764 RN = dyn_cast<RegisterSDNode>(Index);
1765 if (RN && RN->getReg() == 0)
1766 Index = CurDAG->getRegister(0, MVT::i64);
1767 else {
1768 assert(Index.getValueType() == MVT::i32 &&
1769 "Expect to be extending 32-bit registers for use in LEA");
1770 Index = SDValue(CurDAG->getMachineNode(
1771 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001772 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001773 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001774 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1775 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001776 0);
1777 }
1778
1779 return true;
1780}
1781
Sanjay Patelb5723d02015-10-13 15:12:27 +00001782/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001783/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001784bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001785 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001786 SDValue &Index, SDValue &Disp,
1787 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001788 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001789
Justin Bogner32ad24d2016-04-12 21:34:24 +00001790 // Save the DL and VT before calling matchAddress, it can invalidate N.
1791 SDLoc DL(N);
1792 MVT VT = N.getSimpleValueType();
1793
Rafael Espindolabb834f02009-04-10 10:09:34 +00001794 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1795 // segments.
1796 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001797 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001798 AM.Segment = T;
Matt Morehouse9e658c92017-12-01 22:20:26 +00001799 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001800 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001801 assert (T == AM.Segment);
1802 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001803
Evan Cheng77d86ff2006-02-25 10:09:08 +00001804 unsigned Complexity = 0;
1805 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001806 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001807 Complexity = 1;
1808 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001809 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001810 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1811 Complexity = 4;
1812
Gabor Greiff304a7a2008-08-28 21:40:38 +00001813 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001814 Complexity++;
1815 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001816 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001817
Chris Lattner3e1d9172007-03-20 06:08:29 +00001818 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1819 // a simple shift.
1820 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001821 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001822
1823 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001824 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001825 // optimal (especially for code size consideration). LEA is nice because of
1826 // its three-address nature. Tweak the cost function again when we can run
1827 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001828 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001829 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001830 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001831 Complexity = 4;
1832 else
1833 Complexity += 2;
1834 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001835
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001836 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001837 Complexity++;
1838
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001839 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001840 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001841 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001842
Justin Bogner32ad24d2016-04-12 21:34:24 +00001843 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001844 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001845}
1846
Sanjay Patelb5723d02015-10-13 15:12:27 +00001847/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001848bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001849 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001850 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001851 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1852 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001853
Chris Lattner7d2b0492009-06-20 20:38:48 +00001854 X86ISelAddressMode AM;
1855 AM.GV = GA->getGlobal();
1856 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001857 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001858 AM.SymbolFlags = GA->getTargetFlags();
1859
Owen Anderson9f944592009-08-11 20:47:22 +00001860 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001861 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001862 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001863 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001864 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001865 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001866
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001867 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001868 return true;
1869}
1870
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001871bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1872 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1873 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1874 N.getValueType());
1875 return true;
1876 }
1877
Peter Collingbourne235c2752016-12-08 19:01:00 +00001878 // Keep track of the original value type and whether this value was
1879 // truncated. If we see a truncation from pointer type to VT that truncates
1880 // bits that are known to be zero, we can use a narrow reference.
1881 EVT VT = N.getValueType();
1882 bool WasTruncated = false;
1883 if (N.getOpcode() == ISD::TRUNCATE) {
1884 WasTruncated = true;
1885 N = N.getOperand(0);
1886 }
1887
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001888 if (N.getOpcode() != X86ISD::Wrapper)
1889 return false;
1890
Peter Collingbourne235c2752016-12-08 19:01:00 +00001891 // We can only use non-GlobalValues as immediates if they were not truncated,
1892 // as we do not have any range information. If we have a GlobalValue and the
1893 // address was not truncated, we can select it as an operand directly.
1894 unsigned Opc = N.getOperand(0)->getOpcode();
1895 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1896 Op = N.getOperand(0);
1897 // We can only select the operand directly if we didn't have to look past a
1898 // truncate.
1899 return !WasTruncated;
1900 }
1901
1902 // Check that the global's range fits into VT.
1903 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1904 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1905 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1906 return false;
1907
1908 // Okay, we can use a narrow reference.
1909 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1910 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001911 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001912}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001913
Craig Topper78a77042017-11-08 20:17:33 +00001914bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001915 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001916 SDValue &Index, SDValue &Disp,
1917 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001918 if (!ISD::isNON_EXTLoad(N.getNode()) ||
Craig Topper78a77042017-11-08 20:17:33 +00001919 !IsProfitableToFold(N, P, Root) ||
1920 !IsLegalToFold(N, P, Root, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001921 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001922
Sanjay Patel85030aa2015-10-13 16:23:00 +00001923 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001924 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001925}
1926
Sanjay Patelb5723d02015-10-13 15:12:27 +00001927/// Return an SDNode that returns the value of the global base register.
1928/// Output instructions required to initialize the global base register,
1929/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00001930SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001931 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00001932 auto &DL = MF->getDataLayout();
1933 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001934}
1935
Peter Collingbourneef089bd2017-02-09 22:02:28 +00001936bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1937 if (N->getOpcode() == ISD::TRUNCATE)
1938 N = N->getOperand(0).getNode();
1939 if (N->getOpcode() != X86ISD::Wrapper)
1940 return false;
1941
1942 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1943 if (!GA)
1944 return false;
1945
1946 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1947 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1948 CR->getSignedMax().slt(1ull << Width);
1949}
1950
Sanjay Patelb5723d02015-10-13 15:12:27 +00001951/// Test whether the given X86ISD::CMP node has any uses which require the SF
1952/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001953static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001954 // Examine each user of the node.
1955 for (SDNode::use_iterator UI = N->use_begin(),
1956 UE = N->use_end(); UI != UE; ++UI) {
1957 // Only examine CopyToReg uses.
1958 if (UI->getOpcode() != ISD::CopyToReg)
1959 return false;
1960 // Only examine CopyToReg uses that copy to EFLAGS.
1961 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1962 X86::EFLAGS)
1963 return false;
1964 // Examine each user of the CopyToReg use.
1965 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1966 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1967 // Only examine the Flag result.
1968 if (FlagUI.getUse().getResNo() != 1) continue;
1969 // Anything unusual: assume conservatively.
1970 if (!FlagUI->isMachineOpcode()) return false;
1971 // Examine the opcode of the user.
1972 switch (FlagUI->getMachineOpcode()) {
1973 // These comparisons don't treat the most significant bit specially.
1974 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1975 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1976 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1977 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001978 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1979 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001980 case X86::CMOVA16rr: case X86::CMOVA16rm:
1981 case X86::CMOVA32rr: case X86::CMOVA32rm:
1982 case X86::CMOVA64rr: case X86::CMOVA64rm:
1983 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1984 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1985 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1986 case X86::CMOVB16rr: case X86::CMOVB16rm:
1987 case X86::CMOVB32rr: case X86::CMOVB32rm:
1988 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001989 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1990 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1991 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001992 case X86::CMOVE16rr: case X86::CMOVE16rm:
1993 case X86::CMOVE32rr: case X86::CMOVE32rm:
1994 case X86::CMOVE64rr: case X86::CMOVE64rm:
1995 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1996 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1997 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1998 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1999 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2000 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2001 case X86::CMOVP16rr: case X86::CMOVP16rm:
2002 case X86::CMOVP32rr: case X86::CMOVP32rm:
2003 case X86::CMOVP64rr: case X86::CMOVP64rm:
2004 continue;
2005 // Anything else: assume conservatively.
2006 default: return false;
2007 }
2008 }
2009 }
2010 return true;
2011}
2012
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002013/// Test whether the given node which sets flags has any uses which require the
2014/// CF flag to be accurate.
2015static bool hasNoCarryFlagUses(SDNode *N) {
2016 // Examine each user of the node.
2017 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
2018 ++UI) {
2019 // Only check things that use the flags.
2020 if (UI.getUse().getResNo() != 1)
2021 continue;
2022 // Only examine CopyToReg uses.
2023 if (UI->getOpcode() != ISD::CopyToReg)
2024 return false;
2025 // Only examine CopyToReg uses that copy to EFLAGS.
2026 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2027 return false;
2028 // Examine each user of the CopyToReg use.
2029 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2030 FlagUI != FlagUE; ++FlagUI) {
2031 // Only examine the Flag result.
2032 if (FlagUI.getUse().getResNo() != 1)
2033 continue;
2034 // Anything unusual: assume conservatively.
2035 if (!FlagUI->isMachineOpcode())
2036 return false;
2037 // Examine the opcode of the user.
2038 switch (FlagUI->getMachineOpcode()) {
2039 // Comparisons which don't examine the CF flag.
2040 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2041 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2042 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2043 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2044 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2045 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2046 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2047 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2048 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2049 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2050 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2051 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2052 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2053 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2054 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2055 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2056 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2057 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2058 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2059 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2060 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2061 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2062 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2063 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2064 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2065 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2066 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2067 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2068 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2069 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2070 continue;
2071 // Anything else: assume conservatively.
2072 default:
2073 return false;
2074 }
2075 }
2076 }
2077 return true;
2078}
2079
Sanjay Patelb5723d02015-10-13 15:12:27 +00002080/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002081/// the {load; op; store} to modify transformation.
2082static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2083 SDValue StoredVal, SelectionDAG *CurDAG,
2084 LoadSDNode *&LoadNode,
2085 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002086 // is the stored value result 0 of the load?
2087 if (StoredVal.getResNo() != 0) return false;
2088
2089 // are there other uses of the loaded value than the inc or dec?
2090 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2091
Joel Jones68d59e82012-03-29 05:45:48 +00002092 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002093 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002094 return false;
2095
Evan Cheng3e869f02012-04-12 19:14:21 +00002096 SDValue Load = StoredVal->getOperand(0);
2097 // Is the stored value a non-extending and non-indexed load?
2098 if (!ISD::isNormalLoad(Load.getNode())) return false;
2099
2100 // Return LoadNode by reference.
2101 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002102
2103 // Is store the only read of the loaded value?
2104 if (!Load.hasOneUse())
2105 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002106
Evan Cheng3e869f02012-04-12 19:14:21 +00002107 // Is the address of the store the same as the load?
2108 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2109 LoadNode->getOffset() != StoreNode->getOffset())
2110 return false;
2111
Nirav Dave0fab4172018-03-09 20:58:07 +00002112 bool FoundLoad = false;
2113 SmallVector<SDValue, 4> ChainOps;
2114 SmallVector<const SDNode *, 4> LoopWorklist;
2115 SmallPtrSet<const SDNode *, 16> Visited;
2116 const unsigned int Max = 1024;
2117
2118 // Visualization of Load-Op-Store fusion:
2119 // -------------------------
2120 // Legend:
2121 // *-lines = Chain operand dependencies.
2122 // |-lines = Normal operand dependencies.
2123 // Dependencies flow down and right. n-suffix references multiple nodes.
2124 //
2125 // C Xn C
2126 // * * *
2127 // * * *
2128 // Xn A-LD Yn TF Yn
2129 // * * \ | * |
2130 // * * \ | * |
2131 // * * \ | => A--LD_OP_ST
2132 // * * \| \
2133 // TF OP \
2134 // * | \ Zn
2135 // * | \
2136 // A-ST Zn
2137 //
2138
2139 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2140 // #2: Yn -> LD
2141 // #3: ST -> Zn
2142
2143 // Ensure the transform is safe by checking for the dual
2144 // dependencies to make sure we do not induce a loop.
2145
2146 // As LD is a predecessor to both OP and ST we can do this by checking:
2147 // a). if LD is a predecessor to a member of Xn or Yn.
2148 // b). if a Zn is a predecessor to ST.
2149
2150 // However, (b) can only occur through being a chain predecessor to
2151 // ST, which is the same as Zn being a member or predecessor of Xn,
2152 // which is a subset of LD being a predecessor of Xn. So it's
2153 // subsumed by check (a).
2154
Evan Cheng3e869f02012-04-12 19:14:21 +00002155 SDValue Chain = StoreNode->getChain();
2156
Nirav Dave0fab4172018-03-09 20:58:07 +00002157 // Gather X elements in ChainOps.
Evan Cheng3e869f02012-04-12 19:14:21 +00002158 if (Chain == Load.getValue(1)) {
Nirav Dave0fab4172018-03-09 20:58:07 +00002159 FoundLoad = true;
2160 ChainOps.push_back(Load.getOperand(0));
2161 } else if (Chain.getOpcode() == ISD::TokenFactor) {
Evan Cheng3e869f02012-04-12 19:14:21 +00002162 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2163 SDValue Op = Chain.getOperand(i);
2164 if (Op == Load.getValue(1)) {
Nirav Daved668f692018-03-09 20:57:42 +00002165 FoundLoad = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002166 // Drop Load, but keep its chain. No cycle check necessary.
2167 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002168 continue;
2169 }
Nirav Daved668f692018-03-09 20:57:42 +00002170 LoopWorklist.push_back(Op.getNode());
Evan Cheng3e869f02012-04-12 19:14:21 +00002171 ChainOps.push_back(Op);
2172 }
Nirav Daved668f692018-03-09 20:57:42 +00002173 }
Nirav Dave0fab4172018-03-09 20:58:07 +00002174
2175 if (!FoundLoad)
2176 return false;
2177
2178 // Worklist is currently Xn. Add Yn to worklist.
2179 for (SDValue Op : StoredVal->ops())
2180 if (Op.getNode() != LoadNode)
2181 LoopWorklist.push_back(Op.getNode());
2182
2183 // Check (a) if Load is a predecessor to Xn + Yn
2184 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2185 true))
2186 return false;
2187
2188 InputChain =
2189 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
2190 return true;
2191 }
Joel Jones68d59e82012-03-29 05:45:48 +00002192
Chandler Carruth4b611a82017-08-25 22:50:52 +00002193// Change a chain of {load; op; store} of the same value into a simple op
2194// through memory of that value, if the uses of the modified value and its
2195// address are suitable.
2196//
2197// The tablegen pattern memory operand pattern is currently not able to match
2198// the case where the EFLAGS on the original operation are used.
2199//
2200// To move this to tablegen, we'll need to improve tablegen to allow flags to
2201// be transferred from a node in the pattern to the result node, probably with
2202// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002203// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2204// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2205// (implicit EFLAGS)]>;
2206// but maybe need something like this
2207// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2208// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2209// (transferrable EFLAGS)]>;
2210//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002211// Until then, we manually fold these and instruction select the operation
2212// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002213bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2214 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2215 SDValue StoredVal = StoreNode->getOperand(1);
2216 unsigned Opc = StoredVal->getOpcode();
2217
Chandler Carruth4b611a82017-08-25 22:50:52 +00002218 // Before we try to select anything, make sure this is memory operand size
2219 // and opcode we can handle. Note that this must match the code below that
2220 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002221 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002222 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2223 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002224 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002225 switch (Opc) {
2226 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002227 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002228 case X86ISD::INC:
2229 case X86ISD::DEC:
2230 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002231 case X86ISD::ADC:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002232 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002233 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002234 case X86ISD::AND:
2235 case X86ISD::OR:
2236 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002237 break;
2238 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002239
Chandler Carruth03258f22017-08-25 02:04:03 +00002240 LoadSDNode *LoadNode = nullptr;
2241 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002242 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2243 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002244 return false;
2245
2246 SDValue Base, Scale, Index, Disp, Segment;
2247 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2248 Segment))
2249 return false;
2250
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002251 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002252 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002253 switch (MemVT.getSimpleVT().SimpleTy) {
2254 case MVT::i64:
2255 return Opc64;
2256 case MVT::i32:
2257 return Opc32;
2258 case MVT::i16:
2259 return Opc16;
2260 case MVT::i8:
2261 return Opc8;
2262 default:
2263 llvm_unreachable("Invalid size!");
2264 }
2265 };
2266
2267 MachineSDNode *Result;
2268 switch (Opc) {
2269 case X86ISD::INC:
2270 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002271 unsigned NewOpc =
2272 Opc == X86ISD::INC
2273 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2274 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002275 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2276 Result =
2277 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2278 break;
2279 }
2280 case X86ISD::ADD:
Nirav Dave72d32f22018-01-19 15:37:57 +00002281 case X86ISD::ADC:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002282 case X86ISD::SUB:
Nirav Dave72d32f22018-01-19 15:37:57 +00002283 case X86ISD::SBB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002284 case X86ISD::AND:
2285 case X86ISD::OR:
2286 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002287 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2288 switch (Opc) {
2289 case X86ISD::ADD:
2290 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2291 X86::ADD8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002292 case X86ISD::ADC:
2293 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2294 X86::ADC8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002295 case X86ISD::SUB:
2296 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2297 X86::SUB8mr);
Nirav Dave72d32f22018-01-19 15:37:57 +00002298 case X86ISD::SBB:
2299 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2300 X86::SBB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002301 case X86ISD::AND:
2302 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2303 X86::AND8mr);
2304 case X86ISD::OR:
2305 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2306 case X86ISD::XOR:
2307 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2308 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002309 default:
2310 llvm_unreachable("Invalid opcode!");
2311 }
2312 };
2313 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2314 switch (Opc) {
2315 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002316 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002317 case X86ISD::ADC:
2318 return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002319 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002320 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Nirav Dave72d32f22018-01-19 15:37:57 +00002321 case X86ISD::SBB:
2322 return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002323 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002324 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002325 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002326 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002327 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002328 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002329 default:
2330 llvm_unreachable("Invalid opcode!");
2331 }
2332 };
2333 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2334 switch (Opc) {
2335 case X86ISD::ADD:
2336 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2337 X86::ADD8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002338 case X86ISD::ADC:
2339 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2340 X86::ADC8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002341 case X86ISD::SUB:
2342 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2343 X86::SUB8mi);
Nirav Dave72d32f22018-01-19 15:37:57 +00002344 case X86ISD::SBB:
2345 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2346 X86::SBB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002347 case X86ISD::AND:
2348 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2349 X86::AND8mi);
2350 case X86ISD::OR:
2351 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2352 X86::OR8mi);
2353 case X86ISD::XOR:
2354 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2355 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002356 default:
2357 llvm_unreachable("Invalid opcode!");
2358 }
2359 };
2360
2361 unsigned NewOpc = SelectRegOpcode(Opc);
2362 SDValue Operand = StoredVal->getOperand(1);
2363
2364 // See if the operand is a constant that we can fold into an immediate
2365 // operand.
2366 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2367 auto OperandV = OperandC->getAPIntValue();
2368
2369 // Check if we can shrink the operand enough to fit in an immediate (or
2370 // fit into a smaller immediate) by negating it and switching the
2371 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002372 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2373 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002374 (-OperandV).getMinSignedBits() <= 8) ||
2375 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2376 (-OperandV).getMinSignedBits() <= 32)) &&
2377 hasNoCarryFlagUses(StoredVal.getNode())) {
2378 OperandV = -OperandV;
2379 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2380 }
2381
2382 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2383 // the larger immediate operand.
2384 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2385 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2386 NewOpc = SelectImm8Opcode(Opc);
2387 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2388 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2389 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2390 NewOpc = SelectImmOpcode(Opc);
2391 }
2392 }
2393
Nirav Dave72d32f22018-01-19 15:37:57 +00002394 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2395 SDValue CopyTo =
2396 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2397 StoredVal.getOperand(2), SDValue());
2398
2399 const SDValue Ops[] = {Base, Scale, Index, Disp,
2400 Segment, Operand, CopyTo, CopyTo.getValue(1)};
2401 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2402 Ops);
2403 } else {
2404 const SDValue Ops[] = {Base, Scale, Index, Disp,
2405 Segment, Operand, InputChain};
2406 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2407 Ops);
2408 }
Chandler Carruth4b611a82017-08-25 22:50:52 +00002409 break;
2410 }
2411 default:
2412 llvm_unreachable("Invalid opcode!");
2413 }
2414
Chandler Carruth03258f22017-08-25 02:04:03 +00002415 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2416 MemOp[0] = StoreNode->getMemOperand();
2417 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002418 Result->setMemRefs(MemOp, MemOp + 2);
2419
Nirav Daved668f692018-03-09 20:57:42 +00002420 // Update Load Chain uses as well.
2421 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
Chandler Carruth03258f22017-08-25 02:04:03 +00002422 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2423 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2424 CurDAG->RemoveDeadNode(Node);
2425 return true;
2426}
2427
Craig Topper958106d2017-09-12 17:40:25 +00002428// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2429bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2430 MVT NVT = Node->getSimpleValueType(0);
2431 SDLoc dl(Node);
2432
2433 SDValue N0 = Node->getOperand(0);
2434 SDValue N1 = Node->getOperand(1);
2435
2436 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2437 return false;
2438
2439 // Must have a shift right.
2440 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2441 return false;
2442
2443 // Shift can't have additional users.
2444 if (!N0->hasOneUse())
2445 return false;
2446
2447 // Only supported for 32 and 64 bits.
2448 if (NVT != MVT::i32 && NVT != MVT::i64)
2449 return false;
2450
2451 // Shift amount and RHS of and must be constant.
2452 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2453 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2454 if (!MaskCst || !ShiftCst)
2455 return false;
2456
2457 // And RHS must be a mask.
2458 uint64_t Mask = MaskCst->getZExtValue();
2459 if (!isMask_64(Mask))
2460 return false;
2461
2462 uint64_t Shift = ShiftCst->getZExtValue();
2463 uint64_t MaskSize = countPopulation(Mask);
2464
2465 // Don't interfere with something that can be handled by extracting AH.
2466 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2467 if (Shift == 8 && MaskSize == 8)
2468 return false;
2469
2470 // Make sure we are only using bits that were in the original value, not
2471 // shifted in.
2472 if (Shift + MaskSize > NVT.getSizeInBits())
2473 return false;
2474
Craig Topper88939fe2018-02-12 21:18:11 +00002475 // Create a BEXTR node and run it through selection.
2476 SDValue C = CurDAG->getConstant(Shift | (MaskSize << 8), dl, NVT);
2477 SDValue New = CurDAG->getNode(X86ISD::BEXTR, dl, NVT,
2478 N0->getOperand(0), C);
2479 ReplaceNode(Node, New.getNode());
2480 SelectCode(New.getNode());
Craig Topper958106d2017-09-12 17:40:25 +00002481 return true;
2482}
2483
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002484/// If the high bits of an 'and' operand are known zero, try setting the
2485/// high bits of an 'and' constant operand to produce a smaller encoding by
2486/// creating a small, sign-extended negative immediate rather than a large
2487/// positive one. This reverses a transform in SimplifyDemandedBits that
2488/// shrinks mask constants by clearing bits. There is also a possibility that
2489/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
2490/// case, just replace the 'and'. Return 'true' if the node is replaced.
2491bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
2492 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
2493 // have immediate operands.
2494 MVT VT = And->getSimpleValueType(0);
2495 if (VT != MVT::i32 && VT != MVT::i64)
2496 return false;
2497
2498 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
2499 if (!And1C)
2500 return false;
2501
Craig Topper57e06432018-02-05 16:54:07 +00002502 // Bail out if the mask constant is already negative. It's can't shrink more.
2503 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
2504 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
2505 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
2506 // are negative too.
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002507 APInt MaskVal = And1C->getAPIntValue();
2508 unsigned MaskLZ = MaskVal.countLeadingZeros();
Craig Topper57e06432018-02-05 16:54:07 +00002509 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002510 return false;
2511
Craig Topper57e06432018-02-05 16:54:07 +00002512 // Don't extend into the upper 32 bits of a 64 bit mask.
2513 if (VT == MVT::i64 && MaskLZ >= 32) {
2514 MaskLZ -= 32;
2515 MaskVal = MaskVal.trunc(32);
2516 }
2517
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002518 SDValue And0 = And->getOperand(0);
Craig Topper57e06432018-02-05 16:54:07 +00002519 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002520 APInt NegMaskVal = MaskVal | HighZeros;
2521
2522 // If a negative constant would not allow a smaller encoding, there's no need
2523 // to continue. Only change the constant when we know it's a win.
2524 unsigned MinWidth = NegMaskVal.getMinSignedBits();
2525 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
2526 return false;
2527
Craig Topper57e06432018-02-05 16:54:07 +00002528 // Extend masks if we truncated above.
2529 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
2530 NegMaskVal = NegMaskVal.zext(64);
2531 HighZeros = HighZeros.zext(64);
2532 }
2533
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002534 // The variable operand must be all zeros in the top bits to allow using the
2535 // new, negative constant as the mask.
2536 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
2537 return false;
2538
2539 // Check if the mask is -1. In that case, this is an unnecessary instruction
2540 // that escaped earlier analysis.
2541 if (NegMaskVal.isAllOnesValue()) {
2542 ReplaceNode(And, And0.getNode());
2543 return true;
2544 }
2545
2546 // A negative mask allows a smaller encoding. Create a new 'and' node.
2547 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
2548 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
2549 ReplaceNode(And, NewAnd.getNode());
2550 SelectCode(NewAnd.getNode());
2551 return true;
2552}
2553
Justin Bogner593741d2016-05-10 23:55:37 +00002554void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002555 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002556 unsigned Opc, MOpc;
2557 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002558 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002559
Dan Gohman17059682008-07-17 19:10:17 +00002560 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002561 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002562 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002563 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002564 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002565
Evan Cheng10d27902006-01-06 20:36:21 +00002566 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002567 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002568 case ISD::BRIND: {
2569 if (Subtarget->isTargetNaCl())
2570 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2571 // leave the instruction alone.
2572 break;
2573 if (Subtarget->isTarget64BitILP32()) {
2574 // Converts a 32-bit register to a 64-bit, zero-extended version of
2575 // it. This is needed because x86-64 can do many things, but jmp %r32
2576 // ain't one of them.
2577 const SDValue &Target = Node->getOperand(1);
2578 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2579 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2580 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2581 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002582 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002583 SelectCode(ZextTarget.getNode());
2584 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002585 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002586 }
2587 break;
2588 }
Dan Gohman757eee82009-08-02 16:10:52 +00002589 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002590 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002591 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002592
Craig Topper75370b92017-09-19 17:19:45 +00002593 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002594 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002595 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002596 SDValue VSelect = CurDAG->getNode(
2597 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2598 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002599 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002600 SelectCode(VSelect.getNode());
2601 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002602 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002603 }
Craig Topper3af251d2012-07-01 02:55:34 +00002604
Tobias Grosser85508e82015-08-19 11:35:10 +00002605 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002606 if (matchBEXTRFromAnd(Node))
2607 return;
Sanjay Patel74a1eef2018-01-19 16:37:25 +00002608 if (shrinkAndImmediate(Node))
2609 return;
Craig Topper958106d2017-09-12 17:40:25 +00002610
2611 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002612 case ISD::OR:
2613 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002614
Benjamin Kramer4c816242011-04-22 15:30:40 +00002615 // For operations of the form (x << C1) op C2, check if we can use a smaller
2616 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2617 SDValue N0 = Node->getOperand(0);
2618 SDValue N1 = Node->getOperand(1);
2619
2620 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2621 break;
2622
2623 // i8 is unshrinkable, i16 should be promoted to i32.
2624 if (NVT != MVT::i32 && NVT != MVT::i64)
2625 break;
2626
2627 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2628 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2629 if (!Cst || !ShlCst)
2630 break;
2631
2632 int64_t Val = Cst->getSExtValue();
2633 uint64_t ShlVal = ShlCst->getZExtValue();
2634
2635 // Make sure that we don't change the operation by removing bits.
2636 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002637 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2638 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002639 break;
2640
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002641 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002642 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002643
2644 // Check the minimum bitwidth for the new constant.
2645 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2646 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2647 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2648 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2649 CstVT = MVT::i8;
2650 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2651 CstVT = MVT::i32;
2652
2653 // Bail if there is no smaller encoding.
2654 if (NVT == CstVT)
2655 break;
2656
Craig Topper83e042a2013-08-15 05:57:07 +00002657 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002658 default: llvm_unreachable("Unsupported VT!");
2659 case MVT::i32:
2660 assert(CstVT == MVT::i8);
2661 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002662 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002663
2664 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002665 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002666 case ISD::AND: Op = X86::AND32ri8; break;
2667 case ISD::OR: Op = X86::OR32ri8; break;
2668 case ISD::XOR: Op = X86::XOR32ri8; break;
2669 }
2670 break;
2671 case MVT::i64:
2672 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2673 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002674 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002675
2676 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002677 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002678 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2679 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2680 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2681 }
2682 break;
2683 }
2684
2685 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002686 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002687 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002688 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002689 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2690 SDValue(New, 0));
2691 else
2692 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2693 getI8Imm(ShlVal, dl));
2694 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002695 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002696 case X86ISD::UMUL8:
2697 case X86ISD::SMUL8: {
2698 SDValue N0 = Node->getOperand(0);
2699 SDValue N1 = Node->getOperand(1);
2700
2701 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2702
2703 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2704 N0, SDValue()).getValue(1);
2705
2706 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2707 SDValue Ops[] = {N1, InFlag};
2708 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2709
Justin Bogner31d7da32016-05-11 21:13:17 +00002710 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002711 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002712 }
2713
Chris Lattner364bb0a2010-12-05 07:30:36 +00002714 case X86ISD::UMUL: {
2715 SDValue N0 = Node->getOperand(0);
2716 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002717
Ted Kremenekb5241b22011-01-14 22:34:13 +00002718 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002719 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002720 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00002721 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00002722 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2723 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2724 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002725 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002726
Chris Lattner364bb0a2010-12-05 07:30:36 +00002727 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2728 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002729
Chris Lattner364bb0a2010-12-05 07:30:36 +00002730 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2731 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002732 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002733
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002734 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002735 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002736 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002737
Dan Gohman757eee82009-08-02 16:10:52 +00002738 case ISD::SMUL_LOHI:
2739 case ISD::UMUL_LOHI: {
2740 SDValue N0 = Node->getOperand(0);
2741 SDValue N1 = Node->getOperand(1);
2742
2743 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002744 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002745 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002746 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002747 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002748 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2749 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002750 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2751 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2752 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2753 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002754 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002755 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002756 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002757 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002758 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2759 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2760 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2761 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002762 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002763 }
Dan Gohman757eee82009-08-02 16:10:52 +00002764
Michael Liaof9f7b552012-09-26 08:22:37 +00002765 unsigned SrcReg, LoReg, HiReg;
2766 switch (Opc) {
2767 default: llvm_unreachable("Unknown MUL opcode!");
2768 case X86::IMUL8r:
2769 case X86::MUL8r:
2770 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2771 break;
2772 case X86::IMUL16r:
2773 case X86::MUL16r:
2774 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2775 break;
2776 case X86::IMUL32r:
2777 case X86::MUL32r:
2778 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2779 break;
2780 case X86::IMUL64r:
2781 case X86::MUL64r:
2782 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2783 break;
2784 case X86::MULX32rr:
2785 SrcReg = X86::EDX; LoReg = HiReg = 0;
2786 break;
2787 case X86::MULX64rr:
2788 SrcReg = X86::RDX; LoReg = HiReg = 0;
2789 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002790 }
2791
2792 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002793 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002794 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002795 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002796 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002797 if (foldedLoad)
2798 std::swap(N0, N1);
2799 }
2800
Michael Liaof9f7b552012-09-26 08:22:37 +00002801 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002802 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002803 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002804
2805 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002806 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002807 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002808 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2809 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002810 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2811 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002812 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002813 ResHi = SDValue(CNode, 0);
2814 ResLo = SDValue(CNode, 1);
2815 Chain = SDValue(CNode, 2);
2816 InFlag = SDValue(CNode, 3);
2817 } else {
2818 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002819 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002820 Chain = SDValue(CNode, 0);
2821 InFlag = SDValue(CNode, 1);
2822 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002823
Dan Gohman757eee82009-08-02 16:10:52 +00002824 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002825 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002826 // Record the mem-refs
Craig Topper55029d82017-11-08 22:26:37 +00002827 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2828 MemOp[0] = cast<LoadSDNode>(N1)->getMemOperand();
2829 CNode->setMemRefs(MemOp, MemOp + 1);
Dan Gohman757eee82009-08-02 16:10:52 +00002830 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002831 SDValue Ops[] = { N1, InFlag };
2832 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2833 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002834 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002835 ResHi = SDValue(CNode, 0);
2836 ResLo = SDValue(CNode, 1);
2837 InFlag = SDValue(CNode, 2);
2838 } else {
2839 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002840 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002841 InFlag = SDValue(CNode, 0);
2842 }
Dan Gohman757eee82009-08-02 16:10:52 +00002843 }
2844
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002845 // Prevent use of AH in a REX instruction by referencing AX instead.
2846 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2847 !SDValue(Node, 1).use_empty()) {
2848 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2849 X86::AX, MVT::i16, InFlag);
2850 InFlag = Result.getValue(2);
2851 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2852 // registers.
2853 if (!SDValue(Node, 0).use_empty())
Craig Topper40f05842017-10-28 19:56:57 +00002854 ReplaceUses(SDValue(Node, 0),
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002855 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2856
2857 // Shift AX down 8 bits.
2858 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2859 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002860 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2861 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002862 // Then truncate it down to i8.
2863 ReplaceUses(SDValue(Node, 1),
2864 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2865 }
Dan Gohman757eee82009-08-02 16:10:52 +00002866 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002867 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002868 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002869 assert(LoReg && "Register for low half is not defined!");
2870 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2871 InFlag);
2872 InFlag = ResLo.getValue(2);
2873 }
2874 ReplaceUses(SDValue(Node, 0), ResLo);
2875 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002876 }
2877 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002878 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002879 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002880 assert(HiReg && "Register for high half is not defined!");
2881 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2882 InFlag);
2883 InFlag = ResHi.getValue(2);
2884 }
2885 ReplaceUses(SDValue(Node, 1), ResHi);
2886 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002887 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002888
Craig Topper6bed9de2017-09-09 05:57:20 +00002889 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002890 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002891 }
2892
2893 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002894 case ISD::UDIVREM:
2895 case X86ISD::SDIVREM8_SEXT_HREG:
2896 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002897 SDValue N0 = Node->getOperand(0);
2898 SDValue N1 = Node->getOperand(1);
2899
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002900 bool isSigned = (Opcode == ISD::SDIVREM ||
2901 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002902 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002903 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002904 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002905 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2906 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2907 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2908 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002909 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002910 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002911 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002912 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002913 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2914 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2915 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2916 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002917 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002918 }
Dan Gohman757eee82009-08-02 16:10:52 +00002919
Chris Lattner518b0372009-12-23 01:45:04 +00002920 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002921 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002922 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002923 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002924 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002925 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002926 SExtOpcode = X86::CBW;
2927 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002928 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002929 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002930 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002931 SExtOpcode = X86::CWD;
2932 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002933 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002934 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002935 SExtOpcode = X86::CDQ;
2936 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002937 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002938 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002939 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002940 break;
2941 }
2942
Dan Gohman757eee82009-08-02 16:10:52 +00002943 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002944 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002945 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002946
Dan Gohman757eee82009-08-02 16:10:52 +00002947 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002948 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002949 // Special case for div8, just use a move with zero extension to AX to
2950 // clear the upper 8 bits (AH).
2951 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002952 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002953 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2954 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002955 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002956 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002957 Chain = Move.getValue(1);
2958 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002959 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002960 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002961 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002962 Chain = CurDAG->getEntryNode();
2963 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002964 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002965 InFlag = Chain.getValue(1);
2966 } else {
2967 InFlag =
2968 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2969 LoReg, N0, SDValue()).getValue(1);
2970 if (isSigned && !signBitIsZero) {
2971 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002972 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002973 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002974 } else {
2975 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002976 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002977 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002978 case MVT::i16:
2979 ClrNode =
2980 SDValue(CurDAG->getMachineNode(
2981 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002982 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2983 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002984 0);
2985 break;
2986 case MVT::i32:
2987 break;
2988 case MVT::i64:
2989 ClrNode =
2990 SDValue(CurDAG->getMachineNode(
2991 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002992 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2993 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2994 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002995 0);
2996 break;
2997 default:
2998 llvm_unreachable("Unexpected division source");
2999 }
3000
Chris Lattner518b0372009-12-23 01:45:04 +00003001 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00003002 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00003003 }
Evan Cheng92e27972006-01-06 23:19:29 +00003004 }
Dan Gohmana1603612007-10-08 18:33:35 +00003005
Dan Gohman757eee82009-08-02 16:10:52 +00003006 if (foldedLoad) {
3007 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3008 InFlag };
Craig Topper61f81f92017-11-08 22:26:39 +00003009 MachineSDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00003010 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00003011 InFlag = SDValue(CNode, 1);
3012 // Update the chain.
3013 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
Craig Topper61f81f92017-11-08 22:26:39 +00003014 // Record the mem-refs
3015 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3016 MemOp[0] = cast<LoadSDNode>(N1)->getMemOperand();
3017 CNode->setMemRefs(MemOp, MemOp + 1);
Dan Gohman757eee82009-08-02 16:10:52 +00003018 } else {
3019 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003020 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00003021 }
Evan Cheng92e27972006-01-06 23:19:29 +00003022
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003023 // Prevent use of AH in a REX instruction by explicitly copying it to
3024 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00003025 //
3026 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003027 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00003028 // the allocator and/or the backend get enhanced to be more robust in
3029 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003030 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
3031 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
3032 unsigned AHExtOpcode =
3033 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003034
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003035 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
3036 MVT::Glue, AHCopy, InFlag);
3037 SDValue Result(RNode, 0);
3038 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003039
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003040 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
3041 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
Craig Topperb8d7d4d2017-10-26 21:12:03 +00003042 assert(Node->getValueType(1) == MVT::i32 && "Unexpected result type!");
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00003043 } else {
3044 Result =
3045 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
3046 }
3047 ReplaceUses(SDValue(Node, 1), Result);
3048 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003049 }
Dan Gohman757eee82009-08-02 16:10:52 +00003050 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003051 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00003052 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3053 LoReg, NVT, InFlag);
3054 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003055 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00003056 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003057 }
3058 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003059 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00003060 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3061 HiReg, NVT, InFlag);
3062 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003063 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00003064 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00003065 }
Craig Topper6bed9de2017-09-09 05:57:20 +00003066 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003067 return;
Dan Gohman757eee82009-08-02 16:10:52 +00003068 }
3069
Craig Topperb424faf2018-02-12 03:02:02 +00003070 case X86ISD::CMP: {
Dan Gohmanac33a902009-08-19 18:16:17 +00003071 SDValue N0 = Node->getOperand(0);
3072 SDValue N1 = Node->getOperand(1);
3073
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003074 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00003075 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003076 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00003077
Dan Gohmanac33a902009-08-19 18:16:17 +00003078 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
3079 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00003080 // Look past the truncate if CMP is the only use of it.
Craig Topper3ccbd3f2018-02-12 03:02:01 +00003081 if (N0.getOpcode() == ISD::AND &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00003082 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00003083 N0.getValueType() != MVT::i8 &&
3084 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00003085 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00003086 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00003087 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00003088
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003089 MVT VT;
3090 int SubRegOp;
3091 unsigned Op;
3092
Craig Topperfc53dc22017-08-25 05:04:34 +00003093 if (isUInt<8>(Mask) &&
3094 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003095 // For example, convert "testl %eax, $8" to "testb %al, $8"
3096 VT = MVT::i8;
3097 SubRegOp = X86::sub_8bit;
3098 Op = X86::TEST8ri;
3099 } else if (OptForMinSize && isUInt<16>(Mask) &&
3100 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3101 // For example, "testl %eax, $32776" to "testw %ax, $32776".
3102 // NOTE: We only want to form TESTW instructions if optimizing for
3103 // min size. Otherwise we only save one byte and possibly get a length
3104 // changing prefix penalty in the decoders.
3105 VT = MVT::i16;
3106 SubRegOp = X86::sub_16bit;
3107 Op = X86::TEST16ri;
3108 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
3109 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3110 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3111 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
3112 // Otherwize, we find ourselves in a position where we have to do
3113 // promotion. If previous passes did not promote the and, we assume
3114 // they had a good reason not to and do not promote here.
3115 VT = MVT::i32;
3116 SubRegOp = X86::sub_32bit;
3117 Op = X86::TEST32ri;
3118 } else {
3119 // No eligible transformation was found.
3120 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00003121 }
3122
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003123 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
3124 SDValue Reg = N0.getOperand(0);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003125
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003126 // Extract the subregister if necessary.
3127 if (N0.getValueType() != VT)
3128 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
Eric Liu0b69b5e2018-01-30 14:18:33 +00003129
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003130 // Emit a testl or testw.
3131 SDNode *NewNode = CurDAG->getMachineNode(Op, dl, MVT::i32, Reg, Imm);
Craig Topperb424faf2018-02-12 03:02:02 +00003132 // Replace CMP with TEST.
Nirav Dave071699b2018-03-09 20:57:15 +00003133 ReplaceNode(Node, NewNode);
Amaury Sechetf9a9e9a2018-01-31 19:20:06 +00003134 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003135 }
3136 break;
3137 }
Chandler Carruth03258f22017-08-25 02:04:03 +00003138 case ISD::STORE:
3139 if (foldLoadStoreIntoMemOperand(Node))
3140 return;
3141 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003142 }
3143
Justin Bogner593741d2016-05-10 23:55:37 +00003144 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003145}
3146
Chris Lattnerba1ed582006-06-08 18:03:49 +00003147bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003148SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003149 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003150 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003151 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003152 default:
3153 llvm_unreachable("Unexpected asm memory constraint");
3154 case InlineAsm::Constraint_i:
3155 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3156 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003157 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003158 case InlineAsm::Constraint_o: // offsetable ??
3159 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003160 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003161 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003162 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003163 return true;
3164 break;
3165 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003166
Evan Cheng2d487222006-08-26 01:05:16 +00003167 OutOps.push_back(Op0);
3168 OutOps.push_back(Op1);
3169 OutOps.push_back(Op2);
3170 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003171 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003172 return false;
3173}
3174
Sanjay Patelb5723d02015-10-13 15:12:27 +00003175/// This pass converts a legalized DAG into a X86-specific DAG,
3176/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003177FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003178 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003179 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003180}