blob: e43fd508de30c5d89e3638fbc94fd86da910258b [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
Aaron Ballman615eb472017-10-15 14:32:27 +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 Wennborg2a6c9ad2017-10-04 17:54:06 +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();
Craig Topper9563cab2017-10-08 01:33:42 +0000374 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000375 }
376
377 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
378 const SDLoc &DL) {
379 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
380 uint64_t Index = N->getConstantOperandVal(2);
381 MVT VecVT = N->getSimpleValueType(0);
Craig Topper9563cab2017-10-08 01:33:42 +0000382 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
Craig Topper092c2f42017-09-23 05:34:07 +0000383 }
384
Sanjay Patelb5723d02015-10-13 15:12:27 +0000385 /// Return an SDNode that returns the value of the global base register.
386 /// Output instructions required to initialize the global base register,
387 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000388 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000389
Sanjay Patelb5723d02015-10-13 15:12:27 +0000390 /// Return a reference to the TargetMachine, casted to the target-specific
391 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000392 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000393 return static_cast<const X86TargetMachine &>(TM);
394 }
395
Sanjay Patelb5723d02015-10-13 15:12:27 +0000396 /// Return a reference to the TargetInstrInfo, casted to the target-specific
397 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000398 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000399 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000400 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000401
402 /// \brief Address-mode matching performs shift-of-and to and-of-shift
403 /// reassociation in order to expose more scaled addressing
404 /// opportunities.
405 bool ComplexPatternFuncMutatesDAG() const override {
406 return true;
407 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000408
409 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
410
411 /// Returns whether this is a relocatable immediate in the range
412 /// [-2^Width .. 2^Width-1].
413 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
414 if (auto *CN = dyn_cast<ConstantSDNode>(N))
415 return isInt<Width>(CN->getSExtValue());
416 return isSExtAbsoluteSymbolRef(Width, N);
417 }
Craig Topper4de6f582017-08-19 23:21:22 +0000418
419 // Indicates we should prefer to use a non-temporal load for this load.
420 bool useNonTemporalLoad(LoadSDNode *N) const {
421 if (!N->isNonTemporal())
422 return false;
423
424 unsigned StoreSize = N->getMemoryVT().getStoreSize();
425
426 if (N->getAlignment() < StoreSize)
427 return false;
428
429 switch (StoreSize) {
430 default: llvm_unreachable("Unsupported store size");
431 case 16:
432 return Subtarget->hasSSE41();
433 case 32:
434 return Subtarget->hasAVX2();
435 case 64:
436 return Subtarget->hasAVX512();
437 }
438 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000439
440 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000441
442 bool matchBEXTRFromAnd(SDNode *Node);
Craig Topperba3cc2e2017-09-25 18:43:13 +0000443
444 bool isMaskZeroExtended(SDNode *N) const;
Chris Lattner655e7df2005-11-16 01:54:32 +0000445 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000446}
447
Evan Cheng72bb66a2006-08-08 00:31:00 +0000448
Craig Topperba3cc2e2017-09-25 18:43:13 +0000449// Returns true if this masked compare can be implemented legally with this
450// type.
451static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
452 if (N->getOpcode() == X86ISD::PCMPEQM ||
453 N->getOpcode() == X86ISD::PCMPGTM ||
454 N->getOpcode() == X86ISD::CMPM ||
455 N->getOpcode() == X86ISD::CMPMU) {
456 // We can get 256-bit 8 element types here without VLX being enabled. When
457 // this happens we will use 512-bit operations and the mask will not be
458 // zero extended.
459 if (N->getOperand(0).getValueType() == MVT::v8i32 ||
460 N->getOperand(0).getValueType() == MVT::v8f32)
461 return Subtarget->hasVLX();
462
463 return true;
464 }
465
466 return false;
467}
468
469// Returns true if we can assume the writer of the mask has zero extended it
470// for us.
471bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
472 // If this is an AND, check if we have a compare on either side. As long as
473 // one side guarantees the mask is zero extended, the AND will preserve those
474 // zeros.
475 if (N->getOpcode() == ISD::AND)
476 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
477 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
478
479 return isLegalMaskCompare(N, Subtarget);
480}
481
Evan Cheng5e73ff22010-02-15 19:41:07 +0000482bool
483X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000484 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000485
Evan Cheng5e73ff22010-02-15 19:41:07 +0000486 if (!N.hasOneUse())
487 return false;
488
489 if (N.getOpcode() != ISD::LOAD)
490 return true;
491
492 // If N is a load, do additional profitability checks.
493 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000494 switch (U->getOpcode()) {
495 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000496 case X86ISD::ADD:
497 case X86ISD::SUB:
498 case X86ISD::AND:
499 case X86ISD::XOR:
500 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000501 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000502 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000503 case ISD::AND:
504 case ISD::OR:
505 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000506 SDValue Op1 = U->getOperand(1);
507
Evan Cheng83bdb382008-11-27 00:49:46 +0000508 // If the other operand is a 8-bit immediate we should fold the immediate
509 // instead. This reduces code size.
510 // e.g.
511 // movl 4(%esp), %eax
512 // addl $4, %eax
513 // vs.
514 // movl $4, %eax
515 // addl 4(%esp), %eax
516 // The former is 2 bytes shorter. In case where the increment is 1, then
517 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000518 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000519 if (Imm->getAPIntValue().isSignedIntN(8))
520 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000521
522 // If the other operand is a TLS address, we should fold it instead.
523 // This produces
524 // movl %gs:0, %eax
525 // leal i@NTPOFF(%eax), %eax
526 // instead of
527 // movl $i@NTPOFF, %eax
528 // addl %gs:0, %eax
529 // if the block also has an access to a second TLS address this will save
530 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000531 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000532 if (Op1.getOpcode() == X86ISD::Wrapper) {
533 SDValue Val = Op1.getOperand(0);
534 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
535 return false;
536 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000537 }
538 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000539 }
540
541 return true;
542}
543
Sanjay Patelb5723d02015-10-13 15:12:27 +0000544/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000545/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000546static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
547 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000548 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000549 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000550 if (Chain.getNode() == Load.getNode())
551 Ops.push_back(Load.getOperand(0));
552 else {
553 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000554 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000555 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
556 if (Chain.getOperand(i).getNode() == Load.getNode())
557 Ops.push_back(Load.getOperand(0));
558 else
559 Ops.push_back(Chain.getOperand(i));
560 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000561 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000562 Ops.clear();
563 Ops.push_back(NewChain);
564 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000565 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000566 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000567 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000568 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000569
Evan Chengf00f1e52008-08-25 21:27:18 +0000570 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000571 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000572 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000573 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000574}
575
Sanjay Patelb5723d02015-10-13 15:12:27 +0000576/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000577/// moved below CALLSEQ_START and the chains leading up to the call.
578/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000579/// In the case of a tail call, there isn't a callseq node between the call
580/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000581static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000582 // The transformation is somewhat dangerous if the call's chain was glued to
583 // the call. After MoveBelowOrigChain the load is moved between the call and
584 // the chain, this can create a cycle if the load is not folded. So it is
585 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000586 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000587 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000588 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000589 if (!LD ||
590 LD->isVolatile() ||
591 LD->getAddressingMode() != ISD::UNINDEXED ||
592 LD->getExtensionType() != ISD::NON_EXTLOAD)
593 return false;
594
595 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000596 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000597 if (!Chain.hasOneUse())
598 return false;
599 Chain = Chain.getOperand(0);
600 }
Evan Chengd703df62010-03-14 03:48:46 +0000601
602 if (!Chain.getNumOperands())
603 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000604 // Since we are not checking for AA here, conservatively abort if the chain
605 // writes to memory. It's not safe to move the callee (a load) across a store.
606 if (isa<MemSDNode>(Chain.getNode()) &&
607 cast<MemSDNode>(Chain.getNode())->writeMem())
608 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000609 if (Chain.getOperand(0).getNode() == Callee.getNode())
610 return true;
611 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000612 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
613 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000614 return true;
615 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000616}
617
Chris Lattner8d637042010-03-02 23:12:51 +0000618void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000619 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Sanjay Patel68b03252015-08-10 16:47:47 +0000620 OptForSize = MF->getFunction()->optForSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000621 OptForMinSize = MF->getFunction()->optForMinSize();
622 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000623
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000624 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
625 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000626 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000627
Evan Chengd703df62010-03-14 03:48:46 +0000628 if (OptLevel != CodeGenOpt::None &&
Michael Liao96b42602013-03-28 23:13:21 +0000629 // Only does this when target favors doesn't favor register indirect
630 // call.
Craig Topper62c47a22017-08-29 05:14:27 +0000631 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000632 (N->getOpcode() == X86ISD::TC_RETURN &&
Nick Lewyckyf41a80e2013-01-13 19:03:55 +0000633 // Only does this if load can be folded into TC_RETURN.
Evan Cheng847ad442012-10-05 01:48:22 +0000634 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000635 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000636 /// Also try moving call address load from outside callseq_start to just
637 /// before the call to allow it to be folded.
638 ///
639 /// [Load chain]
640 /// ^
641 /// |
642 /// [Load]
643 /// ^ ^
644 /// | |
645 /// / \--
646 /// / |
647 ///[CALLSEQ_START] |
648 /// ^ |
649 /// | |
650 /// [LOAD/C2Reg] |
651 /// | |
652 /// \ /
653 /// \ /
654 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000655 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000656 SDValue Chain = N->getOperand(0);
657 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000658 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000659 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000660 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000661 ++NumLoadMoved;
662 continue;
663 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000664
Chris Lattner8d637042010-03-02 23:12:51 +0000665 // Lower fpround and fpextend nodes that target the FP stack to be store and
666 // load to the stack. This is a gross hack. We would like to simply mark
667 // these as being illegal, but when we do that, legalize produces these when
668 // it expands calls, then expands these in the same legalize pass. We would
669 // like dag combine to be able to hack on these between the call expansion
670 // and the node legalization. As such this pass basically does "really
671 // late" legalization of these inline with the X86 isel pass.
672 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000673 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
674 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000675
Craig Topper83e042a2013-08-15 05:57:07 +0000676 MVT SrcVT = N->getOperand(0).getSimpleValueType();
677 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000678
679 // If any of the sources are vectors, no fp stack involved.
680 if (SrcVT.isVector() || DstVT.isVector())
681 continue;
682
683 // If the source and destination are SSE registers, then this is a legal
684 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000685 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000686 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000687 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
688 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000689 if (SrcIsSSE && DstIsSSE)
690 continue;
691
Chris Lattnerd587e582008-03-09 07:05:32 +0000692 if (!SrcIsSSE && !DstIsSSE) {
693 // If this is an FPStack extension, it is a noop.
694 if (N->getOpcode() == ISD::FP_EXTEND)
695 continue;
696 // If this is a value-preserving FPStack truncation, it is a noop.
697 if (N->getConstantOperandVal(1))
698 continue;
699 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000700
Chris Lattnera91f77e2008-01-24 08:07:48 +0000701 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
702 // FPStack has extload and truncstore. SSE can fold direct loads into other
703 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000704 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000705 if (N->getOpcode() == ISD::FP_ROUND)
706 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
707 else
708 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000709
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000710 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000711 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000712
Chris Lattnera91f77e2008-01-24 08:07:48 +0000713 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000714 SDValue Store =
715 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
716 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000717 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000718 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000719
720 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
721 // extload we created. This will cause general havok on the dag because
722 // anything below the conversion could be folded into other existing nodes.
723 // To avoid invalidating 'I', back it up to the convert node.
724 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000725 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000726
Chris Lattnera91f77e2008-01-24 08:07:48 +0000727 // Now that we did that, the node is dead. Increment the iterator to the
728 // next node to process, then delete N.
729 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000730 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000731 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000732}
733
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000734
Sanjay Patelb5723d02015-10-13 15:12:27 +0000735/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000736void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000737 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000738 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000739 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000740
741 TargetLowering::CallLoweringInfo CLI(*CurDAG);
742 CLI.setChain(CurDAG->getRoot())
743 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000744 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000745 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000746 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
747 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
748 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000749 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000750}
751
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000752void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000753 // If this is main, emit special code for main.
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000754 if (const Function *Fn = MF->getFunction())
755 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
Sanjay Patel85030aa2015-10-13 16:23:00 +0000756 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000757}
758
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000759static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000760 // On 64-bit platforms, we can run into an issue where a frame index
761 // includes a displacement that, when added to the explicit displacement,
762 // will overflow the displacement field. Assuming that the frame index
763 // displacement fits into a 31-bit integer (which is only slightly more
764 // aggressive than the current fundamental assumption that it fits into
765 // a 32-bit integer), a 31-bit disp should always be safe.
766 return isInt<31>(Val);
767}
768
Sanjay Patel85030aa2015-10-13 16:23:00 +0000769bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000770 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000771 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000772 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000773 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000774 int64_t Val = AM.Disp + Offset;
775 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000776 if (Subtarget->is64Bit()) {
777 if (!X86::isOffsetSuitableForCodeModel(Val, M,
778 AM.hasSymbolicDisplacement()))
779 return true;
780 // In addition to the checks required for a register base, check that
781 // we do not try to use an unsafe Disp with a frame index.
782 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
783 !isDispSafeForFrameIndex(Val))
784 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000785 }
Eli Friedman344ec792011-07-13 21:29:53 +0000786 AM.Disp = Val;
787 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000788
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000789}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000790
Sanjay Patel85030aa2015-10-13 16:23:00 +0000791bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000792 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000793
Chris Lattner8a236b62010-09-22 04:39:11 +0000794 // load gs:0 -> GS segment register.
795 // load fs:0 -> FS segment register.
796 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000797 // This optimization is valid because the GNU TLS model defines that
798 // gs:0 (or fs:0 on X86-64) contains its own address.
799 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000801 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000802 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
803 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000804 switch (N->getPointerInfo().getAddrSpace()) {
805 case 256:
806 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
807 return false;
808 case 257:
809 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
810 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000811 // Address space 258 is not handled here, because it is not used to
812 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000813 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000814
Rafael Espindola3b2df102009-04-08 21:14:34 +0000815 return true;
816}
817
Sanjay Patelb5723d02015-10-13 15:12:27 +0000818/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
819/// mode. These wrap things that will resolve down into a symbol reference.
820/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000821bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000822 // If the addressing mode already has a symbol as the displacement, we can
823 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000824 if (AM.hasSymbolicDisplacement())
825 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000826
827 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000828 CodeModel::Model M = TM.getCodeModel();
829
Chris Lattnerfea81da2009-06-27 04:16:01 +0000830 // Handle X86-64 rip-relative addresses. We check this before checking direct
831 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000832 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000833 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
834 // they cannot be folded into immediate fields.
835 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000836 (M == CodeModel::Small || M == CodeModel::Kernel)) {
837 // Base and index reg must be 0 in order to use %rip as base.
838 if (AM.hasBaseOrIndexReg())
839 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000840 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000841 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000842 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000843 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000844 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000845 AM = Backup;
846 return true;
847 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000848 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000849 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000850 AM.CP = CP->getConstVal();
851 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000852 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000853 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000854 AM = Backup;
855 return true;
856 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000857 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
858 AM.ES = S->getSymbol();
859 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000860 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
861 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000862 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000863 AM.JT = J->getIndex();
864 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000865 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
866 X86ISelAddressMode Backup = AM;
867 AM.BlockAddr = BA->getBlockAddress();
868 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000869 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000870 AM = Backup;
871 return true;
872 }
873 } else
874 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000875
Chris Lattnerfea81da2009-06-27 04:16:01 +0000876 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000877 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000878 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000879 }
880
881 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000882 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
883 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000884 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000885 M == CodeModel::Small || M == CodeModel::Kernel) {
886 assert(N.getOpcode() != X86ISD::WrapperRIP &&
887 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000888 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
889 AM.GV = G->getGlobal();
890 AM.Disp += G->getOffset();
891 AM.SymbolFlags = G->getTargetFlags();
892 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
893 AM.CP = CP->getConstVal();
894 AM.Align = CP->getAlignment();
895 AM.Disp += CP->getOffset();
896 AM.SymbolFlags = CP->getTargetFlags();
897 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
898 AM.ES = S->getSymbol();
899 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000900 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
901 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000902 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000903 AM.JT = J->getIndex();
904 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000905 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
906 AM.BlockAddr = BA->getBlockAddress();
907 AM.Disp += BA->getOffset();
908 AM.SymbolFlags = BA->getTargetFlags();
909 } else
910 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000911 return false;
912 }
913
914 return true;
915}
916
Sanjay Patelb5723d02015-10-13 15:12:27 +0000917/// Add the specified node to the specified addressing mode, returning true if
918/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000919bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
920 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000921 return true;
922
923 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
924 // a smaller encoding and avoids a scaled-index.
925 if (AM.Scale == 2 &&
926 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000927 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000928 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000929 AM.Scale = 1;
930 }
931
Dan Gohman05046082009-08-20 18:23:44 +0000932 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
933 // because it has a smaller encoding.
934 // TODO: Which other code models can use this?
935 if (TM.getCodeModel() == CodeModel::Small &&
936 Subtarget->is64Bit() &&
937 AM.Scale == 1 &&
938 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000939 AM.Base_Reg.getNode() == nullptr &&
940 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000941 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000942 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000943 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000944
Dan Gohman824ab402009-07-22 23:26:55 +0000945 return false;
946}
947
Sanjay Patelefab8b02015-10-21 18:56:06 +0000948bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
949 unsigned Depth) {
950 // Add an artificial use to this node so that we can keep track of
951 // it if it gets CSE'd with a different node.
952 HandleSDNode Handle(N);
953
954 X86ISelAddressMode Backup = AM;
955 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
956 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
957 return false;
958 AM = Backup;
959
960 // Try again after commuting the operands.
961 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
962 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
963 return false;
964 AM = Backup;
965
966 // If we couldn't fold both operands into the address at the same time,
967 // see if we can just put each operand into a register and fold at least
968 // the add.
969 if (AM.BaseType == X86ISelAddressMode::RegBase &&
970 !AM.Base_Reg.getNode() &&
971 !AM.IndexReg.getNode()) {
972 N = Handle.getValue();
973 AM.Base_Reg = N.getOperand(0);
974 AM.IndexReg = N.getOperand(1);
975 AM.Scale = 1;
976 return false;
977 }
978 N = Handle.getValue();
979 return true;
980}
981
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000982// Insert a node into the DAG at least before the Pos node's position. This
983// will reposition the node as needed, and will assign it a node ID that is <=
984// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
985// IDs! The selection DAG must no longer depend on their uniqueness when this
986// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000987static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000988 if (N.getNode()->getNodeId() == -1 ||
989 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000990 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000991 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
992 }
993}
994
Adam Nemet0c7caf42014-09-16 17:14:10 +0000995// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
996// safe. This allows us to convert the shift and and into an h-register
997// extract and a scaled index. Returns false if the simplification is
998// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000999static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1000 uint64_t Mask,
1001 SDValue Shift, SDValue X,
1002 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +00001003 if (Shift.getOpcode() != ISD::SRL ||
1004 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1005 !Shift.hasOneUse())
1006 return true;
1007
1008 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1009 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1010 Mask != (0xffu << ScaleLog))
1011 return true;
1012
Craig Topper83e042a2013-08-15 05:57:07 +00001013 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001014 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001015 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1016 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +00001017 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1018 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001019 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +00001020 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1021
Chandler Carrutheb21da02012-01-12 01:34:44 +00001022 // Insert the new nodes into the topological ordering. We must do this in
1023 // a valid topological ordering as nothing is going to go back and re-sort
1024 // these nodes. We continually insert before 'N' in sequence as this is
1025 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1026 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001027 insertDAGNode(DAG, N, Eight);
1028 insertDAGNode(DAG, N, Srl);
1029 insertDAGNode(DAG, N, NewMask);
1030 insertDAGNode(DAG, N, And);
1031 insertDAGNode(DAG, N, ShlCount);
1032 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +00001033 DAG.ReplaceAllUsesWith(N, Shl);
1034 AM.IndexReg = And;
1035 AM.Scale = (1 << ScaleLog);
1036 return false;
1037}
1038
Chandler Carruthaa01e662012-01-11 09:35:00 +00001039// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1040// allows us to fold the shift into this addressing mode. Returns false if the
1041// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001042static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1043 uint64_t Mask,
1044 SDValue Shift, SDValue X,
1045 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +00001046 if (Shift.getOpcode() != ISD::SHL ||
1047 !isa<ConstantSDNode>(Shift.getOperand(1)))
1048 return true;
1049
1050 // Not likely to be profitable if either the AND or SHIFT node has more
1051 // than one use (unless all uses are for address computation). Besides,
1052 // isel mechanism requires their node ids to be reused.
1053 if (!N.hasOneUse() || !Shift.hasOneUse())
1054 return true;
1055
1056 // Verify that the shift amount is something we can fold.
1057 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1058 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1059 return true;
1060
Craig Topper83e042a2013-08-15 05:57:07 +00001061 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001062 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001063 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001064 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1065 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1066
Chandler Carrutheb21da02012-01-12 01:34:44 +00001067 // Insert the new nodes into the topological ordering. We must do this in
1068 // a valid topological ordering as nothing is going to go back and re-sort
1069 // these nodes. We continually insert before 'N' in sequence as this is
1070 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1071 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001072 insertDAGNode(DAG, N, NewMask);
1073 insertDAGNode(DAG, N, NewAnd);
1074 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001075 DAG.ReplaceAllUsesWith(N, NewShift);
1076
1077 AM.Scale = 1 << ShiftAmt;
1078 AM.IndexReg = NewAnd;
1079 return false;
1080}
1081
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001082// Implement some heroics to detect shifts of masked values where the mask can
1083// be replaced by extending the shift and undoing that in the addressing mode
1084// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1085// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1086// the addressing mode. This results in code such as:
1087//
1088// int f(short *y, int *lookup_table) {
1089// ...
1090// return *y + lookup_table[*y >> 11];
1091// }
1092//
1093// Turning into:
1094// movzwl (%rdi), %eax
1095// movl %eax, %ecx
1096// shrl $11, %ecx
1097// addl (%rsi,%rcx,4), %eax
1098//
1099// Instead of:
1100// movzwl (%rdi), %eax
1101// movl %eax, %ecx
1102// shrl $9, %ecx
1103// andl $124, %rcx
1104// addl (%rsi,%rcx), %eax
1105//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001106// Note that this function assumes the mask is provided as a mask *after* the
1107// value is shifted. The input chain may or may not match that, but computing
1108// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001109static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1110 uint64_t Mask,
1111 SDValue Shift, SDValue X,
1112 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001113 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1114 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001115 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001116
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001117 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001118 unsigned MaskLZ = countLeadingZeros(Mask);
1119 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001120
1121 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001122 // from the trailing zeros of the mask.
1123 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001124
1125 // There is nothing we can do here unless the mask is removing some bits.
1126 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1127 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1128
1129 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001130 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001131
1132 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001133 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001134 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1135 if (MaskLZ < ScaleDown)
1136 return true;
1137 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001138
1139 // The final check is to ensure that any masked out high bits of X are
1140 // already known to be zero. Otherwise, the mask has a semantic impact
1141 // other than masking out a couple of low bits. Unfortunately, because of
1142 // the mask, zero extensions will be removed from operands in some cases.
1143 // This code works extra hard to look through extensions because we can
1144 // replace them with zero extensions cheaply if necessary.
1145 bool ReplacingAnyExtend = false;
1146 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001147 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1148 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001149 // Assume that we'll replace the any-extend with a zero-extend, and
1150 // narrow the search to the extended value.
1151 X = X.getOperand(0);
1152 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1153 ReplacingAnyExtend = true;
1154 }
Craig Topper83e042a2013-08-15 05:57:07 +00001155 APInt MaskedHighBits =
1156 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001157 KnownBits Known;
1158 DAG.computeKnownBits(X, Known);
1159 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001160
1161 // We've identified a pattern that can be transformed into a single shift
1162 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001163 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001164 if (ReplacingAnyExtend) {
1165 assert(X.getValueType() != VT);
1166 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001167 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001168 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001169 X = NewX;
1170 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001171 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001172 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001173 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001174 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001175 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001176
1177 // Insert the new nodes into the topological ordering. We must do this in
1178 // a valid topological ordering as nothing is going to go back and re-sort
1179 // these nodes. We continually insert before 'N' in sequence as this is
1180 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1181 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001182 insertDAGNode(DAG, N, NewSRLAmt);
1183 insertDAGNode(DAG, N, NewSRL);
1184 insertDAGNode(DAG, N, NewSHLAmt);
1185 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001186 DAG.ReplaceAllUsesWith(N, NewSHL);
1187
1188 AM.Scale = 1 << AMShiftAmt;
1189 AM.IndexReg = NewSRL;
1190 return false;
1191}
Hans Wennborg2a6c9ad2017-10-04 17:54:06 +00001192
Sanjay Patel85030aa2015-10-13 16:23:00 +00001193bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001194 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001195 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001196 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001197 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001198 AM.dump();
1199 });
Hans Wennborg2a6c9ad2017-10-04 17:54:06 +00001200 // Limit recursion.
1201 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001202 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001203
Chris Lattnerfea81da2009-06-27 04:16:01 +00001204 // If this is already a %rip relative address, we can only merge immediates
1205 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001206 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001207 if (AM.isRIPRelative()) {
1208 // FIXME: JumpTable and ExternalSymbol address currently don't like
1209 // displacements. It isn't very important, but this should be fixed for
1210 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001211 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1212 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001213
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001214 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001215 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001216 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001217 return true;
1218 }
1219
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001220 switch (N.getOpcode()) {
1221 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001222 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001223 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001224 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1225 // Use the symbol and don't prefix it.
1226 AM.MCSym = ESNode->getMCSymbol();
1227 return false;
1228 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001229 break;
1230 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001231 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001232 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001233 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001234 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001235 break;
1236 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001237
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001238 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001239 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001240 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001241 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001242 break;
1243
Rafael Espindola3b2df102009-04-08 21:14:34 +00001244 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001245 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001246 return false;
1247 break;
1248
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001249 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001250 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001251 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001252 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001253 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001254 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001255 return false;
1256 }
1257 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001258
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001259 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001260 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001261 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001262
Simon Pilgrim7f032312017-05-12 13:08:45 +00001263 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001264 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001265 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1266 // that the base operand remains free for further matching. If
1267 // the base doesn't end up getting used, a post-processing step
1268 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001269 if (Val == 1 || Val == 2 || Val == 3) {
1270 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001271 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001272
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001273 // Okay, we know that we have a scale by now. However, if the scaled
1274 // value is an add of something and a constant, we can fold the
1275 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001276 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001277 AM.IndexReg = ShVal.getOperand(0);
1278 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001279 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001280 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001281 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001282 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001283
1284 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001285 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001286 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001287 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001288 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001289
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001290 case ISD::SRL: {
1291 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001292 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001293
1294 SDValue And = N.getOperand(0);
1295 if (And.getOpcode() != ISD::AND) break;
1296 SDValue X = And.getOperand(0);
1297
1298 // We only handle up to 64-bit values here as those are what matter for
1299 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001300 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001301
1302 // The mask used for the transform is expected to be post-shift, but we
1303 // found the shift first so just apply the shift to the mask before passing
1304 // it down.
1305 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1306 !isa<ConstantSDNode>(And.getOperand(1)))
1307 break;
1308 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1309
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001310 // Try to fold the mask and shift into the scale, and return false if we
1311 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001312 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001313 return false;
1314 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001315 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001316
Dan Gohmanbf474952007-10-22 20:22:24 +00001317 case ISD::SMUL_LOHI:
1318 case ISD::UMUL_LOHI:
1319 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001320 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001321 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001322 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001323 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001324 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001325 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001326 AM.Base_Reg.getNode() == nullptr &&
1327 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001328 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001329 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1330 CN->getZExtValue() == 9) {
1331 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001332
Simon Pilgrim7f032312017-05-12 13:08:45 +00001333 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001334 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001335
1336 // Okay, we know that we have a scale by now. However, if the scaled
1337 // value is an add of something and a constant, we can fold the
1338 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001339 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001340 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1341 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001342 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001343 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001344 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001345 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001346 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001347 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001348 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001349 }
1350
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001351 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001352 return false;
1353 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001354 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001355 break;
1356
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001357 case ISD::SUB: {
1358 // Given A-B, if A can be completely folded into the address and
1359 // the index field with the index field unused, use -B as the index.
1360 // This is a win if a has multiple parts that can be folded into
1361 // the address. Also, this saves a mov if the base register has
1362 // other uses, since it avoids a two-address sub instruction, however
1363 // it costs an additional mov if the index register has other uses.
1364
Dan Gohman99ba4da2010-06-18 01:24:29 +00001365 // Add an artificial use to this node so that we can keep track of
1366 // it if it gets CSE'd with a different node.
1367 HandleSDNode Handle(N);
1368
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001369 // Test if the LHS of the sub can be folded.
1370 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001371 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001372 AM = Backup;
1373 break;
1374 }
1375 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001376 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001377 AM = Backup;
1378 break;
1379 }
Evan Cheng68333f52010-03-17 23:58:35 +00001380
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001381 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001382 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001383 // If the RHS involves a register with multiple uses, this
1384 // transformation incurs an extra mov, due to the neg instruction
1385 // clobbering its operand.
1386 if (!RHS.getNode()->hasOneUse() ||
1387 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1388 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1389 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1390 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001391 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001392 ++Cost;
1393 // If the base is a register with multiple uses, this
1394 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001395 // FIXME: Don't rely on DELETED_NODEs.
1396 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1397 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001398 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001399 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1400 --Cost;
1401 // If the folded LHS was interesting, this transformation saves
1402 // address arithmetic.
1403 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1404 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1405 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1406 --Cost;
1407 // If it doesn't look like it may be an overall win, don't do it.
1408 if (Cost >= 0) {
1409 AM = Backup;
1410 break;
1411 }
1412
1413 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001414 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001415 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1416 AM.IndexReg = Neg;
1417 AM.Scale = 1;
1418
1419 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001420 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1421 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001422 return false;
1423 }
1424
Sanjay Patelefab8b02015-10-21 18:56:06 +00001425 case ISD::ADD:
1426 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001427 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001428 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001429
Sanjay Patel533c10c2015-11-09 23:31:38 +00001430 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001431 // We want to look through a transform in InstCombine and DAGCombiner that
1432 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001433 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001434 // An 'lea' can then be used to match the shift (multiply) and add:
1435 // and $1, %esi
1436 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001437 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1438 !matchAdd(N, AM, Depth))
1439 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001440 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001441
Evan Cheng827d30d2007-12-13 00:43:27 +00001442 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001443 // Perform some heroic transforms on an and of a constant-count shift
1444 // with a constant to enable use of the scaled offset field.
1445
Evan Cheng827d30d2007-12-13 00:43:27 +00001446 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001447 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001448
Chandler Carruthaa01e662012-01-11 09:35:00 +00001449 SDValue Shift = N.getOperand(0);
1450 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001451 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001452
1453 // We only handle up to 64-bit values here as those are what matter for
1454 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001455 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001456
Chandler Carruthb0049f42012-01-11 09:35:04 +00001457 if (!isa<ConstantSDNode>(N.getOperand(1)))
1458 break;
1459 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001460
Chandler Carruth51d30762012-01-11 08:48:20 +00001461 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001462 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001463 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001464
Chandler Carruth51d30762012-01-11 08:48:20 +00001465 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001466 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001467 return false;
1468
Chandler Carruthaa01e662012-01-11 09:35:00 +00001469 // Try to swap the mask and shift to place shifts which can be done as
1470 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001471 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001472 return false;
1473 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001474 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001475 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001476
Sanjay Patel85030aa2015-10-13 16:23:00 +00001477 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001478}
1479
Sanjay Patelb5723d02015-10-13 15:12:27 +00001480/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001481/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001482bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001483 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001484 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001485 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001486 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001487 AM.IndexReg = N;
1488 AM.Scale = 1;
1489 return false;
1490 }
1491
1492 // Otherwise, we cannot select it.
1493 return true;
1494 }
1495
1496 // Default, generate it as a register.
1497 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001498 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001499 return false;
1500}
1501
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001502template <class GatherScatterSDNode>
1503bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1504 GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1505 SDValue &Index, SDValue &Disp, SDValue &Segment) {
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001506 X86ISelAddressMode AM;
1507 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001508 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001509 if (AddrSpace == 256)
1510 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1511 if (AddrSpace == 257)
1512 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001513 if (AddrSpace == 258)
1514 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001515
1516 SDLoc DL(N);
1517 Base = Mgs->getBasePtr();
1518 Index = Mgs->getIndex();
Sanjay Patel5f6bb6c2016-09-14 15:43:44 +00001519 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001520 Scale = getI8Imm(ScalarSize/8, DL);
1521
1522 // If Base is 0, the whole address is in index and the Scale is 1
Daniel Jasper232778a2015-04-30 09:01:21 +00001523 if (isa<ConstantSDNode>(Base)) {
Mehdi Amini42152362015-10-21 06:11:01 +00001524 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
Daniel Jasper232778a2015-04-30 09:01:21 +00001525 "Unexpected base in gather/scatter");
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001526 Scale = getI8Imm(1, DL);
1527 Base = CurDAG->getRegister(0, MVT::i32);
1528 }
1529 if (AM.Segment.getNode())
1530 Segment = AM.Segment;
1531 else
1532 Segment = CurDAG->getRegister(0, MVT::i32);
1533 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1534 return true;
1535}
1536
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001537bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1538 SDValue &Scale, SDValue &Index,
1539 SDValue &Disp, SDValue &Segment) {
1540 if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1541 return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1542 Mgs, N, Base, Scale, Index, Disp, Segment);
1543 if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1544 return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1545 X86Gather, N, Base, Scale, Index, Disp, Segment);
1546 return false;
1547}
1548
Sanjay Patelb5723d02015-10-13 15:12:27 +00001549/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001550/// It returns the operands which make up the maximal addressing mode it can
1551/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001552///
1553/// Parent is the parent node of the addr operand that is being matched. It
1554/// is always a load, store, atomic node, or null. It is only null when
1555/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001556bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001557 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001558 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001559 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001560
Chris Lattner8a236b62010-09-22 04:39:11 +00001561 if (Parent &&
1562 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1563 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001564 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001565 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001566 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1567 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1568 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001569 unsigned AddrSpace =
1570 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001571 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001572 if (AddrSpace == 256)
1573 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1574 if (AddrSpace == 257)
1575 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001576 if (AddrSpace == 258)
1577 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001578 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001579
Sanjay Patel85030aa2015-10-13 16:23:00 +00001580 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001581 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001582
Craig Topper83e042a2013-08-15 05:57:07 +00001583 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001584 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001585 if (!AM.Base_Reg.getNode())
1586 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001587 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001588
Gabor Greiff304a7a2008-08-28 21:40:38 +00001589 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001590 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001591
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001592 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001593 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001594}
1595
Craig Topper8078dd22017-08-21 16:04:04 +00001596// We can only fold a load if all nodes between it and the root node have a
1597// single use. If there are additional uses, we could end up duplicating the
1598// load.
1599static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1600 SDNode *User = *N->use_begin();
1601 while (User != Root) {
1602 if (!User->hasOneUse())
1603 return false;
1604 User = *User->use_begin();
1605 }
1606
1607 return true;
1608}
1609
Sanjay Patelb5723d02015-10-13 15:12:27 +00001610/// Match a scalar SSE load. In particular, we want to match a load whose top
1611/// elements are either undef or zeros. The load flavor is derived from the
1612/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001613///
1614/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001615/// PatternChainNode: this is the matched node that has a chain input and
1616/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001617bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001618 SDValue N, SDValue &Base,
1619 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001620 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001621 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001622 // We can allow a full vector load here since narrowing a load is ok.
1623 if (ISD::isNON_EXTLoad(N.getNode())) {
1624 PatternNodeWithChain = N;
1625 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001626 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1627 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001628 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1629 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1630 Segment);
1631 }
1632 }
1633
1634 // We can also match the special zero extended load opcode.
1635 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1636 PatternNodeWithChain = N;
1637 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001638 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1639 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001640 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1641 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1642 Segment);
1643 }
1644 }
1645
Craig Topper991d1ca2016-11-26 17:29:25 +00001646 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1647 // once. Otherwise the load might get duplicated and the chain output of the
1648 // duplicate load will not be observed by all dependencies.
1649 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001650 PatternNodeWithChain = N.getOperand(0);
1651 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001652 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001653 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1654 hasSingleUsesFromRoot(Root, N.getNode())) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001655 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001656 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1657 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001658 }
1659 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001660
1661 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001662 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001663 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001664 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001665 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001666 N.getOperand(0).getNode()->hasOneUse()) {
1667 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1668 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001669 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001670 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1671 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Toppere266e122016-11-26 18:43:24 +00001672 // Okay, this is a zero extending load. Fold it.
1673 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1674 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1675 Segment);
1676 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001677 }
Craig Toppere266e122016-11-26 18:43:24 +00001678
Chris Lattner398195e2006-10-07 21:55:32 +00001679 return false;
1680}
1681
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001682
Sanjay Patel85030aa2015-10-13 16:23:00 +00001683bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001684 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1685 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001686 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001687 return false;
1688
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001689 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001690 return true;
1691 }
1692
1693 // In static codegen with small code model, we can get the address of a label
1694 // into a register with 'movl'. TableGen has already made sure we're looking
1695 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001696 assert(N->getOpcode() == X86ISD::Wrapper &&
1697 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001698 N = N.getOperand(0);
1699
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001700 // At least GNU as does not accept 'movl' for TPOFF relocations.
1701 // FIXME: We could use 'movl' when we know we are targeting MC.
1702 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001703 return false;
1704
1705 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001706 if (N->getOpcode() != ISD::TargetGlobalAddress)
1707 return TM.getCodeModel() == CodeModel::Small;
1708
1709 Optional<ConstantRange> CR =
1710 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1711 if (!CR)
1712 return TM.getCodeModel() == CodeModel::Small;
1713
1714 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001715}
1716
Sanjay Patel85030aa2015-10-13 16:23:00 +00001717bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001718 SDValue &Scale, SDValue &Index,
1719 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001720 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1721 SDLoc DL(N);
Hans Wennborg2a6c9ad2017-10-04 17:54:06 +00001722
Sanjay Patel85030aa2015-10-13 16:23:00 +00001723 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001724 return false;
1725
Tim Northover6833e3f2013-06-10 20:43:49 +00001726 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1727 if (RN && RN->getReg() == 0)
1728 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001729 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001730 // Base could already be %rip, particularly in the x32 ABI.
1731 Base = SDValue(CurDAG->getMachineNode(
1732 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001733 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001734 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001735 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001736 0);
1737 }
1738
1739 RN = dyn_cast<RegisterSDNode>(Index);
1740 if (RN && RN->getReg() == 0)
1741 Index = CurDAG->getRegister(0, MVT::i64);
1742 else {
1743 assert(Index.getValueType() == MVT::i32 &&
1744 "Expect to be extending 32-bit registers for use in LEA");
1745 Index = SDValue(CurDAG->getMachineNode(
1746 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001747 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001748 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001749 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1750 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001751 0);
1752 }
1753
1754 return true;
1755}
1756
Sanjay Patelb5723d02015-10-13 15:12:27 +00001757/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001758/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001759bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001760 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001761 SDValue &Index, SDValue &Disp,
1762 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001763 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001764
Justin Bogner32ad24d2016-04-12 21:34:24 +00001765 // Save the DL and VT before calling matchAddress, it can invalidate N.
1766 SDLoc DL(N);
1767 MVT VT = N.getSimpleValueType();
1768
Rafael Espindolabb834f02009-04-10 10:09:34 +00001769 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1770 // segments.
1771 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001772 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001773 AM.Segment = T;
Hans Wennborg2a6c9ad2017-10-04 17:54:06 +00001774 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001775 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001776 assert (T == AM.Segment);
1777 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001778
Evan Cheng77d86ff2006-02-25 10:09:08 +00001779 unsigned Complexity = 0;
1780 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001781 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001782 Complexity = 1;
1783 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001784 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001785 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1786 Complexity = 4;
1787
Gabor Greiff304a7a2008-08-28 21:40:38 +00001788 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001789 Complexity++;
1790 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001791 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001792
Chris Lattner3e1d9172007-03-20 06:08:29 +00001793 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1794 // a simple shift.
1795 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001796 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001797
1798 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001799 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001800 // optimal (especially for code size consideration). LEA is nice because of
1801 // its three-address nature. Tweak the cost function again when we can run
1802 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001803 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001804 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001805 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001806 Complexity = 4;
1807 else
1808 Complexity += 2;
1809 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001810
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001811 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001812 Complexity++;
1813
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001814 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001815 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001816 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001817
Justin Bogner32ad24d2016-04-12 21:34:24 +00001818 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001819 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001820}
1821
Sanjay Patelb5723d02015-10-13 15:12:27 +00001822/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001823bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001824 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001825 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001826 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1827 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001828
Chris Lattner7d2b0492009-06-20 20:38:48 +00001829 X86ISelAddressMode AM;
1830 AM.GV = GA->getGlobal();
1831 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001832 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001833 AM.SymbolFlags = GA->getTargetFlags();
1834
Owen Anderson9f944592009-08-11 20:47:22 +00001835 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001836 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001837 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001838 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001839 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001840 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001841
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001842 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001843 return true;
1844}
1845
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001846bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1847 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1848 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1849 N.getValueType());
1850 return true;
1851 }
1852
Peter Collingbourne235c2752016-12-08 19:01:00 +00001853 // Keep track of the original value type and whether this value was
1854 // truncated. If we see a truncation from pointer type to VT that truncates
1855 // bits that are known to be zero, we can use a narrow reference.
1856 EVT VT = N.getValueType();
1857 bool WasTruncated = false;
1858 if (N.getOpcode() == ISD::TRUNCATE) {
1859 WasTruncated = true;
1860 N = N.getOperand(0);
1861 }
1862
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001863 if (N.getOpcode() != X86ISD::Wrapper)
1864 return false;
1865
Peter Collingbourne235c2752016-12-08 19:01:00 +00001866 // We can only use non-GlobalValues as immediates if they were not truncated,
1867 // as we do not have any range information. If we have a GlobalValue and the
1868 // address was not truncated, we can select it as an operand directly.
1869 unsigned Opc = N.getOperand(0)->getOpcode();
1870 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1871 Op = N.getOperand(0);
1872 // We can only select the operand directly if we didn't have to look past a
1873 // truncate.
1874 return !WasTruncated;
1875 }
1876
1877 // Check that the global's range fits into VT.
1878 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1879 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1880 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1881 return false;
1882
1883 // Okay, we can use a narrow reference.
1884 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1885 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001886 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001887}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001888
Sanjay Patel85030aa2015-10-13 16:23:00 +00001889bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001890 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001891 SDValue &Index, SDValue &Disp,
1892 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001893 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1894 !IsProfitableToFold(N, P, P) ||
Dan Gohman21cea8a2010-04-17 15:26:15 +00001895 !IsLegalToFold(N, P, P, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001896 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001897
Sanjay Patel85030aa2015-10-13 16:23:00 +00001898 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001899 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001900}
1901
Sanjay Patelb5723d02015-10-13 15:12:27 +00001902/// Return an SDNode that returns the value of the global base register.
1903/// Output instructions required to initialize the global base register,
1904/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00001905SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001906 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00001907 auto &DL = MF->getDataLayout();
1908 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001909}
1910
Peter Collingbourneef089bd2017-02-09 22:02:28 +00001911bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1912 if (N->getOpcode() == ISD::TRUNCATE)
1913 N = N->getOperand(0).getNode();
1914 if (N->getOpcode() != X86ISD::Wrapper)
1915 return false;
1916
1917 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1918 if (!GA)
1919 return false;
1920
1921 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1922 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1923 CR->getSignedMax().slt(1ull << Width);
1924}
1925
Sanjay Patelb5723d02015-10-13 15:12:27 +00001926/// Test whether the given X86ISD::CMP node has any uses which require the SF
1927/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001928static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001929 // Examine each user of the node.
1930 for (SDNode::use_iterator UI = N->use_begin(),
1931 UE = N->use_end(); UI != UE; ++UI) {
1932 // Only examine CopyToReg uses.
1933 if (UI->getOpcode() != ISD::CopyToReg)
1934 return false;
1935 // Only examine CopyToReg uses that copy to EFLAGS.
1936 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1937 X86::EFLAGS)
1938 return false;
1939 // Examine each user of the CopyToReg use.
1940 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1941 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1942 // Only examine the Flag result.
1943 if (FlagUI.getUse().getResNo() != 1) continue;
1944 // Anything unusual: assume conservatively.
1945 if (!FlagUI->isMachineOpcode()) return false;
1946 // Examine the opcode of the user.
1947 switch (FlagUI->getMachineOpcode()) {
1948 // These comparisons don't treat the most significant bit specially.
1949 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1950 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1951 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1952 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001953 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1954 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001955 case X86::CMOVA16rr: case X86::CMOVA16rm:
1956 case X86::CMOVA32rr: case X86::CMOVA32rm:
1957 case X86::CMOVA64rr: case X86::CMOVA64rm:
1958 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1959 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1960 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1961 case X86::CMOVB16rr: case X86::CMOVB16rm:
1962 case X86::CMOVB32rr: case X86::CMOVB32rm:
1963 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001964 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1965 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1966 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001967 case X86::CMOVE16rr: case X86::CMOVE16rm:
1968 case X86::CMOVE32rr: case X86::CMOVE32rm:
1969 case X86::CMOVE64rr: case X86::CMOVE64rm:
1970 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1971 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1972 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1973 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1974 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1975 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1976 case X86::CMOVP16rr: case X86::CMOVP16rm:
1977 case X86::CMOVP32rr: case X86::CMOVP32rm:
1978 case X86::CMOVP64rr: case X86::CMOVP64rm:
1979 continue;
1980 // Anything else: assume conservatively.
1981 default: return false;
1982 }
1983 }
1984 }
1985 return true;
1986}
1987
Chandler Carruth52a31bf2017-09-07 23:54:24 +00001988/// Test whether the given node which sets flags has any uses which require the
1989/// CF flag to be accurate.
1990static bool hasNoCarryFlagUses(SDNode *N) {
1991 // Examine each user of the node.
1992 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
1993 ++UI) {
1994 // Only check things that use the flags.
1995 if (UI.getUse().getResNo() != 1)
1996 continue;
1997 // Only examine CopyToReg uses.
1998 if (UI->getOpcode() != ISD::CopyToReg)
1999 return false;
2000 // Only examine CopyToReg uses that copy to EFLAGS.
2001 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2002 return false;
2003 // Examine each user of the CopyToReg use.
2004 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2005 FlagUI != FlagUE; ++FlagUI) {
2006 // Only examine the Flag result.
2007 if (FlagUI.getUse().getResNo() != 1)
2008 continue;
2009 // Anything unusual: assume conservatively.
2010 if (!FlagUI->isMachineOpcode())
2011 return false;
2012 // Examine the opcode of the user.
2013 switch (FlagUI->getMachineOpcode()) {
2014 // Comparisons which don't examine the CF flag.
2015 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
2016 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
2017 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
2018 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
2019 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
2020 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
2021 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
2022 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
2023 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
2024 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
2025 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
2026 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
2027 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
2028 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
2029 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
2030 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
2031 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
2032 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
2033 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
2034 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
2035 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
2036 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
2037 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
2038 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
2039 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
2040 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
2041 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
2042 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
2043 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
2044 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
2045 continue;
2046 // Anything else: assume conservatively.
2047 default:
2048 return false;
2049 }
2050 }
2051 }
2052 return true;
2053}
2054
Sanjay Patelb5723d02015-10-13 15:12:27 +00002055/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002056/// the {load; op; store} to modify transformation.
2057static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2058 SDValue StoredVal, SelectionDAG *CurDAG,
2059 LoadSDNode *&LoadNode,
2060 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002061 // is the stored value result 0 of the load?
2062 if (StoredVal.getResNo() != 0) return false;
2063
2064 // are there other uses of the loaded value than the inc or dec?
2065 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2066
Joel Jones68d59e82012-03-29 05:45:48 +00002067 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002068 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002069 return false;
2070
Evan Cheng3e869f02012-04-12 19:14:21 +00002071 SDValue Load = StoredVal->getOperand(0);
2072 // Is the stored value a non-extending and non-indexed load?
2073 if (!ISD::isNormalLoad(Load.getNode())) return false;
2074
2075 // Return LoadNode by reference.
2076 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002077
2078 // Is store the only read of the loaded value?
2079 if (!Load.hasOneUse())
2080 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002081
Evan Cheng3e869f02012-04-12 19:14:21 +00002082 // Is the address of the store the same as the load?
2083 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2084 LoadNode->getOffset() != StoreNode->getOffset())
2085 return false;
2086
2087 // Check if the chain is produced by the load or is a TokenFactor with
2088 // the load output chain as an operand. Return InputChain by reference.
2089 SDValue Chain = StoreNode->getChain();
2090
2091 bool ChainCheck = false;
2092 if (Chain == Load.getValue(1)) {
2093 ChainCheck = true;
2094 InputChain = LoadNode->getChain();
2095 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2096 SmallVector<SDValue, 4> ChainOps;
2097 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2098 SDValue Op = Chain.getOperand(i);
2099 if (Op == Load.getValue(1)) {
2100 ChainCheck = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002101 // Drop Load, but keep its chain. No cycle check necessary.
2102 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002103 continue;
2104 }
Evan Cheng58a95f02012-05-16 01:54:27 +00002105
2106 // Make sure using Op as part of the chain would not cause a cycle here.
2107 // In theory, we could check whether the chain node is a predecessor of
2108 // the load. But that can be very expensive. Instead visit the uses and
2109 // make sure they all have smaller node id than the load.
2110 int LoadId = LoadNode->getNodeId();
2111 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2112 UE = UI->use_end(); UI != UE; ++UI) {
2113 if (UI.getUse().getResNo() != 0)
2114 continue;
2115 if (UI->getNodeId() > LoadId)
2116 return false;
2117 }
2118
Evan Cheng3e869f02012-04-12 19:14:21 +00002119 ChainOps.push_back(Op);
2120 }
2121
2122 if (ChainCheck)
2123 // Make a new TokenFactor with all the other input chains except
2124 // for the load.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002125 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
Craig Topper48d114b2014-04-26 18:35:24 +00002126 MVT::Other, ChainOps);
Evan Cheng3e869f02012-04-12 19:14:21 +00002127 }
2128 if (!ChainCheck)
Joel Jones68d59e82012-03-29 05:45:48 +00002129 return false;
2130
2131 return true;
2132}
2133
Chandler Carruth4b611a82017-08-25 22:50:52 +00002134// Change a chain of {load; op; store} of the same value into a simple op
2135// through memory of that value, if the uses of the modified value and its
2136// address are suitable.
2137//
2138// The tablegen pattern memory operand pattern is currently not able to match
2139// the case where the EFLAGS on the original operation are used.
2140//
2141// To move this to tablegen, we'll need to improve tablegen to allow flags to
2142// be transferred from a node in the pattern to the result node, probably with
2143// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002144// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2145// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2146// (implicit EFLAGS)]>;
2147// but maybe need something like this
2148// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2149// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2150// (transferrable EFLAGS)]>;
2151//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002152// Until then, we manually fold these and instruction select the operation
2153// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002154bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2155 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2156 SDValue StoredVal = StoreNode->getOperand(1);
2157 unsigned Opc = StoredVal->getOpcode();
2158
Chandler Carruth4b611a82017-08-25 22:50:52 +00002159 // Before we try to select anything, make sure this is memory operand size
2160 // and opcode we can handle. Note that this must match the code below that
2161 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002162 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002163 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2164 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002165 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002166 switch (Opc) {
2167 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002168 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002169 case X86ISD::INC:
2170 case X86ISD::DEC:
2171 case X86ISD::ADD:
2172 case X86ISD::SUB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002173 case X86ISD::AND:
2174 case X86ISD::OR:
2175 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002176 break;
2177 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002178
Chandler Carruth03258f22017-08-25 02:04:03 +00002179 LoadSDNode *LoadNode = nullptr;
2180 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002181 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2182 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002183 return false;
2184
2185 SDValue Base, Scale, Index, Disp, Segment;
2186 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2187 Segment))
2188 return false;
2189
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002190 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002191 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002192 switch (MemVT.getSimpleVT().SimpleTy) {
2193 case MVT::i64:
2194 return Opc64;
2195 case MVT::i32:
2196 return Opc32;
2197 case MVT::i16:
2198 return Opc16;
2199 case MVT::i8:
2200 return Opc8;
2201 default:
2202 llvm_unreachable("Invalid size!");
2203 }
2204 };
2205
2206 MachineSDNode *Result;
2207 switch (Opc) {
2208 case X86ISD::INC:
2209 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002210 unsigned NewOpc =
2211 Opc == X86ISD::INC
2212 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2213 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002214 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2215 Result =
2216 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2217 break;
2218 }
2219 case X86ISD::ADD:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002220 case X86ISD::SUB:
2221 case X86ISD::AND:
2222 case X86ISD::OR:
2223 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002224 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2225 switch (Opc) {
2226 case X86ISD::ADD:
2227 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2228 X86::ADD8mr);
2229 case X86ISD::SUB:
2230 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2231 X86::SUB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002232 case X86ISD::AND:
2233 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2234 X86::AND8mr);
2235 case X86ISD::OR:
2236 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2237 case X86ISD::XOR:
2238 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2239 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002240 default:
2241 llvm_unreachable("Invalid opcode!");
2242 }
2243 };
2244 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2245 switch (Opc) {
2246 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002247 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002248 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002249 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002250 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002251 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002252 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002253 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002254 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002255 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002256 default:
2257 llvm_unreachable("Invalid opcode!");
2258 }
2259 };
2260 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2261 switch (Opc) {
2262 case X86ISD::ADD:
2263 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2264 X86::ADD8mi);
2265 case X86ISD::SUB:
2266 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2267 X86::SUB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002268 case X86ISD::AND:
2269 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2270 X86::AND8mi);
2271 case X86ISD::OR:
2272 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2273 X86::OR8mi);
2274 case X86ISD::XOR:
2275 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2276 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002277 default:
2278 llvm_unreachable("Invalid opcode!");
2279 }
2280 };
2281
2282 unsigned NewOpc = SelectRegOpcode(Opc);
2283 SDValue Operand = StoredVal->getOperand(1);
2284
2285 // See if the operand is a constant that we can fold into an immediate
2286 // operand.
2287 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2288 auto OperandV = OperandC->getAPIntValue();
2289
2290 // Check if we can shrink the operand enough to fit in an immediate (or
2291 // fit into a smaller immediate) by negating it and switching the
2292 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002293 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2294 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002295 (-OperandV).getMinSignedBits() <= 8) ||
2296 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2297 (-OperandV).getMinSignedBits() <= 32)) &&
2298 hasNoCarryFlagUses(StoredVal.getNode())) {
2299 OperandV = -OperandV;
2300 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2301 }
2302
2303 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2304 // the larger immediate operand.
2305 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2306 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2307 NewOpc = SelectImm8Opcode(Opc);
2308 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2309 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2310 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2311 NewOpc = SelectImmOpcode(Opc);
2312 }
2313 }
2314
2315 const SDValue Ops[] = {Base, Scale, Index, Disp,
2316 Segment, Operand, InputChain};
Chandler Carruth4b611a82017-08-25 22:50:52 +00002317 Result =
2318 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2319 break;
2320 }
2321 default:
2322 llvm_unreachable("Invalid opcode!");
2323 }
2324
Chandler Carruth03258f22017-08-25 02:04:03 +00002325 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2326 MemOp[0] = StoreNode->getMemOperand();
2327 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002328 Result->setMemRefs(MemOp, MemOp + 2);
2329
2330 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2331 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2332 CurDAG->RemoveDeadNode(Node);
2333 return true;
2334}
2335
Craig Topper958106d2017-09-12 17:40:25 +00002336// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2337bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2338 MVT NVT = Node->getSimpleValueType(0);
2339 SDLoc dl(Node);
2340
2341 SDValue N0 = Node->getOperand(0);
2342 SDValue N1 = Node->getOperand(1);
2343
2344 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2345 return false;
2346
2347 // Must have a shift right.
2348 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2349 return false;
2350
2351 // Shift can't have additional users.
2352 if (!N0->hasOneUse())
2353 return false;
2354
2355 // Only supported for 32 and 64 bits.
2356 if (NVT != MVT::i32 && NVT != MVT::i64)
2357 return false;
2358
2359 // Shift amount and RHS of and must be constant.
2360 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2361 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2362 if (!MaskCst || !ShiftCst)
2363 return false;
2364
2365 // And RHS must be a mask.
2366 uint64_t Mask = MaskCst->getZExtValue();
2367 if (!isMask_64(Mask))
2368 return false;
2369
2370 uint64_t Shift = ShiftCst->getZExtValue();
2371 uint64_t MaskSize = countPopulation(Mask);
2372
2373 // Don't interfere with something that can be handled by extracting AH.
2374 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2375 if (Shift == 8 && MaskSize == 8)
2376 return false;
2377
2378 // Make sure we are only using bits that were in the original value, not
2379 // shifted in.
2380 if (Shift + MaskSize > NVT.getSizeInBits())
2381 return false;
2382
2383 SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
2384 unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
2385 unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
2386
2387 // BMI requires the immediate to placed in a register.
2388 if (!Subtarget->hasTBM()) {
2389 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
2390 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
Craig Topper2b6bfda2017-09-13 07:53:21 +00002391 New = SDValue(CurDAG->getMachineNode(X86::MOV32ri, dl, NVT, New), 0);
2392 if (NVT == MVT::i64) {
2393 New =
2394 SDValue(CurDAG->getMachineNode(
2395 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2396 CurDAG->getTargetConstant(0, dl, MVT::i64), New,
2397 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
2398 0);
2399 }
Craig Topper958106d2017-09-12 17:40:25 +00002400 }
2401
2402 MachineSDNode *NewNode;
2403 SDValue Input = N0->getOperand(0);
2404 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2405 if (tryFoldLoad(Node, Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2406 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
2407 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
2408 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2409 // Update the chain.
2410 ReplaceUses(N1.getValue(1), SDValue(NewNode, 1));
2411 // Record the mem-refs
2412 LoadSDNode *LoadNode = cast<LoadSDNode>(Input);
2413 if (LoadNode) {
2414 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2415 MemOp[0] = LoadNode->getMemOperand();
2416 NewNode->setMemRefs(MemOp, MemOp + 1);
2417 }
2418 } else {
2419 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
2420 }
2421
2422 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
2423 CurDAG->RemoveDeadNode(Node);
2424 return true;
2425}
2426
Justin Bogner593741d2016-05-10 23:55:37 +00002427void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002428 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002429 unsigned Opc, MOpc;
2430 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002431 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002432
Chris Lattnerf98f1242010-03-02 06:34:30 +00002433 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
Evan Chengd49cc362006-02-10 22:24:32 +00002434
Dan Gohman17059682008-07-17 19:10:17 +00002435 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002436 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002437 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002438 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002439 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002440
Evan Cheng10d27902006-01-06 20:36:21 +00002441 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002442 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002443 case ISD::BRIND: {
2444 if (Subtarget->isTargetNaCl())
2445 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2446 // leave the instruction alone.
2447 break;
2448 if (Subtarget->isTarget64BitILP32()) {
2449 // Converts a 32-bit register to a 64-bit, zero-extended version of
2450 // it. This is needed because x86-64 can do many things, but jmp %r32
2451 // ain't one of them.
2452 const SDValue &Target = Node->getOperand(1);
2453 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2454 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2455 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2456 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002457 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002458 SelectCode(ZextTarget.getNode());
2459 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002460 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002461 }
2462 break;
2463 }
Dan Gohman757eee82009-08-02 16:10:52 +00002464 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002465 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002466 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002467
Craig Topper75370b92017-09-19 17:19:45 +00002468 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002469 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002470 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002471 SDValue VSelect = CurDAG->getNode(
2472 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2473 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002474 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002475 SelectCode(VSelect.getNode());
2476 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002477 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002478 }
Craig Topper3af251d2012-07-01 02:55:34 +00002479
Tobias Grosser85508e82015-08-19 11:35:10 +00002480 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002481 // Try to match BEXTR/BEXTRI instruction.
2482 if (matchBEXTRFromAnd(Node))
2483 return;
2484
2485 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002486 case ISD::OR:
2487 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002488
Benjamin Kramer4c816242011-04-22 15:30:40 +00002489 // For operations of the form (x << C1) op C2, check if we can use a smaller
2490 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2491 SDValue N0 = Node->getOperand(0);
2492 SDValue N1 = Node->getOperand(1);
2493
2494 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2495 break;
2496
2497 // i8 is unshrinkable, i16 should be promoted to i32.
2498 if (NVT != MVT::i32 && NVT != MVT::i64)
2499 break;
2500
2501 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2502 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2503 if (!Cst || !ShlCst)
2504 break;
2505
2506 int64_t Val = Cst->getSExtValue();
2507 uint64_t ShlVal = ShlCst->getZExtValue();
2508
2509 // Make sure that we don't change the operation by removing bits.
2510 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002511 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2512 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002513 break;
2514
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002515 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002516 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002517
2518 // Check the minimum bitwidth for the new constant.
2519 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2520 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2521 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2522 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2523 CstVT = MVT::i8;
2524 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2525 CstVT = MVT::i32;
2526
2527 // Bail if there is no smaller encoding.
2528 if (NVT == CstVT)
2529 break;
2530
Craig Topper83e042a2013-08-15 05:57:07 +00002531 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002532 default: llvm_unreachable("Unsupported VT!");
2533 case MVT::i32:
2534 assert(CstVT == MVT::i8);
2535 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002536 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002537
2538 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002539 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002540 case ISD::AND: Op = X86::AND32ri8; break;
2541 case ISD::OR: Op = X86::OR32ri8; break;
2542 case ISD::XOR: Op = X86::XOR32ri8; break;
2543 }
2544 break;
2545 case MVT::i64:
2546 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2547 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002548 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002549
2550 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002551 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002552 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2553 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2554 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2555 }
2556 break;
2557 }
2558
2559 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002560 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002561 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002562 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002563 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2564 SDValue(New, 0));
2565 else
2566 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2567 getI8Imm(ShlVal, dl));
2568 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002569 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002570 case X86ISD::UMUL8:
2571 case X86ISD::SMUL8: {
2572 SDValue N0 = Node->getOperand(0);
2573 SDValue N1 = Node->getOperand(1);
2574
2575 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2576
2577 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2578 N0, SDValue()).getValue(1);
2579
2580 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2581 SDValue Ops[] = {N1, InFlag};
2582 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2583
Justin Bogner31d7da32016-05-11 21:13:17 +00002584 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002585 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002586 }
2587
Chris Lattner364bb0a2010-12-05 07:30:36 +00002588 case X86ISD::UMUL: {
2589 SDValue N0 = Node->getOperand(0);
2590 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002591
Ted Kremenekb5241b22011-01-14 22:34:13 +00002592 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002593 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002594 default: llvm_unreachable("Unsupported VT!");
Craig Topperfd6b8a62017-09-28 16:56:36 +00002595 // MVT::i8 is handled by X86ISD::UMUL8.
Ted Kremenekb5241b22011-01-14 22:34:13 +00002596 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2597 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2598 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002599 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002600
Chris Lattner364bb0a2010-12-05 07:30:36 +00002601 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2602 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002603
Chris Lattner364bb0a2010-12-05 07:30:36 +00002604 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2605 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002606 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002607
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002608 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002609 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002610 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002611
Dan Gohman757eee82009-08-02 16:10:52 +00002612 case ISD::SMUL_LOHI:
2613 case ISD::UMUL_LOHI: {
2614 SDValue N0 = Node->getOperand(0);
2615 SDValue N1 = Node->getOperand(1);
2616
2617 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002618 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002619 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002620 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002621 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002622 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2623 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002624 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2625 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2626 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2627 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002628 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002629 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002630 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002631 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002632 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2633 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2634 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2635 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002636 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002637 }
Dan Gohman757eee82009-08-02 16:10:52 +00002638
Michael Liaof9f7b552012-09-26 08:22:37 +00002639 unsigned SrcReg, LoReg, HiReg;
2640 switch (Opc) {
2641 default: llvm_unreachable("Unknown MUL opcode!");
2642 case X86::IMUL8r:
2643 case X86::MUL8r:
2644 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2645 break;
2646 case X86::IMUL16r:
2647 case X86::MUL16r:
2648 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2649 break;
2650 case X86::IMUL32r:
2651 case X86::MUL32r:
2652 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2653 break;
2654 case X86::IMUL64r:
2655 case X86::MUL64r:
2656 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2657 break;
2658 case X86::MULX32rr:
2659 SrcReg = X86::EDX; LoReg = HiReg = 0;
2660 break;
2661 case X86::MULX64rr:
2662 SrcReg = X86::RDX; LoReg = HiReg = 0;
2663 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002664 }
2665
2666 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002667 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002668 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002669 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002670 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002671 if (foldedLoad)
2672 std::swap(N0, N1);
2673 }
2674
Michael Liaof9f7b552012-09-26 08:22:37 +00002675 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002676 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002677 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002678
2679 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002680 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002681 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002682 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2683 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002684 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2685 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002686 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002687 ResHi = SDValue(CNode, 0);
2688 ResLo = SDValue(CNode, 1);
2689 Chain = SDValue(CNode, 2);
2690 InFlag = SDValue(CNode, 3);
2691 } else {
2692 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002693 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002694 Chain = SDValue(CNode, 0);
2695 InFlag = SDValue(CNode, 1);
2696 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002697
Dan Gohman757eee82009-08-02 16:10:52 +00002698 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002699 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002700 // Record the mem-refs
2701 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2702 if (LoadNode) {
2703 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2704 MemOp[0] = LoadNode->getMemOperand();
2705 CNode->setMemRefs(MemOp, MemOp + 1);
2706 }
Dan Gohman757eee82009-08-02 16:10:52 +00002707 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002708 SDValue Ops[] = { N1, InFlag };
2709 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2710 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002711 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002712 ResHi = SDValue(CNode, 0);
2713 ResLo = SDValue(CNode, 1);
2714 InFlag = SDValue(CNode, 2);
2715 } else {
2716 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002717 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002718 InFlag = SDValue(CNode, 0);
2719 }
Dan Gohman757eee82009-08-02 16:10:52 +00002720 }
2721
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002722 // Prevent use of AH in a REX instruction by referencing AX instead.
2723 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2724 !SDValue(Node, 1).use_empty()) {
2725 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2726 X86::AX, MVT::i16, InFlag);
2727 InFlag = Result.getValue(2);
2728 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2729 // registers.
2730 if (!SDValue(Node, 0).use_empty())
Craig Topper40f05842017-10-28 19:56:57 +00002731 ReplaceUses(SDValue(Node, 0),
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002732 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2733
2734 // Shift AX down 8 bits.
2735 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2736 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002737 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2738 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002739 // Then truncate it down to i8.
2740 ReplaceUses(SDValue(Node, 1),
2741 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2742 }
Dan Gohman757eee82009-08-02 16:10:52 +00002743 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002744 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002745 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002746 assert(LoReg && "Register for low half is not defined!");
2747 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2748 InFlag);
2749 InFlag = ResLo.getValue(2);
2750 }
2751 ReplaceUses(SDValue(Node, 0), ResLo);
2752 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002753 }
2754 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002755 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002756 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002757 assert(HiReg && "Register for high half is not defined!");
2758 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2759 InFlag);
2760 InFlag = ResHi.getValue(2);
2761 }
2762 ReplaceUses(SDValue(Node, 1), ResHi);
2763 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002764 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002765
Craig Topper6bed9de2017-09-09 05:57:20 +00002766 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002767 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002768 }
2769
2770 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002771 case ISD::UDIVREM:
2772 case X86ISD::SDIVREM8_SEXT_HREG:
2773 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002774 SDValue N0 = Node->getOperand(0);
2775 SDValue N1 = Node->getOperand(1);
2776
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002777 bool isSigned = (Opcode == ISD::SDIVREM ||
2778 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002779 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002780 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002781 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002782 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2783 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2784 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2785 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002786 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002787 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002788 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002789 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002790 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2791 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2792 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2793 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002794 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002795 }
Dan Gohman757eee82009-08-02 16:10:52 +00002796
Chris Lattner518b0372009-12-23 01:45:04 +00002797 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002798 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002799 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002800 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002801 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002802 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002803 SExtOpcode = X86::CBW;
2804 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002805 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002806 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002807 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002808 SExtOpcode = X86::CWD;
2809 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002810 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002811 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002812 SExtOpcode = X86::CDQ;
2813 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002814 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002815 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002816 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002817 break;
2818 }
2819
Dan Gohman757eee82009-08-02 16:10:52 +00002820 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002821 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002822 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002823
Dan Gohman757eee82009-08-02 16:10:52 +00002824 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002825 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002826 // Special case for div8, just use a move with zero extension to AX to
2827 // clear the upper 8 bits (AH).
2828 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002829 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002830 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2831 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002832 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002833 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002834 Chain = Move.getValue(1);
2835 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002836 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002837 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002838 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002839 Chain = CurDAG->getEntryNode();
2840 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002841 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002842 InFlag = Chain.getValue(1);
2843 } else {
2844 InFlag =
2845 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2846 LoReg, N0, SDValue()).getValue(1);
2847 if (isSigned && !signBitIsZero) {
2848 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002849 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002850 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002851 } else {
2852 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002853 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002854 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002855 case MVT::i16:
2856 ClrNode =
2857 SDValue(CurDAG->getMachineNode(
2858 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002859 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2860 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002861 0);
2862 break;
2863 case MVT::i32:
2864 break;
2865 case MVT::i64:
2866 ClrNode =
2867 SDValue(CurDAG->getMachineNode(
2868 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002869 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2870 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2871 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002872 0);
2873 break;
2874 default:
2875 llvm_unreachable("Unexpected division source");
2876 }
2877
Chris Lattner518b0372009-12-23 01:45:04 +00002878 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00002879 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00002880 }
Evan Cheng92e27972006-01-06 23:19:29 +00002881 }
Dan Gohmana1603612007-10-08 18:33:35 +00002882
Dan Gohman757eee82009-08-02 16:10:52 +00002883 if (foldedLoad) {
2884 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2885 InFlag };
2886 SDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00002887 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00002888 InFlag = SDValue(CNode, 1);
2889 // Update the chain.
2890 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2891 } else {
2892 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002893 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002894 }
Evan Cheng92e27972006-01-06 23:19:29 +00002895
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002896 // Prevent use of AH in a REX instruction by explicitly copying it to
2897 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00002898 //
2899 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002900 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00002901 // the allocator and/or the backend get enhanced to be more robust in
2902 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002903 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2904 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2905 unsigned AHExtOpcode =
2906 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002907
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002908 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2909 MVT::Glue, AHCopy, InFlag);
2910 SDValue Result(RNode, 0);
2911 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002912
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002913 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2914 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
Craig Topperb8d7d4d2017-10-26 21:12:03 +00002915 assert(Node->getValueType(1) == MVT::i32 && "Unexpected result type!");
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002916 } else {
2917 Result =
2918 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2919 }
2920 ReplaceUses(SDValue(Node, 1), Result);
2921 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002922 }
Dan Gohman757eee82009-08-02 16:10:52 +00002923 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002924 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00002925 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2926 LoReg, NVT, InFlag);
2927 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002928 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002929 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002930 }
2931 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002932 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002933 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2934 HiReg, NVT, InFlag);
2935 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002936 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002937 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002938 }
Craig Topper6bed9de2017-09-09 05:57:20 +00002939 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002940 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002941 }
2942
Manman Ren1be131b2012-08-08 00:51:41 +00002943 case X86ISD::CMP:
2944 case X86ISD::SUB: {
2945 // Sometimes a SUB is used to perform comparison.
2946 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2947 // This node is not a CMP.
2948 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00002949 SDValue N0 = Node->getOperand(0);
2950 SDValue N1 = Node->getOperand(1);
2951
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002952 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00002953 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002954 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002955
Dan Gohmanac33a902009-08-19 18:16:17 +00002956 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2957 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002958 // Look past the truncate if CMP is the only use of it.
Craig Topperc93d05562017-08-25 05:36:29 +00002959 if ((N0.getOpcode() == ISD::AND ||
2960 (N0.getResNo() == 0 && N0.getOpcode() == X86ISD::AND)) &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00002961 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00002962 N0.getValueType() != MVT::i8 &&
2963 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00002964 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00002965 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00002966 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00002967
2968 // For example, convert "testl %eax, $8" to "testb %al, $8"
Craig Topperfc53dc22017-08-25 05:04:34 +00002969 if (isUInt<8>(Mask) &&
2970 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
2971 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002972 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002973
Dan Gohmanac33a902009-08-19 18:16:17 +00002974 // Extract the l-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002975 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002976 MVT::i8, Reg);
2977
2978 // Emit a testb.
Manman Ren511c6d02012-09-28 18:53:24 +00002979 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2980 Subreg, Imm);
2981 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2982 // one, do not call ReplaceAllUsesWith.
2983 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2984 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00002985 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002986 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002987 }
2988
2989 // For example, "testl %eax, $2048" to "testb %ah, $8".
Craig Topperfc53dc22017-08-25 05:04:34 +00002990 if (isShiftedUInt<8, 8>(Mask) &&
2991 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002992 // Shift the immediate right by 8 bits.
Craig Topperfc53dc22017-08-25 05:04:34 +00002993 SDValue ShiftedImm = CurDAG->getTargetConstant(Mask >> 8, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002994 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002995
Dan Gohmanac33a902009-08-19 18:16:17 +00002996 // Extract the h-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002997 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002998 MVT::i8, Reg);
2999
Jakob Stoklund Olesen729abd32011-10-08 18:28:28 +00003000 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
3001 // target GR8_NOREX registers, so make sure the register class is
3002 // forced.
Manman Ren511c6d02012-09-28 18:53:24 +00003003 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
3004 MVT::i32, Subreg, ShiftedImm);
3005 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3006 // one, do not call ReplaceAllUsesWith.
3007 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3008 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003009 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003010 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003011 }
3012
3013 // For example, "testl %eax, $32776" to "testw %ax, $32776".
Craig Topper6255c7b2017-09-28 23:35:36 +00003014 // NOTE: We only want to form TESTW instructions if optimizing for
3015 // min size. Otherwise we only save one byte and possibly get a length
3016 // changing prefix penalty in the decoders.
3017 if (OptForMinSize && isUInt<16>(Mask) && N0.getValueType() != MVT::i16 &&
Craig Topperfc53dc22017-08-25 05:04:34 +00003018 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
3019 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i16);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003020 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003021
3022 // Extract the 16-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003023 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003024 MVT::i16, Reg);
3025
3026 // Emit a testw.
Manman Ren511c6d02012-09-28 18:53:24 +00003027 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
3028 Subreg, Imm);
3029 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3030 // one, do not call ReplaceAllUsesWith.
3031 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3032 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003033 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003034 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003035 }
3036
3037 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
Craig Topperfc53dc22017-08-25 05:04:34 +00003038 if (isUInt<32>(Mask) && N0.getValueType() == MVT::i64 &&
3039 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
3040 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
Simon Pilgrim7f032312017-05-12 13:08:45 +00003041 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003042
3043 // Extract the 32-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003044 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003045 MVT::i32, Reg);
3046
3047 // Emit a testl.
Manman Ren511c6d02012-09-28 18:53:24 +00003048 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
3049 Subreg, Imm);
3050 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3051 // one, do not call ReplaceAllUsesWith.
3052 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3053 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003054 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003055 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003056 }
3057 }
3058 break;
3059 }
Chandler Carruth03258f22017-08-25 02:04:03 +00003060 case ISD::STORE:
3061 if (foldLoadStoreIntoMemOperand(Node))
3062 return;
3063 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003064 }
3065
Justin Bogner593741d2016-05-10 23:55:37 +00003066 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003067}
3068
Chris Lattnerba1ed582006-06-08 18:03:49 +00003069bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003070SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003071 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003072 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003073 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003074 default:
3075 llvm_unreachable("Unexpected asm memory constraint");
3076 case InlineAsm::Constraint_i:
3077 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3078 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003079 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003080 case InlineAsm::Constraint_o: // offsetable ??
3081 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003082 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003083 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003084 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003085 return true;
3086 break;
3087 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003088
Evan Cheng2d487222006-08-26 01:05:16 +00003089 OutOps.push_back(Op0);
3090 OutOps.push_back(Op1);
3091 OutOps.push_back(Op2);
3092 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003093 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003094 return false;
3095}
3096
Sanjay Patelb5723d02015-10-13 15:12:27 +00003097/// This pass converts a legalized DAG into a X86-specific DAG,
3098/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003099FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003100 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003101 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003102}