blob: 12a10bf3072ffcc07be51ef7745743f596b9ac7a [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),
168 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);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000207 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
208 bool selectLEAAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000209 SDValue &Scale, SDValue &Index, SDValue &Disp,
210 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000211 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +0000212 SDValue &Scale, SDValue &Index, SDValue &Disp,
213 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000214 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattnerf4693072010-07-08 23:46:44 +0000215 SDValue &Scale, SDValue &Index, SDValue &Disp,
216 SDValue &Segment);
Sanjay Patel85030aa2015-10-13 16:23:00 +0000217 bool selectScalarSSELoad(SDNode *Root, SDValue N,
Chris Lattnerafac7dad2010-02-16 22:35:06 +0000218 SDValue &Base, SDValue &Scale,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000219 SDValue &Index, SDValue &Disp,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000220 SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +0000221 SDValue &NodeWithChain);
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000222 bool selectRelocImm(SDValue N, SDValue &Op);
Chad Rosier24c19d22012-08-01 18:39:17 +0000223
Sanjay Patel85030aa2015-10-13 16:23:00 +0000224 bool tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000225 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +0000226 SDValue &Index, SDValue &Disp,
227 SDValue &Segment);
Chad Rosier24c19d22012-08-01 18:39:17 +0000228
Sanjay Patelb5723d02015-10-13 15:12:27 +0000229 /// Implement addressing mode selection for inline asm expressions.
Craig Topper2d9361e2014-03-09 07:44:38 +0000230 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000231 unsigned ConstraintID,
Craig Topper2d9361e2014-03-09 07:44:38 +0000232 std::vector<SDValue> &OutOps) override;
Chad Rosier24c19d22012-08-01 18:39:17 +0000233
Sanjay Patel85030aa2015-10-13 16:23:00 +0000234 void emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000235
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000236 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000237 SDValue &Base, SDValue &Scale,
238 SDValue &Index, SDValue &Disp,
239 SDValue &Segment) {
Eric Christopherb17140d2014-10-08 07:32:17 +0000240 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
Mehdi Amini44ede332015-07-09 02:09:04 +0000241 ? CurDAG->getTargetFrameIndex(
242 AM.Base_FrameIndex,
243 TLI->getPointerTy(CurDAG->getDataLayout()))
Eric Christopherb17140d2014-10-08 07:32:17 +0000244 : AM.Base_Reg;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000245 Scale = getI8Imm(AM.Scale, DL);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000246 Index = AM.IndexReg;
Sanjay Patelb5723d02015-10-13 15:12:27 +0000247 // These are 32-bit even in 64-bit mode since RIP-relative offset
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000248 // is 32-bit.
249 if (AM.GV)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000250 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
Devang Patela3ca21b2010-07-06 22:08:15 +0000251 MVT::i32, AM.Disp,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000252 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000253 else if (AM.CP)
Owen Anderson9f944592009-08-11 20:47:22 +0000254 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000255 AM.Align, AM.Disp, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000256 else if (AM.ES) {
257 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
Owen Anderson9f944592009-08-11 20:47:22 +0000258 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
Rafael Espindola36b718f2015-06-22 17:46:53 +0000259 } else if (AM.MCSym) {
260 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
261 assert(AM.SymbolFlags == 0 && "oo");
262 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
Michael Liaoabb87d42012-09-12 21:43:09 +0000263 } else if (AM.JT != -1) {
264 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
Owen Anderson9f944592009-08-11 20:47:22 +0000265 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
Michael Liaoabb87d42012-09-12 21:43:09 +0000266 } else if (AM.BlockAddr)
267 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
268 AM.SymbolFlags);
Evan Cheng11b0a5d2006-09-08 06:48:29 +0000269 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000270 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
Rafael Espindola3b2df102009-04-08 21:14:34 +0000271
272 if (AM.Segment.getNode())
273 Segment = AM.Segment;
274 else
Owen Anderson9f944592009-08-11 20:47:22 +0000275 Segment = CurDAG->getRegister(0, MVT::i32);
Evan Cheng67ed58e2005-12-12 21:49:40 +0000276 }
277
Michael Kuperstein243c0732015-08-11 14:10:58 +0000278 // Utility function to determine whether we should avoid selecting
279 // immediate forms of instructions for better code size or not.
280 // At a high level, we'd like to avoid such instructions when
281 // we have similar constants used within the same basic block
282 // that can be kept in a register.
283 //
284 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
285 uint32_t UseCount = 0;
286
287 // Do not want to hoist if we're not optimizing for size.
288 // TODO: We'd like to remove this restriction.
289 // See the comment in X86InstrInfo.td for more info.
290 if (!OptForSize)
291 return false;
292
293 // Walk all the users of the immediate.
294 for (SDNode::use_iterator UI = N->use_begin(),
295 UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000296
Michael Kuperstein243c0732015-08-11 14:10:58 +0000297 SDNode *User = *UI;
298
299 // This user is already selected. Count it as a legitimate use and
300 // move on.
301 if (User->isMachineOpcode()) {
302 UseCount++;
303 continue;
304 }
305
306 // We want to count stores of immediates as real uses.
307 if (User->getOpcode() == ISD::STORE &&
308 User->getOperand(1).getNode() == N) {
309 UseCount++;
310 continue;
311 }
312
313 // We don't currently match users that have > 2 operands (except
314 // for stores, which are handled above)
315 // Those instruction won't match in ISEL, for now, and would
316 // be counted incorrectly.
317 // This may change in the future as we add additional instruction
318 // types.
319 if (User->getNumOperands() != 2)
320 continue;
Justin Bognerb0126992016-05-05 23:19:08 +0000321
Michael Kuperstein243c0732015-08-11 14:10:58 +0000322 // Immediates that are used for offsets as part of stack
323 // manipulation should be left alone. These are typically
324 // used to indicate SP offsets for argument passing and
325 // will get pulled into stores/pushes (implicitly).
326 if (User->getOpcode() == X86ISD::ADD ||
327 User->getOpcode() == ISD::ADD ||
328 User->getOpcode() == X86ISD::SUB ||
329 User->getOpcode() == ISD::SUB) {
330
331 // Find the other operand of the add/sub.
332 SDValue OtherOp = User->getOperand(0);
333 if (OtherOp.getNode() == N)
334 OtherOp = User->getOperand(1);
335
336 // Don't count if the other operand is SP.
337 RegisterSDNode *RegNode;
338 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
339 (RegNode = dyn_cast_or_null<RegisterSDNode>(
340 OtherOp->getOperand(1).getNode())))
341 if ((RegNode->getReg() == X86::ESP) ||
342 (RegNode->getReg() == X86::RSP))
343 continue;
344 }
345
346 // ... otherwise, count this and move on.
347 UseCount++;
348 }
349
350 // If we have more than 1 use, then recommend for hoisting.
351 return (UseCount > 1);
352 }
353
Sanjay Patelb5723d02015-10-13 15:12:27 +0000354 /// Return a target constant with the specified value of type i8.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000355 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000356 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
Chris Lattner3f0f71b2005-11-19 02:11:08 +0000357 }
358
Sanjay Patelb5723d02015-10-13 15:12:27 +0000359 /// Return a target constant with the specified value, of type i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000360 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000361 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
Chris Lattner655e7df2005-11-16 01:54:32 +0000362 }
Evan Chengd49cc362006-02-10 22:24:32 +0000363
Sanjay Patelb5723d02015-10-13 15:12:27 +0000364 /// Return an SDNode that returns the value of the global base register.
365 /// Output instructions required to initialize the global base register,
366 /// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +0000367 SDNode *getGlobalBaseReg();
Evan Cheng5588de92006-02-18 00:15:05 +0000368
Sanjay Patelb5723d02015-10-13 15:12:27 +0000369 /// Return a reference to the TargetMachine, casted to the target-specific
370 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000371 const X86TargetMachine &getTargetMachine() const {
Dan Gohman4751bb92009-06-03 20:20:00 +0000372 return static_cast<const X86TargetMachine &>(TM);
373 }
374
Sanjay Patelb5723d02015-10-13 15:12:27 +0000375 /// Return a reference to the TargetInstrInfo, casted to the target-specific
376 /// type.
Jakub Staszake167cf52013-02-19 21:54:59 +0000377 const X86InstrInfo *getInstrInfo() const {
Eric Christopher05b81972015-02-02 17:38:43 +0000378 return Subtarget->getInstrInfo();
Dan Gohman4751bb92009-06-03 20:20:00 +0000379 }
Adam Nemetff63a2d2014-10-03 20:00:34 +0000380
381 /// \brief Address-mode matching performs shift-of-and to and-of-shift
382 /// reassociation in order to expose more scaled addressing
383 /// opportunities.
384 bool ComplexPatternFuncMutatesDAG() const override {
385 return true;
386 }
Peter Collingbourneef089bd2017-02-09 22:02:28 +0000387
388 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
389
390 /// Returns whether this is a relocatable immediate in the range
391 /// [-2^Width .. 2^Width-1].
392 template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
393 if (auto *CN = dyn_cast<ConstantSDNode>(N))
394 return isInt<Width>(CN->getSExtValue());
395 return isSExtAbsoluteSymbolRef(Width, N);
396 }
Chris Lattner655e7df2005-11-16 01:54:32 +0000397 };
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000398}
399
Evan Cheng72bb66a2006-08-08 00:31:00 +0000400
Evan Cheng5e73ff22010-02-15 19:41:07 +0000401bool
402X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
Bill Wendling026e5d72009-04-29 23:29:43 +0000403 if (OptLevel == CodeGenOpt::None) return false;
Evan Chengb86375c2006-10-14 08:33:25 +0000404
Evan Cheng5e73ff22010-02-15 19:41:07 +0000405 if (!N.hasOneUse())
406 return false;
407
408 if (N.getOpcode() != ISD::LOAD)
409 return true;
410
411 // If N is a load, do additional profitability checks.
412 if (U == Root) {
Evan Cheng83bdb382008-11-27 00:49:46 +0000413 switch (U->getOpcode()) {
414 default: break;
Dan Gohman85d4fdf2010-01-04 20:51:50 +0000415 case X86ISD::ADD:
416 case X86ISD::SUB:
417 case X86ISD::AND:
418 case X86ISD::XOR:
419 case X86ISD::OR:
Evan Cheng83bdb382008-11-27 00:49:46 +0000420 case ISD::ADD:
421 case ISD::ADDC:
422 case ISD::ADDE:
Amaury Sechet8ac81f32017-04-30 19:24:09 +0000423 case ISD::ADDCARRY:
Evan Cheng83bdb382008-11-27 00:49:46 +0000424 case ISD::AND:
425 case ISD::OR:
426 case ISD::XOR: {
Rafael Espindolabb834f02009-04-10 10:09:34 +0000427 SDValue Op1 = U->getOperand(1);
428
Evan Cheng83bdb382008-11-27 00:49:46 +0000429 // If the other operand is a 8-bit immediate we should fold the immediate
430 // instead. This reduces code size.
431 // e.g.
432 // movl 4(%esp), %eax
433 // addl $4, %eax
434 // vs.
435 // movl $4, %eax
436 // addl 4(%esp), %eax
437 // The former is 2 bytes shorter. In case where the increment is 1, then
438 // the saving can be 4 bytes (by using incl %eax).
Rafael Espindolabb834f02009-04-10 10:09:34 +0000439 if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
Dan Gohman2293eb62009-03-14 02:07:16 +0000440 if (Imm->getAPIntValue().isSignedIntN(8))
441 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +0000442
443 // If the other operand is a TLS address, we should fold it instead.
444 // This produces
445 // movl %gs:0, %eax
446 // leal i@NTPOFF(%eax), %eax
447 // instead of
448 // movl $i@NTPOFF, %eax
449 // addl %gs:0, %eax
450 // if the block also has an access to a second TLS address this will save
451 // a load.
Alp Tokerf907b892013-12-05 05:44:44 +0000452 // FIXME: This is probably also true for non-TLS addresses.
Rafael Espindolabb834f02009-04-10 10:09:34 +0000453 if (Op1.getOpcode() == X86ISD::Wrapper) {
454 SDValue Val = Op1.getOperand(0);
455 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
456 return false;
457 }
Evan Cheng83bdb382008-11-27 00:49:46 +0000458 }
459 }
Evan Cheng5e73ff22010-02-15 19:41:07 +0000460 }
461
462 return true;
463}
464
Sanjay Patelb5723d02015-10-13 15:12:27 +0000465/// Replace the original chain operand of the call with
Evan Chengd703df62010-03-14 03:48:46 +0000466/// load's chain operand and move load below the call's chain operand.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000467static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
468 SDValue Call, SDValue OrigChain) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000469 SmallVector<SDValue, 8> Ops;
Evan Chengd703df62010-03-14 03:48:46 +0000470 SDValue Chain = OrigChain.getOperand(0);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000471 if (Chain.getNode() == Load.getNode())
472 Ops.push_back(Load.getOperand(0));
473 else {
474 assert(Chain.getOpcode() == ISD::TokenFactor &&
Evan Chengd703df62010-03-14 03:48:46 +0000475 "Unexpected chain operand");
Evan Cheng6c7e8512009-01-26 18:43:34 +0000476 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
477 if (Chain.getOperand(i).getNode() == Load.getNode())
478 Ops.push_back(Load.getOperand(0));
479 else
480 Ops.push_back(Chain.getOperand(i));
481 SDValue NewChain =
Craig Topper48d114b2014-04-26 18:35:24 +0000482 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
Evan Cheng6c7e8512009-01-26 18:43:34 +0000483 Ops.clear();
484 Ops.push_back(NewChain);
485 }
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000486 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000487 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
Dan Gohman92c11ac2010-06-18 15:30:29 +0000488 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
Evan Chengf00f1e52008-08-25 21:27:18 +0000489 Load.getOperand(1), Load.getOperand(2));
Evan Cheng214156c2012-10-02 23:49:13 +0000490
Evan Chengf00f1e52008-08-25 21:27:18 +0000491 Ops.clear();
Gabor Greiff304a7a2008-08-28 21:40:38 +0000492 Ops.push_back(SDValue(Load.getNode(), 1));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000493 Ops.append(Call->op_begin() + 1, Call->op_end());
Craig Topper8c0b4d02014-04-28 05:57:50 +0000494 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
Evan Chengf00f1e52008-08-25 21:27:18 +0000495}
496
Sanjay Patelb5723d02015-10-13 15:12:27 +0000497/// Return true if call address is a load and it can be
Evan Chengf00f1e52008-08-25 21:27:18 +0000498/// moved below CALLSEQ_START and the chains leading up to the call.
499/// Return the CALLSEQ_START by reference as a second output.
Evan Chengd703df62010-03-14 03:48:46 +0000500/// In the case of a tail call, there isn't a callseq node between the call
501/// chain and the load.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000502static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
Evan Cheng847ad442012-10-05 01:48:22 +0000503 // The transformation is somewhat dangerous if the call's chain was glued to
504 // the call. After MoveBelowOrigChain the load is moved between the call and
505 // the chain, this can create a cycle if the load is not folded. So it is
506 // *really* important that we are sure the load will be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000507 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
Evan Chengf00f1e52008-08-25 21:27:18 +0000508 return false;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000509 LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
Evan Chengf00f1e52008-08-25 21:27:18 +0000510 if (!LD ||
511 LD->isVolatile() ||
512 LD->getAddressingMode() != ISD::UNINDEXED ||
513 LD->getExtensionType() != ISD::NON_EXTLOAD)
514 return false;
515
516 // Now let's find the callseq_start.
Evan Chengd703df62010-03-14 03:48:46 +0000517 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
Evan Chengf00f1e52008-08-25 21:27:18 +0000518 if (!Chain.hasOneUse())
519 return false;
520 Chain = Chain.getOperand(0);
521 }
Evan Chengd703df62010-03-14 03:48:46 +0000522
523 if (!Chain.getNumOperands())
524 return false;
Evan Cheng3fb03e22013-01-06 19:00:15 +0000525 // Since we are not checking for AA here, conservatively abort if the chain
526 // writes to memory. It's not safe to move the callee (a load) across a store.
527 if (isa<MemSDNode>(Chain.getNode()) &&
528 cast<MemSDNode>(Chain.getNode())->writeMem())
529 return false;
Evan Cheng6c7e8512009-01-26 18:43:34 +0000530 if (Chain.getOperand(0).getNode() == Callee.getNode())
531 return true;
532 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
Dan Gohman520a6852009-09-15 01:22:01 +0000533 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
534 Callee.getValue(1).hasOneUse())
Evan Cheng6c7e8512009-01-26 18:43:34 +0000535 return true;
536 return false;
Evan Chengf00f1e52008-08-25 21:27:18 +0000537}
538
Chris Lattner8d637042010-03-02 23:12:51 +0000539void X86DAGToDAGISel::PreprocessISelDAG() {
Hans Wennborg4ae51192016-03-25 01:10:56 +0000540 // OptFor[Min]Size are used in pattern predicates that isel is matching.
Sanjay Patel68b03252015-08-10 16:47:47 +0000541 OptForSize = MF->getFunction()->optForSize();
Hans Wennborg4ae51192016-03-25 01:10:56 +0000542 OptForMinSize = MF->getFunction()->optForMinSize();
543 assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
Chad Rosier24c19d22012-08-01 18:39:17 +0000544
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000545 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
546 E = CurDAG->allnodes_end(); I != E; ) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000547 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
Chris Lattner8d637042010-03-02 23:12:51 +0000548
Evan Chengd703df62010-03-14 03:48:46 +0000549 if (OptLevel != CodeGenOpt::None &&
Michael Liao96b42602013-03-28 23:13:21 +0000550 // Only does this when target favors doesn't favor register indirect
551 // call.
552 ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
Evan Cheng847ad442012-10-05 01:48:22 +0000553 (N->getOpcode() == X86ISD::TC_RETURN &&
Nick Lewyckyf41a80e2013-01-13 19:03:55 +0000554 // Only does this if load can be folded into TC_RETURN.
Evan Cheng847ad442012-10-05 01:48:22 +0000555 (Subtarget->is64Bit() ||
Rafael Espindolaf9e348b2016-06-27 21:33:08 +0000556 !getTargetMachine().isPositionIndependent())))) {
Chris Lattner8d637042010-03-02 23:12:51 +0000557 /// Also try moving call address load from outside callseq_start to just
558 /// before the call to allow it to be folded.
559 ///
560 /// [Load chain]
561 /// ^
562 /// |
563 /// [Load]
564 /// ^ ^
565 /// | |
566 /// / \--
567 /// / |
568 ///[CALLSEQ_START] |
569 /// ^ |
570 /// | |
571 /// [LOAD/C2Reg] |
572 /// | |
573 /// \ /
574 /// \ /
575 /// [CALL]
Evan Chengd703df62010-03-14 03:48:46 +0000576 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
Chris Lattner8d637042010-03-02 23:12:51 +0000577 SDValue Chain = N->getOperand(0);
578 SDValue Load = N->getOperand(1);
Evan Chengd703df62010-03-14 03:48:46 +0000579 if (!isCalleeLoad(Load, Chain, HasCallSeq))
Chris Lattner8d637042010-03-02 23:12:51 +0000580 continue;
Sanjay Patel85030aa2015-10-13 16:23:00 +0000581 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
Chris Lattner8d637042010-03-02 23:12:51 +0000582 ++NumLoadMoved;
583 continue;
584 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000585
Chris Lattner8d637042010-03-02 23:12:51 +0000586 // Lower fpround and fpextend nodes that target the FP stack to be store and
587 // load to the stack. This is a gross hack. We would like to simply mark
588 // these as being illegal, but when we do that, legalize produces these when
589 // it expands calls, then expands these in the same legalize pass. We would
590 // like dag combine to be able to hack on these between the call expansion
591 // and the node legalization. As such this pass basically does "really
592 // late" legalization of these inline with the X86 isel pass.
593 // FIXME: This should only happen when not compiled with -O0.
Chris Lattnera91f77e2008-01-24 08:07:48 +0000594 if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
595 continue;
Chad Rosier24c19d22012-08-01 18:39:17 +0000596
Craig Topper83e042a2013-08-15 05:57:07 +0000597 MVT SrcVT = N->getOperand(0).getSimpleValueType();
598 MVT DstVT = N->getSimpleValueType(0);
Bruno Cardoso Lopes616fe602011-08-01 21:54:05 +0000599
600 // If any of the sources are vectors, no fp stack involved.
601 if (SrcVT.isVector() || DstVT.isVector())
602 continue;
603
604 // If the source and destination are SSE registers, then this is a legal
605 // conversion that should not be lowered.
Benjamin Kramer02ff1cd2013-06-27 11:07:42 +0000606 const X86TargetLowering *X86Lowering =
Eric Christopherb17140d2014-10-08 07:32:17 +0000607 static_cast<const X86TargetLowering *>(TLI);
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000608 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
609 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000610 if (SrcIsSSE && DstIsSSE)
611 continue;
612
Chris Lattnerd587e582008-03-09 07:05:32 +0000613 if (!SrcIsSSE && !DstIsSSE) {
614 // If this is an FPStack extension, it is a noop.
615 if (N->getOpcode() == ISD::FP_EXTEND)
616 continue;
617 // If this is a value-preserving FPStack truncation, it is a noop.
618 if (N->getConstantOperandVal(1))
619 continue;
620 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000621
Chris Lattnera91f77e2008-01-24 08:07:48 +0000622 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
623 // FPStack has extload and truncstore. SSE can fold direct loads into other
624 // operations. Based on this, decide what we want to do.
Craig Topper83e042a2013-08-15 05:57:07 +0000625 MVT MemVT;
Chris Lattnera91f77e2008-01-24 08:07:48 +0000626 if (N->getOpcode() == ISD::FP_ROUND)
627 MemVT = DstVT; // FP_ROUND must use DstVT, we can't do a 'trunc load'.
628 else
629 MemVT = SrcIsSSE ? SrcVT : DstVT;
Chad Rosier24c19d22012-08-01 18:39:17 +0000630
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000631 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000632 SDLoc dl(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000633
Chris Lattnera91f77e2008-01-24 08:07:48 +0000634 // FIXME: optimize the case where the src/dest is a load or store?
Justin Lebar9c375812016-07-15 18:27:10 +0000635 SDValue Store =
636 CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
637 MemTmp, MachinePointerInfo(), MemVT);
Stuart Hastings81c43062011-02-16 16:23:55 +0000638 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
Justin Lebar9c375812016-07-15 18:27:10 +0000639 MachinePointerInfo(), MemVT);
Chris Lattnera91f77e2008-01-24 08:07:48 +0000640
641 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
642 // extload we created. This will cause general havok on the dag because
643 // anything below the conversion could be folded into other existing nodes.
644 // To avoid invalidating 'I', back it up to the convert node.
645 --I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000646 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
Chad Rosier24c19d22012-08-01 18:39:17 +0000647
Chris Lattnera91f77e2008-01-24 08:07:48 +0000648 // Now that we did that, the node is dead. Increment the iterator to the
649 // next node to process, then delete N.
650 ++I;
Dan Gohmaneb0cee92008-08-23 02:25:05 +0000651 CurDAG->DeleteNode(N);
Chad Rosier24c19d22012-08-01 18:39:17 +0000652 }
Chris Lattnera91f77e2008-01-24 08:07:48 +0000653}
654
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000655
Sanjay Patelb5723d02015-10-13 15:12:27 +0000656/// Emit any code that needs to be executed only in the main function.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000657void X86DAGToDAGISel::emitSpecialCodeForMain() {
Bill Wendling81d40712011-01-06 00:47:10 +0000658 if (Subtarget->isTargetCygMing()) {
David Majnemerd5ab35f2015-02-21 05:49:45 +0000659 TargetLowering::ArgListTy Args;
Mehdi Amini44ede332015-07-09 02:09:04 +0000660 auto &DL = CurDAG->getDataLayout();
David Majnemerd5ab35f2015-02-21 05:49:45 +0000661
662 TargetLowering::CallLoweringInfo CLI(*CurDAG);
663 CLI.setChain(CurDAG->getRoot())
664 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
Mehdi Amini44ede332015-07-09 02:09:04 +0000665 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000666 std::move(Args));
David Majnemerd5ab35f2015-02-21 05:49:45 +0000667 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
668 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
669 CurDAG->setRoot(Result.second);
Bill Wendling81d40712011-01-06 00:47:10 +0000670 }
Anton Korobeynikov90910742007-09-25 21:52:30 +0000671}
672
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000673void X86DAGToDAGISel::EmitFunctionEntryCode() {
Anton Korobeynikov90910742007-09-25 21:52:30 +0000674 // If this is main, emit special code for main.
Dan Gohmanc87b74d2010-04-14 20:17:22 +0000675 if (const Function *Fn = MF->getFunction())
676 if (Fn->hasExternalLinkage() && Fn->getName() == "main")
Sanjay Patel85030aa2015-10-13 16:23:00 +0000677 emitSpecialCodeForMain();
Anton Korobeynikov90910742007-09-25 21:52:30 +0000678}
679
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000680static bool isDispSafeForFrameIndex(int64_t Val) {
Eli Friedman344ec792011-07-13 21:29:53 +0000681 // On 64-bit platforms, we can run into an issue where a frame index
682 // includes a displacement that, when added to the explicit displacement,
683 // will overflow the displacement field. Assuming that the frame index
684 // displacement fits into a 31-bit integer (which is only slightly more
685 // aggressive than the current fundamental assumption that it fits into
686 // a 32-bit integer), a 31-bit disp should always be safe.
687 return isInt<31>(Val);
688}
689
Sanjay Patel85030aa2015-10-13 16:23:00 +0000690bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000691 X86ISelAddressMode &AM) {
Reid Kleckner9dad2272015-05-04 23:22:36 +0000692 // Cannot combine ExternalSymbol displacements with integer offsets.
Rafael Espindola36b718f2015-06-22 17:46:53 +0000693 if (Offset != 0 && (AM.ES || AM.MCSym))
Reid Kleckner9dad2272015-05-04 23:22:36 +0000694 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000695 int64_t Val = AM.Disp + Offset;
696 CodeModel::Model M = TM.getCodeModel();
Eli Friedman344ec792011-07-13 21:29:53 +0000697 if (Subtarget->is64Bit()) {
698 if (!X86::isOffsetSuitableForCodeModel(Val, M,
699 AM.hasSymbolicDisplacement()))
700 return true;
701 // In addition to the checks required for a register base, check that
702 // we do not try to use an unsafe Disp with a frame index.
703 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
704 !isDispSafeForFrameIndex(Val))
705 return true;
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000706 }
Eli Friedman344ec792011-07-13 21:29:53 +0000707 AM.Disp = Val;
708 return false;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000709
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000710}
Rafael Espindola3b2df102009-04-08 21:14:34 +0000711
Sanjay Patel85030aa2015-10-13 16:23:00 +0000712bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
Chris Lattner8a236b62010-09-22 04:39:11 +0000713 SDValue Address = N->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +0000714
Chris Lattner8a236b62010-09-22 04:39:11 +0000715 // load gs:0 -> GS segment register.
716 // load fs:0 -> FS segment register.
717 //
Rafael Espindola3b2df102009-04-08 21:14:34 +0000718 // This optimization is valid because the GNU TLS model defines that
719 // gs:0 (or fs:0 on X86-64) contains its own address.
720 // For more information see http://people.redhat.com/drepper/tls.pdf
Chris Lattner8a236b62010-09-22 04:39:11 +0000721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
Craig Topper062a2ba2014-04-25 05:30:21 +0000722 if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
Petr Hoseka7d59162017-02-24 03:10:10 +0000723 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
724 Subtarget->isTargetFuchsia()))
Chris Lattner8a236b62010-09-22 04:39:11 +0000725 switch (N->getPointerInfo().getAddrSpace()) {
726 case 256:
727 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
728 return false;
729 case 257:
730 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
731 return false;
David L Kreitzerc9fbf102016-05-03 20:16:08 +0000732 // Address space 258 is not handled here, because it is not used to
733 // address TLS areas.
Chris Lattner8a236b62010-09-22 04:39:11 +0000734 }
Chad Rosier24c19d22012-08-01 18:39:17 +0000735
Rafael Espindola3b2df102009-04-08 21:14:34 +0000736 return true;
737}
738
Sanjay Patelb5723d02015-10-13 15:12:27 +0000739/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
740/// mode. These wrap things that will resolve down into a symbol reference.
741/// If no match is possible, this returns true, otherwise it returns false.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000742bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000743 // If the addressing mode already has a symbol as the displacement, we can
744 // never match another symbol.
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000745 if (AM.hasSymbolicDisplacement())
746 return true;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000747
748 SDValue N0 = N.getOperand(0);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000749 CodeModel::Model M = TM.getCodeModel();
750
Chris Lattnerfea81da2009-06-27 04:16:01 +0000751 // Handle X86-64 rip-relative addresses. We check this before checking direct
752 // folding because RIP is preferable to non-RIP accesses.
Chandler Carruth3779ac12012-04-09 02:13:06 +0000753 if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
Chris Lattnerfea81da2009-06-27 04:16:01 +0000754 // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
755 // they cannot be folded into immediate fields.
756 // FIXME: This can be improved for kernel and other models?
Chandler Carruth3779ac12012-04-09 02:13:06 +0000757 (M == CodeModel::Small || M == CodeModel::Kernel)) {
758 // Base and index reg must be 0 in order to use %rip as base.
759 if (AM.hasBaseOrIndexReg())
760 return true;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000761 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000762 X86ISelAddressMode Backup = AM;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000763 AM.GV = G->getGlobal();
Chris Lattnerbd7e26d2009-06-26 05:51:45 +0000764 AM.SymbolFlags = G->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000765 if (foldOffsetIntoAddress(G->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000766 AM = Backup;
767 return true;
768 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000769 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000770 X86ISelAddressMode Backup = AM;
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000771 AM.CP = CP->getConstVal();
772 AM.Align = CP->getAlignment();
Chris Lattner1d3b65a2009-06-26 05:56:49 +0000773 AM.SymbolFlags = CP->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000774 if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
Eli Friedmanef67e7d2011-07-13 20:44:23 +0000775 AM = Backup;
776 return true;
777 }
Chris Lattnerfea81da2009-06-27 04:16:01 +0000778 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
779 AM.ES = S->getSymbol();
780 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000781 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
782 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000783 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000784 AM.JT = J->getIndex();
785 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000786 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
787 X86ISelAddressMode Backup = AM;
788 AM.BlockAddr = BA->getBlockAddress();
789 AM.SymbolFlags = BA->getTargetFlags();
Sanjay Patel85030aa2015-10-13 16:23:00 +0000790 if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
Michael Liaoabb87d42012-09-12 21:43:09 +0000791 AM = Backup;
792 return true;
793 }
794 } else
795 llvm_unreachable("Unhandled symbol reference node.");
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +0000796
Chris Lattnerfea81da2009-06-27 04:16:01 +0000797 if (N.getOpcode() == X86ISD::WrapperRIP)
Owen Anderson9f944592009-08-11 20:47:22 +0000798 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000799 return false;
Chris Lattnerfea81da2009-06-27 04:16:01 +0000800 }
801
802 // Handle the case when globals fit in our immediate field: This is true for
Chandler Carruth3779ac12012-04-09 02:13:06 +0000803 // X86-32 always and X86-64 when in -mcmodel=small mode. In 64-bit
804 // mode, this only applies to a non-RIP-relative computation.
Chris Lattnerfea81da2009-06-27 04:16:01 +0000805 if (!Subtarget->is64Bit() ||
Chandler Carruth3779ac12012-04-09 02:13:06 +0000806 M == CodeModel::Small || M == CodeModel::Kernel) {
807 assert(N.getOpcode() != X86ISD::WrapperRIP &&
808 "RIP-relative addressing already handled");
Chris Lattnerfea81da2009-06-27 04:16:01 +0000809 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
810 AM.GV = G->getGlobal();
811 AM.Disp += G->getOffset();
812 AM.SymbolFlags = G->getTargetFlags();
813 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
814 AM.CP = CP->getConstVal();
815 AM.Align = CP->getAlignment();
816 AM.Disp += CP->getOffset();
817 AM.SymbolFlags = CP->getTargetFlags();
818 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
819 AM.ES = S->getSymbol();
820 AM.SymbolFlags = S->getTargetFlags();
Rafael Espindola36b718f2015-06-22 17:46:53 +0000821 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
822 AM.MCSym = S->getMCSymbol();
Chris Lattner50ba5c32009-11-01 03:25:03 +0000823 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
Chris Lattnerfea81da2009-06-27 04:16:01 +0000824 AM.JT = J->getIndex();
825 AM.SymbolFlags = J->getTargetFlags();
Michael Liaoabb87d42012-09-12 21:43:09 +0000826 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
827 AM.BlockAddr = BA->getBlockAddress();
828 AM.Disp += BA->getOffset();
829 AM.SymbolFlags = BA->getTargetFlags();
830 } else
831 llvm_unreachable("Unhandled symbol reference node.");
Rafael Espindola6688b0a2009-04-12 21:55:03 +0000832 return false;
833 }
834
835 return true;
836}
837
Sanjay Patelb5723d02015-10-13 15:12:27 +0000838/// Add the specified node to the specified addressing mode, returning true if
839/// it cannot be done. This just pattern matches for the addressing mode.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000840bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
841 if (matchAddressRecursively(N, AM, 0))
Dan Gohman824ab402009-07-22 23:26:55 +0000842 return true;
843
844 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
845 // a smaller encoding and avoids a scaled-index.
846 if (AM.Scale == 2 &&
847 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000848 AM.Base_Reg.getNode() == nullptr) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000849 AM.Base_Reg = AM.IndexReg;
Dan Gohman824ab402009-07-22 23:26:55 +0000850 AM.Scale = 1;
851 }
852
Dan Gohman05046082009-08-20 18:23:44 +0000853 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
854 // because it has a smaller encoding.
855 // TODO: Which other code models can use this?
856 if (TM.getCodeModel() == CodeModel::Small &&
857 Subtarget->is64Bit() &&
858 AM.Scale == 1 &&
859 AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +0000860 AM.Base_Reg.getNode() == nullptr &&
861 AM.IndexReg.getNode() == nullptr &&
Dan Gohman0f6bf2d2009-08-25 17:47:44 +0000862 AM.SymbolFlags == X86II::MO_NO_FLAG &&
Dan Gohman05046082009-08-20 18:23:44 +0000863 AM.hasSymbolicDisplacement())
Dan Gohman0fd54fb2010-04-29 23:30:41 +0000864 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
Dan Gohman05046082009-08-20 18:23:44 +0000865
Dan Gohman824ab402009-07-22 23:26:55 +0000866 return false;
867}
868
Sanjay Patelefab8b02015-10-21 18:56:06 +0000869bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
870 unsigned Depth) {
871 // Add an artificial use to this node so that we can keep track of
872 // it if it gets CSE'd with a different node.
873 HandleSDNode Handle(N);
874
875 X86ISelAddressMode Backup = AM;
876 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
877 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
878 return false;
879 AM = Backup;
880
881 // Try again after commuting the operands.
882 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
883 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
884 return false;
885 AM = Backup;
886
887 // If we couldn't fold both operands into the address at the same time,
888 // see if we can just put each operand into a register and fold at least
889 // the add.
890 if (AM.BaseType == X86ISelAddressMode::RegBase &&
891 !AM.Base_Reg.getNode() &&
892 !AM.IndexReg.getNode()) {
893 N = Handle.getValue();
894 AM.Base_Reg = N.getOperand(0);
895 AM.IndexReg = N.getOperand(1);
896 AM.Scale = 1;
897 return false;
898 }
899 N = Handle.getValue();
900 return true;
901}
902
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000903// Insert a node into the DAG at least before the Pos node's position. This
904// will reposition the node as needed, and will assign it a node ID that is <=
905// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
906// IDs! The selection DAG must no longer depend on their uniqueness when this
907// is used.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000908static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000909 if (N.getNode()->getNodeId() == -1 ||
910 N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000911 DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
Chandler Carruth3eacfb82012-01-11 11:04:36 +0000912 N.getNode()->setNodeId(Pos.getNode()->getNodeId());
913 }
914}
915
Adam Nemet0c7caf42014-09-16 17:14:10 +0000916// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
917// safe. This allows us to convert the shift and and into an h-register
918// extract and a scaled index. Returns false if the simplification is
919// performed.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000920static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
921 uint64_t Mask,
922 SDValue Shift, SDValue X,
923 X86ISelAddressMode &AM) {
Chandler Carruth51d30762012-01-11 08:48:20 +0000924 if (Shift.getOpcode() != ISD::SRL ||
925 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
926 !Shift.hasOneUse())
927 return true;
928
929 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
930 if (ScaleLog <= 0 || ScaleLog >= 4 ||
931 Mask != (0xffu << ScaleLog))
932 return true;
933
Craig Topper83e042a2013-08-15 05:57:07 +0000934 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000935 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000936 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
937 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
Chandler Carruth51d30762012-01-11 08:48:20 +0000938 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
939 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000940 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
Chandler Carruth51d30762012-01-11 08:48:20 +0000941 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
942
Chandler Carrutheb21da02012-01-12 01:34:44 +0000943 // Insert the new nodes into the topological ordering. We must do this in
944 // a valid topological ordering as nothing is going to go back and re-sort
945 // these nodes. We continually insert before 'N' in sequence as this is
946 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
947 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000948 insertDAGNode(DAG, N, Eight);
949 insertDAGNode(DAG, N, Srl);
950 insertDAGNode(DAG, N, NewMask);
951 insertDAGNode(DAG, N, And);
952 insertDAGNode(DAG, N, ShlCount);
953 insertDAGNode(DAG, N, Shl);
Chandler Carruth51d30762012-01-11 08:48:20 +0000954 DAG.ReplaceAllUsesWith(N, Shl);
955 AM.IndexReg = And;
956 AM.Scale = (1 << ScaleLog);
957 return false;
958}
959
Chandler Carruthaa01e662012-01-11 09:35:00 +0000960// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
961// allows us to fold the shift into this addressing mode. Returns false if the
962// transform succeeded.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000963static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
964 uint64_t Mask,
965 SDValue Shift, SDValue X,
966 X86ISelAddressMode &AM) {
Chandler Carruthaa01e662012-01-11 09:35:00 +0000967 if (Shift.getOpcode() != ISD::SHL ||
968 !isa<ConstantSDNode>(Shift.getOperand(1)))
969 return true;
970
971 // Not likely to be profitable if either the AND or SHIFT node has more
972 // than one use (unless all uses are for address computation). Besides,
973 // isel mechanism requires their node ids to be reused.
974 if (!N.hasOneUse() || !Shift.hasOneUse())
975 return true;
976
977 // Verify that the shift amount is something we can fold.
978 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
979 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
980 return true;
981
Craig Topper83e042a2013-08-15 05:57:07 +0000982 MVT VT = N.getSimpleValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000983 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000984 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
Chandler Carruthaa01e662012-01-11 09:35:00 +0000985 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
986 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
987
Chandler Carrutheb21da02012-01-12 01:34:44 +0000988 // Insert the new nodes into the topological ordering. We must do this in
989 // a valid topological ordering as nothing is going to go back and re-sort
990 // these nodes. We continually insert before 'N' in sequence as this is
991 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
992 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +0000993 insertDAGNode(DAG, N, NewMask);
994 insertDAGNode(DAG, N, NewAnd);
995 insertDAGNode(DAG, N, NewShift);
Chandler Carruthaa01e662012-01-11 09:35:00 +0000996 DAG.ReplaceAllUsesWith(N, NewShift);
997
998 AM.Scale = 1 << ShiftAmt;
999 AM.IndexReg = NewAnd;
1000 return false;
1001}
1002
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001003// Implement some heroics to detect shifts of masked values where the mask can
1004// be replaced by extending the shift and undoing that in the addressing mode
1005// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1006// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1007// the addressing mode. This results in code such as:
1008//
1009// int f(short *y, int *lookup_table) {
1010// ...
1011// return *y + lookup_table[*y >> 11];
1012// }
1013//
1014// Turning into:
1015// movzwl (%rdi), %eax
1016// movl %eax, %ecx
1017// shrl $11, %ecx
1018// addl (%rsi,%rcx,4), %eax
1019//
1020// Instead of:
1021// movzwl (%rdi), %eax
1022// movl %eax, %ecx
1023// shrl $9, %ecx
1024// andl $124, %rcx
1025// addl (%rsi,%rcx), %eax
1026//
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001027// Note that this function assumes the mask is provided as a mask *after* the
1028// value is shifted. The input chain may or may not match that, but computing
1029// such a mask is trivial.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001030static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1031 uint64_t Mask,
1032 SDValue Shift, SDValue X,
1033 X86ISelAddressMode &AM) {
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001034 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1035 !isa<ConstantSDNode>(Shift.getOperand(1)))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001036 return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001037
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001038 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001039 unsigned MaskLZ = countLeadingZeros(Mask);
1040 unsigned MaskTZ = countTrailingZeros(Mask);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001041
1042 // The amount of shift we're trying to fit into the addressing mode is taken
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001043 // from the trailing zeros of the mask.
1044 unsigned AMShiftAmt = MaskTZ;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001045
1046 // There is nothing we can do here unless the mask is removing some bits.
1047 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1048 if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1049
1050 // We also need to ensure that mask is a continuous run of bits.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001051 if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001052
1053 // Scale the leading zero count down based on the actual size of the value.
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001054 // Also scale it down based on the size of the shift.
Craig Topper83e042a2013-08-15 05:57:07 +00001055 MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001056
1057 // The final check is to ensure that any masked out high bits of X are
1058 // already known to be zero. Otherwise, the mask has a semantic impact
1059 // other than masking out a couple of low bits. Unfortunately, because of
1060 // the mask, zero extensions will be removed from operands in some cases.
1061 // This code works extra hard to look through extensions because we can
1062 // replace them with zero extensions cheaply if necessary.
1063 bool ReplacingAnyExtend = false;
1064 if (X.getOpcode() == ISD::ANY_EXTEND) {
Craig Topper83e042a2013-08-15 05:57:07 +00001065 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1066 X.getOperand(0).getSimpleValueType().getSizeInBits();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001067 // Assume that we'll replace the any-extend with a zero-extend, and
1068 // narrow the search to the extended value.
1069 X = X.getOperand(0);
1070 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1071 ReplacingAnyExtend = true;
1072 }
Craig Topper83e042a2013-08-15 05:57:07 +00001073 APInt MaskedHighBits =
1074 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
Craig Topperd0af7e82017-04-28 05:31:46 +00001075 KnownBits Known;
1076 DAG.computeKnownBits(X, Known);
1077 if (MaskedHighBits != Known.Zero) return true;
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001078
1079 // We've identified a pattern that can be transformed into a single shift
1080 // and an addressing mode. Make it so.
Craig Topper83e042a2013-08-15 05:57:07 +00001081 MVT VT = N.getSimpleValueType();
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001082 if (ReplacingAnyExtend) {
1083 assert(X.getValueType() != VT);
1084 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001085 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
Sanjay Patel85030aa2015-10-13 16:23:00 +00001086 insertDAGNode(DAG, N, NewX);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001087 X = NewX;
1088 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00001089 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001090 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001091 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001092 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001093 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
Chandler Carrutheb21da02012-01-12 01:34:44 +00001094
1095 // Insert the new nodes into the topological ordering. We must do this in
1096 // a valid topological ordering as nothing is going to go back and re-sort
1097 // these nodes. We continually insert before 'N' in sequence as this is
1098 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1099 // hierarchy left to express.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001100 insertDAGNode(DAG, N, NewSRLAmt);
1101 insertDAGNode(DAG, N, NewSRL);
1102 insertDAGNode(DAG, N, NewSHLAmt);
1103 insertDAGNode(DAG, N, NewSHL);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001104 DAG.ReplaceAllUsesWith(N, NewSHL);
1105
1106 AM.Scale = 1 << AMShiftAmt;
1107 AM.IndexReg = NewSRL;
1108 return false;
1109}
1110
Sanjay Patel85030aa2015-10-13 16:23:00 +00001111bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
Dan Gohman824ab402009-07-22 23:26:55 +00001112 unsigned Depth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001113 SDLoc dl(N);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001114 DEBUG({
David Greenedbdb1b22010-01-05 01:29:08 +00001115 dbgs() << "MatchAddress: ";
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00001116 AM.dump();
1117 });
Dan Gohmanccb36112007-08-13 20:03:06 +00001118 // Limit recursion.
1119 if (Depth > 5)
Sanjay Patel85030aa2015-10-13 16:23:00 +00001120 return matchAddressBase(N, AM);
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001121
Chris Lattnerfea81da2009-06-27 04:16:01 +00001122 // If this is already a %rip relative address, we can only merge immediates
1123 // into it. Instead of handling this in every case, we handle it here.
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001124 // RIP relative addressing: %rip + 32-bit displacement!
Chris Lattnerfea81da2009-06-27 04:16:01 +00001125 if (AM.isRIPRelative()) {
1126 // FIXME: JumpTable and ExternalSymbol address currently don't like
1127 // displacements. It isn't very important, but this should be fixed for
1128 // consistency.
Rafael Espindola36b718f2015-06-22 17:46:53 +00001129 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1130 return true;
Anton Korobeynikov741ea0d2009-08-05 23:01:26 +00001131
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001132 if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
Sanjay Patel85030aa2015-10-13 16:23:00 +00001133 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001134 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001135 return true;
1136 }
1137
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001138 switch (N.getOpcode()) {
1139 default: break;
Reid Kleckner60381792015-07-07 22:25:32 +00001140 case ISD::LOCAL_RECOVER: {
Reid Kleckner9dad2272015-05-04 23:22:36 +00001141 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
Rafael Espindola36b718f2015-06-22 17:46:53 +00001142 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1143 // Use the symbol and don't prefix it.
1144 AM.MCSym = ESNode->getMCSymbol();
1145 return false;
1146 }
David Majnemer71b9b6b2015-03-05 18:50:12 +00001147 break;
1148 }
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001149 case ISD::Constant: {
Dan Gohman059c4fa2008-11-11 15:52:29 +00001150 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001151 if (!foldOffsetIntoAddress(Val, AM))
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001152 return false;
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001153 break;
1154 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001155
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001156 case X86ISD::Wrapper:
Chris Lattnerfea81da2009-06-27 04:16:01 +00001157 case X86ISD::WrapperRIP:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001158 if (!matchWrapper(N, AM))
Rafael Espindola6688b0a2009-04-12 21:55:03 +00001159 return false;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001160 break;
1161
Rafael Espindola3b2df102009-04-08 21:14:34 +00001162 case ISD::LOAD:
Sanjay Patel85030aa2015-10-13 16:23:00 +00001163 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
Rafael Espindola3b2df102009-04-08 21:14:34 +00001164 return false;
1165 break;
1166
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001167 case ISD::FrameIndex:
Eli Friedman344ec792011-07-13 21:29:53 +00001168 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001169 AM.Base_Reg.getNode() == nullptr &&
Eli Friedman344ec792011-07-13 21:29:53 +00001170 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001171 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001172 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001173 return false;
1174 }
1175 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001176
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001177 case ISD::SHL:
Craig Topper062a2ba2014-04-25 05:30:21 +00001178 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001179 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001180
Gabor Greif81d6a382008-08-31 15:37:04 +00001181 if (ConstantSDNode
1182 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00001183 unsigned Val = CN->getZExtValue();
Dan Gohman824ab402009-07-22 23:26:55 +00001184 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1185 // that the base operand remains free for further matching. If
1186 // the base doesn't end up getting used, a post-processing step
1187 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001188 if (Val == 1 || Val == 2 || Val == 3) {
1189 AM.Scale = 1 << Val;
Gabor Greiff304a7a2008-08-28 21:40:38 +00001190 SDValue ShVal = N.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001191
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001192 // Okay, we know that we have a scale by now. However, if the scaled
1193 // value is an add of something and a constant, we can fold the
1194 // constant into the disp field here.
Chris Lattner46c01a32011-02-13 22:25:43 +00001195 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001196 AM.IndexReg = ShVal.getNode()->getOperand(0);
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001197 ConstantSDNode *AddVal =
Gabor Greiff304a7a2008-08-28 21:40:38 +00001198 cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
Richard Smith228e6d42012-08-24 23:29:28 +00001199 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001200 if (!foldOffsetIntoAddress(Disp, AM))
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001201 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001202 }
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001203
1204 AM.IndexReg = ShVal;
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001205 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001206 }
Chris Lattnerff87f05e2007-12-08 07:22:58 +00001207 }
Jakub Staszak43fafaf2013-01-04 23:01:26 +00001208 break;
Evan Chengc9fab312005-12-08 02:01:35 +00001209
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001210 case ISD::SRL: {
1211 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001212 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001213
1214 SDValue And = N.getOperand(0);
1215 if (And.getOpcode() != ISD::AND) break;
1216 SDValue X = And.getOperand(0);
1217
1218 // We only handle up to 64-bit values here as those are what matter for
1219 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001220 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001221
1222 // The mask used for the transform is expected to be post-shift, but we
1223 // found the shift first so just apply the shift to the mask before passing
1224 // it down.
1225 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1226 !isa<ConstantSDNode>(And.getOperand(1)))
1227 break;
1228 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1229
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001230 // Try to fold the mask and shift into the scale, and return false if we
1231 // succeed.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001232 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001233 return false;
1234 break;
Chandler Carruth3dbcda82012-01-11 09:35:02 +00001235 }
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001236
Dan Gohmanbf474952007-10-22 20:22:24 +00001237 case ISD::SMUL_LOHI:
1238 case ISD::UMUL_LOHI:
1239 // A mul_lohi where we need the low part can be folded as a plain multiply.
Gabor Greifabfdf922008-08-26 22:36:50 +00001240 if (N.getResNo() != 0) break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001241 LLVM_FALLTHROUGH;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001242 case ISD::MUL:
Evan Chenga84a3182009-03-30 21:36:47 +00001243 case X86ISD::MUL_IMM:
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001244 // X*[3,5,9] -> X+X*[2,4,8]
Dan Gohmanf14b77e2008-11-05 04:14:16 +00001245 if (AM.BaseType == X86ISelAddressMode::RegBase &&
Craig Topper062a2ba2014-04-25 05:30:21 +00001246 AM.Base_Reg.getNode() == nullptr &&
1247 AM.IndexReg.getNode() == nullptr) {
Gabor Greif81d6a382008-08-31 15:37:04 +00001248 if (ConstantSDNode
1249 *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
Dan Gohmaneffb8942008-09-12 16:56:44 +00001250 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1251 CN->getZExtValue() == 9) {
1252 AM.Scale = unsigned(CN->getZExtValue())-1;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001253
Gabor Greiff304a7a2008-08-28 21:40:38 +00001254 SDValue MulVal = N.getNode()->getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001255 SDValue Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001256
1257 // Okay, we know that we have a scale by now. However, if the scaled
1258 // value is an add of something and a constant, we can fold the
1259 // constant into the disp field here.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001260 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1261 isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1262 Reg = MulVal.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001263 ConstantSDNode *AddVal =
Gabor Greiff304a7a2008-08-28 21:40:38 +00001264 cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
Eli Friedmanef67e7d2011-07-13 20:44:23 +00001265 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
Sanjay Patel85030aa2015-10-13 16:23:00 +00001266 if (foldOffsetIntoAddress(Disp, AM))
Gabor Greiff304a7a2008-08-28 21:40:38 +00001267 Reg = N.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001268 } else {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001269 Reg = N.getNode()->getOperand(0);
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001270 }
1271
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001272 AM.IndexReg = AM.Base_Reg = Reg;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001273 return false;
1274 }
Chris Lattnerfe8c5302007-02-04 20:18:17 +00001275 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001276 break;
1277
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001278 case ISD::SUB: {
1279 // Given A-B, if A can be completely folded into the address and
1280 // the index field with the index field unused, use -B as the index.
1281 // This is a win if a has multiple parts that can be folded into
1282 // the address. Also, this saves a mov if the base register has
1283 // other uses, since it avoids a two-address sub instruction, however
1284 // it costs an additional mov if the index register has other uses.
1285
Dan Gohman99ba4da2010-06-18 01:24:29 +00001286 // Add an artificial use to this node so that we can keep track of
1287 // it if it gets CSE'd with a different node.
1288 HandleSDNode Handle(N);
1289
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001290 // Test if the LHS of the sub can be folded.
1291 X86ISelAddressMode Backup = AM;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001292 if (matchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001293 AM = Backup;
1294 break;
1295 }
1296 // Test if the index field is free for use.
Chris Lattnerfea81da2009-06-27 04:16:01 +00001297 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001298 AM = Backup;
1299 break;
1300 }
Evan Cheng68333f52010-03-17 23:58:35 +00001301
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001302 int Cost = 0;
Dan Gohman99ba4da2010-06-18 01:24:29 +00001303 SDValue RHS = Handle.getValue().getNode()->getOperand(1);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001304 // If the RHS involves a register with multiple uses, this
1305 // transformation incurs an extra mov, due to the neg instruction
1306 // clobbering its operand.
1307 if (!RHS.getNode()->hasOneUse() ||
1308 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1309 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1310 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1311 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
Owen Anderson9f944592009-08-11 20:47:22 +00001312 RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001313 ++Cost;
1314 // If the base is a register with multiple uses, this
1315 // transformation may save a mov.
Benjamin Kramer58dadd52017-04-20 18:29:14 +00001316 // FIXME: Don't rely on DELETED_NODEs.
1317 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1318 AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001319 !AM.Base_Reg.getNode()->hasOneUse()) ||
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001320 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1321 --Cost;
1322 // If the folded LHS was interesting, this transformation saves
1323 // address arithmetic.
1324 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1325 ((AM.Disp != 0) && (Backup.Disp == 0)) +
1326 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1327 --Cost;
1328 // If it doesn't look like it may be an overall win, don't do it.
1329 if (Cost >= 0) {
1330 AM = Backup;
1331 break;
1332 }
1333
1334 // Ok, the transformation is legal and appears profitable. Go for it.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001335 SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001336 SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1337 AM.IndexReg = Neg;
1338 AM.Scale = 1;
1339
1340 // Insert the new nodes into the topological ordering.
Nirav Dave9ebefeb2017-03-23 18:25:17 +00001341 insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1342 insertDAGNode(*CurDAG, Handle.getValue(), Neg);
Dan Gohmanfaf75c82009-05-11 18:02:53 +00001343 return false;
1344 }
1345
Sanjay Patelefab8b02015-10-21 18:56:06 +00001346 case ISD::ADD:
1347 if (!matchAdd(N, AM, Depth))
Dan Gohman99ba4da2010-06-18 01:24:29 +00001348 return false;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001349 break;
Evan Cheng734e1e22006-05-30 06:59:36 +00001350
Sanjay Patel533c10c2015-11-09 23:31:38 +00001351 case ISD::OR:
Sanjay Patel32538d62015-11-09 21:16:49 +00001352 // We want to look through a transform in InstCombine and DAGCombiner that
1353 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
Sanjay Patel533c10c2015-11-09 23:31:38 +00001354 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
Sanjay Patel32538d62015-11-09 21:16:49 +00001355 // An 'lea' can then be used to match the shift (multiply) and add:
1356 // and $1, %esi
1357 // lea (%rsi, %rdi, 8), %rax
Sanjay Patel533c10c2015-11-09 23:31:38 +00001358 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1359 !matchAdd(N, AM, Depth))
1360 return false;
Evan Cheng734e1e22006-05-30 06:59:36 +00001361 break;
Chad Rosier24c19d22012-08-01 18:39:17 +00001362
Evan Cheng827d30d2007-12-13 00:43:27 +00001363 case ISD::AND: {
Dan Gohman57d6bd32009-04-13 16:09:41 +00001364 // Perform some heroic transforms on an and of a constant-count shift
1365 // with a constant to enable use of the scaled offset field.
1366
Evan Cheng827d30d2007-12-13 00:43:27 +00001367 // Scale must not be used already.
Craig Topper062a2ba2014-04-25 05:30:21 +00001368 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
Evan Chenga20a7732008-02-07 08:53:49 +00001369
Chandler Carruthaa01e662012-01-11 09:35:00 +00001370 SDValue Shift = N.getOperand(0);
1371 if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001372 SDValue X = Shift.getOperand(0);
Chandler Carruthaa01e662012-01-11 09:35:00 +00001373
1374 // We only handle up to 64-bit values here as those are what matter for
1375 // addressing mode optimizations.
Craig Topper83e042a2013-08-15 05:57:07 +00001376 if (X.getSimpleValueType().getSizeInBits() > 64) break;
Chandler Carruthaa01e662012-01-11 09:35:00 +00001377
Chandler Carruthb0049f42012-01-11 09:35:04 +00001378 if (!isa<ConstantSDNode>(N.getOperand(1)))
1379 break;
1380 uint64_t Mask = N.getConstantOperandVal(1);
Evan Cheng827d30d2007-12-13 00:43:27 +00001381
Chandler Carruth51d30762012-01-11 08:48:20 +00001382 // Try to fold the mask and shift into an extract and scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001383 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth51d30762012-01-11 08:48:20 +00001384 return false;
Dan Gohman57d6bd32009-04-13 16:09:41 +00001385
Chandler Carruth51d30762012-01-11 08:48:20 +00001386 // Try to fold the mask and shift directly into the scale.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001387 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruth55b2cde2012-01-11 08:41:08 +00001388 return false;
1389
Chandler Carruthaa01e662012-01-11 09:35:00 +00001390 // Try to swap the mask and shift to place shifts which can be done as
1391 // a scale on the outside of the mask.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001392 if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
Chandler Carruthaa01e662012-01-11 09:35:00 +00001393 return false;
1394 break;
Evan Cheng827d30d2007-12-13 00:43:27 +00001395 }
Evan Cheng734e1e22006-05-30 06:59:36 +00001396 }
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001397
Sanjay Patel85030aa2015-10-13 16:23:00 +00001398 return matchAddressBase(N, AM);
Dan Gohmanccb36112007-08-13 20:03:06 +00001399}
1400
Sanjay Patelb5723d02015-10-13 15:12:27 +00001401/// Helper for MatchAddress. Add the specified node to the
Dan Gohmanccb36112007-08-13 20:03:06 +00001402/// specified addressing mode without any further recursion.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001403bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001404 // Is the base register already occupied?
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001405 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001406 // If so, check to see if the scale index register is set.
Craig Topper062a2ba2014-04-25 05:30:21 +00001407 if (!AM.IndexReg.getNode()) {
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001408 AM.IndexReg = N;
1409 AM.Scale = 1;
1410 return false;
1411 }
1412
1413 // Otherwise, we cannot select it.
1414 return true;
1415 }
1416
1417 // Default, generate it as a register.
1418 AM.BaseType = X86ISelAddressMode::RegBase;
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001419 AM.Base_Reg = N;
Chris Lattner3f0f71b2005-11-19 02:11:08 +00001420 return false;
1421}
1422
Sanjay Patel85030aa2015-10-13 16:23:00 +00001423bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001424 SDValue &Scale, SDValue &Index,
1425 SDValue &Disp, SDValue &Segment) {
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001426
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001427 MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1428 if (!Mgs)
1429 return false;
1430 X86ISelAddressMode AM;
1431 unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001432 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001433 if (AddrSpace == 256)
1434 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1435 if (AddrSpace == 257)
1436 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001437 if (AddrSpace == 258)
1438 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001439
1440 SDLoc DL(N);
1441 Base = Mgs->getBasePtr();
1442 Index = Mgs->getIndex();
Sanjay Patel5f6bb6c2016-09-14 15:43:44 +00001443 unsigned ScalarSize = Mgs->getValue().getScalarValueSizeInBits();
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001444 Scale = getI8Imm(ScalarSize/8, DL);
1445
1446 // If Base is 0, the whole address is in index and the Scale is 1
Daniel Jasper232778a2015-04-30 09:01:21 +00001447 if (isa<ConstantSDNode>(Base)) {
Mehdi Amini42152362015-10-21 06:11:01 +00001448 assert(cast<ConstantSDNode>(Base)->isNullValue() &&
Daniel Jasper232778a2015-04-30 09:01:21 +00001449 "Unexpected base in gather/scatter");
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001450 Scale = getI8Imm(1, DL);
1451 Base = CurDAG->getRegister(0, MVT::i32);
1452 }
1453 if (AM.Segment.getNode())
1454 Segment = AM.Segment;
1455 else
1456 Segment = CurDAG->getRegister(0, MVT::i32);
1457 Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1458 return true;
1459}
1460
Sanjay Patelb5723d02015-10-13 15:12:27 +00001461/// Returns true if it is able to pattern match an addressing mode.
Evan Chengc9fab312005-12-08 02:01:35 +00001462/// It returns the operands which make up the maximal addressing mode it can
1463/// match by reference.
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001464///
1465/// Parent is the parent node of the addr operand that is being matched. It
1466/// is always a load, store, atomic node, or null. It is only null when
1467/// checking memory operands for inline asm nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001468bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001469 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001470 SDValue &Disp, SDValue &Segment) {
Evan Chengc9fab312005-12-08 02:01:35 +00001471 X86ISelAddressMode AM;
Chad Rosier24c19d22012-08-01 18:39:17 +00001472
Chris Lattner8a236b62010-09-22 04:39:11 +00001473 if (Parent &&
1474 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1475 // that are not a MemSDNode, and thus don't have proper addrspace info.
Chris Lattner8a236b62010-09-22 04:39:11 +00001476 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
Eric Christopherc1b3e072010-09-22 20:42:08 +00001477 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
Michael Liao97bf3632012-10-15 22:39:43 +00001478 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1479 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1480 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
Chris Lattner8a236b62010-09-22 04:39:11 +00001481 unsigned AddrSpace =
1482 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001483 // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
Chris Lattner8a236b62010-09-22 04:39:11 +00001484 if (AddrSpace == 256)
1485 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1486 if (AddrSpace == 257)
1487 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
David L Kreitzerc9fbf102016-05-03 20:16:08 +00001488 if (AddrSpace == 258)
1489 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
Chris Lattner8a236b62010-09-22 04:39:11 +00001490 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001491
Sanjay Patel85030aa2015-10-13 16:23:00 +00001492 if (matchAddress(N, AM))
Evan Chengbc7a0f442006-01-11 06:09:51 +00001493 return false;
Evan Chengc9fab312005-12-08 02:01:35 +00001494
Craig Topper83e042a2013-08-15 05:57:07 +00001495 MVT VT = N.getSimpleValueType();
Evan Chengbc7a0f442006-01-11 06:09:51 +00001496 if (AM.BaseType == X86ISelAddressMode::RegBase) {
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001497 if (!AM.Base_Reg.getNode())
1498 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Chengc9fab312005-12-08 02:01:35 +00001499 }
Evan Chengbc7a0f442006-01-11 06:09:51 +00001500
Gabor Greiff304a7a2008-08-28 21:40:38 +00001501 if (!AM.IndexReg.getNode())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001502 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001503
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001504 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Evan Chengbc7a0f442006-01-11 06:09:51 +00001505 return true;
Evan Chengc9fab312005-12-08 02:01:35 +00001506}
1507
Sanjay Patelb5723d02015-10-13 15:12:27 +00001508/// Match a scalar SSE load. In particular, we want to match a load whose top
1509/// elements are either undef or zeros. The load flavor is derived from the
1510/// type of N, which is either v4f32 or v2f64.
Chris Lattner3f482152010-02-17 06:07:47 +00001511///
1512/// We also return:
Chris Lattner18a32ce2010-02-21 03:17:59 +00001513/// PatternChainNode: this is the matched node that has a chain input and
1514/// output.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001515bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001516 SDValue N, SDValue &Base,
1517 SDValue &Scale, SDValue &Index,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001518 SDValue &Disp, SDValue &Segment,
Chris Lattner18a32ce2010-02-21 03:17:59 +00001519 SDValue &PatternNodeWithChain) {
Craig Topper36ecce92016-12-12 07:57:24 +00001520 // We can allow a full vector load here since narrowing a load is ok.
1521 if (ISD::isNON_EXTLoad(N.getNode())) {
1522 PatternNodeWithChain = N;
1523 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper1fd41962016-12-19 08:35:56 +00001524 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001525 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1526 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1527 Segment);
1528 }
1529 }
1530
1531 // We can also match the special zero extended load opcode.
1532 if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1533 PatternNodeWithChain = N;
1534 if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
Craig Topper1fd41962016-12-19 08:35:56 +00001535 IsLegalToFold(PatternNodeWithChain, *N->use_begin(), Root, OptLevel)) {
Craig Topper36ecce92016-12-12 07:57:24 +00001536 auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1537 return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1538 Segment);
1539 }
1540 }
1541
Craig Topper991d1ca2016-11-26 17:29:25 +00001542 // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
1543 // once. Otherwise the load might get duplicated and the chain output of the
1544 // duplicate load will not be observed by all dependencies.
1545 if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001546 PatternNodeWithChain = N.getOperand(0);
1547 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Topper991d1ca2016-11-26 17:29:25 +00001548 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1549 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
Chris Lattner18a32ce2010-02-21 03:17:59 +00001550 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
Craig Topperd3ab1a32016-11-26 18:43:21 +00001551 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1552 Segment);
Chris Lattner398195e2006-10-07 21:55:32 +00001553 }
1554 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001555
1556 // Also handle the case where we explicitly require zeros in the top
Chris Lattner398195e2006-10-07 21:55:32 +00001557 // elements. This is a vector shuffle from the zero vector.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001558 if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
Chris Lattner5728bdd2007-11-25 00:24:49 +00001559 // Check to see if the top elements are all zeros (or bitcast of zeros).
Chad Rosier24c19d22012-08-01 18:39:17 +00001560 N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
Craig Toppere266e122016-11-26 18:43:24 +00001561 N.getOperand(0).getNode()->hasOneUse()) {
1562 PatternNodeWithChain = N.getOperand(0).getOperand(0);
1563 if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
Craig Toppere266e122016-11-26 18:43:24 +00001564 IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1565 IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
1566 // Okay, this is a zero extending load. Fold it.
1567 LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1568 return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1569 Segment);
1570 }
Chris Lattnerd5fcfaa2006-10-11 22:09:58 +00001571 }
Craig Toppere266e122016-11-26 18:43:24 +00001572
Chris Lattner398195e2006-10-07 21:55:32 +00001573 return false;
1574}
1575
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001576
Sanjay Patel85030aa2015-10-13 16:23:00 +00001577bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001578 if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1579 uint64_t ImmVal = CN->getZExtValue();
1580 if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1581 return false;
1582
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001583 Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001584 return true;
1585 }
1586
1587 // In static codegen with small code model, we can get the address of a label
1588 // into a register with 'movl'. TableGen has already made sure we're looking
1589 // at a label of some kind.
Tim Northover6833e3f2013-06-10 20:43:49 +00001590 assert(N->getOpcode() == X86ISD::Wrapper &&
1591 "Unexpected node type for MOV32ri64");
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001592 N = N.getOperand(0);
1593
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001594 // At least GNU as does not accept 'movl' for TPOFF relocations.
1595 // FIXME: We could use 'movl' when we know we are targeting MC.
1596 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001597 return false;
1598
1599 Imm = N;
Peter Collingbourne235c2752016-12-08 19:01:00 +00001600 if (N->getOpcode() != ISD::TargetGlobalAddress)
1601 return TM.getCodeModel() == CodeModel::Small;
1602
1603 Optional<ConstantRange> CR =
1604 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
1605 if (!CR)
1606 return TM.getCodeModel() == CodeModel::Small;
1607
1608 return CR->getUnsignedMax().ult(1ull << 32);
Tim Northover3a1fd4c2013-06-01 09:55:14 +00001609}
1610
Sanjay Patel85030aa2015-10-13 16:23:00 +00001611bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
Tim Northover6833e3f2013-06-10 20:43:49 +00001612 SDValue &Scale, SDValue &Index,
1613 SDValue &Disp, SDValue &Segment) {
Justin Bogner32ad24d2016-04-12 21:34:24 +00001614 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
1615 SDLoc DL(N);
1616
Sanjay Patel85030aa2015-10-13 16:23:00 +00001617 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
Tim Northover6833e3f2013-06-10 20:43:49 +00001618 return false;
1619
Tim Northover6833e3f2013-06-10 20:43:49 +00001620 RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1621 if (RN && RN->getReg() == 0)
1622 Base = CurDAG->getRegister(0, MVT::i64);
Pavel Chupin01a4e0a2014-08-20 11:59:22 +00001623 else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
Tim Northover6833e3f2013-06-10 20:43:49 +00001624 // Base could already be %rip, particularly in the x32 ABI.
1625 Base = SDValue(CurDAG->getMachineNode(
1626 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001627 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001628 Base,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001629 CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001630 0);
1631 }
1632
1633 RN = dyn_cast<RegisterSDNode>(Index);
1634 if (RN && RN->getReg() == 0)
1635 Index = CurDAG->getRegister(0, MVT::i64);
1636 else {
1637 assert(Index.getValueType() == MVT::i32 &&
1638 "Expect to be extending 32-bit registers for use in LEA");
1639 Index = SDValue(CurDAG->getMachineNode(
1640 TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001641 CurDAG->getTargetConstant(0, DL, MVT::i64),
Tim Northover6833e3f2013-06-10 20:43:49 +00001642 Index,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001643 CurDAG->getTargetConstant(X86::sub_32bit, DL,
1644 MVT::i32)),
Tim Northover6833e3f2013-06-10 20:43:49 +00001645 0);
1646 }
1647
1648 return true;
1649}
1650
Sanjay Patelb5723d02015-10-13 15:12:27 +00001651/// Calls SelectAddr and determines if the maximal addressing
Evan Cheng77d86ff2006-02-25 10:09:08 +00001652/// mode it matches can be cost effectively emitted as an LEA instruction.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001653bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001654 SDValue &Base, SDValue &Scale,
Chris Lattnerf4693072010-07-08 23:46:44 +00001655 SDValue &Index, SDValue &Disp,
1656 SDValue &Segment) {
Evan Cheng77d86ff2006-02-25 10:09:08 +00001657 X86ISelAddressMode AM;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001658
Justin Bogner32ad24d2016-04-12 21:34:24 +00001659 // Save the DL and VT before calling matchAddress, it can invalidate N.
1660 SDLoc DL(N);
1661 MVT VT = N.getSimpleValueType();
1662
Rafael Espindolabb834f02009-04-10 10:09:34 +00001663 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1664 // segments.
1665 SDValue Copy = AM.Segment;
Owen Anderson9f944592009-08-11 20:47:22 +00001666 SDValue T = CurDAG->getRegister(0, MVT::i32);
Rafael Espindolabb834f02009-04-10 10:09:34 +00001667 AM.Segment = T;
Sanjay Patel85030aa2015-10-13 16:23:00 +00001668 if (matchAddress(N, AM))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001669 return false;
Rafael Espindolabb834f02009-04-10 10:09:34 +00001670 assert (T == AM.Segment);
1671 AM.Segment = Copy;
Rafael Espindola3b2df102009-04-08 21:14:34 +00001672
Evan Cheng77d86ff2006-02-25 10:09:08 +00001673 unsigned Complexity = 0;
1674 if (AM.BaseType == X86ISelAddressMode::RegBase)
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001675 if (AM.Base_Reg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001676 Complexity = 1;
1677 else
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001678 AM.Base_Reg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001679 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1680 Complexity = 4;
1681
Gabor Greiff304a7a2008-08-28 21:40:38 +00001682 if (AM.IndexReg.getNode())
Evan Cheng77d86ff2006-02-25 10:09:08 +00001683 Complexity++;
1684 else
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001685 AM.IndexReg = CurDAG->getRegister(0, VT);
Evan Cheng77d86ff2006-02-25 10:09:08 +00001686
Chris Lattner3e1d9172007-03-20 06:08:29 +00001687 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1688 // a simple shift.
1689 if (AM.Scale > 1)
Evan Cheng990c3602006-02-28 21:13:57 +00001690 Complexity++;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001691
1692 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
Sanjay Patelb814ef12015-10-12 16:09:59 +00001693 // to a LEA. This is determined with some experimentation but is by no means
Evan Cheng77d86ff2006-02-25 10:09:08 +00001694 // optimal (especially for code size consideration). LEA is nice because of
1695 // its three-address nature. Tweak the cost function again when we can run
1696 // convertToThreeAddress() at register allocation time.
Dan Gohman4e3e3de2009-02-07 00:43:41 +00001697 if (AM.hasSymbolicDisplacement()) {
Sanjay Patelb814ef12015-10-12 16:09:59 +00001698 // For X86-64, always use LEA to materialize RIP-relative addresses.
Evan Cheng47e181c2006-12-05 22:03:40 +00001699 if (Subtarget->is64Bit())
Evan Cheng11b0a5d2006-09-08 06:48:29 +00001700 Complexity = 4;
1701 else
1702 Complexity += 2;
1703 }
Evan Cheng77d86ff2006-02-25 10:09:08 +00001704
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001705 if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
Evan Cheng77d86ff2006-02-25 10:09:08 +00001706 Complexity++;
1707
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001708 // If it isn't worth using an LEA, reject it.
Chris Lattner48cee9b2009-07-11 23:07:30 +00001709 if (Complexity <= 2)
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001710 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001711
Justin Bogner32ad24d2016-04-12 21:34:24 +00001712 getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
Chris Lattner4d10f1a2009-07-11 22:50:33 +00001713 return true;
Evan Cheng77d86ff2006-02-25 10:09:08 +00001714}
1715
Sanjay Patelb5723d02015-10-13 15:12:27 +00001716/// This is only run on TargetGlobalTLSAddress nodes.
Sanjay Patel85030aa2015-10-13 16:23:00 +00001717bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
Chris Lattner7d2b0492009-06-20 20:38:48 +00001718 SDValue &Scale, SDValue &Index,
Chris Lattnerf4693072010-07-08 23:46:44 +00001719 SDValue &Disp, SDValue &Segment) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001720 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1721 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
Chad Rosier24c19d22012-08-01 18:39:17 +00001722
Chris Lattner7d2b0492009-06-20 20:38:48 +00001723 X86ISelAddressMode AM;
1724 AM.GV = GA->getGlobal();
1725 AM.Disp += GA->getOffset();
Dan Gohman0fd54fb2010-04-29 23:30:41 +00001726 AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
Chris Lattner899abc42009-06-26 21:18:37 +00001727 AM.SymbolFlags = GA->getTargetFlags();
1728
Owen Anderson9f944592009-08-11 20:47:22 +00001729 if (N.getValueType() == MVT::i32) {
Chris Lattner7d2b0492009-06-20 20:38:48 +00001730 AM.Scale = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00001731 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001732 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00001733 AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001734 }
Chad Rosier24c19d22012-08-01 18:39:17 +00001735
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001736 getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
Chris Lattner7d2b0492009-06-20 20:38:48 +00001737 return true;
1738}
1739
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001740bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
1741 if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1742 Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
1743 N.getValueType());
1744 return true;
1745 }
1746
Peter Collingbourne235c2752016-12-08 19:01:00 +00001747 // Keep track of the original value type and whether this value was
1748 // truncated. If we see a truncation from pointer type to VT that truncates
1749 // bits that are known to be zero, we can use a narrow reference.
1750 EVT VT = N.getValueType();
1751 bool WasTruncated = false;
1752 if (N.getOpcode() == ISD::TRUNCATE) {
1753 WasTruncated = true;
1754 N = N.getOperand(0);
1755 }
1756
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001757 if (N.getOpcode() != X86ISD::Wrapper)
1758 return false;
1759
Peter Collingbourne235c2752016-12-08 19:01:00 +00001760 // We can only use non-GlobalValues as immediates if they were not truncated,
1761 // as we do not have any range information. If we have a GlobalValue and the
1762 // address was not truncated, we can select it as an operand directly.
1763 unsigned Opc = N.getOperand(0)->getOpcode();
1764 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
1765 Op = N.getOperand(0);
1766 // We can only select the operand directly if we didn't have to look past a
1767 // truncate.
1768 return !WasTruncated;
1769 }
1770
1771 // Check that the global's range fits into VT.
1772 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
1773 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1774 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
1775 return false;
1776
1777 // Okay, we can use a narrow reference.
1778 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
1779 GA->getOffset(), GA->getTargetFlags());
Peter Collingbourne7d0c8692016-11-16 21:48:59 +00001780 return true;
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001781}
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001782
Sanjay Patel85030aa2015-10-13 16:23:00 +00001783bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001784 SDValue &Base, SDValue &Scale,
Rafael Espindola3b2df102009-04-08 21:14:34 +00001785 SDValue &Index, SDValue &Disp,
1786 SDValue &Segment) {
Chris Lattnerdd030702010-03-02 22:20:06 +00001787 if (!ISD::isNON_EXTLoad(N.getNode()) ||
1788 !IsProfitableToFold(N, P, P) ||
Dan Gohman21cea8a2010-04-17 15:26:15 +00001789 !IsLegalToFold(N, P, P, OptLevel))
Chris Lattnerdd030702010-03-02 22:20:06 +00001790 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001791
Sanjay Patel85030aa2015-10-13 16:23:00 +00001792 return selectAddr(N.getNode(),
Chris Lattnerd58d7c12010-09-21 22:07:31 +00001793 N.getOperand(1), Base, Scale, Index, Disp, Segment);
Evan Cheng10d27902006-01-06 20:36:21 +00001794}
1795
Sanjay Patelb5723d02015-10-13 15:12:27 +00001796/// Return an SDNode that returns the value of the global base register.
1797/// Output instructions required to initialize the global base register,
1798/// if necessary.
Evan Cheng61413a32006-08-26 05:34:46 +00001799SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
Dan Gohman4751bb92009-06-03 20:20:00 +00001800 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
Mehdi Amini44ede332015-07-09 02:09:04 +00001801 auto &DL = MF->getDataLayout();
1802 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
Evan Cheng5588de92006-02-18 00:15:05 +00001803}
1804
Peter Collingbourneef089bd2017-02-09 22:02:28 +00001805bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
1806 if (N->getOpcode() == ISD::TRUNCATE)
1807 N = N->getOperand(0).getNode();
1808 if (N->getOpcode() != X86ISD::Wrapper)
1809 return false;
1810
1811 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
1812 if (!GA)
1813 return false;
1814
1815 Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
1816 return CR && CR->getSignedMin().sge(-1ull << Width) &&
1817 CR->getSignedMax().slt(1ull << Width);
1818}
1819
Sanjay Patelb5723d02015-10-13 15:12:27 +00001820/// Test whether the given X86ISD::CMP node has any uses which require the SF
1821/// or OF bits to be accurate.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001822static bool hasNoSignedComparisonUses(SDNode *N) {
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001823 // Examine each user of the node.
1824 for (SDNode::use_iterator UI = N->use_begin(),
1825 UE = N->use_end(); UI != UE; ++UI) {
1826 // Only examine CopyToReg uses.
1827 if (UI->getOpcode() != ISD::CopyToReg)
1828 return false;
1829 // Only examine CopyToReg uses that copy to EFLAGS.
1830 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1831 X86::EFLAGS)
1832 return false;
1833 // Examine each user of the CopyToReg use.
1834 for (SDNode::use_iterator FlagUI = UI->use_begin(),
1835 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1836 // Only examine the Flag result.
1837 if (FlagUI.getUse().getResNo() != 1) continue;
1838 // Anything unusual: assume conservatively.
1839 if (!FlagUI->isMachineOpcode()) return false;
1840 // Examine the opcode of the user.
1841 switch (FlagUI->getMachineOpcode()) {
1842 // These comparisons don't treat the most significant bit specially.
1843 case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1844 case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1845 case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1846 case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
Craig Topper49758aa2015-01-06 04:23:53 +00001847 case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1848 case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001849 case X86::CMOVA16rr: case X86::CMOVA16rm:
1850 case X86::CMOVA32rr: case X86::CMOVA32rm:
1851 case X86::CMOVA64rr: case X86::CMOVA64rm:
1852 case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1853 case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1854 case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1855 case X86::CMOVB16rr: case X86::CMOVB16rm:
1856 case X86::CMOVB32rr: case X86::CMOVB32rm:
1857 case X86::CMOVB64rr: case X86::CMOVB64rm:
Chris Lattner1a1c6002010-10-05 23:00:14 +00001858 case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1859 case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1860 case X86::CMOVBE64rr: case X86::CMOVBE64rm:
Dan Gohman7d9dffb2009-10-09 20:35:19 +00001861 case X86::CMOVE16rr: case X86::CMOVE16rm:
1862 case X86::CMOVE32rr: case X86::CMOVE32rm:
1863 case X86::CMOVE64rr: case X86::CMOVE64rm:
1864 case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1865 case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1866 case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1867 case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1868 case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1869 case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1870 case X86::CMOVP16rr: case X86::CMOVP16rm:
1871 case X86::CMOVP32rr: case X86::CMOVP32rm:
1872 case X86::CMOVP64rr: case X86::CMOVP64rm:
1873 continue;
1874 // Anything else: assume conservatively.
1875 default: return false;
1876 }
1877 }
1878 }
1879 return true;
1880}
1881
Sanjay Patelb5723d02015-10-13 15:12:27 +00001882/// Check whether or not the chain ending in StoreNode is suitable for doing
1883/// the {load; increment or decrement; store} to modify transformation.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001884static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1885 SDValue StoredVal, SelectionDAG *CurDAG,
1886 LoadSDNode* &LoadNode, SDValue &InputChain) {
1887
Joel Jones68d59e82012-03-29 05:45:48 +00001888 // is the value stored the result of a DEC or INC?
1889 if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1890
Joel Jones68d59e82012-03-29 05:45:48 +00001891 // is the stored value result 0 of the load?
1892 if (StoredVal.getResNo() != 0) return false;
1893
1894 // are there other uses of the loaded value than the inc or dec?
1895 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1896
Joel Jones68d59e82012-03-29 05:45:48 +00001897 // is the store non-extending and non-indexed?
Evan Cheng3e869f02012-04-12 19:14:21 +00001898 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
Joel Jones68d59e82012-03-29 05:45:48 +00001899 return false;
1900
Evan Cheng3e869f02012-04-12 19:14:21 +00001901 SDValue Load = StoredVal->getOperand(0);
1902 // Is the stored value a non-extending and non-indexed load?
1903 if (!ISD::isNormalLoad(Load.getNode())) return false;
1904
1905 // Return LoadNode by reference.
1906 LoadNode = cast<LoadSDNode>(Load);
1907 // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
Chad Rosier24c19d22012-08-01 18:39:17 +00001908 EVT LdVT = LoadNode->getMemoryVT();
1909 if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
Evan Cheng3e869f02012-04-12 19:14:21 +00001910 LdVT != MVT::i8)
1911 return false;
1912
1913 // Is store the only read of the loaded value?
1914 if (!Load.hasOneUse())
1915 return false;
Chad Rosier24c19d22012-08-01 18:39:17 +00001916
Evan Cheng3e869f02012-04-12 19:14:21 +00001917 // Is the address of the store the same as the load?
1918 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1919 LoadNode->getOffset() != StoreNode->getOffset())
1920 return false;
1921
1922 // Check if the chain is produced by the load or is a TokenFactor with
1923 // the load output chain as an operand. Return InputChain by reference.
1924 SDValue Chain = StoreNode->getChain();
1925
1926 bool ChainCheck = false;
1927 if (Chain == Load.getValue(1)) {
1928 ChainCheck = true;
1929 InputChain = LoadNode->getChain();
1930 } else if (Chain.getOpcode() == ISD::TokenFactor) {
1931 SmallVector<SDValue, 4> ChainOps;
1932 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1933 SDValue Op = Chain.getOperand(i);
1934 if (Op == Load.getValue(1)) {
1935 ChainCheck = true;
Nirav Davee14300e2017-02-02 14:39:26 +00001936 // Drop Load, but keep its chain. No cycle check necessary.
1937 ChainOps.push_back(Load.getOperand(0));
Evan Cheng3e869f02012-04-12 19:14:21 +00001938 continue;
1939 }
Evan Cheng58a95f02012-05-16 01:54:27 +00001940
1941 // Make sure using Op as part of the chain would not cause a cycle here.
1942 // In theory, we could check whether the chain node is a predecessor of
1943 // the load. But that can be very expensive. Instead visit the uses and
1944 // make sure they all have smaller node id than the load.
1945 int LoadId = LoadNode->getNodeId();
1946 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1947 UE = UI->use_end(); UI != UE; ++UI) {
1948 if (UI.getUse().getResNo() != 0)
1949 continue;
1950 if (UI->getNodeId() > LoadId)
1951 return false;
1952 }
1953
Evan Cheng3e869f02012-04-12 19:14:21 +00001954 ChainOps.push_back(Op);
1955 }
1956
1957 if (ChainCheck)
1958 // Make a new TokenFactor with all the other input chains except
1959 // for the load.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001960 InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
Craig Topper48d114b2014-04-26 18:35:24 +00001961 MVT::Other, ChainOps);
Evan Cheng3e869f02012-04-12 19:14:21 +00001962 }
1963 if (!ChainCheck)
Joel Jones68d59e82012-03-29 05:45:48 +00001964 return false;
1965
1966 return true;
1967}
1968
Sanjay Patelb5723d02015-10-13 15:12:27 +00001969/// Get the appropriate X86 opcode for an in-memory increment or decrement.
1970/// Opc should be X86ISD::DEC or X86ISD::INC.
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001971static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
Joel Jones68d59e82012-03-29 05:45:48 +00001972 if (Opc == X86ISD::DEC) {
1973 if (LdVT == MVT::i64) return X86::DEC64m;
1974 if (LdVT == MVT::i32) return X86::DEC32m;
1975 if (LdVT == MVT::i16) return X86::DEC16m;
1976 if (LdVT == MVT::i8) return X86::DEC8m;
Benjamin Kramer8619c372012-03-29 12:37:26 +00001977 } else {
1978 assert(Opc == X86ISD::INC && "unrecognized opcode");
Joel Jones68d59e82012-03-29 05:45:48 +00001979 if (LdVT == MVT::i64) return X86::INC64m;
1980 if (LdVT == MVT::i32) return X86::INC32m;
1981 if (LdVT == MVT::i16) return X86::INC16m;
1982 if (LdVT == MVT::i8) return X86::INC8m;
Joel Jones68d59e82012-03-29 05:45:48 +00001983 }
Benjamin Kramer8619c372012-03-29 12:37:26 +00001984 llvm_unreachable("unrecognized size for LdVT");
Joel Jones68d59e82012-03-29 05:45:48 +00001985}
1986
Justin Bogner593741d2016-05-10 23:55:37 +00001987void X86DAGToDAGISel::Select(SDNode *Node) {
Craig Topper83e042a2013-08-15 05:57:07 +00001988 MVT NVT = Node->getSimpleValueType(0);
Evan Cheng10d27902006-01-06 20:36:21 +00001989 unsigned Opc, MOpc;
1990 unsigned Opcode = Node->getOpcode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001991 SDLoc dl(Node);
Chad Rosier24c19d22012-08-01 18:39:17 +00001992
Chris Lattnerf98f1242010-03-02 06:34:30 +00001993 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
Evan Chengd49cc362006-02-10 22:24:32 +00001994
Dan Gohman17059682008-07-17 19:10:17 +00001995 if (Node->isMachineOpcode()) {
Chris Lattnerf98f1242010-03-02 06:34:30 +00001996 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
Tim Northover31d093c2013-09-22 08:21:56 +00001997 Node->setNodeId(-1);
Justin Bogner593741d2016-05-10 23:55:37 +00001998 return; // Already selected.
Evan Cheng6dc90ca2006-02-09 00:37:58 +00001999 }
Evan Cheng2ae799a2006-01-11 22:15:18 +00002000
Evan Cheng10d27902006-01-06 20:36:21 +00002001 switch (Opcode) {
Tobias Grosser85508e82015-08-19 11:35:10 +00002002 default: break;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002003 case ISD::BRIND: {
2004 if (Subtarget->isTargetNaCl())
2005 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
2006 // leave the instruction alone.
2007 break;
2008 if (Subtarget->isTarget64BitILP32()) {
2009 // Converts a 32-bit register to a 64-bit, zero-extended version of
2010 // it. This is needed because x86-64 can do many things, but jmp %r32
2011 // ain't one of them.
2012 const SDValue &Target = Node->getOperand(1);
2013 assert(Target.getSimpleValueType() == llvm::MVT::i32);
2014 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
2015 SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
2016 Node->getOperand(0), ZextTarget);
Justin Bogner9b6b9c72016-05-13 23:26:28 +00002017 ReplaceNode(Node, Brind.getNode());
JF Bastien5ab87ed2015-08-19 16:17:08 +00002018 SelectCode(ZextTarget.getNode());
2019 SelectCode(Brind.getNode());
Justin Bogner593741d2016-05-10 23:55:37 +00002020 return;
JF Bastien5ab87ed2015-08-19 16:17:08 +00002021 }
2022 break;
2023 }
Dan Gohman757eee82009-08-02 16:10:52 +00002024 case X86ISD::GlobalBaseReg:
Justin Bogner31d7da32016-05-11 21:13:17 +00002025 ReplaceNode(Node, getGlobalBaseReg());
Justin Bogner593741d2016-05-10 23:55:37 +00002026 return;
Evan Chenge0ed6ec2006-02-23 20:41:18 +00002027
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002028 case X86ISD::SHRUNKBLEND: {
2029 // SHRUNKBLEND selects like a regular VSELECT.
2030 SDValue VSelect = CurDAG->getNode(
2031 ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2032 Node->getOperand(1), Node->getOperand(2));
2033 ReplaceUses(SDValue(Node, 0), VSelect);
2034 SelectCode(VSelect.getNode());
2035 // We already called ReplaceUses.
Justin Bogner593741d2016-05-10 23:55:37 +00002036 return;
Quentin Colombetdbe33e72014-11-06 02:25:03 +00002037 }
Craig Topper3af251d2012-07-01 02:55:34 +00002038
Tobias Grosser85508e82015-08-19 11:35:10 +00002039 case ISD::AND:
Benjamin Kramer4c816242011-04-22 15:30:40 +00002040 case ISD::OR:
2041 case ISD::XOR: {
2042 // For operations of the form (x << C1) op C2, check if we can use a smaller
2043 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2044 SDValue N0 = Node->getOperand(0);
2045 SDValue N1 = Node->getOperand(1);
2046
2047 if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2048 break;
2049
2050 // i8 is unshrinkable, i16 should be promoted to i32.
2051 if (NVT != MVT::i32 && NVT != MVT::i64)
2052 break;
2053
2054 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2055 ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2056 if (!Cst || !ShlCst)
2057 break;
2058
2059 int64_t Val = Cst->getSExtValue();
2060 uint64_t ShlVal = ShlCst->getZExtValue();
2061
2062 // Make sure that we don't change the operation by removing bits.
2063 // This only matters for OR and XOR, AND is unaffected.
Richard Smith228e6d42012-08-24 23:29:28 +00002064 uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2065 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
Benjamin Kramer4c816242011-04-22 15:30:40 +00002066 break;
2067
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002068 unsigned ShlOp, AddOp, Op;
Craig Topper83e042a2013-08-15 05:57:07 +00002069 MVT CstVT = NVT;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002070
2071 // Check the minimum bitwidth for the new constant.
2072 // TODO: AND32ri is the same as AND64ri32 with zext imm.
2073 // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2074 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2075 if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2076 CstVT = MVT::i8;
2077 else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2078 CstVT = MVT::i32;
2079
2080 // Bail if there is no smaller encoding.
2081 if (NVT == CstVT)
2082 break;
2083
Craig Topper83e042a2013-08-15 05:57:07 +00002084 switch (NVT.SimpleTy) {
Benjamin Kramer4c816242011-04-22 15:30:40 +00002085 default: llvm_unreachable("Unsupported VT!");
2086 case MVT::i32:
2087 assert(CstVT == MVT::i8);
2088 ShlOp = X86::SHL32ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002089 AddOp = X86::ADD32rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002090
2091 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002092 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002093 case ISD::AND: Op = X86::AND32ri8; break;
2094 case ISD::OR: Op = X86::OR32ri8; break;
2095 case ISD::XOR: Op = X86::XOR32ri8; break;
2096 }
2097 break;
2098 case MVT::i64:
2099 assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2100 ShlOp = X86::SHL64ri;
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002101 AddOp = X86::ADD64rr;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002102
2103 switch (Opcode) {
Craig Topper22cb0c52012-08-11 17:44:14 +00002104 default: llvm_unreachable("Impossible opcode");
Benjamin Kramer4c816242011-04-22 15:30:40 +00002105 case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2106 case ISD::OR: Op = CstVT==MVT::i8? X86::OR64ri8 : X86::OR64ri32; break;
2107 case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2108 }
2109 break;
2110 }
2111
2112 // Emit the smaller op and the shift.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002113 SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
Benjamin Kramer4c816242011-04-22 15:30:40 +00002114 SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
Benjamin Kramer3a16a362015-04-01 19:01:09 +00002115 if (ShlVal == 1)
Justin Bogner593741d2016-05-10 23:55:37 +00002116 CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2117 SDValue(New, 0));
2118 else
2119 CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2120 getI8Imm(ShlVal, dl));
2121 return;
Benjamin Kramer4c816242011-04-22 15:30:40 +00002122 }
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002123 case X86ISD::UMUL8:
2124 case X86ISD::SMUL8: {
2125 SDValue N0 = Node->getOperand(0);
2126 SDValue N1 = Node->getOperand(1);
2127
2128 Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2129
2130 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2131 N0, SDValue()).getValue(1);
2132
2133 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2134 SDValue Ops[] = {N1, InFlag};
2135 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2136
Justin Bogner31d7da32016-05-11 21:13:17 +00002137 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002138 return;
Ahmed Bougacha5175bcf2014-10-23 21:55:31 +00002139 }
2140
Chris Lattner364bb0a2010-12-05 07:30:36 +00002141 case X86ISD::UMUL: {
2142 SDValue N0 = Node->getOperand(0);
2143 SDValue N1 = Node->getOperand(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002144
Ted Kremenekb5241b22011-01-14 22:34:13 +00002145 unsigned LoReg;
Craig Topper83e042a2013-08-15 05:57:07 +00002146 switch (NVT.SimpleTy) {
Chris Lattner364bb0a2010-12-05 07:30:36 +00002147 default: llvm_unreachable("Unsupported VT!");
Ted Kremenekb5241b22011-01-14 22:34:13 +00002148 case MVT::i8: LoReg = X86::AL; Opc = X86::MUL8r; break;
2149 case MVT::i16: LoReg = X86::AX; Opc = X86::MUL16r; break;
2150 case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2151 case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002152 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002153
Chris Lattner364bb0a2010-12-05 07:30:36 +00002154 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2155 N0, SDValue()).getValue(1);
Chad Rosier24c19d22012-08-01 18:39:17 +00002156
Chris Lattner364bb0a2010-12-05 07:30:36 +00002157 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2158 SDValue Ops[] = {N1, InFlag};
Michael Liaob53d8962013-04-19 22:22:57 +00002159 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Chad Rosier24c19d22012-08-01 18:39:17 +00002160
Justin Bognerfde9f2e2016-05-11 22:21:50 +00002161 ReplaceNode(Node, CNode);
Justin Bogner593741d2016-05-10 23:55:37 +00002162 return;
Chris Lattner364bb0a2010-12-05 07:30:36 +00002163 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002164
Dan Gohman757eee82009-08-02 16:10:52 +00002165 case ISD::SMUL_LOHI:
2166 case ISD::UMUL_LOHI: {
2167 SDValue N0 = Node->getOperand(0);
2168 SDValue N1 = Node->getOperand(1);
2169
2170 bool isSigned = Opcode == ISD::SMUL_LOHI;
Michael Liaof9f7b552012-09-26 08:22:37 +00002171 bool hasBMI2 = Subtarget->hasBMI2();
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002172 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002173 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002174 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002175 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
2176 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
Michael Liaof9f7b552012-09-26 08:22:37 +00002177 case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2178 MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2179 case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2180 MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002181 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002182 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002183 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002184 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002185 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
2186 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2187 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2188 case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002189 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002190 }
Dan Gohman757eee82009-08-02 16:10:52 +00002191
Michael Liaof9f7b552012-09-26 08:22:37 +00002192 unsigned SrcReg, LoReg, HiReg;
2193 switch (Opc) {
2194 default: llvm_unreachable("Unknown MUL opcode!");
2195 case X86::IMUL8r:
2196 case X86::MUL8r:
2197 SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2198 break;
2199 case X86::IMUL16r:
2200 case X86::MUL16r:
2201 SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2202 break;
2203 case X86::IMUL32r:
2204 case X86::MUL32r:
2205 SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2206 break;
2207 case X86::IMUL64r:
2208 case X86::MUL64r:
2209 SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2210 break;
2211 case X86::MULX32rr:
2212 SrcReg = X86::EDX; LoReg = HiReg = 0;
2213 break;
2214 case X86::MULX64rr:
2215 SrcReg = X86::RDX; LoReg = HiReg = 0;
2216 break;
Dan Gohman757eee82009-08-02 16:10:52 +00002217 }
2218
2219 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002220 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002221 // Multiply is commmutative.
Dan Gohman757eee82009-08-02 16:10:52 +00002222 if (!foldedLoad) {
Sanjay Patel85030aa2015-10-13 16:23:00 +00002223 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002224 if (foldedLoad)
2225 std::swap(N0, N1);
2226 }
2227
Michael Liaof9f7b552012-09-26 08:22:37 +00002228 SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
Craig Toppera4fd6d62012-05-23 05:44:51 +00002229 N0, SDValue()).getValue(1);
Michael Liaof9f7b552012-09-26 08:22:37 +00002230 SDValue ResHi, ResLo;
Dan Gohman757eee82009-08-02 16:10:52 +00002231
2232 if (foldedLoad) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002233 SDValue Chain;
Kyle Butt991df782016-06-23 21:40:35 +00002234 MachineSDNode *CNode = nullptr;
Dan Gohman757eee82009-08-02 16:10:52 +00002235 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2236 InFlag };
Michael Liaof9f7b552012-09-26 08:22:37 +00002237 if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2238 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002239 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002240 ResHi = SDValue(CNode, 0);
2241 ResLo = SDValue(CNode, 1);
2242 Chain = SDValue(CNode, 2);
2243 InFlag = SDValue(CNode, 3);
2244 } else {
2245 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
Kyle Butt991df782016-06-23 21:40:35 +00002246 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002247 Chain = SDValue(CNode, 0);
2248 InFlag = SDValue(CNode, 1);
2249 }
Chris Lattner364bb0a2010-12-05 07:30:36 +00002250
Dan Gohman757eee82009-08-02 16:10:52 +00002251 // Update the chain.
Michael Liaof9f7b552012-09-26 08:22:37 +00002252 ReplaceUses(N1.getValue(1), Chain);
Kyle Butt991df782016-06-23 21:40:35 +00002253 // Record the mem-refs
2254 LoadSDNode *LoadNode = cast<LoadSDNode>(N1);
2255 if (LoadNode) {
2256 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2257 MemOp[0] = LoadNode->getMemOperand();
2258 CNode->setMemRefs(MemOp, MemOp + 1);
2259 }
Dan Gohman757eee82009-08-02 16:10:52 +00002260 } else {
Michael Liaof9f7b552012-09-26 08:22:37 +00002261 SDValue Ops[] = { N1, InFlag };
2262 if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2263 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002264 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002265 ResHi = SDValue(CNode, 0);
2266 ResLo = SDValue(CNode, 1);
2267 InFlag = SDValue(CNode, 2);
2268 } else {
2269 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
Michael Liaob53d8962013-04-19 22:22:57 +00002270 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
Michael Liaof9f7b552012-09-26 08:22:37 +00002271 InFlag = SDValue(CNode, 0);
2272 }
Dan Gohman757eee82009-08-02 16:10:52 +00002273 }
2274
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002275 // Prevent use of AH in a REX instruction by referencing AX instead.
2276 if (HiReg == X86::AH && Subtarget->is64Bit() &&
2277 !SDValue(Node, 1).use_empty()) {
2278 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2279 X86::AX, MVT::i16, InFlag);
2280 InFlag = Result.getValue(2);
2281 // Get the low part if needed. Don't use getCopyFromReg for aliasing
2282 // registers.
2283 if (!SDValue(Node, 0).use_empty())
2284 ReplaceUses(SDValue(Node, 1),
2285 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2286
2287 // Shift AX down 8 bits.
2288 Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2289 Result,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002290 CurDAG->getTargetConstant(8, dl, MVT::i8)),
2291 0);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002292 // Then truncate it down to i8.
2293 ReplaceUses(SDValue(Node, 1),
2294 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2295 }
Dan Gohman757eee82009-08-02 16:10:52 +00002296 // Copy the low half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002297 if (!SDValue(Node, 0).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002298 if (!ResLo.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002299 assert(LoReg && "Register for low half is not defined!");
2300 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2301 InFlag);
2302 InFlag = ResLo.getValue(2);
2303 }
2304 ReplaceUses(SDValue(Node, 0), ResLo);
2305 DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002306 }
2307 // Copy the high half of the result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002308 if (!SDValue(Node, 1).use_empty()) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002309 if (!ResHi.getNode()) {
Michael Liaof9f7b552012-09-26 08:22:37 +00002310 assert(HiReg && "Register for high half is not defined!");
2311 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2312 InFlag);
2313 InFlag = ResHi.getValue(2);
2314 }
2315 ReplaceUses(SDValue(Node, 1), ResHi);
2316 DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002317 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002318
Justin Bogner593741d2016-05-10 23:55:37 +00002319 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002320 }
2321
2322 case ISD::SDIVREM:
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002323 case ISD::UDIVREM:
2324 case X86ISD::SDIVREM8_SEXT_HREG:
2325 case X86ISD::UDIVREM8_ZEXT_HREG: {
Dan Gohman757eee82009-08-02 16:10:52 +00002326 SDValue N0 = Node->getOperand(0);
2327 SDValue N1 = Node->getOperand(1);
2328
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002329 bool isSigned = (Opcode == ISD::SDIVREM ||
2330 Opcode == X86ISD::SDIVREM8_SEXT_HREG);
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002331 if (!isSigned) {
Craig Topper83e042a2013-08-15 05:57:07 +00002332 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002333 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002334 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
2335 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2336 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2337 case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002338 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002339 } else {
Craig Topper83e042a2013-08-15 05:57:07 +00002340 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002341 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002342 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
2343 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2344 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2345 case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
Dan Gohman757eee82009-08-02 16:10:52 +00002346 }
Bill Wendlingfe3bdb42009-08-07 21:33:25 +00002347 }
Dan Gohman757eee82009-08-02 16:10:52 +00002348
Chris Lattner518b0372009-12-23 01:45:04 +00002349 unsigned LoReg, HiReg, ClrReg;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002350 unsigned SExtOpcode;
Craig Topper83e042a2013-08-15 05:57:07 +00002351 switch (NVT.SimpleTy) {
Dan Gohman757eee82009-08-02 16:10:52 +00002352 default: llvm_unreachable("Unsupported VT!");
Owen Anderson9f944592009-08-11 20:47:22 +00002353 case MVT::i8:
Chris Lattner518b0372009-12-23 01:45:04 +00002354 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
Dan Gohman757eee82009-08-02 16:10:52 +00002355 SExtOpcode = X86::CBW;
2356 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002357 case MVT::i16:
Dan Gohman757eee82009-08-02 16:10:52 +00002358 LoReg = X86::AX; HiReg = X86::DX;
Tim Northover64ec0ff2013-05-30 13:19:42 +00002359 ClrReg = X86::DX;
Dan Gohman757eee82009-08-02 16:10:52 +00002360 SExtOpcode = X86::CWD;
2361 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002362 case MVT::i32:
Chris Lattner518b0372009-12-23 01:45:04 +00002363 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002364 SExtOpcode = X86::CDQ;
2365 break;
Owen Anderson9f944592009-08-11 20:47:22 +00002366 case MVT::i64:
Chris Lattner518b0372009-12-23 01:45:04 +00002367 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
Dan Gohman757eee82009-08-02 16:10:52 +00002368 SExtOpcode = X86::CQO;
Evan Chenge62288f2009-07-30 08:33:02 +00002369 break;
2370 }
2371
Dan Gohman757eee82009-08-02 16:10:52 +00002372 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002373 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
Dan Gohman757eee82009-08-02 16:10:52 +00002374 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
Dan Gohmana1603612007-10-08 18:33:35 +00002375
Dan Gohman757eee82009-08-02 16:10:52 +00002376 SDValue InFlag;
Owen Anderson9f944592009-08-11 20:47:22 +00002377 if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002378 // Special case for div8, just use a move with zero extension to AX to
2379 // clear the upper 8 bits (AH).
2380 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002381 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
Dan Gohman757eee82009-08-02 16:10:52 +00002382 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2383 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002384 SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
Michael Liaob53d8962013-04-19 22:22:57 +00002385 MVT::Other, Ops), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002386 Chain = Move.getValue(1);
2387 ReplaceUses(N0.getValue(1), Chain);
Evan Cheng10d27902006-01-06 20:36:21 +00002388 } else {
Dan Gohman757eee82009-08-02 16:10:52 +00002389 Move =
Stuart Hastings91f1d242011-05-20 19:04:40 +00002390 SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002391 Chain = CurDAG->getEntryNode();
2392 }
Stuart Hastings91f1d242011-05-20 19:04:40 +00002393 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
Dan Gohman757eee82009-08-02 16:10:52 +00002394 InFlag = Chain.getValue(1);
2395 } else {
2396 InFlag =
2397 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2398 LoReg, N0, SDValue()).getValue(1);
2399 if (isSigned && !signBitIsZero) {
2400 // Sign extend the low part into the high part.
Evan Chengd1b82d82006-02-09 07:17:49 +00002401 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002402 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
Dan Gohman757eee82009-08-02 16:10:52 +00002403 } else {
2404 // Zero out the high part, effectively zero extending the input.
Michael Liao5bf95782014-12-04 05:20:33 +00002405 SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
Craig Topper83e042a2013-08-15 05:57:07 +00002406 switch (NVT.SimpleTy) {
Tim Northover64ec0ff2013-05-30 13:19:42 +00002407 case MVT::i16:
2408 ClrNode =
2409 SDValue(CurDAG->getMachineNode(
2410 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002411 CurDAG->getTargetConstant(X86::sub_16bit, dl,
2412 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002413 0);
2414 break;
2415 case MVT::i32:
2416 break;
2417 case MVT::i64:
2418 ClrNode =
2419 SDValue(CurDAG->getMachineNode(
2420 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002421 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2422 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2423 MVT::i32)),
Tim Northover64ec0ff2013-05-30 13:19:42 +00002424 0);
2425 break;
2426 default:
2427 llvm_unreachable("Unexpected division source");
2428 }
2429
Chris Lattner518b0372009-12-23 01:45:04 +00002430 InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
Dan Gohman757eee82009-08-02 16:10:52 +00002431 ClrNode, InFlag).getValue(1);
Dan Gohmana1603612007-10-08 18:33:35 +00002432 }
Evan Cheng92e27972006-01-06 23:19:29 +00002433 }
Dan Gohmana1603612007-10-08 18:33:35 +00002434
Dan Gohman757eee82009-08-02 16:10:52 +00002435 if (foldedLoad) {
2436 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2437 InFlag };
2438 SDNode *CNode =
Michael Liaob53d8962013-04-19 22:22:57 +00002439 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
Dan Gohman757eee82009-08-02 16:10:52 +00002440 InFlag = SDValue(CNode, 1);
2441 // Update the chain.
2442 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2443 } else {
2444 InFlag =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002445 SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
Dan Gohman757eee82009-08-02 16:10:52 +00002446 }
Evan Cheng92e27972006-01-06 23:19:29 +00002447
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002448 // Prevent use of AH in a REX instruction by explicitly copying it to
2449 // an ABCD_L register.
Jim Grosbach340b6da2013-07-09 02:07:28 +00002450 //
2451 // The current assumption of the register allocator is that isel
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002452 // won't generate explicit references to the GR8_ABCD_H registers. If
Jim Grosbach340b6da2013-07-09 02:07:28 +00002453 // the allocator and/or the backend get enhanced to be more robust in
2454 // that regard, this can be, and should be, removed.
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002455 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2456 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2457 unsigned AHExtOpcode =
2458 isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002459
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002460 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2461 MVT::Glue, AHCopy, InFlag);
2462 SDValue Result(RNode, 0);
2463 InFlag = SDValue(RNode, 1);
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002464
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002465 if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2466 Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2467 if (Node->getValueType(1) == MVT::i64) {
2468 // It's not possible to directly movsx AH to a 64bit register, because
2469 // the latter needs the REX prefix, but the former can't have it.
2470 assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2471 "Unexpected i64 sext of h-register");
2472 Result =
2473 SDValue(CurDAG->getMachineNode(
2474 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002475 CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2476 CurDAG->getTargetConstant(X86::sub_32bit, dl,
2477 MVT::i32)),
Ahmed Bougacha12eb5582014-11-03 20:26:35 +00002478 0);
2479 }
2480 } else {
2481 Result =
2482 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2483 }
2484 ReplaceUses(SDValue(Node, 1), Result);
2485 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002486 }
Dan Gohman757eee82009-08-02 16:10:52 +00002487 // Copy the division (low) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002488 if (!SDValue(Node, 0).use_empty()) {
Dan Gohman757eee82009-08-02 16:10:52 +00002489 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2490 LoReg, NVT, InFlag);
2491 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002492 ReplaceUses(SDValue(Node, 0), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002493 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002494 }
2495 // Copy the remainder (high) result, if it is needed.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002496 if (!SDValue(Node, 1).use_empty()) {
Jakob Stoklund Olesend7d0d4e2010-06-26 00:39:23 +00002497 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2498 HiReg, NVT, InFlag);
2499 InFlag = Result.getValue(2);
Dan Gohmanea6f91f2010-01-05 01:24:18 +00002500 ReplaceUses(SDValue(Node, 1), Result);
Chris Lattnerf98f1242010-03-02 06:34:30 +00002501 DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
Dan Gohman757eee82009-08-02 16:10:52 +00002502 }
Justin Bogner593741d2016-05-10 23:55:37 +00002503 return;
Dan Gohman757eee82009-08-02 16:10:52 +00002504 }
2505
Manman Ren1be131b2012-08-08 00:51:41 +00002506 case X86ISD::CMP:
2507 case X86ISD::SUB: {
2508 // Sometimes a SUB is used to perform comparison.
2509 if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2510 // This node is not a CMP.
2511 break;
Dan Gohmanac33a902009-08-19 18:16:17 +00002512 SDValue N0 = Node->getOperand(0);
2513 SDValue N1 = Node->getOperand(1);
2514
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002515 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
Sanjay Patel85030aa2015-10-13 16:23:00 +00002516 hasNoSignedComparisonUses(Node))
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002517 N0 = N0.getOperand(0);
Elena Demikhovskyd2cb3c82015-02-12 08:40:34 +00002518
Dan Gohmanac33a902009-08-19 18:16:17 +00002519 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2520 // use a smaller encoding.
Elena Demikhovsky34d2d762014-08-18 11:59:06 +00002521 // Look past the truncate if CMP is the only use of it.
Dan Gohman198b7ff2011-11-03 21:49:52 +00002522 if ((N0.getNode()->getOpcode() == ISD::AND ||
2523 (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2524 N0.getNode()->hasOneUse() &&
Dan Gohmanac33a902009-08-19 18:16:17 +00002525 N0.getValueType() != MVT::i8 &&
2526 X86::isZeroNode(N1)) {
2527 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2528 if (!C) break;
2529
2530 // For example, convert "testl %eax, $8" to "testb %al, $8"
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002531 if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2532 (!(C->getZExtValue() & 0x80) ||
Sanjay Patel85030aa2015-10-13 16:23:00 +00002533 hasNoSignedComparisonUses(Node))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002534 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
Dan Gohmanac33a902009-08-19 18:16:17 +00002535 SDValue Reg = N0.getNode()->getOperand(0);
2536
2537 // On x86-32, only the ABCD registers have 8-bit subregisters.
2538 if (!Subtarget->is64Bit()) {
Craig Toppercc830f82012-02-22 07:28:11 +00002539 const TargetRegisterClass *TRC;
Craig Topper56710102013-08-15 02:33:50 +00002540 switch (N0.getSimpleValueType().SimpleTy) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002541 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2542 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2543 default: llvm_unreachable("Unsupported TEST operand type!");
2544 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002545 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Dan Gohman32f71d72009-09-25 18:54:59 +00002546 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2547 Reg.getValueType(), Reg, RC), 0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002548 }
2549
2550 // Extract the l-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002551 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002552 MVT::i8, Reg);
2553
2554 // Emit a testb.
Manman Ren511c6d02012-09-28 18:53:24 +00002555 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2556 Subreg, Imm);
2557 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2558 // one, do not call ReplaceAllUsesWith.
2559 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2560 SDValue(NewNode, 0));
Justin Bogner593741d2016-05-10 23:55:37 +00002561 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002562 }
2563
2564 // For example, "testl %eax, $2048" to "testb %ah, $8".
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002565 if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2566 (!(C->getZExtValue() & 0x8000) ||
Sanjay Patel85030aa2015-10-13 16:23:00 +00002567 hasNoSignedComparisonUses(Node))) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002568 // Shift the immediate right by 8 bits.
2569 SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002570 dl, MVT::i8);
Dan Gohmanac33a902009-08-19 18:16:17 +00002571 SDValue Reg = N0.getNode()->getOperand(0);
2572
2573 // Put the value in an ABCD register.
Craig Toppercc830f82012-02-22 07:28:11 +00002574 const TargetRegisterClass *TRC;
Craig Topper56710102013-08-15 02:33:50 +00002575 switch (N0.getSimpleValueType().SimpleTy) {
Dan Gohmanac33a902009-08-19 18:16:17 +00002576 case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2577 case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2578 case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2579 default: llvm_unreachable("Unsupported TEST operand type!");
2580 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002581 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Dan Gohman32f71d72009-09-25 18:54:59 +00002582 Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2583 Reg.getValueType(), Reg, RC), 0);
Dan Gohmanac33a902009-08-19 18:16:17 +00002584
2585 // Extract the h-register.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002586 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002587 MVT::i8, Reg);
2588
Jakob Stoklund Olesen729abd32011-10-08 18:28:28 +00002589 // Emit a testb. The EXTRACT_SUBREG becomes a COPY that can only
2590 // target GR8_NOREX registers, so make sure the register class is
2591 // forced.
Manman Ren511c6d02012-09-28 18:53:24 +00002592 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2593 MVT::i32, Subreg, ShiftedImm);
2594 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2595 // one, do not call ReplaceAllUsesWith.
2596 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2597 SDValue(NewNode, 0));
Justin Bogner593741d2016-05-10 23:55:37 +00002598 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002599 }
2600
2601 // For example, "testl %eax, $32776" to "testw %ax, $32776".
2602 if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002603 N0.getValueType() != MVT::i16 &&
2604 (!(C->getZExtValue() & 0x8000) ||
Sanjay Patel85030aa2015-10-13 16:23:00 +00002605 hasNoSignedComparisonUses(Node))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002606 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2607 MVT::i16);
Dan Gohmanac33a902009-08-19 18:16:17 +00002608 SDValue Reg = N0.getNode()->getOperand(0);
2609
2610 // Extract the 16-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002611 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002612 MVT::i16, Reg);
2613
2614 // Emit a testw.
Manman Ren511c6d02012-09-28 18:53:24 +00002615 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2616 Subreg, Imm);
2617 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2618 // one, do not call ReplaceAllUsesWith.
2619 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2620 SDValue(NewNode, 0));
Justin Bogner593741d2016-05-10 23:55:37 +00002621 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002622 }
2623
2624 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2625 if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
Dan Gohman7d9dffb2009-10-09 20:35:19 +00002626 N0.getValueType() == MVT::i64 &&
2627 (!(C->getZExtValue() & 0x80000000) ||
Sanjay Patel85030aa2015-10-13 16:23:00 +00002628 hasNoSignedComparisonUses(Node))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002629 SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2630 MVT::i32);
Dan Gohmanac33a902009-08-19 18:16:17 +00002631 SDValue Reg = N0.getNode()->getOperand(0);
2632
2633 // Extract the 32-bit subregister.
Jakob Stoklund Olesen9340ea52010-05-24 14:48:17 +00002634 SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
Dan Gohmanac33a902009-08-19 18:16:17 +00002635 MVT::i32, Reg);
2636
2637 // Emit a testl.
Manman Ren511c6d02012-09-28 18:53:24 +00002638 SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2639 Subreg, Imm);
2640 // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2641 // one, do not call ReplaceAllUsesWith.
2642 ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2643 SDValue(NewNode, 0));
Justin Bogner593741d2016-05-10 23:55:37 +00002644 return;
Dan Gohmanac33a902009-08-19 18:16:17 +00002645 }
2646 }
2647 break;
2648 }
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002649 case ISD::STORE: {
Joel Jones68d59e82012-03-29 05:45:48 +00002650 // Change a chain of {load; incr or dec; store} of the same value into
2651 // a simple increment or decrement through memory of that value, if the
2652 // uses of the modified value and its address are suitable.
Pete Cooper48784ed2011-11-16 19:03:23 +00002653 // The DEC64m tablegen pattern is currently not able to match the case where
Chad Rosier24c19d22012-08-01 18:39:17 +00002654 // the EFLAGS on the original DEC are used. (This also applies to
Joel Jones68d59e82012-03-29 05:45:48 +00002655 // {INC,DEC}X{64,32,16,8}.)
2656 // We'll need to improve tablegen to allow flags to be transferred from a
Pete Cooper48784ed2011-11-16 19:03:23 +00002657 // node in the pattern to the result node. probably with a new keyword
2658 // for example, we have this
2659 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2660 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2661 // (implicit EFLAGS)]>;
2662 // but maybe need something like this
2663 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2664 // [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2665 // (transferrable EFLAGS)]>;
Joel Jones68d59e82012-03-29 05:45:48 +00002666
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002667 StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002668 SDValue StoredVal = StoreNode->getOperand(1);
Joel Jones68d59e82012-03-29 05:45:48 +00002669 unsigned Opc = StoredVal->getOpcode();
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002670
Craig Topper062a2ba2014-04-25 05:30:21 +00002671 LoadSDNode *LoadNode = nullptr;
Evan Cheng3e869f02012-04-12 19:14:21 +00002672 SDValue InputChain;
2673 if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2674 LoadNode, InputChain))
2675 break;
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002676
2677 SDValue Base, Scale, Index, Disp, Segment;
Sanjay Patel85030aa2015-10-13 16:23:00 +00002678 if (!selectAddr(LoadNode, LoadNode->getBasePtr(),
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002679 Base, Scale, Index, Disp, Segment))
2680 break;
2681
2682 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2683 MemOp[0] = StoreNode->getMemOperand();
2684 MemOp[1] = LoadNode->getMemOperand();
2685 const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
Chad Rosier24c19d22012-08-01 18:39:17 +00002686 EVT LdVT = LoadNode->getMemoryVT();
Joel Jones68d59e82012-03-29 05:45:48 +00002687 unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2688 MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002689 SDLoc(Node),
Michael Liaob53d8962013-04-19 22:22:57 +00002690 MVT::i32, MVT::Other, Ops);
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002691 Result->setMemRefs(MemOp, MemOp + 2);
2692
2693 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2694 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
Justin Bogner593741d2016-05-10 23:55:37 +00002695 CurDAG->RemoveDeadNode(Node);
2696 return;
Pete Cooper7c7ba1b2011-11-15 21:57:53 +00002697 }
Chris Lattner655e7df2005-11-16 01:54:32 +00002698 }
2699
Justin Bogner593741d2016-05-10 23:55:37 +00002700 SelectCode(Node);
Chris Lattner655e7df2005-11-16 01:54:32 +00002701}
2702
Chris Lattnerba1ed582006-06-08 18:03:49 +00002703bool X86DAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +00002704SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Dan Gohmaneb0cee92008-08-23 02:25:05 +00002705 std::vector<SDValue> &OutOps) {
Rafael Espindola3b2df102009-04-08 21:14:34 +00002706 SDValue Op0, Op1, Op2, Op3, Op4;
Daniel Sanders60f1db02015-03-13 12:45:09 +00002707 switch (ConstraintID) {
Daniel Sandersd0496692015-05-16 12:09:54 +00002708 default:
2709 llvm_unreachable("Unexpected asm memory constraint");
2710 case InlineAsm::Constraint_i:
2711 // FIXME: It seems strange that 'i' is needed here since it's supposed to
2712 // be an immediate and not a memory constraint.
Justin Bognerb03fd122016-08-17 05:10:15 +00002713 LLVM_FALLTHROUGH;
Daniel Sanders60f1db02015-03-13 12:45:09 +00002714 case InlineAsm::Constraint_o: // offsetable ??
2715 case InlineAsm::Constraint_v: // not offsetable ??
Daniel Sanders60f1db02015-03-13 12:45:09 +00002716 case InlineAsm::Constraint_m: // memory
Daniel Sandersd0496692015-05-16 12:09:54 +00002717 case InlineAsm::Constraint_X:
Sanjay Patel85030aa2015-10-13 16:23:00 +00002718 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
Chris Lattnerba1ed582006-06-08 18:03:49 +00002719 return true;
2720 break;
2721 }
Chad Rosier24c19d22012-08-01 18:39:17 +00002722
Evan Cheng2d487222006-08-26 01:05:16 +00002723 OutOps.push_back(Op0);
2724 OutOps.push_back(Op1);
2725 OutOps.push_back(Op2);
2726 OutOps.push_back(Op3);
Rafael Espindola3b2df102009-04-08 21:14:34 +00002727 OutOps.push_back(Op4);
Chris Lattnerba1ed582006-06-08 18:03:49 +00002728 return false;
2729}
2730
Sanjay Patelb5723d02015-10-13 15:12:27 +00002731/// This pass converts a legalized DAG into a X86-specific DAG,
2732/// ready for instruction scheduling.
Bill Wendling026e5d72009-04-29 23:29:43 +00002733FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
Craig Topperf6e7e122012-03-27 07:21:54 +00002734 CodeGenOpt::Level OptLevel) {
Bill Wendling084669a2009-04-29 00:15:41 +00002735 return new X86DAGToDAGISel(TM, OptLevel);
Chris Lattner655e7df2005-11-16 01:54:32 +00002736}