blob: 84b1f9624ad9f1301e54ff160c6d41211ec3a2e4 [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 Chengbc7a0f442006-01-11 06:09:51 +000016#include "X86InstrBuilder.h"
Evan Chengf55b7382008-01-05 00:41:47 +000017#include "X86MachineFunctionInfo.h"
Chris Lattner7c551262006-01-11 01:15:34 +000018#include "X86RegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000019#include "X86Subtarget.h"
Evan Cheng2dd2c652006-03-13 23:20:37 +000020#include "X86TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Statistic.h"
Evan Cheng73a1ad92006-01-10 20:26:56 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner7c551262006-01-11 01:15:34 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000026#include "llvm/CodeGen/SelectionDAGISel.h"
Peter Collingbourne235c2752016-12-08 19:01:00 +000027#include "llvm/IR/ConstantRange.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000028#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Type.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000032#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000033#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000034#include "llvm/Support/KnownBits.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000035#include "llvm/Support/MathExtras.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000039#include <stdint.h>
Chris Lattner655e7df2005-11-16 01:54:32 +000040using namespace llvm;
41
Chandler Carruth84e68b22014-04-22 02:41:26 +000042#define DEBUG_TYPE "x86-isel"
43
Chris Lattner1ef9cd42006-12-19 22:59:26 +000044STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45
Chris Lattner655e7df2005-11-16 01:54:32 +000046//===----------------------------------------------------------------------===//
47// Pattern Matcher Implementation
48//===----------------------------------------------------------------------===//
49
50namespace {
Sanjay Patelb5723d02015-10-13 15:12:27 +000051 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52 /// numbers for the leaves of the matched tree.
Chris Lattner3f0f71b2005-11-19 02:11:08 +000053 struct X86ISelAddressMode {
54 enum {
55 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000056 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000057 } BaseType;
58
Dan Gohman0fd54fb2010-04-29 23:30:41 +000059 // This is really a union, discriminated by BaseType!
60 SDValue Base_Reg;
61 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000062
63 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000064 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000065 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000066 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000067 const GlobalValue *GV;
68 const Constant *CP;
69 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000070 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000071 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000072 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000073 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000074 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000075
76 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000077 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
78 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
79 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000080
81 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000082 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000083 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000084 }
Chad Rosier24c19d22012-08-01 18:39:17 +000085
Chris Lattnerfea81da2009-06-27 04:16:01 +000086 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000087 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000088 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000089 }
Chad Rosier24c19d22012-08-01 18:39:17 +000090
Sanjay Patelb5723d02015-10-13 15:12:27 +000091 /// Return true if this addressing mode is already RIP-relative.
Chris Lattnerfea81da2009-06-27 04:16:01 +000092 bool isRIPRelative() const {
93 if (BaseType != RegBase) return false;
94 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +000095 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +000096 return RegNode->getReg() == X86::RIP;
97 return false;
98 }
Chad Rosier24c19d22012-08-01 18:39:17 +000099
Chris Lattnerfea81da2009-06-27 04:16:01 +0000100 void setBaseReg(SDValue Reg) {
101 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000102 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000103 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000104
Manman Ren19f49ac2012-09-11 22:23:19 +0000105#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesendafdbf72008-08-11 23:46:25 +0000106 void dump() {
David Greenedbdb1b22010-01-05 01:29:08 +0000107 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000108 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000109 if (Base_Reg.getNode())
Chad Rosier24c19d22012-08-01 18:39:17 +0000110 Base_Reg.getNode()->dump();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000111 else
David Greenedbdb1b22010-01-05 01:29:08 +0000112 dbgs() << "nul";
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000113 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000114 << " Scale" << Scale << '\n'
115 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000116 if (IndexReg.getNode())
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000117 IndexReg.getNode()->dump();
118 else
Chad Rosier24c19d22012-08-01 18:39:17 +0000119 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000120 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000121 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000122 if (GV)
123 GV->dump();
124 else
David Greenedbdb1b22010-01-05 01:29:08 +0000125 dbgs() << "nul";
126 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000127 if (CP)
128 CP->dump();
129 else
David Greenedbdb1b22010-01-05 01:29:08 +0000130 dbgs() << "nul";
131 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000132 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000133 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000134 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000135 else
David Greenedbdb1b22010-01-05 01:29:08 +0000136 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000137 dbgs() << " MCSym ";
138 if (MCSym)
139 dbgs() << MCSym;
140 else
141 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000142 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000143 }
Manman Ren742534c2012-09-06 19:06:06 +0000144#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000145 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000146}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000147
148namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000149 //===--------------------------------------------------------------------===//
Sanjay Patelb5723d02015-10-13 15:12:27 +0000150 /// ISel - X86-specific code to select X86 machine instructions for
Chris Lattner655e7df2005-11-16 01:54:32 +0000151 /// SelectionDAG operations.
152 ///
Craig Topper26eec092014-03-31 06:22:15 +0000153 class X86DAGToDAGISel final : public SelectionDAGISel {
Sanjay Patelb5723d02015-10-13 15:12:27 +0000154 /// Keep a pointer to the X86Subtarget around so that we can
Chris Lattner655e7df2005-11-16 01:54:32 +0000155 /// make the right decision when generating code for different targets.
156 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000157
Sanjay Patelb5723d02015-10-13 15:12:27 +0000158 /// If true, selector should try to optimize for code size instead of
159 /// performance.
Evan Cheng7d6fa972008-09-26 23:41:32 +0000160 bool OptForSize;
161
Hans Wennborg4ae51192016-03-25 01:10:56 +0000162 /// If true, selector should try to optimize for minimum code size.
163 bool OptForMinSize;
164
Chris Lattner655e7df2005-11-16 01:54:32 +0000165 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000166 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000167 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Hans Wennborg534bfbd2017-09-15 18:40:26 +0000168 OptForMinSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000169
Mehdi Amini117296c2016-10-01 02:56:57 +0000170 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000171 return "X86 DAG->DAG Instruction Selection";
172 }
173
Eric Christopher4f09c592014-05-22 01:53:26 +0000174 bool runOnMachineFunction(MachineFunction &MF) override {
175 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000176 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000177 SelectionDAGISel::runOnMachineFunction(MF);
178 return true;
179 }
180
Craig Topper2d9361e2014-03-09 07:44:38 +0000181 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000182
Craig Topper2d9361e2014-03-09 07:44:38 +0000183 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000184
Craig Topper2d9361e2014-03-09 07:44:38 +0000185 void PreprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000186
Chris Lattner655e7df2005-11-16 01:54:32 +0000187// Include the pieces autogenerated from the target description.
188#include "X86GenDAGISel.inc"
189
190 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000191 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000192
Sanjay Patel85030aa2015-10-13 16:23:00 +0000193 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
194 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
195 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
196 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000197 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000198 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000199 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000200 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000202 SDValue &Scale, SDValue &Index, SDValue &Disp,
203 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000204 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000205 SDValue &Scale, SDValue &Index, SDValue &Disp,
206 SDValue &Segment);
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +0000207 template <class GatherScatterSDNode>
208 bool selectAddrOfGatherScatterNode(GatherScatterSDNode *Parent, SDValue N,
209 SDValue &Base, SDValue &Scale,
210 SDValue &Index, SDValue &Disp,
211 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000212 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
213 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000214 SDValue &Scale, SDValue &Index, SDValue &Disp,
215 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000216 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000217 SDValue &Scale, SDValue &Index, SDValue &Disp,
218 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000219 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000220 SDValue &Scale, SDValue &Index, SDValue &Disp,
221 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000222 bool selectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000223 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000224 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000225 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000226 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000227 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000228
Sanjay Patel85030aa2015-10-13 16:23:00 +0000229 bool tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000230 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000231 SDValue &Index, SDValue &Disp,
232 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000233
Sanjay Patelb5723d02015-10-13 15:12:27 +0000234 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000235 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000236 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000237 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000238
Sanjay Patel85030aa2015-10-13 16:23:00 +0000239 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000240
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000241 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000242 SDValue &Base, SDValue &Scale,
243 SDValue &Index, SDValue &Disp,
244 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000245 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000246 ? CurDAG->getTargetFrameIndex(
247 AM.Base_FrameIndex,
248 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000249 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000250 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000251 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000252 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000253 // is 32-bit.
254 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000255 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000256 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000257 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000258 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000259 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000260 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000261 else if (AM.ES) {
262 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000263 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000264 } else if (AM.MCSym) {
265 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
266 assert(AM.SymbolFlags == 0 && "oo");
267 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000268 } else if (AM.JT != -1) {
269 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000270 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000271 } else if (AM.BlockAddr)
272 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
273 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000274 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000275 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000276
277 if (AM.Segment.getNode())
278 Segment = AM.Segment;
279 else
Owen Anderson9f944592009-08-11 20:47:22 +0000280 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000281 }
282
Michael Kuperstein243c0732015-08-11 14:10:58 +0000283 // Utility function to determine whether we should avoid selecting
284 // immediate forms of instructions for better code size or not.
285 // At a high level, we'd like to avoid such instructions when
286 // we have similar constants used within the same basic block
287 // that can be kept in a register.
288 //
289 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
290 uint32_t UseCount = 0;
291
292 // Do not want to hoist if we're not optimizing for size.
293 // TODO: We'd like to remove this restriction.
294 // See the comment in X86InstrInfo.td for more info.
295 if (!OptForSize)
296 return false;
297
298 // Walk all the users of the immediate.
299 for (SDNode::use_iterator UI = N->use_begin(),
300 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000301
Michael Kuperstein243c0732015-08-11 14:10:58 +0000302 SDNode *User = *UI;
303
304 // This user is already selected. Count it as a legitimate use and
305 // move on.
306 if (User->isMachineOpcode()) {
307 UseCount++;
308 continue;
309 }
310
311 // We want to count stores of immediates as real uses.
312 if (User->getOpcode() == ISD::STORE &&
313 User->getOperand(1).getNode() == N) {
314 UseCount++;
315 continue;
316 }
317
318 // We don't currently match users that have > 2 operands (except
319 // for stores, which are handled above)
320 // Those instruction won't match in ISEL, for now, and would
321 // be counted incorrectly.
322 // This may change in the future as we add additional instruction
323 // types.
324 if (User->getNumOperands() != 2)
325 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000326
Michael Kuperstein243c0732015-08-11 14:10:58 +0000327 // Immediates that are used for offsets as part of stack
328 // manipulation should be left alone. These are typically
329 // used to indicate SP offsets for argument passing and
330 // will get pulled into stores/pushes (implicitly).
331 if (User->getOpcode() == X86ISD::ADD ||
332 User->getOpcode() == ISD::ADD ||
333 User->getOpcode() == X86ISD::SUB ||
334 User->getOpcode() == ISD::SUB) {
335
336 // Find the other operand of the add/sub.
337 SDValue OtherOp = User->getOperand(0);
338 if (OtherOp.getNode() == N)
339 OtherOp = User->getOperand(1);
340
341 // Don't count if the other operand is SP.
342 RegisterSDNode *RegNode;
343 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
344 (RegNode = dyn_cast_or_null<RegisterSDNode>(
345 OtherOp->getOperand(1).getNode())))
346 if ((RegNode->getReg() == X86::ESP) ||
347 (RegNode->getReg() == X86::RSP))
348 continue;
349 }
350
351 // ... otherwise, count this and move on.
352 UseCount++;
353 }
354
355 // If we have more than 1 use, then recommend for hoisting.
356 return (UseCount > 1);
357 }
358
Sanjay Patelb5723d02015-10-13 15:12:27 +0000359 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000360 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000361 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000362 }
363
Sanjay Patelb5723d02015-10-13 15:12:27 +0000364 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000365 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000366 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000367 }
Evan Chengd49cc362006-02-10 22:24:32 +0000368
Craig Topper092c2f42017-09-23 05:34:07 +0000369 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
370 const SDLoc &DL) {
371 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
372 uint64_t Index = N->getConstantOperandVal(1);
373 MVT VecVT = N->getOperand(0).getSimpleValueType();
374 unsigned NumElemsPerChunk = VecWidth / VecVT.getScalarSizeInBits();
375 return getI8Imm(Index / NumElemsPerChunk, DL);
376 }
377
378 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
379 const SDLoc &DL) {
380 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
381 uint64_t Index = N->getConstantOperandVal(2);
382 MVT VecVT = N->getSimpleValueType(0);
383 unsigned NumElemsPerChunk = VecWidth / VecVT.getScalarSizeInBits();
384 return getI8Imm(Index / NumElemsPerChunk, DL);
385 }
386
Sanjay Patelb5723d02015-10-13 15:12:27 +0000387 /// Return an SDNode that returns the value of the global base register.
388 /// Output instructions required to initialize the global base register,
389 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000390 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000391
Sanjay Patelb5723d02015-10-13 15:12:27 +0000392 /// Return a reference to the TargetMachine, casted to the target-specific
393 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000394 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000395 return static_cast<const X86TargetMachine &>(TM);
396 }
397
Sanjay Patelb5723d02015-10-13 15:12:27 +0000398 /// Return a reference to the TargetInstrInfo, casted to the target-specific
399 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000400 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000401 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000402 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000403
404 /// \brief Address-mode matching performs shift-of-and to and-of-shift
405 /// reassociation in order to expose more scaled addressing
406 /// opportunities.
407 bool ComplexPatternFuncMutatesDAG() const override {
408 return true;
409 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000410
411 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
412
413 /// Returns whether this is a relocatable immediate in the range
414 /// [-2^Width .. 2^Width-1].
415 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
416 if (auto *CN = dyn_cast<ConstantSDNode>(N))
417 return isInt<Width>(CN->getSExtValue());
418 return isSExtAbsoluteSymbolRef(Width, N);
419 }
Craig Topper4de6f582017-08-19 23:21:22 +0000420
421 // Indicates we should prefer to use a non-temporal load for this load.
422 bool useNonTemporalLoad(LoadSDNode *N) const {
423 if (!N->isNonTemporal())
424 return false;
425
426 unsigned StoreSize = N->getMemoryVT().getStoreSize();
427
428 if (N->getAlignment() < StoreSize)
429 return false;
430
431 switch (StoreSize) {
432 default: llvm_unreachable("Unsupported store size");
433 case 16:
434 return Subtarget->hasSSE41();
435 case 32:
436 return Subtarget->hasAVX2();
437 case 64:
438 return Subtarget->hasAVX512();
439 }
440 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000441
442 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000443
444 bool matchBEXTRFromAnd(SDNode *Node);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000445
446 bool isMaskZeroExtended(SDNode *N) const;
Chris Lattner655e7df2005-11-16 01:54:32 +0000447 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000448}
449
Evan Cheng72bb66a2006-08-08 00:31:00 +0000450
Craig Topperba3cc2e2017-09-25 18:43:13 +0000451// Returns true if this masked compare can be implemented legally with this
452// type.
453static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
454 if (N->getOpcode() == X86ISD::PCMPEQM ||
455 N->getOpcode() == X86ISD::PCMPGTM ||
456 N->getOpcode() == X86ISD::CMPM ||
457 N->getOpcode() == X86ISD::CMPMU) {
458 // We can get 256-bit 8 element types here without VLX being enabled. When
459 // this happens we will use 512-bit operations and the mask will not be
460 // zero extended.
461 if (N->getOperand(0).getValueType() == MVT::v8i32 ||
462 N->getOperand(0).getValueType() == MVT::v8f32)
463 return Subtarget->hasVLX();
464
465 return true;
466 }
467
468 return false;
469}
470
471// Returns true if we can assume the writer of the mask has zero extended it
472// for us.
473bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
474 // If this is an AND, check if we have a compare on either side. As long as
475 // one side guarantees the mask is zero extended, the AND will preserve those
476 // zeros.
477 if (N->getOpcode() == ISD::AND)
478 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
479 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
480
481 return isLegalMaskCompare(N, Subtarget);
482}
483
Evan Cheng5e73ff22010-02-15 19:41:07 +0000484bool
485X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000486 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000487
Evan Cheng5e73ff22010-02-15 19:41:07 +0000488 if (!N.hasOneUse())
489 return false;
490
491 if (N.getOpcode() != ISD::LOAD)
492 return true;
493
494 // If N is a load, do additional profitability checks.
495 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000496 switch (U->getOpcode()) {
497 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000498 case X86ISD::ADD:
499 case X86ISD::SUB:
500 case X86ISD::AND:
501 case X86ISD::XOR:
502 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000503 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000504 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000505 case ISD::AND:
506 case ISD::OR:
507 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000508 SDValue Op1 = U->getOperand(1);
509
Evan Cheng83bdb382008-11-27 00:49:46 +0000510 // If the other operand is a 8-bit immediate we should fold the immediate
511 // instead. This reduces code size.
512 // e.g.
513 // movl 4(%esp), %eax
514 // addl $4, %eax
515 // vs.
516 // movl $4, %eax
517 // addl 4(%esp), %eax
518 // The former is 2 bytes shorter. In case where the increment is 1, then
519 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000520 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000521 if (Imm->getAPIntValue().isSignedIntN(8))
522 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000523
524 // If the other operand is a TLS address, we should fold it instead.
525 // This produces
526 // movl %gs:0, %eax
527 // leal i@NTPOFF(%eax), %eax
528 // instead of
529 // movl $i@NTPOFF, %eax
530 // addl %gs:0, %eax
531 // if the block also has an access to a second TLS address this will save
532 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000533 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000534 if (Op1.getOpcode() == X86ISD::Wrapper) {
535 SDValue Val = Op1.getOperand(0);
536 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
537 return false;
538 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000539 }
540 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000541 }
542
543 return true;
544}
545
Sanjay Patelb5723d02015-10-13 15:12:27 +0000546/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000547/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000548static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
549 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000550 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000551 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000552 if (Chain.getNode() == Load.getNode())
553 Ops.push_back(Load.getOperand(0));
554 else {
555 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000556 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000557 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
558 if (Chain.getOperand(i).getNode() == Load.getNode())
559 Ops.push_back(Load.getOperand(0));
560 else
561 Ops.push_back(Chain.getOperand(i));
562 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000563 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000564 Ops.clear();
565 Ops.push_back(NewChain);
566 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000567 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000568 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000569 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000570 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000571
Evan Chengf00f1e52008-08-25 21:27:18 +0000572 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000573 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000574 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000575 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000576}
577
Sanjay Patelb5723d02015-10-13 15:12:27 +0000578/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000579/// moved below CALLSEQ_START and the chains leading up to the call.
580/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000581/// In the case of a tail call, there isn't a callseq node between the call
582/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000583static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000584 // The transformation is somewhat dangerous if the call's chain was glued to
585 // the call. After MoveBelowOrigChain the load is moved between the call and
586 // the chain, this can create a cycle if the load is not folded. So it is
587 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000588 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000589 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000590 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000591 if (!LD ||
592 LD->isVolatile() ||
593 LD->getAddressingMode() != ISD::UNINDEXED ||
594 LD->getExtensionType() != ISD::NON_EXTLOAD)
595 return false;
596
597 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000598 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000599 if (!Chain.hasOneUse())
600 return false;
601 Chain = Chain.getOperand(0);
602 }
Evan Chengd703df62010-03-14 03:48:46 +0000603
604 if (!Chain.getNumOperands())
605 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000606 // Since we are not checking for AA here, conservatively abort if the chain
607 // writes to memory. It's not safe to move the callee (a load) across a store.
608 if (isa<MemSDNode>(Chain.getNode()) &&
609 cast<MemSDNode>(Chain.getNode())->writeMem())
610 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000611 if (Chain.getOperand(0).getNode() == Callee.getNode())
612 return true;
613 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000614 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
615 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000616 return true;
617 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000618}
619
Chris Lattner8d637042010-03-02 23:12:51 +0000620void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000621 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Sanjay Patel68b03252015-08-10 16:47:47 +0000622 OptForSize = MF->getFunction()->optForSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000623 OptForMinSize = MF->getFunction()->optForMinSize();
624 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000625
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000626 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
627 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000628 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000629
Evan Chengd703df62010-03-14 03:48:46 +0000630 if (OptLevel != CodeGenOpt::None &&
Michael Liao96b42602013-03-28 23:13:21 +0000631 // Only does this when target favors doesn't favor register indirect
632 // call.
Craig Topper62c47a22017-08-29 05:14:27 +0000633 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000634 (N->getOpcode() == X86ISD::TC_RETURN &&
Nick Lewyckyf41a80e2013-01-13 19:03:55 +0000635 // Only does this if load can be folded into TC_RETURN.
Evan Cheng847ad442012-10-05 01:48:22 +0000636 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000637 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000638 /// Also try moving call address load from outside callseq_start to just
639 /// before the call to allow it to be folded.
640 ///
641 /// [Load chain]
642 /// ^
643 /// |
644 /// [Load]
645 /// ^ ^
646 /// | |
647 /// / \--
648 /// / |
649 ///[CALLSEQ_START] |
650 /// ^ |
651 /// | |
652 /// [LOAD/C2Reg] |
653 /// | |
654 /// \ /
655 /// \ /
656 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000657 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000658 SDValue Chain = N->getOperand(0);
659 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000660 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000661 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000662 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000663 ++NumLoadMoved;
664 continue;
665 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000666
Chris Lattner8d637042010-03-02 23:12:51 +0000667 // Lower fpround and fpextend nodes that target the FP stack to be store and
668 // load to the stack. This is a gross hack. We would like to simply mark
669 // these as being illegal, but when we do that, legalize produces these when
670 // it expands calls, then expands these in the same legalize pass. We would
671 // like dag combine to be able to hack on these between the call expansion
672 // and the node legalization. As such this pass basically does "really
673 // late" legalization of these inline with the X86 isel pass.
674 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000675 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
676 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000677
Craig Topper83e042a2013-08-15 05:57:07 +0000678 MVT SrcVT = N->getOperand(0).getSimpleValueType();
679 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000680
681 // If any of the sources are vectors, no fp stack involved.
682 if (SrcVT.isVector() || DstVT.isVector())
683 continue;
684
685 // If the source and destination are SSE registers, then this is a legal
686 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000687 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000688 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000689 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
690 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000691 if (SrcIsSSE && DstIsSSE)
692 continue;
693
Chris Lattnerd587e582008-03-09 07:05:32 +0000694 if (!SrcIsSSE && !DstIsSSE) {
695 // If this is an FPStack extension, it is a noop.
696 if (N->getOpcode() == ISD::FP_EXTEND)
697 continue;
698 // If this is a value-preserving FPStack truncation, it is a noop.
699 if (N->getConstantOperandVal(1))
700 continue;
701 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000702
Chris Lattnera91f77e2008-01-24 08:07:48 +0000703 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
704 // FPStack has extload and truncstore. SSE can fold direct loads into other
705 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000706 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000707 if (N->getOpcode() == ISD::FP_ROUND)
708 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
709 else
710 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000711
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000712 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000713 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000714
Chris Lattnera91f77e2008-01-24 08:07:48 +0000715 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000716 SDValue Store =
717 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
718 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000719 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000720 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000721
722 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
723 // extload we created. This will cause general havok on the dag because
724 // anything below the conversion could be folded into other existing nodes.
725 // To avoid invalidating 'I', back it up to the convert node.
726 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000727 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000728
Chris Lattnera91f77e2008-01-24 08:07:48 +0000729 // Now that we did that, the node is dead. Increment the iterator to the
730 // next node to process, then delete N.
731 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000732 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000733 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000734}
735
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000736
Sanjay Patelb5723d02015-10-13 15:12:27 +0000737/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000738void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000739 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000740 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000741 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000742
743 TargetLowering::CallLoweringInfo CLI(*CurDAG);
744 CLI.setChain(CurDAG->getRoot())
745 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000746 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000747 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000748 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
749 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
750 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000751 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000752}
753
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000754void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000755 // If this is main, emit special code for main.
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000756 if (const Function *Fn = MF->getFunction())
757 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
Sanjay Patel85030aa2015-10-13 16:23:00 +0000758 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000759}
760
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000761static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000762 // On 64-bit platforms, we can run into an issue where a frame index
763 // includes a displacement that, when added to the explicit displacement,
764 // will overflow the displacement field. Assuming that the frame index
765 // displacement fits into a 31-bit integer (which is only slightly more
766 // aggressive than the current fundamental assumption that it fits into
767 // a 32-bit integer), a 31-bit disp should always be safe.
768 return isInt<31>(Val);
769}
770
Sanjay Patel85030aa2015-10-13 16:23:00 +0000771bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000772 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000773 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000774 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000775 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000776 int64_t Val = AM.Disp + Offset;
777 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000778 if (Subtarget->is64Bit()) {
779 if (!X86::isOffsetSuitableForCodeModel(Val, M,
780 AM.hasSymbolicDisplacement()))
781 return true;
782 // In addition to the checks required for a register base, check that
783 // we do not try to use an unsafe Disp with a frame index.
784 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
785 !isDispSafeForFrameIndex(Val))
786 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000787 }
Eli Friedman344ec792011-07-13 21:29:53 +0000788 AM.Disp = Val;
789 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000790
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000791}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000792
Sanjay Patel85030aa2015-10-13 16:23:00 +0000793bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000794 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000795
Chris Lattner8a236b62010-09-22 04:39:11 +0000796 // load gs:0 -> GS segment register.
797 // load fs:0 -> FS segment register.
798 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000799 // This optimization is valid because the GNU TLS model defines that
800 // gs:0 (or fs:0 on X86-64) contains its own address.
801 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000802 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000803 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000804 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
805 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000806 switch (N->getPointerInfo().getAddrSpace()) {
807 case 256:
808 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
809 return false;
810 case 257:
811 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
812 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000813 // Address space 258 is not handled here, because it is not used to
814 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000815 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000816
Rafael Espindola3b2df102009-04-08 21:14:34 +0000817 return true;
818}
819
Sanjay Patelb5723d02015-10-13 15:12:27 +0000820/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
821/// mode. These wrap things that will resolve down into a symbol reference.
822/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000823bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000824 // If the addressing mode already has a symbol as the displacement, we can
825 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000826 if (AM.hasSymbolicDisplacement())
827 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000828
829 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000830 CodeModel::Model M = TM.getCodeModel();
831
Chris Lattnerfea81da2009-06-27 04:16:01 +0000832 // Handle X86-64 rip-relative addresses. We check this before checking direct
833 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000834 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000835 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
836 // they cannot be folded into immediate fields.
837 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000838 (M == CodeModel::Small || M == CodeModel::Kernel)) {
839 // Base and index reg must be 0 in order to use %rip as base.
840 if (AM.hasBaseOrIndexReg())
841 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000842 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000843 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000844 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000845 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000846 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000847 AM = Backup;
848 return true;
849 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000850 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000851 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000852 AM.CP = CP->getConstVal();
853 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000854 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000855 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000856 AM = Backup;
857 return true;
858 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000859 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
860 AM.ES = S->getSymbol();
861 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000862 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
863 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000864 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000865 AM.JT = J->getIndex();
866 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000867 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
868 X86ISelAddressMode Backup = AM;
869 AM.BlockAddr = BA->getBlockAddress();
870 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000871 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000872 AM = Backup;
873 return true;
874 }
875 } else
876 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000877
Chris Lattnerfea81da2009-06-27 04:16:01 +0000878 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000879 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000880 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000881 }
882
883 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000884 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
885 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000886 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000887 M == CodeModel::Small || M == CodeModel::Kernel) {
888 assert(N.getOpcode() != X86ISD::WrapperRIP &&
889 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000890 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
891 AM.GV = G->getGlobal();
892 AM.Disp += G->getOffset();
893 AM.SymbolFlags = G->getTargetFlags();
894 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
895 AM.CP = CP->getConstVal();
896 AM.Align = CP->getAlignment();
897 AM.Disp += CP->getOffset();
898 AM.SymbolFlags = CP->getTargetFlags();
899 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
900 AM.ES = S->getSymbol();
901 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000902 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
903 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000904 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000905 AM.JT = J->getIndex();
906 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000907 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
908 AM.BlockAddr = BA->getBlockAddress();
909 AM.Disp += BA->getOffset();
910 AM.SymbolFlags = BA->getTargetFlags();
911 } else
912 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000913 return false;
914 }
915
916 return true;
917}
918
Sanjay Patelb5723d02015-10-13 15:12:27 +0000919/// Add the specified node to the specified addressing mode, returning true if
920/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000921bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
922 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000923 return true;
924
925 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
926 // a smaller encoding and avoids a scaled-index.
927 if (AM.Scale == 2 &&
928 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000929 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000930 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000931 AM.Scale = 1;
932 }
933
Dan Gohman05046082009-08-20 18:23:44 +0000934 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
935 // because it has a smaller encoding.
936 // TODO: Which other code models can use this?
937 if (TM.getCodeModel() == CodeModel::Small &&
938 Subtarget->is64Bit() &&
939 AM.Scale == 1 &&
940 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000941 AM.Base_Reg.getNode() == nullptr &&
942 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000943 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000944 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000945 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000946
Dan Gohman824ab402009-07-22 23:26:55 +0000947 return false;
948}
949
Sanjay Patelefab8b02015-10-21 18:56:06 +0000950bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
951 unsigned Depth) {
952 // Add an artificial use to this node so that we can keep track of
953 // it if it gets CSE'd with a different node.
954 HandleSDNode Handle(N);
955
956 X86ISelAddressMode Backup = AM;
957 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
958 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
959 return false;
960 AM = Backup;
961
962 // Try again after commuting the operands.
963 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
964 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
965 return false;
966 AM = Backup;
967
968 // If we couldn't fold both operands into the address at the same time,
969 // see if we can just put each operand into a register and fold at least
970 // the add.
971 if (AM.BaseType == X86ISelAddressMode::RegBase &&
972 !AM.Base_Reg.getNode() &&
973 !AM.IndexReg.getNode()) {
974 N = Handle.getValue();
975 AM.Base_Reg = N.getOperand(0);
976 AM.IndexReg = N.getOperand(1);
977 AM.Scale = 1;
978 return false;
979 }
980 N = Handle.getValue();
981 return true;
982}
983
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000984// Insert a node into the DAG at least before the Pos node's position. This
985// will reposition the node as needed, and will assign it a node ID that is <=
986// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
987// IDs! The selection DAG must no longer depend on their uniqueness when this
988// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000989static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000990 if (N.getNode()->getNodeId() == -1 ||
991 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000992 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000993 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
994 }
995}
996
Adam Nemet0c7caf42014-09-16 17:14:10 +0000997// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
998// safe. This allows us to convert the shift and and into an h-register
999// extract and a scaled index. Returns false if the simplification is
1000// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001001static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1002 uint64_t Mask,
1003 SDValue Shift, SDValue X,
1004 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001005 if (Shift.getOpcode() != ISD::SRL ||
1006 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1007 !Shift.hasOneUse())
1008 return true;
1009
1010 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1011 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1012 Mask != (0xffu << ScaleLog))
1013 return true;
1014
Craig Topper83e042a2013-08-15 05:57:07 +00001015 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001016 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001017 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1018 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001019 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1020 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001021 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001022 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1023
Chandler Carrutheb21da02012-01-12 01:34:44 +00001024 // Insert the new nodes into the topological ordering. We must do this in
1025 // a valid topological ordering as nothing is going to go back and re-sort
1026 // these nodes. We continually insert before 'N' in sequence as this is
1027 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1028 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001029 insertDAGNode(DAG, N, Eight);
1030 insertDAGNode(DAG, N, Srl);
1031 insertDAGNode(DAG, N, NewMask);
1032 insertDAGNode(DAG, N, And);
1033 insertDAGNode(DAG, N, ShlCount);
1034 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001035 DAG.ReplaceAllUsesWith(N, Shl);
1036 AM.IndexReg = And;
1037 AM.Scale = (1 << ScaleLog);
1038 return false;
1039}
1040
Chandler Carruthaa01e662012-01-11 09:35:00 +00001041// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1042// allows us to fold the shift into this addressing mode. Returns false if the
1043// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001044static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1045 uint64_t Mask,
1046 SDValue Shift, SDValue X,
1047 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001048 if (Shift.getOpcode() != ISD::SHL ||
1049 !isa<ConstantSDNode>(Shift.getOperand(1)))
1050 return true;
1051
1052 // Not likely to be profitable if either the AND or SHIFT node has more
1053 // than one use (unless all uses are for address computation). Besides,
1054 // isel mechanism requires their node ids to be reused.
1055 if (!N.hasOneUse() || !Shift.hasOneUse())
1056 return true;
1057
1058 // Verify that the shift amount is something we can fold.
1059 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1060 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1061 return true;
1062
Craig Topper83e042a2013-08-15 05:57:07 +00001063 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001064 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001065 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001066 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1067 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1068
Chandler Carrutheb21da02012-01-12 01:34:44 +00001069 // Insert the new nodes into the topological ordering. We must do this in
1070 // a valid topological ordering as nothing is going to go back and re-sort
1071 // these nodes. We continually insert before 'N' in sequence as this is
1072 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1073 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001074 insertDAGNode(DAG, N, NewMask);
1075 insertDAGNode(DAG, N, NewAnd);
1076 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001077 DAG.ReplaceAllUsesWith(N, NewShift);
1078
1079 AM.Scale = 1 << ShiftAmt;
1080 AM.IndexReg = NewAnd;
1081 return false;
1082}
1083
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001084// Implement some heroics to detect shifts of masked values where the mask can
1085// be replaced by extending the shift and undoing that in the addressing mode
1086// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1087// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1088// the addressing mode. This results in code such as:
1089//
1090// int f(short *y, int *lookup_table) {
1091// ...
1092// return *y + lookup_table[*y >> 11];
1093// }
1094//
1095// Turning into:
1096// movzwl (%rdi), %eax
1097// movl %eax, %ecx
1098// shrl $11, %ecx
1099// addl (%rsi,%rcx,4), %eax
1100//
1101// Instead of:
1102// movzwl (%rdi), %eax
1103// movl %eax, %ecx
1104// shrl $9, %ecx
1105// andl $124, %rcx
1106// addl (%rsi,%rcx), %eax
1107//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001108// Note that this function assumes the mask is provided as a mask *after* the
1109// value is shifted. The input chain may or may not match that, but computing
1110// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001111static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1112 uint64_t Mask,
1113 SDValue Shift, SDValue X,
1114 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001115 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1116 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001117 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001118
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001119 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001120 unsigned MaskLZ = countLeadingZeros(Mask);
1121 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001122
1123 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001124 // from the trailing zeros of the mask.
1125 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001126
1127 // There is nothing we can do here unless the mask is removing some bits.
1128 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1129 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1130
1131 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001132 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001133
1134 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001135 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001136 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1137 if (MaskLZ < ScaleDown)
1138 return true;
1139 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001140
1141 // The final check is to ensure that any masked out high bits of X are
1142 // already known to be zero. Otherwise, the mask has a semantic impact
1143 // other than masking out a couple of low bits. Unfortunately, because of
1144 // the mask, zero extensions will be removed from operands in some cases.
1145 // This code works extra hard to look through extensions because we can
1146 // replace them with zero extensions cheaply if necessary.
1147 bool ReplacingAnyExtend = false;
1148 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001149 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1150 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001151 // Assume that we'll replace the any-extend with a zero-extend, and
1152 // narrow the search to the extended value.
1153 X = X.getOperand(0);
1154 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1155 ReplacingAnyExtend = true;
1156 }
Craig Topper83e042a2013-08-15 05:57:07 +00001157 APInt MaskedHighBits =
1158 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001159 KnownBits Known;
1160 DAG.computeKnownBits(X, Known);
1161 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001162
1163 // We've identified a pattern that can be transformed into a single shift
1164 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001165 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001166 if (ReplacingAnyExtend) {
1167 assert(X.getValueType() != VT);
1168 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001169 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001170 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001171 X = NewX;
1172 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001173 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001174 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001175 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001176 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001177 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001178
1179 // Insert the new nodes into the topological ordering. We must do this in
1180 // a valid topological ordering as nothing is going to go back and re-sort
1181 // these nodes. We continually insert before 'N' in sequence as this is
1182 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1183 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001184 insertDAGNode(DAG, N, NewSRLAmt);
1185 insertDAGNode(DAG, N, NewSRL);
1186 insertDAGNode(DAG, N, NewSHLAmt);
1187 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001188 DAG.ReplaceAllUsesWith(N, NewSHL);
1189
1190 AM.Scale = 1 << AMShiftAmt;
1191 AM.IndexReg = NewSRL;
1192 return false;
1193}
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001194
Sanjay Patel85030aa2015-10-13 16:23:00 +00001195bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001196 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001197 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001198 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001199 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001200 AM.dump();
1201 });
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001202 // Limit recursion.
1203 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001204 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001205
Chris Lattnerfea81da2009-06-27 04:16:01 +00001206 // If this is already a %rip relative address, we can only merge immediates
1207 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001208 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001209 if (AM.isRIPRelative()) {
1210 // FIXME: JumpTable and ExternalSymbol address currently don't like
1211 // displacements. It isn't very important, but this should be fixed for
1212 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001213 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1214 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001215
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001216 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001217 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001218 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001219 return true;
1220 }
1221
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001222 switch (N.getOpcode()) {
1223 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001224 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001225 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001226 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1227 // Use the symbol and don't prefix it.
1228 AM.MCSym = ESNode->getMCSymbol();
1229 return false;
1230 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001231 break;
1232 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001233 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001234 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001235 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001236 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001237 break;
1238 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001239
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001240 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001241 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001242 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001243 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001244 break;
1245
Rafael Espindola3b2df102009-04-08 21:14:34 +00001246 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001247 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001248 return false;
1249 break;
1250
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001251 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001252 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001253 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001254 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001255 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001256 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001257 return false;
1258 }
1259 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001260
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001261 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001262 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001263 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001264
Simon Pilgrim7f032312017-05-12 13:08:45 +00001265 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001266 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001267 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1268 // that the base operand remains free for further matching. If
1269 // the base doesn't end up getting used, a post-processing step
1270 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001271 if (Val == 1 || Val == 2 || Val == 3) {
1272 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001273 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001274
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001275 // Okay, we know that we have a scale by now. However, if the scaled
1276 // value is an add of something and a constant, we can fold the
1277 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001278 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001279 AM.IndexReg = ShVal.getOperand(0);
1280 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001281 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001282 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001283 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001284 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001285
1286 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001287 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001288 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001289 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001290 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001291
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001292 case ISD::SRL: {
1293 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001294 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001295
1296 SDValue And = N.getOperand(0);
1297 if (And.getOpcode() != ISD::AND) break;
1298 SDValue X = And.getOperand(0);
1299
1300 // We only handle up to 64-bit values here as those are what matter for
1301 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001302 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001303
1304 // The mask used for the transform is expected to be post-shift, but we
1305 // found the shift first so just apply the shift to the mask before passing
1306 // it down.
1307 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1308 !isa<ConstantSDNode>(And.getOperand(1)))
1309 break;
1310 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1311
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001312 // Try to fold the mask and shift into the scale, and return false if we
1313 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001314 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001315 return false;
1316 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001317 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001318
Dan Gohmanbf474952007-10-22 20:22:24 +00001319 case ISD::SMUL_LOHI:
1320 case ISD::UMUL_LOHI:
1321 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001322 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001323 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001324 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001325 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001326 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001327 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001328 AM.Base_Reg.getNode() == nullptr &&
1329 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001330 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001331 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1332 CN->getZExtValue() == 9) {
1333 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001334
Simon Pilgrim7f032312017-05-12 13:08:45 +00001335 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001336 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001337
1338 // Okay, we know that we have a scale by now. However, if the scaled
1339 // value is an add of something and a constant, we can fold the
1340 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001341 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001342 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1343 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001344 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001345 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001346 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001347 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001348 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001349 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001350 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001351 }
1352
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001353 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001354 return false;
1355 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001356 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001357 break;
1358
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001359 case ISD::SUB: {
1360 // Given A-B, if A can be completely folded into the address and
1361 // the index field with the index field unused, use -B as the index.
1362 // This is a win if a has multiple parts that can be folded into
1363 // the address. Also, this saves a mov if the base register has
1364 // other uses, since it avoids a two-address sub instruction, however
1365 // it costs an additional mov if the index register has other uses.
1366
Dan Gohman99ba4da2010-06-18 01:24:29 +00001367 // Add an artificial use to this node so that we can keep track of
1368 // it if it gets CSE'd with a different node.
1369 HandleSDNode Handle(N);
1370
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001371 // Test if the LHS of the sub can be folded.
1372 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001373 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001374 AM = Backup;
1375 break;
1376 }
1377 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001378 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001379 AM = Backup;
1380 break;
1381 }
Evan Cheng68333f52010-03-17 23:58:35 +00001382
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001383 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001384 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001385 // If the RHS involves a register with multiple uses, this
1386 // transformation incurs an extra mov, due to the neg instruction
1387 // clobbering its operand.
1388 if (!RHS.getNode()->hasOneUse() ||
1389 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1390 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1391 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1392 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001393 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001394 ++Cost;
1395 // If the base is a register with multiple uses, this
1396 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001397 // FIXME: Don't rely on DELETED_NODEs.
1398 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1399 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001400 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001401 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1402 --Cost;
1403 // If the folded LHS was interesting, this transformation saves
1404 // address arithmetic.
1405 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1406 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1407 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1408 --Cost;
1409 // If it doesn't look like it may be an overall win, don't do it.
1410 if (Cost >= 0) {
1411 AM = Backup;
1412 break;
1413 }
1414
1415 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001416 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001417 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1418 AM.IndexReg = Neg;
1419 AM.Scale = 1;
1420
1421 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001422 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1423 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001424 return false;
1425 }
1426
Sanjay Patelefab8b02015-10-21 18:56:06 +00001427 case ISD::ADD:
1428 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001429 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001430 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001431
Sanjay Patel533c10c2015-11-09 23:31:38 +00001432 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001433 // We want to look through a transform in InstCombine and DAGCombiner that
1434 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001435 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001436 // An 'lea' can then be used to match the shift (multiply) and add:
1437 // and $1, %esi
1438 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001439 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1440 !matchAdd(N, AM, Depth))
1441 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001442 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001443
Evan Cheng827d30d2007-12-13 00:43:27 +00001444 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001445 // Perform some heroic transforms on an and of a constant-count shift
1446 // with a constant to enable use of the scaled offset field.
1447
Evan Cheng827d30d2007-12-13 00:43:27 +00001448 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001449 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001450
Chandler Carruthaa01e662012-01-11 09:35:00 +00001451 SDValue Shift = N.getOperand(0);
1452 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001453 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001454
1455 // We only handle up to 64-bit values here as those are what matter for
1456 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001457 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001458
Chandler Carruthb0049f42012-01-11 09:35:04 +00001459 if (!isa<ConstantSDNode>(N.getOperand(1)))
1460 break;
1461 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001462
Chandler Carruth51d30762012-01-11 08:48:20 +00001463 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001464 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001465 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001466
Chandler Carruth51d30762012-01-11 08:48:20 +00001467 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001468 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001469 return false;
1470
Chandler Carruthaa01e662012-01-11 09:35:00 +00001471 // Try to swap the mask and shift to place shifts which can be done as
1472 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001473 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001474 return false;
1475 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001476 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001477 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001478
Sanjay Patel85030aa2015-10-13 16:23:00 +00001479 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001480}
1481
Sanjay Patelb5723d02015-10-13 15:12:27 +00001482/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001483/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001484bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001485 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001486 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001487 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001488 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001489 AM.IndexReg = N;
1490 AM.Scale = 1;
1491 return false;
1492 }
1493
1494 // Otherwise, we cannot select it.
1495 return true;
1496 }
1497
1498 // Default, generate it as a register.
1499 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001500 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001501 return false;
1502}
1503
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001504template <class GatherScatterSDNode>
1505bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1506 GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1507 SDValue &Index, SDValue &Disp, SDValue &Segment) {
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001508 X86ISelAddressMode AM;
1509 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001510 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001511 if (AddrSpace == 256)
1512 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1513 if (AddrSpace == 257)
1514 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001515 if (AddrSpace == 258)
1516 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001517
1518 SDLoc DL(N);
1519 Base = Mgs->getBasePtr();
1520 Index = Mgs->getIndex();
Sanjay Patel5f6bb6c2016-09-14 15:43:44 +00001521 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001522 Scale = getI8Imm(ScalarSize/8, DL);
1523
1524 // If Base is 0, the whole address is in index and the Scale is 1
Daniel Jasper232778a2015-04-30 09:01:21 +00001525 if (isa<ConstantSDNode>(Base)) {
Mehdi Amini42152362015-10-21 06:11:01 +00001526 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
Daniel Jasper232778a2015-04-30 09:01:21 +00001527 "Unexpected base in gather/scatter");
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001528 Scale = getI8Imm(1, DL);
1529 Base = CurDAG->getRegister(0, MVT::i32);
1530 }
1531 if (AM.Segment.getNode())
1532 Segment = AM.Segment;
1533 else
1534 Segment = CurDAG->getRegister(0, MVT::i32);
1535 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1536 return true;
1537}
1538
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001539bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1540 SDValue &Scale, SDValue &Index,
1541 SDValue &Disp, SDValue &Segment) {
1542 if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1543 return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1544 Mgs, N, Base, Scale, Index, Disp, Segment);
1545 if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1546 return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1547 X86Gather, N, Base, Scale, Index, Disp, Segment);
1548 return false;
1549}
1550
Sanjay Patelb5723d02015-10-13 15:12:27 +00001551/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001552/// It returns the operands which make up the maximal addressing mode it can
1553/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001554///
1555/// Parent is the parent node of the addr operand that is being matched. It
1556/// is always a load, store, atomic node, or null. It is only null when
1557/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001558bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001559 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001560 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001561 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001562
Chris Lattner8a236b62010-09-22 04:39:11 +00001563 if (Parent &&
1564 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1565 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001566 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001567 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001568 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1569 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1570 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001571 unsigned AddrSpace =
1572 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001573 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001574 if (AddrSpace == 256)
1575 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1576 if (AddrSpace == 257)
1577 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001578 if (AddrSpace == 258)
1579 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001580 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001581
Sanjay Patel85030aa2015-10-13 16:23:00 +00001582 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001583 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001584
Craig Topper83e042a2013-08-15 05:57:07 +00001585 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001586 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001587 if (!AM.Base_Reg.getNode())
1588 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001589 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001590
Gabor Greiff304a7a2008-08-28 21:40:38 +00001591 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001592 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001593
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001594 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001595 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001596}
1597
Craig Topper8078dd22017-08-21 16:04:04 +00001598// We can only fold a load if all nodes between it and the root node have a
1599// single use. If there are additional uses, we could end up duplicating the
1600// load.
1601static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1602 SDNode *User = *N->use_begin();
1603 while (User != Root) {
1604 if (!User->hasOneUse())
1605 return false;
1606 User = *User->use_begin();
1607 }
1608
1609 return true;
1610}
1611
Sanjay Patelb5723d02015-10-13 15:12:27 +00001612/// Match a scalar SSE load. In particular, we want to match a load whose top
1613/// elements are either undef or zeros. The load flavor is derived from the
1614/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001615///
1616/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001617/// PatternChainNode: this is the matched node that has a chain input and
1618/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001619bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001620 SDValue N, SDValue &Base,
1621 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001622 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001623 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001624 // We can allow a full vector load here since narrowing a load is ok.
1625 if (ISD::isNON_EXTLoad(N.getNode())) {
1626 PatternNodeWithChain = N;
1627 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001628 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1629 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001630 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1631 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1632 Segment);
1633 }
1634 }
1635
1636 // We can also match the special zero extended load opcode.
1637 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1638 PatternNodeWithChain = N;
1639 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001640 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1641 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001642 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1643 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1644 Segment);
1645 }
1646 }
1647
Craig Topper991d1ca2016-11-26 17:29:25 +00001648 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1649 // once. Otherwise the load might get duplicated and the chain output of the
1650 // duplicate load will not be observed by all dependencies.
1651 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001652 PatternNodeWithChain = N.getOperand(0);
1653 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001654 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001655 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1656 hasSingleUsesFromRoot(Root, N.getNode())) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001657 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001658 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1659 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001660 }
1661 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001662
1663 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001664 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001665 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001666 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001667 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001668 N.getOperand(0).getNode()->hasOneUse()) {
1669 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1670 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001671 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001672 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1673 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Toppere266e122016-11-26 18:43:24 +00001674 // Okay, this is a zero extending load. Fold it.
1675 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1676 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1677 Segment);
1678 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001679 }
Craig Toppere266e122016-11-26 18:43:24 +00001680
Chris Lattner398195e2006-10-07 21:55:32 +00001681 return false;
1682}
1683
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001684
Sanjay Patel85030aa2015-10-13 16:23:00 +00001685bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001686 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1687 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001688 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001689 return false;
1690
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001691 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001692 return true;
1693 }
1694
1695 // In static codegen with small code model, we can get the address of a label
1696 // into a register with 'movl'. TableGen has already made sure we're looking
1697 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001698 assert(N->getOpcode() == X86ISD::Wrapper &&
1699 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001700 N = N.getOperand(0);
1701
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001702 // At least GNU as does not accept 'movl' for TPOFF relocations.
1703 // FIXME: We could use 'movl' when we know we are targeting MC.
1704 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001705 return false;
1706
1707 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001708 if (N->getOpcode() != ISD::TargetGlobalAddress)
1709 return TM.getCodeModel() == CodeModel::Small;
1710
1711 Optional<ConstantRange> CR =
1712 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1713 if (!CR)
1714 return TM.getCodeModel() == CodeModel::Small;
1715
1716 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001717}
1718
Sanjay Patel85030aa2015-10-13 16:23:00 +00001719bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001720 SDValue &Scale, SDValue &Index,
1721 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001722 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1723 SDLoc DL(N);
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001724
Sanjay Patel85030aa2015-10-13 16:23:00 +00001725 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001726 return false;
1727
Tim Northover6833e3f2013-06-10 20:43:49 +00001728 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1729 if (RN && RN->getReg() == 0)
1730 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001731 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001732 // Base could already be %rip, particularly in the x32 ABI.
1733 Base = SDValue(CurDAG->getMachineNode(
1734 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001735 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001736 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001737 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001738 0);
1739 }
1740
1741 RN = dyn_cast<RegisterSDNode>(Index);
1742 if (RN && RN->getReg() == 0)
1743 Index = CurDAG->getRegister(0, MVT::i64);
1744 else {
1745 assert(Index.getValueType() == MVT::i32 &&
1746 "Expect to be extending 32-bit registers for use in LEA");
1747 Index = SDValue(CurDAG->getMachineNode(
1748 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001749 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001750 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001751 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1752 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001753 0);
1754 }
1755
1756 return true;
1757}
1758
Sanjay Patelb5723d02015-10-13 15:12:27 +00001759/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001760/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001761bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001762 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001763 SDValue &Index, SDValue &Disp,
1764 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001765 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001766
Justin Bogner32ad24d2016-04-12 21:34:24 +00001767 // Save the DL and VT before calling matchAddress, it can invalidate N.
1768 SDLoc DL(N);
1769 MVT VT = N.getSimpleValueType();
1770
Rafael Espindolabb834f02009-04-10 10:09:34 +00001771 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1772 // segments.
1773 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001774 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001775 AM.Segment = T;
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001776 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001777 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001778 assert (T == AM.Segment);
1779 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001780
Evan Cheng77d86ff2006-02-25 10:09:08 +00001781 unsigned Complexity = 0;
1782 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001783 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001784 Complexity = 1;
1785 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001786 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001787 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1788 Complexity = 4;
1789
Gabor Greiff304a7a2008-08-28 21:40:38 +00001790 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001791 Complexity++;
1792 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001793 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001794
Chris Lattner3e1d9172007-03-20 06:08:29 +00001795 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1796 // a simple shift.
1797 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001798 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001799
1800 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001801 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001802 // optimal (especially for code size consideration). LEA is nice because of
1803 // its three-address nature. Tweak the cost function again when we can run
1804 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001805 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001806 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001807 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001808 Complexity = 4;
1809 else
1810 Complexity += 2;
1811 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001812
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001813 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001814 Complexity++;
1815
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001816 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001817 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001818 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001819
Justin Bogner32ad24d2016-04-12 21:34:24 +00001820 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001821 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001822}
1823
Sanjay Patelb5723d02015-10-13 15:12:27 +00001824/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001825bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001826 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001827 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001828 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1829 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001830
Chris Lattner7d2b0492009-06-20 20:38:48 +00001831 X86ISelAddressMode AM;
1832 AM.GV = GA->getGlobal();
1833 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001834 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001835 AM.SymbolFlags = GA->getTargetFlags();
1836
Owen Anderson9f944592009-08-11 20:47:22 +00001837 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001838 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001839 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001840 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001841 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001842 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001843
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001844 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001845 return true;
1846}
1847
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001848bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1849 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1850 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1851 N.getValueType());
1852 return true;
1853 }
1854
Peter Collingbourne235c2752016-12-08 19:01:00 +00001855 // Keep track of the original value type and whether this value was
1856 // truncated. If we see a truncation from pointer type to VT that truncates
1857 // bits that are known to be zero, we can use a narrow reference.
1858 EVT VT = N.getValueType();
1859 bool WasTruncated = false;
1860 if (N.getOpcode() == ISD::TRUNCATE) {
1861 WasTruncated = true;
1862 N = N.getOperand(0);
1863 }
1864
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001865 if (N.getOpcode() != X86ISD::Wrapper)
1866 return false;
1867
Peter Collingbourne235c2752016-12-08 19:01:00 +00001868 // We can only use non-GlobalValues as immediates if they were not truncated,
1869 // as we do not have any range information. If we have a GlobalValue and the
1870 // address was not truncated, we can select it as an operand directly.
1871 unsigned Opc = N.getOperand(0)->getOpcode();
1872 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1873 Op = N.getOperand(0);
1874 // We can only select the operand directly if we didn't have to look past a
1875 // truncate.
1876 return !WasTruncated;
1877 }
1878
1879 // Check that the global's range fits into VT.
1880 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1881 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1882 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1883 return false;
1884
1885 // Okay, we can use a narrow reference.
1886 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1887 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001888 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001889}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001890
Sanjay Patel85030aa2015-10-13 16:23:00 +00001891bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001892 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001893 SDValue &Index, SDValue &Disp,
1894 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001895 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1896 !IsProfitableToFold(N, P, P) ||
Dan Gohman21cea8a2010-04-17 15:26:15 +00001897 !IsLegalToFold(N, P, P, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001898 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001899
Sanjay Patel85030aa2015-10-13 16:23:00 +00001900 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001901 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001902}
1903
Sanjay Patelb5723d02015-10-13 15:12:27 +00001904/// Return an SDNode that returns the value of the global base register.
1905/// Output instructions required to initialize the global base register,
1906/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00001907SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001908 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00001909 auto &DL = MF->getDataLayout();
1910 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001911}
1912
Peter Collingbourneef089bd2017-02-09 22:02:28 +00001913bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1914 if (N->getOpcode() == ISD::TRUNCATE)
1915 N = N->getOperand(0).getNode();
1916 if (N->getOpcode() != X86ISD::Wrapper)
1917 return false;
1918
1919 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1920 if (!GA)
1921 return false;
1922
1923 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1924 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1925 CR->getSignedMax().slt(1ull << Width);
1926}
1927
Sanjay Patelb5723d02015-10-13 15:12:27 +00001928/// Test whether the given X86ISD::CMP node has any uses which require the SF
1929/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001930static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001931 // Examine each user of the node.
1932 for (SDNode::use_iterator UI = N->use_begin(),
1933 UE = N->use_end(); UI != UE; ++UI) {
1934 // Only examine CopyToReg uses.
1935 if (UI->getOpcode() != ISD::CopyToReg)
1936 return false;
1937 // Only examine CopyToReg uses that copy to EFLAGS.
1938 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1939 X86::EFLAGS)
1940 return false;
1941 // Examine each user of the CopyToReg use.
1942 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1943 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1944 // Only examine the Flag result.
1945 if (FlagUI.getUse().getResNo() != 1) continue;
1946 // Anything unusual: assume conservatively.
1947 if (!FlagUI->isMachineOpcode()) return false;
1948 // Examine the opcode of the user.
1949 switch (FlagUI->getMachineOpcode()) {
1950 // These comparisons don't treat the most significant bit specially.
1951 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1952 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1953 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1954 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001955 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1956 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001957 case X86::CMOVA16rr: case X86::CMOVA16rm:
1958 case X86::CMOVA32rr: case X86::CMOVA32rm:
1959 case X86::CMOVA64rr: case X86::CMOVA64rm:
1960 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1961 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1962 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1963 case X86::CMOVB16rr: case X86::CMOVB16rm:
1964 case X86::CMOVB32rr: case X86::CMOVB32rm:
1965 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001966 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1967 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1968 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001969 case X86::CMOVE16rr: case X86::CMOVE16rm:
1970 case X86::CMOVE32rr: case X86::CMOVE32rm:
1971 case X86::CMOVE64rr: case X86::CMOVE64rm:
1972 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1973 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1974 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1975 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1976 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1977 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1978 case X86::CMOVP16rr: case X86::CMOVP16rm:
1979 case X86::CMOVP32rr: case X86::CMOVP32rm:
1980 case X86::CMOVP64rr: case X86::CMOVP64rm:
1981 continue;
1982 // Anything else: assume conservatively.
1983 default: return false;
1984 }
1985 }
1986 }
1987 return true;
1988}
1989
Chandler Carruth52a31bf2017-09-07 23:54:24 +00001990/// Test whether the given node which sets flags has any uses which require the
1991/// CF flag to be accurate.
1992static bool hasNoCarryFlagUses(SDNode *N) {
1993 // Examine each user of the node.
1994 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
1995 ++UI) {
1996 // Only check things that use the flags.
1997 if (UI.getUse().getResNo() != 1)
1998 continue;
1999 // Only examine CopyToReg uses.
2000 if (UI->getOpcode() != ISD::CopyToReg)
2001 return false;
2002 // Only examine CopyToReg uses that copy to EFLAGS.
2003 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2004 return false;
2005 // Examine each user of the CopyToReg use.
2006 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2007 FlagUI != FlagUE; ++FlagUI) {
2008 // Only examine the Flag result.
2009 if (FlagUI.getUse().getResNo() != 1)
2010 continue;
2011 // Anything unusual: assume conservatively.
2012 if (!FlagUI->isMachineOpcode())
2013 return false;
2014 // Examine the opcode of the user.
2015 switch (FlagUI->getMachineOpcode()) {
2016 // Comparisons which don't examine the CF flag.
2017 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2018 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2019 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2020 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2021 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2022 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2023 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2024 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2025 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2026 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2027 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2028 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2029 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2030 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2031 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2032 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2033 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2034 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2035 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2036 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2037 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2038 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2039 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2040 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2041 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2042 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2043 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2044 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2045 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2046 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2047 continue;
2048 // Anything else: assume conservatively.
2049 default:
2050 return false;
2051 }
2052 }
2053 }
2054 return true;
2055}
2056
Sanjay Patelb5723d02015-10-13 15:12:27 +00002057/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002058/// the {load; op; store} to modify transformation.
2059static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2060 SDValue StoredVal, SelectionDAG *CurDAG,
2061 LoadSDNode *&LoadNode,
2062 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002063 // is the stored value result 0 of the load?
2064 if (StoredVal.getResNo() != 0) return false;
2065
2066 // are there other uses of the loaded value than the inc or dec?
2067 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2068
Joel Jones68d59e82012-03-29 05:45:48 +00002069 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002070 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002071 return false;
2072
Evan Cheng3e869f02012-04-12 19:14:21 +00002073 SDValue Load = StoredVal->getOperand(0);
2074 // Is the stored value a non-extending and non-indexed load?
2075 if (!ISD::isNormalLoad(Load.getNode())) return false;
2076
2077 // Return LoadNode by reference.
2078 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002079
2080 // Is store the only read of the loaded value?
2081 if (!Load.hasOneUse())
2082 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002083
Evan Cheng3e869f02012-04-12 19:14:21 +00002084 // Is the address of the store the same as the load?
2085 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2086 LoadNode->getOffset() != StoreNode->getOffset())
2087 return false;
2088
2089 // Check if the chain is produced by the load or is a TokenFactor with
2090 // the load output chain as an operand. Return InputChain by reference.
2091 SDValue Chain = StoreNode->getChain();
2092
2093 bool ChainCheck = false;
2094 if (Chain == Load.getValue(1)) {
2095 ChainCheck = true;
2096 InputChain = LoadNode->getChain();
2097 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2098 SmallVector<SDValue, 4> ChainOps;
2099 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2100 SDValue Op = Chain.getOperand(i);
2101 if (Op == Load.getValue(1)) {
2102 ChainCheck = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002103 // Drop Load, but keep its chain. No cycle check necessary.
2104 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002105 continue;
2106 }
Evan Cheng58a95f02012-05-16 01:54:27 +00002107
2108 // Make sure using Op as part of the chain would not cause a cycle here.
2109 // In theory, we could check whether the chain node is a predecessor of
2110 // the load. But that can be very expensive. Instead visit the uses and
2111 // make sure they all have smaller node id than the load.
2112 int LoadId = LoadNode->getNodeId();
2113 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2114 UE = UI->use_end(); UI != UE; ++UI) {
2115 if (UI.getUse().getResNo() != 0)
2116 continue;
2117 if (UI->getNodeId() > LoadId)
2118 return false;
2119 }
2120
Evan Cheng3e869f02012-04-12 19:14:21 +00002121 ChainOps.push_back(Op);
2122 }
2123
2124 if (ChainCheck)
2125 // Make a new TokenFactor with all the other input chains except
2126 // for the load.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002127 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
Craig Topper48d114b2014-04-26 18:35:24 +00002128 MVT::Other, ChainOps);
Evan Cheng3e869f02012-04-12 19:14:21 +00002129 }
2130 if (!ChainCheck)
Joel Jones68d59e82012-03-29 05:45:48 +00002131 return false;
2132
2133 return true;
2134}
2135
Chandler Carruth4b611a82017-08-25 22:50:52 +00002136// Change a chain of {load; op; store} of the same value into a simple op
2137// through memory of that value, if the uses of the modified value and its
2138// address are suitable.
2139//
2140// The tablegen pattern memory operand pattern is currently not able to match
2141// the case where the EFLAGS on the original operation are used.
2142//
2143// To move this to tablegen, we'll need to improve tablegen to allow flags to
2144// be transferred from a node in the pattern to the result node, probably with
2145// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002146// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2147// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2148// (implicit EFLAGS)]>;
2149// but maybe need something like this
2150// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2151// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2152// (transferrable EFLAGS)]>;
2153//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002154// Until then, we manually fold these and instruction select the operation
2155// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002156bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2157 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2158 SDValue StoredVal = StoreNode->getOperand(1);
2159 unsigned Opc = StoredVal->getOpcode();
2160
Chandler Carruth4b611a82017-08-25 22:50:52 +00002161 // Before we try to select anything, make sure this is memory operand size
2162 // and opcode we can handle. Note that this must match the code below that
2163 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002164 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002165 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2166 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002167 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002168 switch (Opc) {
2169 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002170 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002171 case X86ISD::INC:
2172 case X86ISD::DEC:
2173 case X86ISD::ADD:
2174 case X86ISD::SUB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002175 case X86ISD::AND:
2176 case X86ISD::OR:
2177 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002178 break;
2179 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002180
Chandler Carruth03258f22017-08-25 02:04:03 +00002181 LoadSDNode *LoadNode = nullptr;
2182 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002183 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2184 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002185 return false;
2186
2187 SDValue Base, Scale, Index, Disp, Segment;
2188 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2189 Segment))
2190 return false;
2191
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002192 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002193 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002194 switch (MemVT.getSimpleVT().SimpleTy) {
2195 case MVT::i64:
2196 return Opc64;
2197 case MVT::i32:
2198 return Opc32;
2199 case MVT::i16:
2200 return Opc16;
2201 case MVT::i8:
2202 return Opc8;
2203 default:
2204 llvm_unreachable("Invalid size!");
2205 }
2206 };
2207
2208 MachineSDNode *Result;
2209 switch (Opc) {
2210 case X86ISD::INC:
2211 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002212 unsigned NewOpc =
2213 Opc == X86ISD::INC
2214 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2215 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002216 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2217 Result =
2218 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2219 break;
2220 }
2221 case X86ISD::ADD:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002222 case X86ISD::SUB:
2223 case X86ISD::AND:
2224 case X86ISD::OR:
2225 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002226 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2227 switch (Opc) {
2228 case X86ISD::ADD:
2229 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2230 X86::ADD8mr);
2231 case X86ISD::SUB:
2232 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2233 X86::SUB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002234 case X86ISD::AND:
2235 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2236 X86::AND8mr);
2237 case X86ISD::OR:
2238 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2239 case X86ISD::XOR:
2240 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2241 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002242 default:
2243 llvm_unreachable("Invalid opcode!");
2244 }
2245 };
2246 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2247 switch (Opc) {
2248 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002249 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002250 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002251 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002252 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002253 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002254 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002255 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002256 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002257 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002258 default:
2259 llvm_unreachable("Invalid opcode!");
2260 }
2261 };
2262 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2263 switch (Opc) {
2264 case X86ISD::ADD:
2265 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2266 X86::ADD8mi);
2267 case X86ISD::SUB:
2268 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2269 X86::SUB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002270 case X86ISD::AND:
2271 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2272 X86::AND8mi);
2273 case X86ISD::OR:
2274 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2275 X86::OR8mi);
2276 case X86ISD::XOR:
2277 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2278 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002279 default:
2280 llvm_unreachable("Invalid opcode!");
2281 }
2282 };
2283
2284 unsigned NewOpc = SelectRegOpcode(Opc);
2285 SDValue Operand = StoredVal->getOperand(1);
2286
2287 // See if the operand is a constant that we can fold into an immediate
2288 // operand.
2289 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2290 auto OperandV = OperandC->getAPIntValue();
2291
2292 // Check if we can shrink the operand enough to fit in an immediate (or
2293 // fit into a smaller immediate) by negating it and switching the
2294 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002295 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2296 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002297 (-OperandV).getMinSignedBits() <= 8) ||
2298 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2299 (-OperandV).getMinSignedBits() <= 32)) &&
2300 hasNoCarryFlagUses(StoredVal.getNode())) {
2301 OperandV = -OperandV;
2302 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2303 }
2304
2305 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2306 // the larger immediate operand.
2307 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2308 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2309 NewOpc = SelectImm8Opcode(Opc);
2310 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2311 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2312 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2313 NewOpc = SelectImmOpcode(Opc);
2314 }
2315 }
2316
2317 const SDValue Ops[] = {Base, Scale, Index, Disp,
2318 Segment, Operand, InputChain};
Chandler Carruth4b611a82017-08-25 22:50:52 +00002319 Result =
2320 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2321 break;
2322 }
2323 default:
2324 llvm_unreachable("Invalid opcode!");
2325 }
2326
Chandler Carruth03258f22017-08-25 02:04:03 +00002327 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2328 MemOp[0] = StoreNode->getMemOperand();
2329 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002330 Result->setMemRefs(MemOp, MemOp + 2);
2331
2332 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2333 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2334 CurDAG->RemoveDeadNode(Node);
2335 return true;
2336}
2337
Craig Topper958106d2017-09-12 17:40:25 +00002338// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2339bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2340 MVT NVT = Node->getSimpleValueType(0);
2341 SDLoc dl(Node);
2342
2343 SDValue N0 = Node->getOperand(0);
2344 SDValue N1 = Node->getOperand(1);
2345
2346 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2347 return false;
2348
2349 // Must have a shift right.
2350 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2351 return false;
2352
2353 // Shift can't have additional users.
2354 if (!N0->hasOneUse())
2355 return false;
2356
2357 // Only supported for 32 and 64 bits.
2358 if (NVT != MVT::i32 && NVT != MVT::i64)
2359 return false;
2360
2361 // Shift amount and RHS of and must be constant.
2362 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2363 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2364 if (!MaskCst || !ShiftCst)
2365 return false;
2366
2367 // And RHS must be a mask.
2368 uint64_t Mask = MaskCst->getZExtValue();
2369 if (!isMask_64(Mask))
2370 return false;
2371
2372 uint64_t Shift = ShiftCst->getZExtValue();
2373 uint64_t MaskSize = countPopulation(Mask);
2374
2375 // Don't interfere with something that can be handled by extracting AH.
2376 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2377 if (Shift == 8 && MaskSize == 8)
2378 return false;
2379
2380 // Make sure we are only using bits that were in the original value, not
2381 // shifted in.
2382 if (Shift + MaskSize > NVT.getSizeInBits())
2383 return false;
2384
2385 SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
2386 unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
2387 unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
2388
2389 // BMI requires the immediate to placed in a register.
2390 if (!Subtarget->hasTBM()) {
2391 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
2392 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
Craig Topper2b6bfda2017-09-13 07:53:21 +00002393 New = SDValue(CurDAG->getMachineNode(X86::MOV32ri, dl, NVT, New), 0);
2394 if (NVT == MVT::i64) {
2395 New =
2396 SDValue(CurDAG->getMachineNode(
2397 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2398 CurDAG->getTargetConstant(0, dl, MVT::i64), New,
2399 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
2400 0);
2401 }
Craig Topper958106d2017-09-12 17:40:25 +00002402 }
2403
2404 MachineSDNode *NewNode;
2405 SDValue Input = N0->getOperand(0);
2406 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2407 if (tryFoldLoad(Node, Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2408 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
2409 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
2410 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2411 // Update the chain.
2412 ReplaceUses(N1.getValue(1), SDValue(NewNode, 1));
2413 // Record the mem-refs
2414 LoadSDNode *LoadNode = cast<LoadSDNode>(Input);
2415 if (LoadNode) {
2416 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2417 MemOp[0] = LoadNode->getMemOperand();
2418 NewNode->setMemRefs(MemOp, MemOp + 1);
2419 }
2420 } else {
2421 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
2422 }
2423
2424 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
2425 CurDAG->RemoveDeadNode(Node);
2426 return true;
2427}
2428
Justin Bogner593741d2016-05-10 23:55:37 +00002429void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002430 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002431 unsigned Opc, MOpc;
2432 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002433 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002434
Chris Lattnerf98f1242010-03-02 06:34:30 +00002435 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
Evan Chengd49cc362006-02-10 22:24:32 +00002436
Dan Gohman17059682008-07-17 19:10:17 +00002437 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002438 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002439 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002440 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002441 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002442
Evan Cheng10d27902006-01-06 20:36:21 +00002443 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002444 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002445 case ISD::BRIND: {
2446 if (Subtarget->isTargetNaCl())
2447 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2448 // leave the instruction alone.
2449 break;
2450 if (Subtarget->isTarget64BitILP32()) {
2451 // Converts a 32-bit register to a 64-bit, zero-extended version of
2452 // it. This is needed because x86-64 can do many things, but jmp %r32
2453 // ain't one of them.
2454 const SDValue &Target = Node->getOperand(1);
2455 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2456 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2457 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2458 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002459 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002460 SelectCode(ZextTarget.getNode());
2461 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002462 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002463 }
2464 break;
2465 }
Dan Gohman757eee82009-08-02 16:10:52 +00002466 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002467 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002468 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002469
Craig Topper75370b92017-09-19 17:19:45 +00002470 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002471 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002472 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002473 SDValue VSelect = CurDAG->getNode(
2474 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2475 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002476 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002477 SelectCode(VSelect.getNode());
2478 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002479 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002480 }
Craig Topper3af251d2012-07-01 02:55:34 +00002481
Tobias Grosser85508e82015-08-19 11:35:10 +00002482 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002483 // Try to match BEXTR/BEXTRI instruction.
2484 if (matchBEXTRFromAnd(Node))
2485 return;
2486
2487 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002488 case ISD::OR:
2489 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002490
Benjamin Kramer4c816242011-04-22 15:30:40 +00002491 // For operations of the form (x << C1) op C2, check if we can use a smaller
2492 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2493 SDValue N0 = Node->getOperand(0);
2494 SDValue N1 = Node->getOperand(1);
2495
2496 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2497 break;
2498
2499 // i8 is unshrinkable, i16 should be promoted to i32.
2500 if (NVT != MVT::i32 && NVT != MVT::i64)
2501 break;
2502
2503 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2504 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2505 if (!Cst || !ShlCst)
2506 break;
2507
2508 int64_t Val = Cst->getSExtValue();
2509 uint64_t ShlVal = ShlCst->getZExtValue();
2510
2511 // Make sure that we don't change the operation by removing bits.
2512 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002513 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2514 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002515 break;
2516
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002517 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002518 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002519
2520 // Check the minimum bitwidth for the new constant.
2521 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2522 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2523 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2524 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2525 CstVT = MVT::i8;
2526 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2527 CstVT = MVT::i32;
2528
2529 // Bail if there is no smaller encoding.
2530 if (NVT == CstVT)
2531 break;
2532
Craig Topper83e042a2013-08-15 05:57:07 +00002533 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002534 default: llvm_unreachable("Unsupported VT!");
2535 case MVT::i32:
2536 assert(CstVT == MVT::i8);
2537 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002538 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002539
2540 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002541 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002542 case ISD::AND: Op = X86::AND32ri8; break;
2543 case ISD::OR: Op = X86::OR32ri8; break;
2544 case ISD::XOR: Op = X86::XOR32ri8; break;
2545 }
2546 break;
2547 case MVT::i64:
2548 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2549 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002550 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002551
2552 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002553 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002554 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2555 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2556 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2557 }
2558 break;
2559 }
2560
2561 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002562 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002563 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002564 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002565 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2566 SDValue(New, 0));
2567 else
2568 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2569 getI8Imm(ShlVal, dl));
2570 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002571 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002572 case X86ISD::UMUL8:
2573 case X86ISD::SMUL8: {
2574 SDValue N0 = Node->getOperand(0);
2575 SDValue N1 = Node->getOperand(1);
2576
2577 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2578
2579 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2580 N0, SDValue()).getValue(1);
2581
2582 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2583 SDValue Ops[] = {N1, InFlag};
2584 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2585
Justin Bogner31d7da32016-05-11 21:13:17 +00002586 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002587 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002588 }
2589
Chris Lattner364bb0a2010-12-05 07:30:36 +00002590 case X86ISD::UMUL: {
2591 SDValue N0 = Node->getOperand(0);
2592 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002593
Ted Kremenekb5241b22011-01-14 22:34:13 +00002594 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002595 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002596 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00002597 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00002598 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2599 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2600 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002601 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002602
Chris Lattner364bb0a2010-12-05 07:30:36 +00002603 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2604 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002605
Chris Lattner364bb0a2010-12-05 07:30:36 +00002606 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2607 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002608 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002609
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002610 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002611 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002612 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002613
Dan Gohman757eee82009-08-02 16:10:52 +00002614 case ISD::SMUL_LOHI:
2615 case ISD::UMUL_LOHI: {
2616 SDValue N0 = Node->getOperand(0);
2617 SDValue N1 = Node->getOperand(1);
2618
2619 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002620 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002621 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002622 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002623 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002624 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2625 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002626 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2627 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2628 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2629 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002630 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002631 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002632 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002633 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002634 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2635 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2636 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2637 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002638 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002639 }
Dan Gohman757eee82009-08-02 16:10:52 +00002640
Michael Liaof9f7b552012-09-26 08:22:37 +00002641 unsigned SrcReg, LoReg, HiReg;
2642 switch (Opc) {
2643 default: llvm_unreachable("Unknown MUL opcode!");
2644 case X86::IMUL8r:
2645 case X86::MUL8r:
2646 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2647 break;
2648 case X86::IMUL16r:
2649 case X86::MUL16r:
2650 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2651 break;
2652 case X86::IMUL32r:
2653 case X86::MUL32r:
2654 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2655 break;
2656 case X86::IMUL64r:
2657 case X86::MUL64r:
2658 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2659 break;
2660 case X86::MULX32rr:
2661 SrcReg = X86::EDX; LoReg = HiReg = 0;
2662 break;
2663 case X86::MULX64rr:
2664 SrcReg = X86::RDX; LoReg = HiReg = 0;
2665 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002666 }
2667
2668 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002669 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002670 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002671 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002672 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002673 if (foldedLoad)
2674 std::swap(N0, N1);
2675 }
2676
Michael Liaof9f7b552012-09-26 08:22:37 +00002677 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002678 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002679 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002680
2681 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002682 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002683 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002684 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2685 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002686 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2687 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002688 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002689 ResHi = SDValue(CNode, 0);
2690 ResLo = SDValue(CNode, 1);
2691 Chain = SDValue(CNode, 2);
2692 InFlag = SDValue(CNode, 3);
2693 } else {
2694 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002695 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002696 Chain = SDValue(CNode, 0);
2697 InFlag = SDValue(CNode, 1);
2698 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002699
Dan Gohman757eee82009-08-02 16:10:52 +00002700 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002701 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002702 // Record the mem-refs
2703 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2704 if (LoadNode) {
2705 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2706 MemOp[0] = LoadNode->getMemOperand();
2707 CNode->setMemRefs(MemOp, MemOp + 1);
2708 }
Dan Gohman757eee82009-08-02 16:10:52 +00002709 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002710 SDValue Ops[] = { N1, InFlag };
2711 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2712 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002713 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002714 ResHi = SDValue(CNode, 0);
2715 ResLo = SDValue(CNode, 1);
2716 InFlag = SDValue(CNode, 2);
2717 } else {
2718 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002719 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002720 InFlag = SDValue(CNode, 0);
2721 }
Dan Gohman757eee82009-08-02 16:10:52 +00002722 }
2723
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002724 // Prevent use of AH in a REX instruction by referencing AX instead.
2725 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2726 !SDValue(Node, 1).use_empty()) {
2727 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2728 X86::AX, MVT::i16, InFlag);
2729 InFlag = Result.getValue(2);
2730 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2731 // registers.
2732 if (!SDValue(Node, 0).use_empty())
2733 ReplaceUses(SDValue(Node, 1),
2734 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2735
2736 // Shift AX down 8 bits.
2737 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2738 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002739 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2740 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002741 // Then truncate it down to i8.
2742 ReplaceUses(SDValue(Node, 1),
2743 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2744 }
Dan Gohman757eee82009-08-02 16:10:52 +00002745 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002746 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002747 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002748 assert(LoReg && "Register for low half is not defined!");
2749 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2750 InFlag);
2751 InFlag = ResLo.getValue(2);
2752 }
2753 ReplaceUses(SDValue(Node, 0), ResLo);
2754 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002755 }
2756 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002757 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002758 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002759 assert(HiReg && "Register for high half is not defined!");
2760 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2761 InFlag);
2762 InFlag = ResHi.getValue(2);
2763 }
2764 ReplaceUses(SDValue(Node, 1), ResHi);
2765 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002766 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002767
Craig Topper6bed9de2017-09-09 05:57:20 +00002768 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002769 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002770 }
2771
2772 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002773 case ISD::UDIVREM:
2774 case X86ISD::SDIVREM8_SEXT_HREG:
2775 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002776 SDValue N0 = Node->getOperand(0);
2777 SDValue N1 = Node->getOperand(1);
2778
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002779 bool isSigned = (Opcode == ISD::SDIVREM ||
2780 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002781 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002782 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002783 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002784 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2785 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2786 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2787 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002788 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002789 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002790 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002791 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002792 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2793 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2794 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2795 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002796 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002797 }
Dan Gohman757eee82009-08-02 16:10:52 +00002798
Chris Lattner518b0372009-12-23 01:45:04 +00002799 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002800 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002801 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002802 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002803 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002804 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002805 SExtOpcode = X86::CBW;
2806 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002807 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002808 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002809 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002810 SExtOpcode = X86::CWD;
2811 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002812 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002813 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002814 SExtOpcode = X86::CDQ;
2815 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002816 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002817 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002818 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002819 break;
2820 }
2821
Dan Gohman757eee82009-08-02 16:10:52 +00002822 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002823 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002824 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002825
Dan Gohman757eee82009-08-02 16:10:52 +00002826 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002827 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002828 // Special case for div8, just use a move with zero extension to AX to
2829 // clear the upper 8 bits (AH).
2830 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002831 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002832 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2833 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002834 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002835 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002836 Chain = Move.getValue(1);
2837 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002838 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002839 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002840 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002841 Chain = CurDAG->getEntryNode();
2842 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002843 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002844 InFlag = Chain.getValue(1);
2845 } else {
2846 InFlag =
2847 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2848 LoReg, N0, SDValue()).getValue(1);
2849 if (isSigned && !signBitIsZero) {
2850 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002851 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002852 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002853 } else {
2854 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002855 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002856 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002857 case MVT::i16:
2858 ClrNode =
2859 SDValue(CurDAG->getMachineNode(
2860 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002861 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2862 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002863 0);
2864 break;
2865 case MVT::i32:
2866 break;
2867 case MVT::i64:
2868 ClrNode =
2869 SDValue(CurDAG->getMachineNode(
2870 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002871 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2872 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2873 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002874 0);
2875 break;
2876 default:
2877 llvm_unreachable("Unexpected division source");
2878 }
2879
Chris Lattner518b0372009-12-23 01:45:04 +00002880 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00002881 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00002882 }
Evan Cheng92e27972006-01-06 23:19:29 +00002883 }
Dan Gohmana1603612007-10-08 18:33:35 +00002884
Dan Gohman757eee82009-08-02 16:10:52 +00002885 if (foldedLoad) {
2886 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2887 InFlag };
2888 SDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00002889 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00002890 InFlag = SDValue(CNode, 1);
2891 // Update the chain.
2892 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2893 } else {
2894 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002895 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002896 }
Evan Cheng92e27972006-01-06 23:19:29 +00002897
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002898 // Prevent use of AH in a REX instruction by explicitly copying it to
2899 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00002900 //
2901 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002902 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00002903 // the allocator and/or the backend get enhanced to be more robust in
2904 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002905 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2906 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2907 unsigned AHExtOpcode =
2908 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002909
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002910 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2911 MVT::Glue, AHCopy, InFlag);
2912 SDValue Result(RNode, 0);
2913 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002914
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002915 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2916 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2917 if (Node->getValueType(1) == MVT::i64) {
2918 // It's not possible to directly movsx AH to a 64bit register, because
2919 // the latter needs the REX prefix, but the former can't have it.
2920 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2921 "Unexpected i64 sext of h-register");
2922 Result =
2923 SDValue(CurDAG->getMachineNode(
2924 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002925 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2926 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2927 MVT::i32)),
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002928 0);
2929 }
2930 } else {
2931 Result =
2932 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2933 }
2934 ReplaceUses(SDValue(Node, 1), Result);
2935 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002936 }
Dan Gohman757eee82009-08-02 16:10:52 +00002937 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002938 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00002939 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2940 LoReg, NVT, InFlag);
2941 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002942 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002943 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002944 }
2945 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002946 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002947 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2948 HiReg, NVT, InFlag);
2949 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002950 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002951 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002952 }
Craig Topper6bed9de2017-09-09 05:57:20 +00002953 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002954 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002955 }
2956
Manman Ren1be131b2012-08-08 00:51:41 +00002957 case X86ISD::CMP:
2958 case X86ISD::SUB: {
2959 // Sometimes a SUB is used to perform comparison.
2960 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2961 // This node is not a CMP.
2962 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00002963 SDValue N0 = Node->getOperand(0);
2964 SDValue N1 = Node->getOperand(1);
2965
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002966 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00002967 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002968 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002969
Dan Gohmanac33a902009-08-19 18:16:17 +00002970 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2971 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002972 // Look past the truncate if CMP is the only use of it.
Craig Topperc93d05562017-08-25 05:36:29 +00002973 if ((N0.getOpcode() == ISD::AND ||
2974 (N0.getResNo() == 0 && N0.getOpcode() == X86ISD::AND)) &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00002975 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00002976 N0.getValueType() != MVT::i8 &&
2977 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00002978 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00002979 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00002980 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00002981
2982 // For example, convert "testl %eax, $8" to "testb %al, $8"
Craig Topperfc53dc22017-08-25 05:04:34 +00002983 if (isUInt<8>(Mask) &&
2984 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
2985 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002986 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002987
Dan Gohmanac33a902009-08-19 18:16:17 +00002988 // Extract the l-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002989 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002990 MVT::i8, Reg);
2991
2992 // Emit a testb.
Manman Ren511c6d02012-09-28 18:53:24 +00002993 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2994 Subreg, Imm);
2995 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2996 // one, do not call ReplaceAllUsesWith.
2997 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2998 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00002999 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003000 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003001 }
3002
3003 // For example, "testl %eax, $2048" to "testb %ah, $8".
Craig Topperfc53dc22017-08-25 05:04:34 +00003004 if (isShiftedUInt<8, 8>(Mask) &&
3005 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
Dan Gohmanac33a902009-08-19 18:16:17 +00003006 // Shift the immediate right by 8 bits.
Craig Topperfc53dc22017-08-25 05:04:34 +00003007 SDValue ShiftedImm = CurDAG->getTargetConstant(Mask >> 8, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003008 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003009
Dan Gohmanac33a902009-08-19 18:16:17 +00003010 // Extract the h-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003011 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003012 MVT::i8, Reg);
3013
Jakob Stoklund Olesen729abd32011-10-08 18:28:28 +00003014 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
3015 // target GR8_NOREX registers, so make sure the register class is
3016 // forced.
Manman Ren511c6d02012-09-28 18:53:24 +00003017 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
3018 MVT::i32, Subreg, ShiftedImm);
3019 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3020 // one, do not call ReplaceAllUsesWith.
3021 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3022 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003023 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003024 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003025 }
3026
3027 // For example, "testl %eax, $32776" to "testw %ax, $32776".
Craig Topperfc53dc22017-08-25 05:04:34 +00003028 if (isUInt<16>(Mask) && N0.getValueType() != MVT::i16 &&
3029 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3030 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i16);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003031 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003032
3033 // Extract the 16-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003034 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003035 MVT::i16, Reg);
3036
3037 // Emit a testw.
Manman Ren511c6d02012-09-28 18:53:24 +00003038 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
3039 Subreg, Imm);
3040 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3041 // one, do not call ReplaceAllUsesWith.
3042 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3043 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003044 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003045 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003046 }
3047
3048 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
Craig Topperfc53dc22017-08-25 05:04:34 +00003049 if (isUInt<32>(Mask) && N0.getValueType() == MVT::i64 &&
3050 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3051 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003052 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003053
3054 // Extract the 32-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003055 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003056 MVT::i32, Reg);
3057
3058 // Emit a testl.
Manman Ren511c6d02012-09-28 18:53:24 +00003059 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
3060 Subreg, Imm);
3061 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3062 // one, do not call ReplaceAllUsesWith.
3063 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3064 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003065 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003066 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003067 }
3068 }
3069 break;
3070 }
Chandler Carruth03258f22017-08-25 02:04:03 +00003071 case ISD::STORE:
3072 if (foldLoadStoreIntoMemOperand(Node))
3073 return;
3074 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003075 }
3076
Justin Bogner593741d2016-05-10 23:55:37 +00003077 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003078}
3079
Chris Lattnerba1ed582006-06-08 18:03:49 +00003080bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003081SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003082 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003083 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003084 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003085 default:
3086 llvm_unreachable("Unexpected asm memory constraint");
3087 case InlineAsm::Constraint_i:
3088 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3089 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003090 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003091 case InlineAsm::Constraint_o: // offsetable ??
3092 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003093 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003094 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003095 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003096 return true;
3097 break;
3098 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003099
Evan Cheng2d487222006-08-26 01:05:16 +00003100 OutOps.push_back(Op0);
3101 OutOps.push_back(Op1);
3102 OutOps.push_back(Op2);
3103 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003104 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003105 return false;
3106}
3107
Sanjay Patelb5723d02015-10-13 15:12:27 +00003108/// This pass converts a legalized DAG into a X86-specific DAG,
3109/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003110FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003111 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003112 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003113}