blob: bec812bedfafc84c4cf0348fdd6153ec3ee81574 [file] [log] [blame]
Chris Lattner5930d3d2005-11-16 22:59:19 +00001//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
Chris Lattner655e7df2005-11-16 01:54:32 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner655e7df2005-11-16 01:54:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a DAG pattern matching instruction selector for X86,
11// converting from a legalized dag to a X86 dag.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
Evan Chengbc7a0f442006-01-11 06:09:51 +000016#include "X86InstrBuilder.h"
Evan Chengf55b7382008-01-05 00:41:47 +000017#include "X86MachineFunctionInfo.h"
Chris Lattner7c551262006-01-11 01:15:34 +000018#include "X86RegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000019#include "X86Subtarget.h"
Evan Cheng2dd2c652006-03-13 23:20:37 +000020#include "X86TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Statistic.h"
Evan Cheng73a1ad92006-01-10 20:26:56 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner7c551262006-01-11 01:15:34 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Chris Lattner655e7df2005-11-16 01:54:32 +000026#include "llvm/CodeGen/SelectionDAGISel.h"
Peter Collingbourne235c2752016-12-08 19:01:00 +000027#include "llvm/IR/ConstantRange.h"
Eric Christopher79cc1e32014-09-02 22:28:02 +000028#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Type.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000032#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000033#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000034#include "llvm/Support/KnownBits.h"
Evan Cheng11b0a5d2006-09-08 06:48:29 +000035#include "llvm/Support/MathExtras.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000039#include <stdint.h>
Chris Lattner655e7df2005-11-16 01:54:32 +000040using namespace llvm;
41
Chandler Carruth84e68b22014-04-22 02:41:26 +000042#define DEBUG_TYPE "x86-isel"
43
Chris Lattner1ef9cd42006-12-19 22:59:26 +000044STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45
Chris Lattner655e7df2005-11-16 01:54:32 +000046//===----------------------------------------------------------------------===//
47// Pattern Matcher Implementation
48//===----------------------------------------------------------------------===//
49
50namespace {
Sanjay Patelb5723d02015-10-13 15:12:27 +000051 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
52 /// numbers for the leaves of the matched tree.
Chris Lattner3f0f71b2005-11-19 02:11:08 +000053 struct X86ISelAddressMode {
54 enum {
55 RegBase,
Chris Lattneraa2372562006-05-24 17:04:05 +000056 FrameIndexBase
Chris Lattner3f0f71b2005-11-19 02:11:08 +000057 } BaseType;
58
Dan Gohman0fd54fb2010-04-29 23:30:41 +000059 // This is really a union, discriminated by BaseType!
60 SDValue Base_Reg;
61 int Base_FrameIndex;
Chris Lattner3f0f71b2005-11-19 02:11:08 +000062
63 unsigned Scale;
Chad Rosier24c19d22012-08-01 18:39:17 +000064 SDValue IndexReg;
Dan Gohman059c4fa2008-11-11 15:52:29 +000065 int32_t Disp;
Rafael Espindola3b2df102009-04-08 21:14:34 +000066 SDValue Segment;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000067 const GlobalValue *GV;
68 const Constant *CP;
69 const BlockAddress *BlockAddr;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000070 const char *ES;
Rafael Espindola36b718f2015-06-22 17:46:53 +000071 MCSymbol *MCSym;
Evan Cheng11b0a5d2006-09-08 06:48:29 +000072 int JT;
Evan Cheng77d86ff2006-02-25 10:09:08 +000073 unsigned Align; // CP alignment.
Chris Lattnerbd7e26d2009-06-26 05:51:45 +000074 unsigned char SymbolFlags; // X86II::MO_*
Chris Lattner3f0f71b2005-11-19 02:11:08 +000075
76 X86ISelAddressMode()
Rafael Espindola36b718f2015-06-22 17:46:53 +000077 : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
78 Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
79 MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
Dan Gohman4e3e3de2009-02-07 00:43:41 +000080
81 bool hasSymbolicDisplacement() const {
Craig Topper062a2ba2014-04-25 05:30:21 +000082 return GV != nullptr || CP != nullptr || ES != nullptr ||
Rafael Espindola36b718f2015-06-22 17:46:53 +000083 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
Dan Gohman4e3e3de2009-02-07 00:43:41 +000084 }
Chad Rosier24c19d22012-08-01 18:39:17 +000085
Chris Lattnerfea81da2009-06-27 04:16:01 +000086 bool hasBaseOrIndexReg() const {
Tim Northover97347a82013-09-19 11:33:53 +000087 return BaseType == FrameIndexBase ||
Craig Topper062a2ba2014-04-25 05:30:21 +000088 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
Chris Lattnerfea81da2009-06-27 04:16:01 +000089 }
Chad Rosier24c19d22012-08-01 18:39:17 +000090
Sanjay Patelb5723d02015-10-13 15:12:27 +000091 /// Return true if this addressing mode is already RIP-relative.
Chris Lattnerfea81da2009-06-27 04:16:01 +000092 bool isRIPRelative() const {
93 if (BaseType != RegBase) return false;
94 if (RegisterSDNode *RegNode =
Dan Gohman0fd54fb2010-04-29 23:30:41 +000095 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
Chris Lattnerfea81da2009-06-27 04:16:01 +000096 return RegNode->getReg() == X86::RIP;
97 return false;
98 }
Chad Rosier24c19d22012-08-01 18:39:17 +000099
Chris Lattnerfea81da2009-06-27 04:16:01 +0000100 void setBaseReg(SDValue Reg) {
101 BaseType = RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000102 Base_Reg = Reg;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000103 }
Dan Gohman4e3e3de2009-02-07 00:43:41 +0000104
Manman Ren19f49ac2012-09-11 22:23:19 +0000105#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dale Johannesendafdbf72008-08-11 23:46:25 +0000106 void dump() {
David Greenedbdb1b22010-01-05 01:29:08 +0000107 dbgs() << "X86ISelAddressMode " << this << '\n';
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000108 dbgs() << "Base_Reg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000109 if (Base_Reg.getNode())
Chad Rosier24c19d22012-08-01 18:39:17 +0000110 Base_Reg.getNode()->dump();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000111 else
David Greenedbdb1b22010-01-05 01:29:08 +0000112 dbgs() << "nul";
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000113 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000114 << " Scale" << Scale << '\n'
115 << "IndexReg ";
Craig Toppere73658d2014-04-28 04:05:08 +0000116 if (IndexReg.getNode())
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000117 IndexReg.getNode()->dump();
118 else
Chad Rosier24c19d22012-08-01 18:39:17 +0000119 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000120 dbgs() << " Disp " << Disp << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000121 << "GV ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000122 if (GV)
123 GV->dump();
124 else
David Greenedbdb1b22010-01-05 01:29:08 +0000125 dbgs() << "nul";
126 dbgs() << " CP ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000127 if (CP)
128 CP->dump();
129 else
David Greenedbdb1b22010-01-05 01:29:08 +0000130 dbgs() << "nul";
131 dbgs() << '\n'
Benjamin Kramer940fbb02009-08-23 11:52:17 +0000132 << "ES ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000133 if (ES)
David Greenedbdb1b22010-01-05 01:29:08 +0000134 dbgs() << ES;
Bill Wendlingfe3bdb42009-08-07 21:33:25 +0000135 else
David Greenedbdb1b22010-01-05 01:29:08 +0000136 dbgs() << "nul";
Rafael Espindola36b718f2015-06-22 17:46:53 +0000137 dbgs() << " MCSym ";
138 if (MCSym)
139 dbgs() << MCSym;
140 else
141 dbgs() << "nul";
David Greenedbdb1b22010-01-05 01:29:08 +0000142 dbgs() << " JT" << JT << " Align" << Align << '\n';
Dale Johannesendafdbf72008-08-11 23:46:25 +0000143 }
Manman Ren742534c2012-09-06 19:06:06 +0000144#endif
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000145 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000146}
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000147
148namespace {
Chris Lattner655e7df2005-11-16 01:54:32 +0000149 //===--------------------------------------------------------------------===//
Sanjay Patelb5723d02015-10-13 15:12:27 +0000150 /// ISel - X86-specific code to select X86 machine instructions for
Chris Lattner655e7df2005-11-16 01:54:32 +0000151 /// SelectionDAG operations.
152 ///
Craig Topper26eec092014-03-31 06:22:15 +0000153 class X86DAGToDAGISel final : public SelectionDAGISel {
Sanjay Patelb5723d02015-10-13 15:12:27 +0000154 /// Keep a pointer to the X86Subtarget around so that we can
Chris Lattner655e7df2005-11-16 01:54:32 +0000155 /// make the right decision when generating code for different targets.
156 const X86Subtarget *Subtarget;
Evan Cheng5588de92006-02-18 00:15:05 +0000157
Sanjay Patelb5723d02015-10-13 15:12:27 +0000158 /// If true, selector should try to optimize for code size instead of
159 /// performance.
Evan Cheng7d6fa972008-09-26 23:41:32 +0000160 bool OptForSize;
161
Hans Wennborg4ae51192016-03-25 01:10:56 +0000162 /// If true, selector should try to optimize for minimum code size.
163 bool OptForMinSize;
164
Chris Lattner655e7df2005-11-16 01:54:32 +0000165 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000166 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
Hans Wennborg4ae51192016-03-25 01:10:56 +0000167 : SelectionDAGISel(tm, OptLevel), OptForSize(false),
Hans Wennborg534bfbd2017-09-15 18:40:26 +0000168 OptForMinSize(false) {}
Chris Lattner655e7df2005-11-16 01:54:32 +0000169
Mehdi Amini117296c2016-10-01 02:56:57 +0000170 StringRef getPassName() const override {
Chris Lattner655e7df2005-11-16 01:54:32 +0000171 return "X86 DAG->DAG Instruction Selection";
172 }
173
Eric Christopher4f09c592014-05-22 01:53:26 +0000174 bool runOnMachineFunction(MachineFunction &MF) override {
175 // Reset the subtarget each time through.
Eric Christopher05b81972015-02-02 17:38:43 +0000176 Subtarget = &MF.getSubtarget<X86Subtarget>();
Eric Christopher4f09c592014-05-22 01:53:26 +0000177 SelectionDAGISel::runOnMachineFunction(MF);
178 return true;
179 }
180
Craig Topper2d9361e2014-03-09 07:44:38 +0000181 void EmitFunctionEntryCode() override;
Anton Korobeynikov90910742007-09-25 21:52:30 +0000182
Craig Topper2d9361e2014-03-09 07:44:38 +0000183 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
Evan Cheng5e73ff22010-02-15 19:41:07 +0000184
Craig Topper2d9361e2014-03-09 07:44:38 +0000185 void PreprocessISelDAG() override;
Chris Lattnerf98f1242010-03-02 06:34:30 +0000186
Chris Lattner655e7df2005-11-16 01:54:32 +0000187// Include the pieces autogenerated from the target description.
188#include "X86GenDAGISel.inc"
189
190 private:
Justin Bogner593741d2016-05-10 23:55:37 +0000191 void Select(SDNode *N) override;
Chris Lattner655e7df2005-11-16 01:54:32 +0000192
Sanjay Patel85030aa2015-10-13 16:23:00 +0000193 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
194 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
195 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
196 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
Sanjay Patelefab8b02015-10-21 18:56:06 +0000197 bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000198 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +0000199 unsigned Depth);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000200 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
201 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000202 SDValue &Scale, SDValue &Index, SDValue &Disp,
203 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000204 bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000205 SDValue &Scale, SDValue &Index, SDValue &Disp,
206 SDValue &Segment);
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +0000207 template <class GatherScatterSDNode>
208 bool selectAddrOfGatherScatterNode(GatherScatterSDNode *Parent, SDValue N,
209 SDValue &Base, SDValue &Scale,
210 SDValue &Index, SDValue &Disp,
211 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000212 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
213 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000214 SDValue &Scale, SDValue &Index, SDValue &Disp,
215 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000216 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000217 SDValue &Scale, SDValue &Index, SDValue &Disp,
218 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000219 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000220 SDValue &Scale, SDValue &Index, SDValue &Disp,
221 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000222 bool selectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000223 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000224 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000225 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000226 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000227 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000228
Sanjay Patel85030aa2015-10-13 16:23:00 +0000229 bool tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000230 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000231 SDValue &Index, SDValue &Disp,
232 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000233
Sanjay Patelb5723d02015-10-13 15:12:27 +0000234 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000235 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000236 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000237 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000238
Sanjay Patel85030aa2015-10-13 16:23:00 +0000239 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000240
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000241 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000242 SDValue &Base, SDValue &Scale,
243 SDValue &Index, SDValue &Disp,
244 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000245 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000246 ? CurDAG->getTargetFrameIndex(
247 AM.Base_FrameIndex,
248 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000249 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000250 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000251 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000252 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000253 // is 32-bit.
254 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000255 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000256 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000257 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000258 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000259 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000260 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000261 else if (AM.ES) {
262 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000263 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000264 } else if (AM.MCSym) {
265 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
266 assert(AM.SymbolFlags == 0 && "oo");
267 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000268 } else if (AM.JT != -1) {
269 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000270 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000271 } else if (AM.BlockAddr)
272 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
273 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000274 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000275 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000276
277 if (AM.Segment.getNode())
278 Segment = AM.Segment;
279 else
Owen Anderson9f944592009-08-11 20:47:22 +0000280 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000281 }
282
Michael Kuperstein243c0732015-08-11 14:10:58 +0000283 // Utility function to determine whether we should avoid selecting
284 // immediate forms of instructions for better code size or not.
285 // At a high level, we'd like to avoid such instructions when
286 // we have similar constants used within the same basic block
287 // that can be kept in a register.
288 //
289 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
290 uint32_t UseCount = 0;
291
292 // Do not want to hoist if we're not optimizing for size.
293 // TODO: We'd like to remove this restriction.
294 // See the comment in X86InstrInfo.td for more info.
295 if (!OptForSize)
296 return false;
297
298 // Walk all the users of the immediate.
299 for (SDNode::use_iterator UI = N->use_begin(),
300 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000301
Michael Kuperstein243c0732015-08-11 14:10:58 +0000302 SDNode *User = *UI;
303
304 // This user is already selected. Count it as a legitimate use and
305 // move on.
306 if (User->isMachineOpcode()) {
307 UseCount++;
308 continue;
309 }
310
311 // We want to count stores of immediates as real uses.
312 if (User->getOpcode() == ISD::STORE &&
313 User->getOperand(1).getNode() == N) {
314 UseCount++;
315 continue;
316 }
317
318 // We don't currently match users that have > 2 operands (except
319 // for stores, which are handled above)
320 // Those instruction won't match in ISEL, for now, and would
321 // be counted incorrectly.
322 // This may change in the future as we add additional instruction
323 // types.
324 if (User->getNumOperands() != 2)
325 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000326
Michael Kuperstein243c0732015-08-11 14:10:58 +0000327 // Immediates that are used for offsets as part of stack
328 // manipulation should be left alone. These are typically
329 // used to indicate SP offsets for argument passing and
330 // will get pulled into stores/pushes (implicitly).
331 if (User->getOpcode() == X86ISD::ADD ||
332 User->getOpcode() == ISD::ADD ||
333 User->getOpcode() == X86ISD::SUB ||
334 User->getOpcode() == ISD::SUB) {
335
336 // Find the other operand of the add/sub.
337 SDValue OtherOp = User->getOperand(0);
338 if (OtherOp.getNode() == N)
339 OtherOp = User->getOperand(1);
340
341 // Don't count if the other operand is SP.
342 RegisterSDNode *RegNode;
343 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
344 (RegNode = dyn_cast_or_null<RegisterSDNode>(
345 OtherOp->getOperand(1).getNode())))
346 if ((RegNode->getReg() == X86::ESP) ||
347 (RegNode->getReg() == X86::RSP))
348 continue;
349 }
350
351 // ... otherwise, count this and move on.
352 UseCount++;
353 }
354
355 // If we have more than 1 use, then recommend for hoisting.
356 return (UseCount > 1);
357 }
358
Sanjay Patelb5723d02015-10-13 15:12:27 +0000359 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000360 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000361 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000362 }
363
Sanjay Patelb5723d02015-10-13 15:12:27 +0000364 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000365 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000366 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000367 }
Evan Chengd49cc362006-02-10 22:24:32 +0000368
Sanjay Patelb5723d02015-10-13 15:12:27 +0000369 /// Return an SDNode that returns the value of the global base register.
370 /// Output instructions required to initialize the global base register,
371 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000372 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000373
Sanjay Patelb5723d02015-10-13 15:12:27 +0000374 /// Return a reference to the TargetMachine, casted to the target-specific
375 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000376 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000377 return static_cast<const X86TargetMachine &>(TM);
378 }
379
Sanjay Patelb5723d02015-10-13 15:12:27 +0000380 /// Return a reference to the TargetInstrInfo, casted to the target-specific
381 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000382 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000383 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000384 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000385
386 /// \brief Address-mode matching performs shift-of-and to and-of-shift
387 /// reassociation in order to expose more scaled addressing
388 /// opportunities.
389 bool ComplexPatternFuncMutatesDAG() const override {
390 return true;
391 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000392
393 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
394
395 /// Returns whether this is a relocatable immediate in the range
396 /// [-2^Width .. 2^Width-1].
397 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
398 if (auto *CN = dyn_cast<ConstantSDNode>(N))
399 return isInt<Width>(CN->getSExtValue());
400 return isSExtAbsoluteSymbolRef(Width, N);
401 }
Craig Topper4de6f582017-08-19 23:21:22 +0000402
403 // Indicates we should prefer to use a non-temporal load for this load.
404 bool useNonTemporalLoad(LoadSDNode *N) const {
405 if (!N->isNonTemporal())
406 return false;
407
408 unsigned StoreSize = N->getMemoryVT().getStoreSize();
409
410 if (N->getAlignment() < StoreSize)
411 return false;
412
413 switch (StoreSize) {
414 default: llvm_unreachable("Unsupported store size");
415 case 16:
416 return Subtarget->hasSSE41();
417 case 32:
418 return Subtarget->hasAVX2();
419 case 64:
420 return Subtarget->hasAVX512();
421 }
422 }
Chandler Carruth03258f22017-08-25 02:04:03 +0000423
424 bool foldLoadStoreIntoMemOperand(SDNode *Node);
Craig Topper958106d2017-09-12 17:40:25 +0000425
426 bool matchBEXTRFromAnd(SDNode *Node);
Chris Lattner655e7df2005-11-16 01:54:32 +0000427 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000428}
429
Evan Cheng72bb66a2006-08-08 00:31:00 +0000430
Evan Cheng5e73ff22010-02-15 19:41:07 +0000431bool
432X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000433 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000434
Evan Cheng5e73ff22010-02-15 19:41:07 +0000435 if (!N.hasOneUse())
436 return false;
437
438 if (N.getOpcode() != ISD::LOAD)
439 return true;
440
441 // If N is a load, do additional profitability checks.
442 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000443 switch (U->getOpcode()) {
444 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000445 case X86ISD::ADD:
446 case X86ISD::SUB:
447 case X86ISD::AND:
448 case X86ISD::XOR:
449 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000450 case ISD::ADD:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000451 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000452 case ISD::AND:
453 case ISD::OR:
454 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000455 SDValue Op1 = U->getOperand(1);
456
Evan Cheng83bdb382008-11-27 00:49:46 +0000457 // If the other operand is a 8-bit immediate we should fold the immediate
458 // instead. This reduces code size.
459 // e.g.
460 // movl 4(%esp), %eax
461 // addl $4, %eax
462 // vs.
463 // movl $4, %eax
464 // addl 4(%esp), %eax
465 // The former is 2 bytes shorter. In case where the increment is 1, then
466 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000467 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000468 if (Imm->getAPIntValue().isSignedIntN(8))
469 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000470
471 // If the other operand is a TLS address, we should fold it instead.
472 // This produces
473 // movl %gs:0, %eax
474 // leal i@NTPOFF(%eax), %eax
475 // instead of
476 // movl $i@NTPOFF, %eax
477 // addl %gs:0, %eax
478 // if the block also has an access to a second TLS address this will save
479 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000480 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000481 if (Op1.getOpcode() == X86ISD::Wrapper) {
482 SDValue Val = Op1.getOperand(0);
483 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
484 return false;
485 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000486 }
487 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000488 }
489
490 return true;
491}
492
Sanjay Patelb5723d02015-10-13 15:12:27 +0000493/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000494/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000495static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
496 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000497 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000498 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000499 if (Chain.getNode() == Load.getNode())
500 Ops.push_back(Load.getOperand(0));
501 else {
502 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000503 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000504 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
505 if (Chain.getOperand(i).getNode() == Load.getNode())
506 Ops.push_back(Load.getOperand(0));
507 else
508 Ops.push_back(Chain.getOperand(i));
509 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000510 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000511 Ops.clear();
512 Ops.push_back(NewChain);
513 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000514 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000515 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000516 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000517 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000518
Evan Chengf00f1e52008-08-25 21:27:18 +0000519 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000520 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000521 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000522 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000523}
524
Sanjay Patelb5723d02015-10-13 15:12:27 +0000525/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000526/// moved below CALLSEQ_START and the chains leading up to the call.
527/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000528/// In the case of a tail call, there isn't a callseq node between the call
529/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000530static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000531 // The transformation is somewhat dangerous if the call's chain was glued to
532 // the call. After MoveBelowOrigChain the load is moved between the call and
533 // the chain, this can create a cycle if the load is not folded. So it is
534 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000535 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000536 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000537 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000538 if (!LD ||
539 LD->isVolatile() ||
540 LD->getAddressingMode() != ISD::UNINDEXED ||
541 LD->getExtensionType() != ISD::NON_EXTLOAD)
542 return false;
543
544 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000545 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000546 if (!Chain.hasOneUse())
547 return false;
548 Chain = Chain.getOperand(0);
549 }
Evan Chengd703df62010-03-14 03:48:46 +0000550
551 if (!Chain.getNumOperands())
552 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000553 // Since we are not checking for AA here, conservatively abort if the chain
554 // writes to memory. It's not safe to move the callee (a load) across a store.
555 if (isa<MemSDNode>(Chain.getNode()) &&
556 cast<MemSDNode>(Chain.getNode())->writeMem())
557 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000558 if (Chain.getOperand(0).getNode() == Callee.getNode())
559 return true;
560 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000561 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
562 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000563 return true;
564 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000565}
566
Chris Lattner8d637042010-03-02 23:12:51 +0000567void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000568 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Sanjay Patel68b03252015-08-10 16:47:47 +0000569 OptForSize = MF->getFunction()->optForSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000570 OptForMinSize = MF->getFunction()->optForMinSize();
571 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000572
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000573 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
574 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000575 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000576
Evan Chengd703df62010-03-14 03:48:46 +0000577 if (OptLevel != CodeGenOpt::None &&
Michael Liao96b42602013-03-28 23:13:21 +0000578 // Only does this when target favors doesn't favor register indirect
579 // call.
Craig Topper62c47a22017-08-29 05:14:27 +0000580 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000581 (N->getOpcode() == X86ISD::TC_RETURN &&
Nick Lewyckyf41a80e2013-01-13 19:03:55 +0000582 // Only does this if load can be folded into TC_RETURN.
Evan Cheng847ad442012-10-05 01:48:22 +0000583 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000584 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000585 /// Also try moving call address load from outside callseq_start to just
586 /// before the call to allow it to be folded.
587 ///
588 /// [Load chain]
589 /// ^
590 /// |
591 /// [Load]
592 /// ^ ^
593 /// | |
594 /// / \--
595 /// / |
596 ///[CALLSEQ_START] |
597 /// ^ |
598 /// | |
599 /// [LOAD/C2Reg] |
600 /// | |
601 /// \ /
602 /// \ /
603 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000604 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000605 SDValue Chain = N->getOperand(0);
606 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000607 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000608 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000609 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000610 ++NumLoadMoved;
611 continue;
612 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000613
Chris Lattner8d637042010-03-02 23:12:51 +0000614 // Lower fpround and fpextend nodes that target the FP stack to be store and
615 // load to the stack. This is a gross hack. We would like to simply mark
616 // these as being illegal, but when we do that, legalize produces these when
617 // it expands calls, then expands these in the same legalize pass. We would
618 // like dag combine to be able to hack on these between the call expansion
619 // and the node legalization. As such this pass basically does "really
620 // late" legalization of these inline with the X86 isel pass.
621 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000622 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
623 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000624
Craig Topper83e042a2013-08-15 05:57:07 +0000625 MVT SrcVT = N->getOperand(0).getSimpleValueType();
626 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000627
628 // If any of the sources are vectors, no fp stack involved.
629 if (SrcVT.isVector() || DstVT.isVector())
630 continue;
631
632 // If the source and destination are SSE registers, then this is a legal
633 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000634 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000635 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000636 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
637 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000638 if (SrcIsSSE && DstIsSSE)
639 continue;
640
Chris Lattnerd587e582008-03-09 07:05:32 +0000641 if (!SrcIsSSE && !DstIsSSE) {
642 // If this is an FPStack extension, it is a noop.
643 if (N->getOpcode() == ISD::FP_EXTEND)
644 continue;
645 // If this is a value-preserving FPStack truncation, it is a noop.
646 if (N->getConstantOperandVal(1))
647 continue;
648 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000649
Chris Lattnera91f77e2008-01-24 08:07:48 +0000650 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
651 // FPStack has extload and truncstore. SSE can fold direct loads into other
652 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000653 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000654 if (N->getOpcode() == ISD::FP_ROUND)
655 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
656 else
657 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000658
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000659 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000660 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000661
Chris Lattnera91f77e2008-01-24 08:07:48 +0000662 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000663 SDValue Store =
664 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
665 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000666 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000667 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000668
669 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
670 // extload we created. This will cause general havok on the dag because
671 // anything below the conversion could be folded into other existing nodes.
672 // To avoid invalidating 'I', back it up to the convert node.
673 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000674 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000675
Chris Lattnera91f77e2008-01-24 08:07:48 +0000676 // Now that we did that, the node is dead. Increment the iterator to the
677 // next node to process, then delete N.
678 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000679 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000680 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000681}
682
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000683
Sanjay Patelb5723d02015-10-13 15:12:27 +0000684/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000685void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000686 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000687 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000688 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000689
690 TargetLowering::CallLoweringInfo CLI(*CurDAG);
691 CLI.setChain(CurDAG->getRoot())
692 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000693 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000694 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000695 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
696 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
697 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000698 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000699}
700
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000701void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000702 // If this is main, emit special code for main.
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000703 if (const Function *Fn = MF->getFunction())
704 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
Sanjay Patel85030aa2015-10-13 16:23:00 +0000705 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000706}
707
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000708static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000709 // On 64-bit platforms, we can run into an issue where a frame index
710 // includes a displacement that, when added to the explicit displacement,
711 // will overflow the displacement field. Assuming that the frame index
712 // displacement fits into a 31-bit integer (which is only slightly more
713 // aggressive than the current fundamental assumption that it fits into
714 // a 32-bit integer), a 31-bit disp should always be safe.
715 return isInt<31>(Val);
716}
717
Sanjay Patel85030aa2015-10-13 16:23:00 +0000718bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000719 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000720 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000721 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000722 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000723 int64_t Val = AM.Disp + Offset;
724 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000725 if (Subtarget->is64Bit()) {
726 if (!X86::isOffsetSuitableForCodeModel(Val, M,
727 AM.hasSymbolicDisplacement()))
728 return true;
729 // In addition to the checks required for a register base, check that
730 // we do not try to use an unsafe Disp with a frame index.
731 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
732 !isDispSafeForFrameIndex(Val))
733 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000734 }
Eli Friedman344ec792011-07-13 21:29:53 +0000735 AM.Disp = Val;
736 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000737
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000738}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000739
Sanjay Patel85030aa2015-10-13 16:23:00 +0000740bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000741 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000742
Chris Lattner8a236b62010-09-22 04:39:11 +0000743 // load gs:0 -> GS segment register.
744 // load fs:0 -> FS segment register.
745 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000746 // This optimization is valid because the GNU TLS model defines that
747 // gs:0 (or fs:0 on X86-64) contains its own address.
748 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000750 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000751 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
752 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000753 switch (N->getPointerInfo().getAddrSpace()) {
754 case 256:
755 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
756 return false;
757 case 257:
758 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
759 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000760 // Address space 258 is not handled here, because it is not used to
761 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000762 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000763
Rafael Espindola3b2df102009-04-08 21:14:34 +0000764 return true;
765}
766
Sanjay Patelb5723d02015-10-13 15:12:27 +0000767/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
768/// mode. These wrap things that will resolve down into a symbol reference.
769/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000770bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000771 // If the addressing mode already has a symbol as the displacement, we can
772 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000773 if (AM.hasSymbolicDisplacement())
774 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000775
776 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000777 CodeModel::Model M = TM.getCodeModel();
778
Chris Lattnerfea81da2009-06-27 04:16:01 +0000779 // Handle X86-64 rip-relative addresses. We check this before checking direct
780 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000781 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000782 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
783 // they cannot be folded into immediate fields.
784 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000785 (M == CodeModel::Small || M == CodeModel::Kernel)) {
786 // Base and index reg must be 0 in order to use %rip as base.
787 if (AM.hasBaseOrIndexReg())
788 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000789 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000790 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000791 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000792 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000793 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000794 AM = Backup;
795 return true;
796 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000797 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000798 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000799 AM.CP = CP->getConstVal();
800 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000801 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000802 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000803 AM = Backup;
804 return true;
805 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000806 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
807 AM.ES = S->getSymbol();
808 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000809 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
810 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000811 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000812 AM.JT = J->getIndex();
813 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000814 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
815 X86ISelAddressMode Backup = AM;
816 AM.BlockAddr = BA->getBlockAddress();
817 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000818 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000819 AM = Backup;
820 return true;
821 }
822 } else
823 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000824
Chris Lattnerfea81da2009-06-27 04:16:01 +0000825 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000826 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000827 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000828 }
829
830 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000831 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
832 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000833 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000834 M == CodeModel::Small || M == CodeModel::Kernel) {
835 assert(N.getOpcode() != X86ISD::WrapperRIP &&
836 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000837 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
838 AM.GV = G->getGlobal();
839 AM.Disp += G->getOffset();
840 AM.SymbolFlags = G->getTargetFlags();
841 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
842 AM.CP = CP->getConstVal();
843 AM.Align = CP->getAlignment();
844 AM.Disp += CP->getOffset();
845 AM.SymbolFlags = CP->getTargetFlags();
846 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
847 AM.ES = S->getSymbol();
848 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000849 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
850 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000851 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000852 AM.JT = J->getIndex();
853 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000854 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
855 AM.BlockAddr = BA->getBlockAddress();
856 AM.Disp += BA->getOffset();
857 AM.SymbolFlags = BA->getTargetFlags();
858 } else
859 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000860 return false;
861 }
862
863 return true;
864}
865
Sanjay Patelb5723d02015-10-13 15:12:27 +0000866/// Add the specified node to the specified addressing mode, returning true if
867/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000868bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
869 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000870 return true;
871
872 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
873 // a smaller encoding and avoids a scaled-index.
874 if (AM.Scale == 2 &&
875 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000876 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000877 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000878 AM.Scale = 1;
879 }
880
Dan Gohman05046082009-08-20 18:23:44 +0000881 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
882 // because it has a smaller encoding.
883 // TODO: Which other code models can use this?
884 if (TM.getCodeModel() == CodeModel::Small &&
885 Subtarget->is64Bit() &&
886 AM.Scale == 1 &&
887 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000888 AM.Base_Reg.getNode() == nullptr &&
889 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000890 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000891 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000892 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000893
Dan Gohman824ab402009-07-22 23:26:55 +0000894 return false;
895}
896
Sanjay Patelefab8b02015-10-21 18:56:06 +0000897bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
898 unsigned Depth) {
899 // Add an artificial use to this node so that we can keep track of
900 // it if it gets CSE'd with a different node.
901 HandleSDNode Handle(N);
902
903 X86ISelAddressMode Backup = AM;
904 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
905 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
906 return false;
907 AM = Backup;
908
909 // Try again after commuting the operands.
910 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
911 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
912 return false;
913 AM = Backup;
914
915 // If we couldn't fold both operands into the address at the same time,
916 // see if we can just put each operand into a register and fold at least
917 // the add.
918 if (AM.BaseType == X86ISelAddressMode::RegBase &&
919 !AM.Base_Reg.getNode() &&
920 !AM.IndexReg.getNode()) {
921 N = Handle.getValue();
922 AM.Base_Reg = N.getOperand(0);
923 AM.IndexReg = N.getOperand(1);
924 AM.Scale = 1;
925 return false;
926 }
927 N = Handle.getValue();
928 return true;
929}
930
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000931// Insert a node into the DAG at least before the Pos node's position. This
932// will reposition the node as needed, and will assign it a node ID that is <=
933// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
934// IDs! The selection DAG must no longer depend on their uniqueness when this
935// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000936static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000937 if (N.getNode()->getNodeId() == -1 ||
938 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000939 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000940 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
941 }
942}
943
Adam Nemet0c7caf42014-09-16 17:14:10 +0000944// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
945// safe. This allows us to convert the shift and and into an h-register
946// extract and a scaled index. Returns false if the simplification is
947// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000948static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
949 uint64_t Mask,
950 SDValue Shift, SDValue X,
951 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +0000952 if (Shift.getOpcode() != ISD::SRL ||
953 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
954 !Shift.hasOneUse())
955 return true;
956
957 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
958 if (ScaleLog <= 0 || ScaleLog >= 4 ||
959 Mask != (0xffu << ScaleLog))
960 return true;
961
Craig Topper83e042a2013-08-15 05:57:07 +0000962 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000963 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000964 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
965 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +0000966 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
967 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000968 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +0000969 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
970
Chandler Carrutheb21da02012-01-12 01:34:44 +0000971 // Insert the new nodes into the topological ordering. We must do this in
972 // a valid topological ordering as nothing is going to go back and re-sort
973 // these nodes. We continually insert before 'N' in sequence as this is
974 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
975 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000976 insertDAGNode(DAG, N, Eight);
977 insertDAGNode(DAG, N, Srl);
978 insertDAGNode(DAG, N, NewMask);
979 insertDAGNode(DAG, N, And);
980 insertDAGNode(DAG, N, ShlCount);
981 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +0000982 DAG.ReplaceAllUsesWith(N, Shl);
983 AM.IndexReg = And;
984 AM.Scale = (1 << ScaleLog);
985 return false;
986}
987
Chandler Carruthaa01e662012-01-11 09:35:00 +0000988// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
989// allows us to fold the shift into this addressing mode. Returns false if the
990// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000991static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
992 uint64_t Mask,
993 SDValue Shift, SDValue X,
994 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +0000995 if (Shift.getOpcode() != ISD::SHL ||
996 !isa<ConstantSDNode>(Shift.getOperand(1)))
997 return true;
998
999 // Not likely to be profitable if either the AND or SHIFT node has more
1000 // than one use (unless all uses are for address computation). Besides,
1001 // isel mechanism requires their node ids to be reused.
1002 if (!N.hasOneUse() || !Shift.hasOneUse())
1003 return true;
1004
1005 // Verify that the shift amount is something we can fold.
1006 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1007 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1008 return true;
1009
Craig Topper83e042a2013-08-15 05:57:07 +00001010 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001011 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001012 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001013 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1014 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1015
Chandler Carrutheb21da02012-01-12 01:34:44 +00001016 // Insert the new nodes into the topological ordering. We must do this in
1017 // a valid topological ordering as nothing is going to go back and re-sort
1018 // these nodes. We continually insert before 'N' in sequence as this is
1019 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1020 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001021 insertDAGNode(DAG, N, NewMask);
1022 insertDAGNode(DAG, N, NewAnd);
1023 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001024 DAG.ReplaceAllUsesWith(N, NewShift);
1025
1026 AM.Scale = 1 << ShiftAmt;
1027 AM.IndexReg = NewAnd;
1028 return false;
1029}
1030
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001031// Implement some heroics to detect shifts of masked values where the mask can
1032// be replaced by extending the shift and undoing that in the addressing mode
1033// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1034// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1035// the addressing mode. This results in code such as:
1036//
1037// int f(short *y, int *lookup_table) {
1038// ...
1039// return *y + lookup_table[*y >> 11];
1040// }
1041//
1042// Turning into:
1043// movzwl (%rdi), %eax
1044// movl %eax, %ecx
1045// shrl $11, %ecx
1046// addl (%rsi,%rcx,4), %eax
1047//
1048// Instead of:
1049// movzwl (%rdi), %eax
1050// movl %eax, %ecx
1051// shrl $9, %ecx
1052// andl $124, %rcx
1053// addl (%rsi,%rcx), %eax
1054//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001055// Note that this function assumes the mask is provided as a mask *after* the
1056// value is shifted. The input chain may or may not match that, but computing
1057// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001058static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1059 uint64_t Mask,
1060 SDValue Shift, SDValue X,
1061 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001062 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1063 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001064 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001065
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001066 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001067 unsigned MaskLZ = countLeadingZeros(Mask);
1068 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001069
1070 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001071 // from the trailing zeros of the mask.
1072 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001073
1074 // There is nothing we can do here unless the mask is removing some bits.
1075 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1076 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1077
1078 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001079 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001080
1081 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001082 // Also scale it down based on the size of the shift.
Davide Italiano5fc5d0a2017-07-19 18:09:46 +00001083 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1084 if (MaskLZ < ScaleDown)
1085 return true;
1086 MaskLZ -= ScaleDown;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001087
1088 // The final check is to ensure that any masked out high bits of X are
1089 // already known to be zero. Otherwise, the mask has a semantic impact
1090 // other than masking out a couple of low bits. Unfortunately, because of
1091 // the mask, zero extensions will be removed from operands in some cases.
1092 // This code works extra hard to look through extensions because we can
1093 // replace them with zero extensions cheaply if necessary.
1094 bool ReplacingAnyExtend = false;
1095 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001096 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1097 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001098 // Assume that we'll replace the any-extend with a zero-extend, and
1099 // narrow the search to the extended value.
1100 X = X.getOperand(0);
1101 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1102 ReplacingAnyExtend = true;
1103 }
Craig Topper83e042a2013-08-15 05:57:07 +00001104 APInt MaskedHighBits =
1105 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001106 KnownBits Known;
1107 DAG.computeKnownBits(X, Known);
1108 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001109
1110 // We've identified a pattern that can be transformed into a single shift
1111 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001112 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001113 if (ReplacingAnyExtend) {
1114 assert(X.getValueType() != VT);
1115 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001116 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001117 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001118 X = NewX;
1119 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001120 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001121 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001122 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001123 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001124 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001125
1126 // Insert the new nodes into the topological ordering. We must do this in
1127 // a valid topological ordering as nothing is going to go back and re-sort
1128 // these nodes. We continually insert before 'N' in sequence as this is
1129 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1130 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001131 insertDAGNode(DAG, N, NewSRLAmt);
1132 insertDAGNode(DAG, N, NewSRL);
1133 insertDAGNode(DAG, N, NewSHLAmt);
1134 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001135 DAG.ReplaceAllUsesWith(N, NewSHL);
1136
1137 AM.Scale = 1 << AMShiftAmt;
1138 AM.IndexReg = NewSRL;
1139 return false;
1140}
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001141
Sanjay Patel85030aa2015-10-13 16:23:00 +00001142bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001143 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001144 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001145 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001146 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001147 AM.dump();
1148 });
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001149 // Limit recursion.
1150 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001151 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001152
Chris Lattnerfea81da2009-06-27 04:16:01 +00001153 // If this is already a %rip relative address, we can only merge immediates
1154 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001155 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001156 if (AM.isRIPRelative()) {
1157 // FIXME: JumpTable and ExternalSymbol address currently don't like
1158 // displacements. It isn't very important, but this should be fixed for
1159 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001160 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1161 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001162
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001163 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001164 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001165 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001166 return true;
1167 }
1168
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001169 switch (N.getOpcode()) {
1170 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001171 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001172 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001173 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1174 // Use the symbol and don't prefix it.
1175 AM.MCSym = ESNode->getMCSymbol();
1176 return false;
1177 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001178 break;
1179 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001180 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001181 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001182 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001183 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001184 break;
1185 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001186
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001187 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001188 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001189 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001190 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001191 break;
1192
Rafael Espindola3b2df102009-04-08 21:14:34 +00001193 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001194 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001195 return false;
1196 break;
1197
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001198 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001199 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001200 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001201 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001202 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001203 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001204 return false;
1205 }
1206 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001207
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001208 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001209 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001210 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001211
Simon Pilgrim7f032312017-05-12 13:08:45 +00001212 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001213 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001214 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1215 // that the base operand remains free for further matching. If
1216 // the base doesn't end up getting used, a post-processing step
1217 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001218 if (Val == 1 || Val == 2 || Val == 3) {
1219 AM.Scale = 1 << Val;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001220 SDValue ShVal = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001221
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001222 // Okay, we know that we have a scale by now. However, if the scaled
1223 // value is an add of something and a constant, we can fold the
1224 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001225 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001226 AM.IndexReg = ShVal.getOperand(0);
1227 ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001228 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001229 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001230 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001231 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001232
1233 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001234 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001235 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001236 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001237 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001238
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001239 case ISD::SRL: {
1240 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001241 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001242
1243 SDValue And = N.getOperand(0);
1244 if (And.getOpcode() != ISD::AND) break;
1245 SDValue X = And.getOperand(0);
1246
1247 // We only handle up to 64-bit values here as those are what matter for
1248 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001249 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001250
1251 // The mask used for the transform is expected to be post-shift, but we
1252 // found the shift first so just apply the shift to the mask before passing
1253 // it down.
1254 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1255 !isa<ConstantSDNode>(And.getOperand(1)))
1256 break;
1257 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1258
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001259 // Try to fold the mask and shift into the scale, and return false if we
1260 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001261 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001262 return false;
1263 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001264 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001265
Dan Gohmanbf474952007-10-22 20:22:24 +00001266 case ISD::SMUL_LOHI:
1267 case ISD::UMUL_LOHI:
1268 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001269 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001270 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001271 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001272 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001273 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001274 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001275 AM.Base_Reg.getNode() == nullptr &&
1276 AM.IndexReg.getNode() == nullptr) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001277 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001278 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1279 CN->getZExtValue() == 9) {
1280 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001281
Simon Pilgrim7f032312017-05-12 13:08:45 +00001282 SDValue MulVal = N.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001283 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001284
1285 // Okay, we know that we have a scale by now. However, if the scaled
1286 // value is an add of something and a constant, we can fold the
1287 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001288 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001289 isa<ConstantSDNode>(MulVal.getOperand(1))) {
1290 Reg = MulVal.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001291 ConstantSDNode *AddVal =
Simon Pilgrim7f032312017-05-12 13:08:45 +00001292 cast<ConstantSDNode>(MulVal.getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001293 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001294 if (foldOffsetIntoAddress(Disp, AM))
Simon Pilgrim7f032312017-05-12 13:08:45 +00001295 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001296 } else {
Simon Pilgrim7f032312017-05-12 13:08:45 +00001297 Reg = N.getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001298 }
1299
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001300 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001301 return false;
1302 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001303 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001304 break;
1305
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001306 case ISD::SUB: {
1307 // Given A-B, if A can be completely folded into the address and
1308 // the index field with the index field unused, use -B as the index.
1309 // This is a win if a has multiple parts that can be folded into
1310 // the address. Also, this saves a mov if the base register has
1311 // other uses, since it avoids a two-address sub instruction, however
1312 // it costs an additional mov if the index register has other uses.
1313
Dan Gohman99ba4da2010-06-18 01:24:29 +00001314 // Add an artificial use to this node so that we can keep track of
1315 // it if it gets CSE'd with a different node.
1316 HandleSDNode Handle(N);
1317
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001318 // Test if the LHS of the sub can be folded.
1319 X86ISelAddressMode Backup = AM;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001320 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001321 AM = Backup;
1322 break;
1323 }
1324 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001325 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001326 AM = Backup;
1327 break;
1328 }
Evan Cheng68333f52010-03-17 23:58:35 +00001329
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001330 int Cost = 0;
Simon Pilgrim7f032312017-05-12 13:08:45 +00001331 SDValue RHS = Handle.getValue().getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001332 // If the RHS involves a register with multiple uses, this
1333 // transformation incurs an extra mov, due to the neg instruction
1334 // clobbering its operand.
1335 if (!RHS.getNode()->hasOneUse() ||
1336 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1337 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1338 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1339 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Simon Pilgrim7f032312017-05-12 13:08:45 +00001340 RHS.getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001341 ++Cost;
1342 // If the base is a register with multiple uses, this
1343 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001344 // FIXME: Don't rely on DELETED_NODEs.
1345 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1346 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001347 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001348 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1349 --Cost;
1350 // If the folded LHS was interesting, this transformation saves
1351 // address arithmetic.
1352 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1353 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1354 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1355 --Cost;
1356 // If it doesn't look like it may be an overall win, don't do it.
1357 if (Cost >= 0) {
1358 AM = Backup;
1359 break;
1360 }
1361
1362 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001363 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001364 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1365 AM.IndexReg = Neg;
1366 AM.Scale = 1;
1367
1368 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001369 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1370 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001371 return false;
1372 }
1373
Sanjay Patelefab8b02015-10-21 18:56:06 +00001374 case ISD::ADD:
1375 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001376 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001377 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001378
Sanjay Patel533c10c2015-11-09 23:31:38 +00001379 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001380 // We want to look through a transform in InstCombine and DAGCombiner that
1381 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001382 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001383 // An 'lea' can then be used to match the shift (multiply) and add:
1384 // and $1, %esi
1385 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001386 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1387 !matchAdd(N, AM, Depth))
1388 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001389 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001390
Evan Cheng827d30d2007-12-13 00:43:27 +00001391 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001392 // Perform some heroic transforms on an and of a constant-count shift
1393 // with a constant to enable use of the scaled offset field.
1394
Evan Cheng827d30d2007-12-13 00:43:27 +00001395 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001396 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001397
Chandler Carruthaa01e662012-01-11 09:35:00 +00001398 SDValue Shift = N.getOperand(0);
1399 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001400 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001401
1402 // We only handle up to 64-bit values here as those are what matter for
1403 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001404 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001405
Chandler Carruthb0049f42012-01-11 09:35:04 +00001406 if (!isa<ConstantSDNode>(N.getOperand(1)))
1407 break;
1408 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001409
Chandler Carruth51d30762012-01-11 08:48:20 +00001410 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001411 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001412 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001413
Chandler Carruth51d30762012-01-11 08:48:20 +00001414 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001415 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001416 return false;
1417
Chandler Carruthaa01e662012-01-11 09:35:00 +00001418 // Try to swap the mask and shift to place shifts which can be done as
1419 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001420 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001421 return false;
1422 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001423 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001424 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001425
Sanjay Patel85030aa2015-10-13 16:23:00 +00001426 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001427}
1428
Sanjay Patelb5723d02015-10-13 15:12:27 +00001429/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001430/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001431bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001432 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001433 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001434 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001435 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001436 AM.IndexReg = N;
1437 AM.Scale = 1;
1438 return false;
1439 }
1440
1441 // Otherwise, we cannot select it.
1442 return true;
1443 }
1444
1445 // Default, generate it as a register.
1446 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001447 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001448 return false;
1449}
1450
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001451template <class GatherScatterSDNode>
1452bool X86DAGToDAGISel::selectAddrOfGatherScatterNode(
1453 GatherScatterSDNode *Mgs, SDValue N, SDValue &Base, SDValue &Scale,
1454 SDValue &Index, SDValue &Disp, SDValue &Segment) {
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001455 X86ISelAddressMode AM;
1456 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001457 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001458 if (AddrSpace == 256)
1459 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1460 if (AddrSpace == 257)
1461 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001462 if (AddrSpace == 258)
1463 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001464
1465 SDLoc DL(N);
1466 Base = Mgs->getBasePtr();
1467 Index = Mgs->getIndex();
Sanjay Patel5f6bb6c2016-09-14 15:43:44 +00001468 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001469 Scale = getI8Imm(ScalarSize/8, DL);
1470
1471 // If Base is 0, the whole address is in index and the Scale is 1
Daniel Jasper232778a2015-04-30 09:01:21 +00001472 if (isa<ConstantSDNode>(Base)) {
Mehdi Amini42152362015-10-21 06:11:01 +00001473 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
Daniel Jasper232778a2015-04-30 09:01:21 +00001474 "Unexpected base in gather/scatter");
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001475 Scale = getI8Imm(1, DL);
1476 Base = CurDAG->getRegister(0, MVT::i32);
1477 }
1478 if (AM.Segment.getNode())
1479 Segment = AM.Segment;
1480 else
1481 Segment = CurDAG->getRegister(0, MVT::i32);
1482 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1483 return true;
1484}
1485
Elena Demikhovsky2dac0b42017-06-22 06:47:41 +00001486bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1487 SDValue &Scale, SDValue &Index,
1488 SDValue &Disp, SDValue &Segment) {
1489 if (auto Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent))
1490 return selectAddrOfGatherScatterNode<MaskedGatherScatterSDNode>(
1491 Mgs, N, Base, Scale, Index, Disp, Segment);
1492 if (auto X86Gather = dyn_cast<X86MaskedGatherSDNode>(Parent))
1493 return selectAddrOfGatherScatterNode<X86MaskedGatherSDNode>(
1494 X86Gather, N, Base, Scale, Index, Disp, Segment);
1495 return false;
1496}
1497
Sanjay Patelb5723d02015-10-13 15:12:27 +00001498/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001499/// It returns the operands which make up the maximal addressing mode it can
1500/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001501///
1502/// Parent is the parent node of the addr operand that is being matched. It
1503/// is always a load, store, atomic node, or null. It is only null when
1504/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001505bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001506 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001507 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001508 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001509
Chris Lattner8a236b62010-09-22 04:39:11 +00001510 if (Parent &&
1511 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1512 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001513 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001514 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001515 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1516 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1517 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001518 unsigned AddrSpace =
1519 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001520 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001521 if (AddrSpace == 256)
1522 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1523 if (AddrSpace == 257)
1524 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001525 if (AddrSpace == 258)
1526 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001527 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001528
Sanjay Patel85030aa2015-10-13 16:23:00 +00001529 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001530 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001531
Craig Topper83e042a2013-08-15 05:57:07 +00001532 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001533 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001534 if (!AM.Base_Reg.getNode())
1535 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001536 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001537
Gabor Greiff304a7a2008-08-28 21:40:38 +00001538 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001539 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001540
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001541 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001542 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001543}
1544
Craig Topper8078dd22017-08-21 16:04:04 +00001545// We can only fold a load if all nodes between it and the root node have a
1546// single use. If there are additional uses, we could end up duplicating the
1547// load.
1548static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *N) {
1549 SDNode *User = *N->use_begin();
1550 while (User != Root) {
1551 if (!User->hasOneUse())
1552 return false;
1553 User = *User->use_begin();
1554 }
1555
1556 return true;
1557}
1558
Sanjay Patelb5723d02015-10-13 15:12:27 +00001559/// Match a scalar SSE load. In particular, we want to match a load whose top
1560/// elements are either undef or zeros. The load flavor is derived from the
1561/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001562///
1563/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001564/// PatternChainNode: this is the matched node that has a chain input and
1565/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001566bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001567 SDValue N, SDValue &Base,
1568 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001569 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001570 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001571 // We can allow a full vector load here since narrowing a load is ok.
1572 if (ISD::isNON_EXTLoad(N.getNode())) {
1573 PatternNodeWithChain = N;
1574 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001575 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1576 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001577 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1578 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1579 Segment);
1580 }
1581 }
1582
1583 // We can also match the special zero extended load opcode.
1584 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1585 PatternNodeWithChain = N;
1586 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001587 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel) &&
1588 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Topper36ecce92016-12-12 07:57:24 +00001589 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1590 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1591 Segment);
1592 }
1593 }
1594
Craig Topper991d1ca2016-11-26 17:29:25 +00001595 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1596 // once. Otherwise the load might get duplicated and the chain output of the
1597 // duplicate load will not be observed by all dependencies.
1598 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001599 PatternNodeWithChain = N.getOperand(0);
1600 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001601 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001602 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1603 hasSingleUsesFromRoot(Root, N.getNode())) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001604 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001605 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1606 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001607 }
1608 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001609
1610 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001611 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001612 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001613 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001614 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001615 N.getOperand(0).getNode()->hasOneUse()) {
1616 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1617 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001618 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper8078dd22017-08-21 16:04:04 +00001619 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel) &&
1620 hasSingleUsesFromRoot(Root, N.getNode())) {
Craig Toppere266e122016-11-26 18:43:24 +00001621 // Okay, this is a zero extending load. Fold it.
1622 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1623 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1624 Segment);
1625 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001626 }
Craig Toppere266e122016-11-26 18:43:24 +00001627
Chris Lattner398195e2006-10-07 21:55:32 +00001628 return false;
1629}
1630
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001631
Sanjay Patel85030aa2015-10-13 16:23:00 +00001632bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001633 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1634 uint64_t ImmVal = CN->getZExtValue();
Craig Topper0a3bceb2017-09-13 02:29:59 +00001635 if (!isUInt<32>(ImmVal))
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001636 return false;
1637
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001638 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001639 return true;
1640 }
1641
1642 // In static codegen with small code model, we can get the address of a label
1643 // into a register with 'movl'. TableGen has already made sure we're looking
1644 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001645 assert(N->getOpcode() == X86ISD::Wrapper &&
1646 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001647 N = N.getOperand(0);
1648
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001649 // At least GNU as does not accept 'movl' for TPOFF relocations.
1650 // FIXME: We could use 'movl' when we know we are targeting MC.
1651 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001652 return false;
1653
1654 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001655 if (N->getOpcode() != ISD::TargetGlobalAddress)
1656 return TM.getCodeModel() == CodeModel::Small;
1657
1658 Optional<ConstantRange> CR =
1659 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1660 if (!CR)
1661 return TM.getCodeModel() == CodeModel::Small;
1662
1663 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001664}
1665
Sanjay Patel85030aa2015-10-13 16:23:00 +00001666bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001667 SDValue &Scale, SDValue &Index,
1668 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001669 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1670 SDLoc DL(N);
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001671
Sanjay Patel85030aa2015-10-13 16:23:00 +00001672 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001673 return false;
1674
Tim Northover6833e3f2013-06-10 20:43:49 +00001675 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1676 if (RN && RN->getReg() == 0)
1677 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001678 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001679 // Base could already be %rip, particularly in the x32 ABI.
1680 Base = SDValue(CurDAG->getMachineNode(
1681 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001682 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001683 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001684 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001685 0);
1686 }
1687
1688 RN = dyn_cast<RegisterSDNode>(Index);
1689 if (RN && RN->getReg() == 0)
1690 Index = CurDAG->getRegister(0, MVT::i64);
1691 else {
1692 assert(Index.getValueType() == MVT::i32 &&
1693 "Expect to be extending 32-bit registers for use in LEA");
1694 Index = SDValue(CurDAG->getMachineNode(
1695 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001696 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001697 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001698 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1699 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001700 0);
1701 }
1702
1703 return true;
1704}
1705
Sanjay Patelb5723d02015-10-13 15:12:27 +00001706/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001707/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001708bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001709 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001710 SDValue &Index, SDValue &Disp,
1711 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001712 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001713
Justin Bogner32ad24d2016-04-12 21:34:24 +00001714 // Save the DL and VT before calling matchAddress, it can invalidate N.
1715 SDLoc DL(N);
1716 MVT VT = N.getSimpleValueType();
1717
Rafael Espindolabb834f02009-04-10 10:09:34 +00001718 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1719 // segments.
1720 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001721 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001722 AM.Segment = T;
Hans Wennborg534bfbd2017-09-15 18:40:26 +00001723 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001724 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001725 assert (T == AM.Segment);
1726 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001727
Evan Cheng77d86ff2006-02-25 10:09:08 +00001728 unsigned Complexity = 0;
1729 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001730 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001731 Complexity = 1;
1732 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001733 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001734 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1735 Complexity = 4;
1736
Gabor Greiff304a7a2008-08-28 21:40:38 +00001737 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001738 Complexity++;
1739 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001740 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001741
Chris Lattner3e1d9172007-03-20 06:08:29 +00001742 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1743 // a simple shift.
1744 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001745 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001746
1747 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001748 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001749 // optimal (especially for code size consideration). LEA is nice because of
1750 // its three-address nature. Tweak the cost function again when we can run
1751 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001752 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001753 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001754 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001755 Complexity = 4;
1756 else
1757 Complexity += 2;
1758 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001759
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001760 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001761 Complexity++;
1762
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001763 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001764 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001765 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001766
Justin Bogner32ad24d2016-04-12 21:34:24 +00001767 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001768 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001769}
1770
Sanjay Patelb5723d02015-10-13 15:12:27 +00001771/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001772bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001773 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001774 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001775 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1776 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001777
Chris Lattner7d2b0492009-06-20 20:38:48 +00001778 X86ISelAddressMode AM;
1779 AM.GV = GA->getGlobal();
1780 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001781 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001782 AM.SymbolFlags = GA->getTargetFlags();
1783
Owen Anderson9f944592009-08-11 20:47:22 +00001784 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001785 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001786 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001787 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001788 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001789 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001790
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001791 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001792 return true;
1793}
1794
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001795bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1796 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1797 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1798 N.getValueType());
1799 return true;
1800 }
1801
Peter Collingbourne235c2752016-12-08 19:01:00 +00001802 // Keep track of the original value type and whether this value was
1803 // truncated. If we see a truncation from pointer type to VT that truncates
1804 // bits that are known to be zero, we can use a narrow reference.
1805 EVT VT = N.getValueType();
1806 bool WasTruncated = false;
1807 if (N.getOpcode() == ISD::TRUNCATE) {
1808 WasTruncated = true;
1809 N = N.getOperand(0);
1810 }
1811
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001812 if (N.getOpcode() != X86ISD::Wrapper)
1813 return false;
1814
Peter Collingbourne235c2752016-12-08 19:01:00 +00001815 // We can only use non-GlobalValues as immediates if they were not truncated,
1816 // as we do not have any range information. If we have a GlobalValue and the
1817 // address was not truncated, we can select it as an operand directly.
1818 unsigned Opc = N.getOperand(0)->getOpcode();
1819 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1820 Op = N.getOperand(0);
1821 // We can only select the operand directly if we didn't have to look past a
1822 // truncate.
1823 return !WasTruncated;
1824 }
1825
1826 // Check that the global's range fits into VT.
1827 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1828 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1829 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1830 return false;
1831
1832 // Okay, we can use a narrow reference.
1833 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1834 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001835 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001836}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001837
Sanjay Patel85030aa2015-10-13 16:23:00 +00001838bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001839 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001840 SDValue &Index, SDValue &Disp,
1841 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001842 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1843 !IsProfitableToFold(N, P, P) ||
Dan Gohman21cea8a2010-04-17 15:26:15 +00001844 !IsLegalToFold(N, P, P, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001845 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001846
Sanjay Patel85030aa2015-10-13 16:23:00 +00001847 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001848 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001849}
1850
Sanjay Patelb5723d02015-10-13 15:12:27 +00001851/// Return an SDNode that returns the value of the global base register.
1852/// Output instructions required to initialize the global base register,
1853/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00001854SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001855 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00001856 auto &DL = MF->getDataLayout();
1857 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001858}
1859
Peter Collingbourneef089bd2017-02-09 22:02:28 +00001860bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1861 if (N->getOpcode() == ISD::TRUNCATE)
1862 N = N->getOperand(0).getNode();
1863 if (N->getOpcode() != X86ISD::Wrapper)
1864 return false;
1865
1866 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1867 if (!GA)
1868 return false;
1869
1870 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1871 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1872 CR->getSignedMax().slt(1ull << Width);
1873}
1874
Sanjay Patelb5723d02015-10-13 15:12:27 +00001875/// Test whether the given X86ISD::CMP node has any uses which require the SF
1876/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001877static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001878 // Examine each user of the node.
1879 for (SDNode::use_iterator UI = N->use_begin(),
1880 UE = N->use_end(); UI != UE; ++UI) {
1881 // Only examine CopyToReg uses.
1882 if (UI->getOpcode() != ISD::CopyToReg)
1883 return false;
1884 // Only examine CopyToReg uses that copy to EFLAGS.
1885 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1886 X86::EFLAGS)
1887 return false;
1888 // Examine each user of the CopyToReg use.
1889 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1890 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1891 // Only examine the Flag result.
1892 if (FlagUI.getUse().getResNo() != 1) continue;
1893 // Anything unusual: assume conservatively.
1894 if (!FlagUI->isMachineOpcode()) return false;
1895 // Examine the opcode of the user.
1896 switch (FlagUI->getMachineOpcode()) {
1897 // These comparisons don't treat the most significant bit specially.
1898 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1899 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1900 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1901 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001902 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1903 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001904 case X86::CMOVA16rr: case X86::CMOVA16rm:
1905 case X86::CMOVA32rr: case X86::CMOVA32rm:
1906 case X86::CMOVA64rr: case X86::CMOVA64rm:
1907 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1908 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1909 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1910 case X86::CMOVB16rr: case X86::CMOVB16rm:
1911 case X86::CMOVB32rr: case X86::CMOVB32rm:
1912 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001913 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1914 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1915 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001916 case X86::CMOVE16rr: case X86::CMOVE16rm:
1917 case X86::CMOVE32rr: case X86::CMOVE32rm:
1918 case X86::CMOVE64rr: case X86::CMOVE64rm:
1919 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1920 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1921 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1922 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1923 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1924 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1925 case X86::CMOVP16rr: case X86::CMOVP16rm:
1926 case X86::CMOVP32rr: case X86::CMOVP32rm:
1927 case X86::CMOVP64rr: case X86::CMOVP64rm:
1928 continue;
1929 // Anything else: assume conservatively.
1930 default: return false;
1931 }
1932 }
1933 }
1934 return true;
1935}
1936
Chandler Carruth52a31bf2017-09-07 23:54:24 +00001937/// Test whether the given node which sets flags has any uses which require the
1938/// CF flag to be accurate.
1939static bool hasNoCarryFlagUses(SDNode *N) {
1940 // Examine each user of the node.
1941 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
1942 ++UI) {
1943 // Only check things that use the flags.
1944 if (UI.getUse().getResNo() != 1)
1945 continue;
1946 // Only examine CopyToReg uses.
1947 if (UI->getOpcode() != ISD::CopyToReg)
1948 return false;
1949 // Only examine CopyToReg uses that copy to EFLAGS.
1950 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
1951 return false;
1952 // Examine each user of the CopyToReg use.
1953 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
1954 FlagUI != FlagUE; ++FlagUI) {
1955 // Only examine the Flag result.
1956 if (FlagUI.getUse().getResNo() != 1)
1957 continue;
1958 // Anything unusual: assume conservatively.
1959 if (!FlagUI->isMachineOpcode())
1960 return false;
1961 // Examine the opcode of the user.
1962 switch (FlagUI->getMachineOpcode()) {
1963 // Comparisons which don't examine the CF flag.
1964 case X86::SETOr: case X86::SETNOr: case X86::SETEr: case X86::SETNEr:
1965 case X86::SETSr: case X86::SETNSr: case X86::SETPr: case X86::SETNPr:
1966 case X86::SETLr: case X86::SETGEr: case X86::SETLEr: case X86::SETGr:
1967 case X86::JO_1: case X86::JNO_1: case X86::JE_1: case X86::JNE_1:
1968 case X86::JS_1: case X86::JNS_1: case X86::JP_1: case X86::JNP_1:
1969 case X86::JL_1: case X86::JGE_1: case X86::JLE_1: case X86::JG_1:
1970 case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
1971 case X86::CMOVO16rm: case X86::CMOVO32rm: case X86::CMOVO64rm:
1972 case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr:
1973 case X86::CMOVNO16rm: case X86::CMOVNO32rm: case X86::CMOVNO64rm:
1974 case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
1975 case X86::CMOVE16rm: case X86::CMOVE32rm: case X86::CMOVE64rm:
1976 case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
1977 case X86::CMOVNE16rm: case X86::CMOVNE32rm: case X86::CMOVNE64rm:
1978 case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
1979 case X86::CMOVS16rm: case X86::CMOVS32rm: case X86::CMOVS64rm:
1980 case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
1981 case X86::CMOVNS16rm: case X86::CMOVNS32rm: case X86::CMOVNS64rm:
1982 case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
1983 case X86::CMOVP16rm: case X86::CMOVP32rm: case X86::CMOVP64rm:
1984 case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
1985 case X86::CMOVNP16rm: case X86::CMOVNP32rm: case X86::CMOVNP64rm:
1986 case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
1987 case X86::CMOVL16rm: case X86::CMOVL32rm: case X86::CMOVL64rm:
1988 case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
1989 case X86::CMOVGE16rm: case X86::CMOVGE32rm: case X86::CMOVGE64rm:
1990 case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
1991 case X86::CMOVLE16rm: case X86::CMOVLE32rm: case X86::CMOVLE64rm:
1992 case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
1993 case X86::CMOVG16rm: case X86::CMOVG32rm: case X86::CMOVG64rm:
1994 continue;
1995 // Anything else: assume conservatively.
1996 default:
1997 return false;
1998 }
1999 }
2000 }
2001 return true;
2002}
2003
Sanjay Patelb5723d02015-10-13 15:12:27 +00002004/// Check whether or not the chain ending in StoreNode is suitable for doing
Chandler Carruth96db3082017-08-25 02:06:36 +00002005/// the {load; op; store} to modify transformation.
2006static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2007 SDValue StoredVal, SelectionDAG *CurDAG,
2008 LoadSDNode *&LoadNode,
2009 SDValue &InputChain) {
Joel Jones68d59e82012-03-29 05:45:48 +00002010 // is the stored value result 0 of the load?
2011 if (StoredVal.getResNo() != 0) return false;
2012
2013 // are there other uses of the loaded value than the inc or dec?
2014 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2015
Joel Jones68d59e82012-03-29 05:45:48 +00002016 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00002017 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00002018 return false;
2019
Evan Cheng3e869f02012-04-12 19:14:21 +00002020 SDValue Load = StoredVal->getOperand(0);
2021 // Is the stored value a non-extending and non-indexed load?
2022 if (!ISD::isNormalLoad(Load.getNode())) return false;
2023
2024 // Return LoadNode by reference.
2025 LoadNode = cast<LoadSDNode>(Load);
Evan Cheng3e869f02012-04-12 19:14:21 +00002026
2027 // Is store the only read of the loaded value?
2028 if (!Load.hasOneUse())
2029 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00002030
Evan Cheng3e869f02012-04-12 19:14:21 +00002031 // Is the address of the store the same as the load?
2032 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2033 LoadNode->getOffset() != StoreNode->getOffset())
2034 return false;
2035
2036 // Check if the chain is produced by the load or is a TokenFactor with
2037 // the load output chain as an operand. Return InputChain by reference.
2038 SDValue Chain = StoreNode->getChain();
2039
2040 bool ChainCheck = false;
2041 if (Chain == Load.getValue(1)) {
2042 ChainCheck = true;
2043 InputChain = LoadNode->getChain();
2044 } else if (Chain.getOpcode() == ISD::TokenFactor) {
2045 SmallVector<SDValue, 4> ChainOps;
2046 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2047 SDValue Op = Chain.getOperand(i);
2048 if (Op == Load.getValue(1)) {
2049 ChainCheck = true;
Nirav Davee14300e2017-02-02 14:39:26 +00002050 // Drop Load, but keep its chain. No cycle check necessary.
2051 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00002052 continue;
2053 }
Evan Cheng58a95f02012-05-16 01:54:27 +00002054
2055 // Make sure using Op as part of the chain would not cause a cycle here.
2056 // In theory, we could check whether the chain node is a predecessor of
2057 // the load. But that can be very expensive. Instead visit the uses and
2058 // make sure they all have smaller node id than the load.
2059 int LoadId = LoadNode->getNodeId();
2060 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2061 UE = UI->use_end(); UI != UE; ++UI) {
2062 if (UI.getUse().getResNo() != 0)
2063 continue;
2064 if (UI->getNodeId() > LoadId)
2065 return false;
2066 }
2067
Evan Cheng3e869f02012-04-12 19:14:21 +00002068 ChainOps.push_back(Op);
2069 }
2070
2071 if (ChainCheck)
2072 // Make a new TokenFactor with all the other input chains except
2073 // for the load.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002074 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
Craig Topper48d114b2014-04-26 18:35:24 +00002075 MVT::Other, ChainOps);
Evan Cheng3e869f02012-04-12 19:14:21 +00002076 }
2077 if (!ChainCheck)
Joel Jones68d59e82012-03-29 05:45:48 +00002078 return false;
2079
2080 return true;
2081}
2082
Chandler Carruth4b611a82017-08-25 22:50:52 +00002083// Change a chain of {load; op; store} of the same value into a simple op
2084// through memory of that value, if the uses of the modified value and its
2085// address are suitable.
2086//
2087// The tablegen pattern memory operand pattern is currently not able to match
2088// the case where the EFLAGS on the original operation are used.
2089//
2090// To move this to tablegen, we'll need to improve tablegen to allow flags to
2091// be transferred from a node in the pattern to the result node, probably with
2092// a new keyword. For example, we have this
Chandler Carruth03258f22017-08-25 02:04:03 +00002093// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2094// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2095// (implicit EFLAGS)]>;
2096// but maybe need something like this
2097// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2098// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2099// (transferrable EFLAGS)]>;
2100//
Chandler Carruth4b611a82017-08-25 22:50:52 +00002101// Until then, we manually fold these and instruction select the operation
2102// here.
Chandler Carruth03258f22017-08-25 02:04:03 +00002103bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2104 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2105 SDValue StoredVal = StoreNode->getOperand(1);
2106 unsigned Opc = StoredVal->getOpcode();
2107
Chandler Carruth4b611a82017-08-25 22:50:52 +00002108 // Before we try to select anything, make sure this is memory operand size
2109 // and opcode we can handle. Note that this must match the code below that
2110 // actually lowers the opcodes.
Chandler Carruth96db3082017-08-25 02:06:36 +00002111 EVT MemVT = StoreNode->getMemoryVT();
Chandler Carruth4b611a82017-08-25 22:50:52 +00002112 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2113 MemVT != MVT::i8)
Chandler Carruth96db3082017-08-25 02:06:36 +00002114 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002115 switch (Opc) {
2116 default:
Chandler Carruth96db3082017-08-25 02:06:36 +00002117 return false;
Chandler Carruth4b611a82017-08-25 22:50:52 +00002118 case X86ISD::INC:
2119 case X86ISD::DEC:
2120 case X86ISD::ADD:
2121 case X86ISD::SUB:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002122 case X86ISD::AND:
2123 case X86ISD::OR:
2124 case X86ISD::XOR:
Chandler Carruth4b611a82017-08-25 22:50:52 +00002125 break;
2126 }
Chandler Carruth96db3082017-08-25 02:06:36 +00002127
Chandler Carruth03258f22017-08-25 02:04:03 +00002128 LoadSDNode *LoadNode = nullptr;
2129 SDValue InputChain;
Chandler Carruth96db3082017-08-25 02:06:36 +00002130 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadNode,
2131 InputChain))
Chandler Carruth03258f22017-08-25 02:04:03 +00002132 return false;
2133
2134 SDValue Base, Scale, Index, Disp, Segment;
2135 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2136 Segment))
2137 return false;
2138
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002139 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
Chandler Carruth38e2b502017-09-08 18:23:42 +00002140 unsigned Opc8) {
Chandler Carruth4b611a82017-08-25 22:50:52 +00002141 switch (MemVT.getSimpleVT().SimpleTy) {
2142 case MVT::i64:
2143 return Opc64;
2144 case MVT::i32:
2145 return Opc32;
2146 case MVT::i16:
2147 return Opc16;
2148 case MVT::i8:
2149 return Opc8;
2150 default:
2151 llvm_unreachable("Invalid size!");
2152 }
2153 };
2154
2155 MachineSDNode *Result;
2156 switch (Opc) {
2157 case X86ISD::INC:
2158 case X86ISD::DEC: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002159 unsigned NewOpc =
2160 Opc == X86ISD::INC
2161 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2162 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
Chandler Carruth4b611a82017-08-25 22:50:52 +00002163 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2164 Result =
2165 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2166 break;
2167 }
2168 case X86ISD::ADD:
Chandler Carruthacbcf062017-09-08 00:17:12 +00002169 case X86ISD::SUB:
2170 case X86ISD::AND:
2171 case X86ISD::OR:
2172 case X86ISD::XOR: {
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002173 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2174 switch (Opc) {
2175 case X86ISD::ADD:
2176 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2177 X86::ADD8mr);
2178 case X86ISD::SUB:
2179 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2180 X86::SUB8mr);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002181 case X86ISD::AND:
2182 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2183 X86::AND8mr);
2184 case X86ISD::OR:
2185 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2186 case X86ISD::XOR:
2187 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2188 X86::XOR8mr);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002189 default:
2190 llvm_unreachable("Invalid opcode!");
2191 }
2192 };
2193 auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2194 switch (Opc) {
2195 case X86ISD::ADD:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002196 return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002197 case X86ISD::SUB:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002198 return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002199 case X86ISD::AND:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002200 return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002201 case X86ISD::OR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002202 return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002203 case X86ISD::XOR:
Chandler Carruth38e2b502017-09-08 18:23:42 +00002204 return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002205 default:
2206 llvm_unreachable("Invalid opcode!");
2207 }
2208 };
2209 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2210 switch (Opc) {
2211 case X86ISD::ADD:
2212 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2213 X86::ADD8mi);
2214 case X86ISD::SUB:
2215 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2216 X86::SUB8mi);
Chandler Carruthacbcf062017-09-08 00:17:12 +00002217 case X86ISD::AND:
2218 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2219 X86::AND8mi);
2220 case X86ISD::OR:
2221 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2222 X86::OR8mi);
2223 case X86ISD::XOR:
2224 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2225 X86::XOR8mi);
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002226 default:
2227 llvm_unreachable("Invalid opcode!");
2228 }
2229 };
2230
2231 unsigned NewOpc = SelectRegOpcode(Opc);
2232 SDValue Operand = StoredVal->getOperand(1);
2233
2234 // See if the operand is a constant that we can fold into an immediate
2235 // operand.
2236 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2237 auto OperandV = OperandC->getAPIntValue();
2238
2239 // Check if we can shrink the operand enough to fit in an immediate (or
2240 // fit into a smaller immediate) by negating it and switching the
2241 // operation.
Chandler Carruthacbcf062017-09-08 00:17:12 +00002242 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2243 ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
Chandler Carruth52a31bf2017-09-07 23:54:24 +00002244 (-OperandV).getMinSignedBits() <= 8) ||
2245 (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2246 (-OperandV).getMinSignedBits() <= 32)) &&
2247 hasNoCarryFlagUses(StoredVal.getNode())) {
2248 OperandV = -OperandV;
2249 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2250 }
2251
2252 // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2253 // the larger immediate operand.
2254 if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2255 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2256 NewOpc = SelectImm8Opcode(Opc);
2257 } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2258 (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2259 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2260 NewOpc = SelectImmOpcode(Opc);
2261 }
2262 }
2263
2264 const SDValue Ops[] = {Base, Scale, Index, Disp,
2265 Segment, Operand, InputChain};
Chandler Carruth4b611a82017-08-25 22:50:52 +00002266 Result =
2267 CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, Ops);
2268 break;
2269 }
2270 default:
2271 llvm_unreachable("Invalid opcode!");
2272 }
2273
Chandler Carruth03258f22017-08-25 02:04:03 +00002274 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2275 MemOp[0] = StoreNode->getMemOperand();
2276 MemOp[1] = LoadNode->getMemOperand();
Chandler Carruth03258f22017-08-25 02:04:03 +00002277 Result->setMemRefs(MemOp, MemOp + 2);
2278
2279 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2280 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2281 CurDAG->RemoveDeadNode(Node);
2282 return true;
2283}
2284
Craig Topper958106d2017-09-12 17:40:25 +00002285// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
2286bool X86DAGToDAGISel::matchBEXTRFromAnd(SDNode *Node) {
2287 MVT NVT = Node->getSimpleValueType(0);
2288 SDLoc dl(Node);
2289
2290 SDValue N0 = Node->getOperand(0);
2291 SDValue N1 = Node->getOperand(1);
2292
2293 if (!Subtarget->hasBMI() && !Subtarget->hasTBM())
2294 return false;
2295
2296 // Must have a shift right.
2297 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
2298 return false;
2299
2300 // Shift can't have additional users.
2301 if (!N0->hasOneUse())
2302 return false;
2303
2304 // Only supported for 32 and 64 bits.
2305 if (NVT != MVT::i32 && NVT != MVT::i64)
2306 return false;
2307
2308 // Shift amount and RHS of and must be constant.
2309 ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
2310 ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2311 if (!MaskCst || !ShiftCst)
2312 return false;
2313
2314 // And RHS must be a mask.
2315 uint64_t Mask = MaskCst->getZExtValue();
2316 if (!isMask_64(Mask))
2317 return false;
2318
2319 uint64_t Shift = ShiftCst->getZExtValue();
2320 uint64_t MaskSize = countPopulation(Mask);
2321
2322 // Don't interfere with something that can be handled by extracting AH.
2323 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
2324 if (Shift == 8 && MaskSize == 8)
2325 return false;
2326
2327 // Make sure we are only using bits that were in the original value, not
2328 // shifted in.
2329 if (Shift + MaskSize > NVT.getSizeInBits())
2330 return false;
2331
2332 SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
2333 unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
2334 unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
2335
2336 // BMI requires the immediate to placed in a register.
2337 if (!Subtarget->hasTBM()) {
2338 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
2339 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
Craig Topper2b6bfda2017-09-13 07:53:21 +00002340 New = SDValue(CurDAG->getMachineNode(X86::MOV32ri, dl, NVT, New), 0);
2341 if (NVT == MVT::i64) {
2342 New =
2343 SDValue(CurDAG->getMachineNode(
2344 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2345 CurDAG->getTargetConstant(0, dl, MVT::i64), New,
2346 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
2347 0);
2348 }
Craig Topper958106d2017-09-12 17:40:25 +00002349 }
2350
2351 MachineSDNode *NewNode;
2352 SDValue Input = N0->getOperand(0);
2353 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2354 if (tryFoldLoad(Node, Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2355 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
2356 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
2357 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2358 // Update the chain.
2359 ReplaceUses(N1.getValue(1), SDValue(NewNode, 1));
2360 // Record the mem-refs
2361 LoadSDNode *LoadNode = cast<LoadSDNode>(Input);
2362 if (LoadNode) {
2363 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2364 MemOp[0] = LoadNode->getMemOperand();
2365 NewNode->setMemRefs(MemOp, MemOp + 1);
2366 }
2367 } else {
2368 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
2369 }
2370
2371 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
2372 CurDAG->RemoveDeadNode(Node);
2373 return true;
2374}
2375
Justin Bogner593741d2016-05-10 23:55:37 +00002376void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00002377 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00002378 unsigned Opc, MOpc;
2379 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002380 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00002381
Chris Lattnerf98f1242010-03-02 06:34:30 +00002382 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
Evan Chengd49cc362006-02-10 22:24:32 +00002383
Dan Gohman17059682008-07-17 19:10:17 +00002384 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00002385 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00002386 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00002387 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00002388 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002389
Evan Cheng10d27902006-01-06 20:36:21 +00002390 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002391 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002392 case ISD::BRIND: {
2393 if (Subtarget->isTargetNaCl())
2394 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2395 // leave the instruction alone.
2396 break;
2397 if (Subtarget->isTarget64BitILP32()) {
2398 // Converts a 32-bit register to a 64-bit, zero-extended version of
2399 // it. This is needed because x86-64 can do many things, but jmp %r32
2400 // ain't one of them.
2401 const SDValue &Target = Node->getOperand(1);
2402 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2403 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2404 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2405 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002406 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002407 SelectCode(ZextTarget.getNode());
2408 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002409 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002410 }
2411 break;
2412 }
Dan Gohman757eee82009-08-02 16:10:52 +00002413 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002414 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002415 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002416
Craig Topper75370b92017-09-19 17:19:45 +00002417 case X86ISD::SELECT:
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002418 case X86ISD::SHRUNKBLEND: {
Craig Topper75370b92017-09-19 17:19:45 +00002419 // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002420 SDValue VSelect = CurDAG->getNode(
2421 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2422 Node->getOperand(1), Node->getOperand(2));
Craig Topper63c50472017-09-09 05:57:19 +00002423 ReplaceNode(Node, VSelect.getNode());
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002424 SelectCode(VSelect.getNode());
2425 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002426 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002427 }
Craig Topper3af251d2012-07-01 02:55:34 +00002428
Tobias Grosser85508e82015-08-19 11:35:10 +00002429 case ISD::AND:
Craig Topper958106d2017-09-12 17:40:25 +00002430 // Try to match BEXTR/BEXTRI instruction.
2431 if (matchBEXTRFromAnd(Node))
2432 return;
2433
2434 LLVM_FALLTHROUGH;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002435 case ISD::OR:
2436 case ISD::XOR: {
Craig Topper958106d2017-09-12 17:40:25 +00002437
Benjamin Kramer4c816242011-04-22 15:30:40 +00002438 // For operations of the form (x << C1) op C2, check if we can use a smaller
2439 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2440 SDValue N0 = Node->getOperand(0);
2441 SDValue N1 = Node->getOperand(1);
2442
2443 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2444 break;
2445
2446 // i8 is unshrinkable, i16 should be promoted to i32.
2447 if (NVT != MVT::i32 && NVT != MVT::i64)
2448 break;
2449
2450 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2451 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2452 if (!Cst || !ShlCst)
2453 break;
2454
2455 int64_t Val = Cst->getSExtValue();
2456 uint64_t ShlVal = ShlCst->getZExtValue();
2457
2458 // Make sure that we don't change the operation by removing bits.
2459 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002460 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2461 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002462 break;
2463
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002464 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002465 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002466
2467 // Check the minimum bitwidth for the new constant.
2468 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2469 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2470 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2471 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2472 CstVT = MVT::i8;
2473 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2474 CstVT = MVT::i32;
2475
2476 // Bail if there is no smaller encoding.
2477 if (NVT == CstVT)
2478 break;
2479
Craig Topper83e042a2013-08-15 05:57:07 +00002480 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002481 default: llvm_unreachable("Unsupported VT!");
2482 case MVT::i32:
2483 assert(CstVT == MVT::i8);
2484 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002485 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002486
2487 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002488 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002489 case ISD::AND: Op = X86::AND32ri8; break;
2490 case ISD::OR: Op = X86::OR32ri8; break;
2491 case ISD::XOR: Op = X86::XOR32ri8; break;
2492 }
2493 break;
2494 case MVT::i64:
2495 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2496 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002497 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002498
2499 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002500 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002501 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2502 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2503 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2504 }
2505 break;
2506 }
2507
2508 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002509 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002510 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002511 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002512 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2513 SDValue(New, 0));
2514 else
2515 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2516 getI8Imm(ShlVal, dl));
2517 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002518 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002519 case X86ISD::UMUL8:
2520 case X86ISD::SMUL8: {
2521 SDValue N0 = Node->getOperand(0);
2522 SDValue N1 = Node->getOperand(1);
2523
2524 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2525
2526 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2527 N0, SDValue()).getValue(1);
2528
2529 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2530 SDValue Ops[] = {N1, InFlag};
2531 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2532
Justin Bogner31d7da32016-05-11 21:13:17 +00002533 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002534 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002535 }
2536
Chris Lattner364bb0a2010-12-05 07:30:36 +00002537 case X86ISD::UMUL: {
2538 SDValue N0 = Node->getOperand(0);
2539 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002540
Ted Kremenekb5241b22011-01-14 22:34:13 +00002541 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002542 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002543 default: llvm_unreachable("Unsupported VT!");
Ted Kremenekb5241b22011-01-14 22:34:13 +00002544 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2545 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2546 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2547 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002548 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002549
Chris Lattner364bb0a2010-12-05 07:30:36 +00002550 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2551 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002552
Chris Lattner364bb0a2010-12-05 07:30:36 +00002553 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2554 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002555 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002556
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002557 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002558 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002559 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002560
Dan Gohman757eee82009-08-02 16:10:52 +00002561 case ISD::SMUL_LOHI:
2562 case ISD::UMUL_LOHI: {
2563 SDValue N0 = Node->getOperand(0);
2564 SDValue N1 = Node->getOperand(1);
2565
2566 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002567 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002568 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002569 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002570 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002571 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2572 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002573 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2574 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2575 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2576 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002577 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002578 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002579 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002580 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002581 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2582 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2583 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2584 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002585 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002586 }
Dan Gohman757eee82009-08-02 16:10:52 +00002587
Michael Liaof9f7b552012-09-26 08:22:37 +00002588 unsigned SrcReg, LoReg, HiReg;
2589 switch (Opc) {
2590 default: llvm_unreachable("Unknown MUL opcode!");
2591 case X86::IMUL8r:
2592 case X86::MUL8r:
2593 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2594 break;
2595 case X86::IMUL16r:
2596 case X86::MUL16r:
2597 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2598 break;
2599 case X86::IMUL32r:
2600 case X86::MUL32r:
2601 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2602 break;
2603 case X86::IMUL64r:
2604 case X86::MUL64r:
2605 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2606 break;
2607 case X86::MULX32rr:
2608 SrcReg = X86::EDX; LoReg = HiReg = 0;
2609 break;
2610 case X86::MULX64rr:
2611 SrcReg = X86::RDX; LoReg = HiReg = 0;
2612 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002613 }
2614
2615 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002616 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002617 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002618 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002619 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002620 if (foldedLoad)
2621 std::swap(N0, N1);
2622 }
2623
Michael Liaof9f7b552012-09-26 08:22:37 +00002624 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002625 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002626 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002627
2628 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002629 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002630 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002631 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2632 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002633 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2634 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002635 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002636 ResHi = SDValue(CNode, 0);
2637 ResLo = SDValue(CNode, 1);
2638 Chain = SDValue(CNode, 2);
2639 InFlag = SDValue(CNode, 3);
2640 } else {
2641 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002642 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002643 Chain = SDValue(CNode, 0);
2644 InFlag = SDValue(CNode, 1);
2645 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002646
Dan Gohman757eee82009-08-02 16:10:52 +00002647 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002648 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002649 // Record the mem-refs
2650 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2651 if (LoadNode) {
2652 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2653 MemOp[0] = LoadNode->getMemOperand();
2654 CNode->setMemRefs(MemOp, MemOp + 1);
2655 }
Dan Gohman757eee82009-08-02 16:10:52 +00002656 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002657 SDValue Ops[] = { N1, InFlag };
2658 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2659 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002660 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002661 ResHi = SDValue(CNode, 0);
2662 ResLo = SDValue(CNode, 1);
2663 InFlag = SDValue(CNode, 2);
2664 } else {
2665 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002666 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002667 InFlag = SDValue(CNode, 0);
2668 }
Dan Gohman757eee82009-08-02 16:10:52 +00002669 }
2670
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002671 // Prevent use of AH in a REX instruction by referencing AX instead.
2672 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2673 !SDValue(Node, 1).use_empty()) {
2674 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2675 X86::AX, MVT::i16, InFlag);
2676 InFlag = Result.getValue(2);
2677 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2678 // registers.
2679 if (!SDValue(Node, 0).use_empty())
2680 ReplaceUses(SDValue(Node, 1),
2681 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2682
2683 // Shift AX down 8 bits.
2684 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2685 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002686 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2687 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002688 // Then truncate it down to i8.
2689 ReplaceUses(SDValue(Node, 1),
2690 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2691 }
Dan Gohman757eee82009-08-02 16:10:52 +00002692 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002693 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002694 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002695 assert(LoReg && "Register for low half is not defined!");
2696 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2697 InFlag);
2698 InFlag = ResLo.getValue(2);
2699 }
2700 ReplaceUses(SDValue(Node, 0), ResLo);
2701 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002702 }
2703 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002704 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002705 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002706 assert(HiReg && "Register for high half is not defined!");
2707 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2708 InFlag);
2709 InFlag = ResHi.getValue(2);
2710 }
2711 ReplaceUses(SDValue(Node, 1), ResHi);
2712 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002713 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002714
Craig Topper6bed9de2017-09-09 05:57:20 +00002715 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002716 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002717 }
2718
2719 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002720 case ISD::UDIVREM:
2721 case X86ISD::SDIVREM8_SEXT_HREG:
2722 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002723 SDValue N0 = Node->getOperand(0);
2724 SDValue N1 = Node->getOperand(1);
2725
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002726 bool isSigned = (Opcode == ISD::SDIVREM ||
2727 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002728 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002729 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002730 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002731 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2732 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2733 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2734 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002735 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002736 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002737 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002738 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002739 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2740 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2741 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2742 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002743 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002744 }
Dan Gohman757eee82009-08-02 16:10:52 +00002745
Chris Lattner518b0372009-12-23 01:45:04 +00002746 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002747 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002748 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002749 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002750 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002751 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002752 SExtOpcode = X86::CBW;
2753 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002754 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002755 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002756 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002757 SExtOpcode = X86::CWD;
2758 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002759 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002760 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002761 SExtOpcode = X86::CDQ;
2762 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002763 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002764 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002765 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002766 break;
2767 }
2768
Dan Gohman757eee82009-08-02 16:10:52 +00002769 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002770 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002771 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002772
Dan Gohman757eee82009-08-02 16:10:52 +00002773 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002774 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002775 // Special case for div8, just use a move with zero extension to AX to
2776 // clear the upper 8 bits (AH).
2777 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002778 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002779 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2780 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002781 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002782 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002783 Chain = Move.getValue(1);
2784 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002785 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002786 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002787 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002788 Chain = CurDAG->getEntryNode();
2789 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002790 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002791 InFlag = Chain.getValue(1);
2792 } else {
2793 InFlag =
2794 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2795 LoReg, N0, SDValue()).getValue(1);
2796 if (isSigned && !signBitIsZero) {
2797 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002798 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002799 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002800 } else {
2801 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002802 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002803 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002804 case MVT::i16:
2805 ClrNode =
2806 SDValue(CurDAG->getMachineNode(
2807 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002808 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2809 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002810 0);
2811 break;
2812 case MVT::i32:
2813 break;
2814 case MVT::i64:
2815 ClrNode =
2816 SDValue(CurDAG->getMachineNode(
2817 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002818 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2819 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2820 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002821 0);
2822 break;
2823 default:
2824 llvm_unreachable("Unexpected division source");
2825 }
2826
Chris Lattner518b0372009-12-23 01:45:04 +00002827 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00002828 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00002829 }
Evan Cheng92e27972006-01-06 23:19:29 +00002830 }
Dan Gohmana1603612007-10-08 18:33:35 +00002831
Dan Gohman757eee82009-08-02 16:10:52 +00002832 if (foldedLoad) {
2833 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2834 InFlag };
2835 SDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00002836 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00002837 InFlag = SDValue(CNode, 1);
2838 // Update the chain.
2839 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2840 } else {
2841 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002842 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002843 }
Evan Cheng92e27972006-01-06 23:19:29 +00002844
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002845 // Prevent use of AH in a REX instruction by explicitly copying it to
2846 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00002847 //
2848 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002849 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00002850 // the allocator and/or the backend get enhanced to be more robust in
2851 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002852 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2853 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2854 unsigned AHExtOpcode =
2855 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002856
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002857 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2858 MVT::Glue, AHCopy, InFlag);
2859 SDValue Result(RNode, 0);
2860 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002861
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002862 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2863 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2864 if (Node->getValueType(1) == MVT::i64) {
2865 // It's not possible to directly movsx AH to a 64bit register, because
2866 // the latter needs the REX prefix, but the former can't have it.
2867 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2868 "Unexpected i64 sext of h-register");
2869 Result =
2870 SDValue(CurDAG->getMachineNode(
2871 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002872 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2873 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2874 MVT::i32)),
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002875 0);
2876 }
2877 } else {
2878 Result =
2879 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2880 }
2881 ReplaceUses(SDValue(Node, 1), Result);
2882 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002883 }
Dan Gohman757eee82009-08-02 16:10:52 +00002884 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002885 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00002886 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2887 LoReg, NVT, InFlag);
2888 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002889 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002890 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002891 }
2892 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002893 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002894 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2895 HiReg, NVT, InFlag);
2896 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002897 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002898 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002899 }
Craig Topper6bed9de2017-09-09 05:57:20 +00002900 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002901 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002902 }
2903
Manman Ren1be131b2012-08-08 00:51:41 +00002904 case X86ISD::CMP:
2905 case X86ISD::SUB: {
2906 // Sometimes a SUB is used to perform comparison.
2907 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2908 // This node is not a CMP.
2909 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00002910 SDValue N0 = Node->getOperand(0);
2911 SDValue N1 = Node->getOperand(1);
2912
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002913 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00002914 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002915 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002916
Dan Gohmanac33a902009-08-19 18:16:17 +00002917 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2918 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002919 // Look past the truncate if CMP is the only use of it.
Craig Topperc93d05562017-08-25 05:36:29 +00002920 if ((N0.getOpcode() == ISD::AND ||
2921 (N0.getResNo() == 0 && N0.getOpcode() == X86ISD::AND)) &&
Dan Gohman198b7ff2011-11-03 21:49:52 +00002922 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00002923 N0.getValueType() != MVT::i8 &&
2924 X86::isZeroNode(N1)) {
Simon Pilgrim7f032312017-05-12 13:08:45 +00002925 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Dan Gohmanac33a902009-08-19 18:16:17 +00002926 if (!C) break;
Craig Topperfc53dc22017-08-25 05:04:34 +00002927 uint64_t Mask = C->getZExtValue();
Dan Gohmanac33a902009-08-19 18:16:17 +00002928
2929 // For example, convert "testl %eax, $8" to "testb %al, $8"
Craig Topperfc53dc22017-08-25 05:04:34 +00002930 if (isUInt<8>(Mask) &&
2931 (!(Mask & 0x80) || hasNoSignedComparisonUses(Node))) {
2932 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002933 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002934
Dan Gohmanac33a902009-08-19 18:16:17 +00002935 // Extract the l-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002936 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002937 MVT::i8, Reg);
2938
2939 // Emit a testb.
Manman Ren511c6d02012-09-28 18:53:24 +00002940 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2941 Subreg, Imm);
2942 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2943 // one, do not call ReplaceAllUsesWith.
2944 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2945 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00002946 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002947 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002948 }
2949
2950 // For example, "testl %eax, $2048" to "testb %ah, $8".
Craig Topperfc53dc22017-08-25 05:04:34 +00002951 if (isShiftedUInt<8, 8>(Mask) &&
2952 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002953 // Shift the immediate right by 8 bits.
Craig Topperfc53dc22017-08-25 05:04:34 +00002954 SDValue ShiftedImm = CurDAG->getTargetConstant(Mask >> 8, dl, MVT::i8);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002955 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002956
Dan Gohmanac33a902009-08-19 18:16:17 +00002957 // Extract the h-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002958 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002959 MVT::i8, Reg);
2960
Jakob Stoklund Olesen729abd32011-10-08 18:28:28 +00002961 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2962 // target GR8_NOREX registers, so make sure the register class is
2963 // forced.
Manman Ren511c6d02012-09-28 18:53:24 +00002964 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2965 MVT::i32, Subreg, ShiftedImm);
2966 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2967 // one, do not call ReplaceAllUsesWith.
2968 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2969 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00002970 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002971 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002972 }
2973
2974 // For example, "testl %eax, $32776" to "testw %ax, $32776".
Craig Topperfc53dc22017-08-25 05:04:34 +00002975 if (isUInt<16>(Mask) && N0.getValueType() != MVT::i16 &&
2976 (!(Mask & 0x8000) || hasNoSignedComparisonUses(Node))) {
2977 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i16);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002978 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002979
2980 // Extract the 16-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002981 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002982 MVT::i16, Reg);
2983
2984 // Emit a testw.
Manman Ren511c6d02012-09-28 18:53:24 +00002985 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2986 Subreg, Imm);
2987 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2988 // one, do not call ReplaceAllUsesWith.
2989 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2990 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00002991 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00002992 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002993 }
2994
2995 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
Craig Topperfc53dc22017-08-25 05:04:34 +00002996 if (isUInt<32>(Mask) && N0.getValueType() == MVT::i64 &&
2997 (!(Mask & 0x80000000) || hasNoSignedComparisonUses(Node))) {
2998 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
Simon Pilgrim7f032312017-05-12 13:08:45 +00002999 SDValue Reg = N0.getOperand(0);
Dan Gohmanac33a902009-08-19 18:16:17 +00003000
3001 // Extract the 32-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00003002 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00003003 MVT::i32, Reg);
3004
3005 // Emit a testl.
Manman Ren511c6d02012-09-28 18:53:24 +00003006 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
3007 Subreg, Imm);
3008 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
3009 // one, do not call ReplaceAllUsesWith.
3010 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
3011 SDValue(NewNode, 0));
Craig Topper6bed9de2017-09-09 05:57:20 +00003012 CurDAG->RemoveDeadNode(Node);
Justin Bogner593741d2016-05-10 23:55:37 +00003013 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00003014 }
3015 }
3016 break;
3017 }
Chandler Carruth03258f22017-08-25 02:04:03 +00003018 case ISD::STORE:
3019 if (foldLoadStoreIntoMemOperand(Node))
3020 return;
3021 break;
Chris Lattner655e7df2005-11-16 01:54:32 +00003022 }
3023
Justin Bogner593741d2016-05-10 23:55:37 +00003024 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00003025}
3026
Chris Lattnerba1ed582006-06-08 18:03:49 +00003027bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00003028SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00003029 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00003030 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003031 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00003032 default:
3033 llvm_unreachable("Unexpected asm memory constraint");
3034 case InlineAsm::Constraint_i:
3035 // FIXME: It seems strange that 'i' is needed here since it's supposed to
3036 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00003037 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00003038 case InlineAsm::Constraint_o: // offsetable ??
3039 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00003040 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00003041 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00003042 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00003043 return true;
3044 break;
3045 }
Chad Rosier24c19d22012-08-01 18:39:17 +00003046
Evan Cheng2d487222006-08-26 01:05:16 +00003047 OutOps.push_back(Op0);
3048 OutOps.push_back(Op1);
3049 OutOps.push_back(Op2);
3050 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00003051 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00003052 return false;
3053}
3054
Sanjay Patelb5723d02015-10-13 15:12:27 +00003055/// This pass converts a legalized DAG into a X86-specific DAG,
3056/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00003057FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00003058 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00003059 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00003060}