[X86] Allow merging of immediates within a basic block for code size savings
[oota-llvm.git] / lib / Target / X86 / X86ISelDAGToDAG.cpp
1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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"
16 #include "X86InstrBuilder.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include <stdint.h>
38 using namespace llvm;
39
40 #define DEBUG_TYPE "x86-isel"
41
42 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
43
44 //===----------------------------------------------------------------------===//
45 //                      Pattern Matcher Implementation
46 //===----------------------------------------------------------------------===//
47
48 namespace {
49   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
50   /// SDValue's instead of register numbers for the leaves of the matched
51   /// tree.
52   struct X86ISelAddressMode {
53     enum {
54       RegBase,
55       FrameIndexBase
56     } BaseType;
57
58     // This is really a union, discriminated by BaseType!
59     SDValue Base_Reg;
60     int Base_FrameIndex;
61
62     unsigned Scale;
63     SDValue IndexReg;
64     int32_t Disp;
65     SDValue Segment;
66     const GlobalValue *GV;
67     const Constant *CP;
68     const BlockAddress *BlockAddr;
69     const char *ES;
70     MCSymbol *MCSym;
71     int JT;
72     unsigned Align;    // CP alignment.
73     unsigned char SymbolFlags;  // X86II::MO_*
74
75     X86ISelAddressMode()
76         : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
77           Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
78           MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
79
80     bool hasSymbolicDisplacement() const {
81       return GV != nullptr || CP != nullptr || ES != nullptr ||
82              MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
83     }
84
85     bool hasBaseOrIndexReg() const {
86       return BaseType == FrameIndexBase ||
87              IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
88     }
89
90     /// isRIPRelative - Return true if this addressing mode is already RIP
91     /// relative.
92     bool isRIPRelative() const {
93       if (BaseType != RegBase) return false;
94       if (RegisterSDNode *RegNode =
95             dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
96         return RegNode->getReg() == X86::RIP;
97       return false;
98     }
99
100     void setBaseReg(SDValue Reg) {
101       BaseType = RegBase;
102       Base_Reg = Reg;
103     }
104
105 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
106     void dump() {
107       dbgs() << "X86ISelAddressMode " << this << '\n';
108       dbgs() << "Base_Reg ";
109       if (Base_Reg.getNode())
110         Base_Reg.getNode()->dump();
111       else
112         dbgs() << "nul";
113       dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
114              << " Scale" << Scale << '\n'
115              << "IndexReg ";
116       if (IndexReg.getNode())
117         IndexReg.getNode()->dump();
118       else
119         dbgs() << "nul";
120       dbgs() << " Disp " << Disp << '\n'
121              << "GV ";
122       if (GV)
123         GV->dump();
124       else
125         dbgs() << "nul";
126       dbgs() << " CP ";
127       if (CP)
128         CP->dump();
129       else
130         dbgs() << "nul";
131       dbgs() << '\n'
132              << "ES ";
133       if (ES)
134         dbgs() << ES;
135       else
136         dbgs() << "nul";
137       dbgs() << " MCSym ";
138       if (MCSym)
139         dbgs() << MCSym;
140       else
141         dbgs() << "nul";
142       dbgs() << " JT" << JT << " Align" << Align << '\n';
143     }
144 #endif
145   };
146 }
147
148 namespace {
149   //===--------------------------------------------------------------------===//
150   /// ISel - X86 specific code to select X86 machine instructions for
151   /// SelectionDAG operations.
152   ///
153   class X86DAGToDAGISel final : public SelectionDAGISel {
154     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
155     /// make the right decision when generating code for different targets.
156     const X86Subtarget *Subtarget;
157
158     /// OptForSize - If true, selector should try to optimize for code size
159     /// instead of performance.
160     bool OptForSize;
161
162   public:
163     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
164         : SelectionDAGISel(tm, OptLevel), OptForSize(false) {}
165
166     const char *getPassName() const override {
167       return "X86 DAG->DAG Instruction Selection";
168     }
169
170     bool runOnMachineFunction(MachineFunction &MF) override {
171       // Reset the subtarget each time through.
172       Subtarget = &MF.getSubtarget<X86Subtarget>();
173       SelectionDAGISel::runOnMachineFunction(MF);
174       return true;
175     }
176
177     void EmitFunctionEntryCode() override;
178
179     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
180
181     void PreprocessISelDAG() override;
182
183     inline bool immSext8(SDNode *N) const {
184       return isInt<8>(cast<ConstantSDNode>(N)->getSExtValue());
185     }
186
187     // i64immSExt32 predicate - True if the 64-bit immediate fits in a 32-bit
188     // sign extended field.
189     inline bool i64immSExt32(SDNode *N) const {
190       uint64_t v = cast<ConstantSDNode>(N)->getZExtValue();
191       return (int64_t)v == (int32_t)v;
192     }
193
194 // Include the pieces autogenerated from the target description.
195 #include "X86GenDAGISel.inc"
196
197   private:
198     SDNode *Select(SDNode *N) override;
199     SDNode *SelectGather(SDNode *N, unsigned Opc);
200     SDNode *SelectAtomicLoadArith(SDNode *Node, MVT NVT);
201
202     bool FoldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
203     bool MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
204     bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
205     bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
206     bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
207                                  unsigned Depth);
208     bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
209     bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
210                     SDValue &Scale, SDValue &Index, SDValue &Disp,
211                     SDValue &Segment);
212     bool SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
213                           SDValue &Scale, SDValue &Index, SDValue &Disp,
214                           SDValue &Segment);
215     bool SelectMOV64Imm32(SDValue N, SDValue &Imm);
216     bool SelectLEAAddr(SDValue N, SDValue &Base,
217                        SDValue &Scale, SDValue &Index, SDValue &Disp,
218                        SDValue &Segment);
219     bool SelectLEA64_32Addr(SDValue N, SDValue &Base,
220                             SDValue &Scale, SDValue &Index, SDValue &Disp,
221                             SDValue &Segment);
222     bool SelectTLSADDRAddr(SDValue N, SDValue &Base,
223                            SDValue &Scale, SDValue &Index, SDValue &Disp,
224                            SDValue &Segment);
225     bool SelectScalarSSELoad(SDNode *Root, SDValue N,
226                              SDValue &Base, SDValue &Scale,
227                              SDValue &Index, SDValue &Disp,
228                              SDValue &Segment,
229                              SDValue &NodeWithChain);
230
231     bool TryFoldLoad(SDNode *P, SDValue N,
232                      SDValue &Base, SDValue &Scale,
233                      SDValue &Index, SDValue &Disp,
234                      SDValue &Segment);
235
236     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
237     /// inline asm expressions.
238     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
239                                       unsigned ConstraintID,
240                                       std::vector<SDValue> &OutOps) override;
241
242     void EmitSpecialCodeForMain();
243
244     inline void getAddressOperands(X86ISelAddressMode &AM, SDLoc DL,
245                                    SDValue &Base, SDValue &Scale,
246                                    SDValue &Index, SDValue &Disp,
247                                    SDValue &Segment) {
248       Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
249                  ? CurDAG->getTargetFrameIndex(
250                        AM.Base_FrameIndex,
251                        TLI->getPointerTy(CurDAG->getDataLayout()))
252                  : AM.Base_Reg;
253       Scale = getI8Imm(AM.Scale, DL);
254       Index = AM.IndexReg;
255       // These are 32-bit even in 64-bit mode since RIP relative offset
256       // is 32-bit.
257       if (AM.GV)
258         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
259                                               MVT::i32, AM.Disp,
260                                               AM.SymbolFlags);
261       else if (AM.CP)
262         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
263                                              AM.Align, AM.Disp, AM.SymbolFlags);
264       else if (AM.ES) {
265         assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
266         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
267       } else if (AM.MCSym) {
268         assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
269         assert(AM.SymbolFlags == 0 && "oo");
270         Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
271       } else if (AM.JT != -1) {
272         assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
273         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
274       } else if (AM.BlockAddr)
275         Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
276                                              AM.SymbolFlags);
277       else
278         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
279
280       if (AM.Segment.getNode())
281         Segment = AM.Segment;
282       else
283         Segment = CurDAG->getRegister(0, MVT::i32);
284     }
285
286     // Utility function to determine whether we should avoid selecting
287     // immediate forms of instructions for better code size or not.
288     // At a high level, we'd like to avoid such instructions when
289     // we have similar constants used within the same basic block
290     // that can be kept in a register.
291     //
292     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
293       uint32_t UseCount = 0;
294
295       // Do not want to hoist if we're not optimizing for size.
296       // TODO: We'd like to remove this restriction.
297       // See the comment in X86InstrInfo.td for more info.
298       if (!OptForSize)
299         return false;
300
301       // Walk all the users of the immediate.
302       for (SDNode::use_iterator UI = N->use_begin(),
303            UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
304
305         SDNode *User = *UI;
306
307         // This user is already selected. Count it as a legitimate use and
308         // move on.
309         if (User->isMachineOpcode()) {
310           UseCount++;
311           continue;
312         }
313
314         // We want to count stores of immediates as real uses.
315         if (User->getOpcode() == ISD::STORE &&
316             User->getOperand(1).getNode() == N) {
317           UseCount++;
318           continue;
319         }
320
321         // We don't currently match users that have > 2 operands (except
322         // for stores, which are handled above)
323         // Those instruction won't match in ISEL, for now, and would
324         // be counted incorrectly.
325         // This may change in the future as we add additional instruction
326         // types.
327         if (User->getNumOperands() != 2)
328           continue;
329         
330         // Immediates that are used for offsets as part of stack
331         // manipulation should be left alone. These are typically
332         // used to indicate SP offsets for argument passing and
333         // will get pulled into stores/pushes (implicitly).
334         if (User->getOpcode() == X86ISD::ADD ||
335             User->getOpcode() == ISD::ADD    ||
336             User->getOpcode() == X86ISD::SUB ||
337             User->getOpcode() == ISD::SUB) {
338
339           // Find the other operand of the add/sub.
340           SDValue OtherOp = User->getOperand(0);
341           if (OtherOp.getNode() == N)
342             OtherOp = User->getOperand(1);
343
344           // Don't count if the other operand is SP.
345           RegisterSDNode *RegNode;
346           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
347               (RegNode = dyn_cast_or_null<RegisterSDNode>(
348                  OtherOp->getOperand(1).getNode())))
349             if ((RegNode->getReg() == X86::ESP) ||
350                 (RegNode->getReg() == X86::RSP))
351               continue;
352         }
353
354         // ... otherwise, count this and move on.
355         UseCount++;
356       }
357
358       // If we have more than 1 use, then recommend for hoisting.
359       return (UseCount > 1);
360     }
361
362     /// getI8Imm - Return a target constant with the specified value, of type
363     /// i8.
364     inline SDValue getI8Imm(unsigned Imm, SDLoc DL) {
365       return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
366     }
367
368     /// getI32Imm - Return a target constant with the specified value, of type
369     /// i32.
370     inline SDValue getI32Imm(unsigned Imm, SDLoc DL) {
371       return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
372     }
373
374     /// getGlobalBaseReg - Return an SDNode that returns the value of
375     /// the global base register. Output instructions required to
376     /// initialize the global base register, if necessary.
377     ///
378     SDNode *getGlobalBaseReg();
379
380     /// getTargetMachine - Return a reference to the TargetMachine, casted
381     /// to the target-specific type.
382     const X86TargetMachine &getTargetMachine() const {
383       return static_cast<const X86TargetMachine &>(TM);
384     }
385
386     /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
387     /// to the target-specific type.
388     const X86InstrInfo *getInstrInfo() const {
389       return Subtarget->getInstrInfo();
390     }
391
392     /// \brief Address-mode matching performs shift-of-and to and-of-shift
393     /// reassociation in order to expose more scaled addressing
394     /// opportunities.
395     bool ComplexPatternFuncMutatesDAG() const override {
396       return true;
397     }
398   };
399 }
400
401
402 bool
403 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
404   if (OptLevel == CodeGenOpt::None) return false;
405
406   if (!N.hasOneUse())
407     return false;
408
409   if (N.getOpcode() != ISD::LOAD)
410     return true;
411
412   // If N is a load, do additional profitability checks.
413   if (U == Root) {
414     switch (U->getOpcode()) {
415     default: break;
416     case X86ISD::ADD:
417     case X86ISD::SUB:
418     case X86ISD::AND:
419     case X86ISD::XOR:
420     case X86ISD::OR:
421     case ISD::ADD:
422     case ISD::ADDC:
423     case ISD::ADDE:
424     case ISD::AND:
425     case ISD::OR:
426     case ISD::XOR: {
427       SDValue Op1 = U->getOperand(1);
428
429       // 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).
439       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
440         if (Imm->getAPIntValue().isSignedIntN(8))
441           return false;
442
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.
452       // FIXME: This is probably also true for non-TLS addresses.
453       if (Op1.getOpcode() == X86ISD::Wrapper) {
454         SDValue Val = Op1.getOperand(0);
455         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
456           return false;
457       }
458     }
459     }
460   }
461
462   return true;
463 }
464
465 /// MoveBelowCallOrigChain - Replace the original chain operand of the call with
466 /// load's chain operand and move load below the call's chain operand.
467 static void MoveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
468                                SDValue Call, SDValue OrigChain) {
469   SmallVector<SDValue, 8> Ops;
470   SDValue Chain = OrigChain.getOperand(0);
471   if (Chain.getNode() == Load.getNode())
472     Ops.push_back(Load.getOperand(0));
473   else {
474     assert(Chain.getOpcode() == ISD::TokenFactor &&
475            "Unexpected chain operand");
476     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 =
482       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
483     Ops.clear();
484     Ops.push_back(NewChain);
485   }
486   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
487   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
488   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
489                              Load.getOperand(1), Load.getOperand(2));
490
491   Ops.clear();
492   Ops.push_back(SDValue(Load.getNode(), 1));
493   Ops.append(Call->op_begin() + 1, Call->op_end());
494   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
495 }
496
497 /// isCalleeLoad - Return true if call address is a load and it can be
498 /// moved below CALLSEQ_START and the chains leading up to the call.
499 /// Return the CALLSEQ_START by reference as a second output.
500 /// In the case of a tail call, there isn't a callseq node between the call
501 /// chain and the load.
502 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
503   // 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.
507   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
508     return false;
509   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
510   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.
517   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
518     if (!Chain.hasOneUse())
519       return false;
520     Chain = Chain.getOperand(0);
521   }
522
523   if (!Chain.getNumOperands())
524     return false;
525   // 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;
530   if (Chain.getOperand(0).getNode() == Callee.getNode())
531     return true;
532   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
533       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
534       Callee.getValue(1).hasOneUse())
535     return true;
536   return false;
537 }
538
539 void X86DAGToDAGISel::PreprocessISelDAG() {
540   // OptForSize is used in pattern predicates that isel is matching.
541   OptForSize = MF->getFunction()->optForSize();
542
543   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
544        E = CurDAG->allnodes_end(); I != E; ) {
545     SDNode *N = I++;  // Preincrement iterator to avoid invalidation issues.
546
547     if (OptLevel != CodeGenOpt::None &&
548         // Only does this when target favors doesn't favor register indirect
549         // call.
550         ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
551          (N->getOpcode() == X86ISD::TC_RETURN &&
552           // Only does this if load can be folded into TC_RETURN.
553           (Subtarget->is64Bit() ||
554            getTargetMachine().getRelocationModel() != Reloc::PIC_)))) {
555       /// Also try moving call address load from outside callseq_start to just
556       /// before the call to allow it to be folded.
557       ///
558       ///     [Load chain]
559       ///         ^
560       ///         |
561       ///       [Load]
562       ///       ^    ^
563       ///       |    |
564       ///      /      \--
565       ///     /          |
566       ///[CALLSEQ_START] |
567       ///     ^          |
568       ///     |          |
569       /// [LOAD/C2Reg]   |
570       ///     |          |
571       ///      \        /
572       ///       \      /
573       ///       [CALL]
574       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
575       SDValue Chain = N->getOperand(0);
576       SDValue Load  = N->getOperand(1);
577       if (!isCalleeLoad(Load, Chain, HasCallSeq))
578         continue;
579       MoveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
580       ++NumLoadMoved;
581       continue;
582     }
583
584     // Lower fpround and fpextend nodes that target the FP stack to be store and
585     // load to the stack.  This is a gross hack.  We would like to simply mark
586     // these as being illegal, but when we do that, legalize produces these when
587     // it expands calls, then expands these in the same legalize pass.  We would
588     // like dag combine to be able to hack on these between the call expansion
589     // and the node legalization.  As such this pass basically does "really
590     // late" legalization of these inline with the X86 isel pass.
591     // FIXME: This should only happen when not compiled with -O0.
592     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
593       continue;
594
595     MVT SrcVT = N->getOperand(0).getSimpleValueType();
596     MVT DstVT = N->getSimpleValueType(0);
597
598     // If any of the sources are vectors, no fp stack involved.
599     if (SrcVT.isVector() || DstVT.isVector())
600       continue;
601
602     // If the source and destination are SSE registers, then this is a legal
603     // conversion that should not be lowered.
604     const X86TargetLowering *X86Lowering =
605         static_cast<const X86TargetLowering *>(TLI);
606     bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
607     bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
608     if (SrcIsSSE && DstIsSSE)
609       continue;
610
611     if (!SrcIsSSE && !DstIsSSE) {
612       // If this is an FPStack extension, it is a noop.
613       if (N->getOpcode() == ISD::FP_EXTEND)
614         continue;
615       // If this is a value-preserving FPStack truncation, it is a noop.
616       if (N->getConstantOperandVal(1))
617         continue;
618     }
619
620     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
621     // FPStack has extload and truncstore.  SSE can fold direct loads into other
622     // operations.  Based on this, decide what we want to do.
623     MVT MemVT;
624     if (N->getOpcode() == ISD::FP_ROUND)
625       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
626     else
627       MemVT = SrcIsSSE ? SrcVT : DstVT;
628
629     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
630     SDLoc dl(N);
631
632     // FIXME: optimize the case where the src/dest is a load or store?
633     SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
634                                           N->getOperand(0),
635                                           MemTmp, MachinePointerInfo(), MemVT,
636                                           false, false, 0);
637     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
638                                         MachinePointerInfo(),
639                                         MemVT, false, false, false, 0);
640
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;
646     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
647
648     // Now that we did that, the node is dead.  Increment the iterator to the
649     // next node to process, then delete N.
650     ++I;
651     CurDAG->DeleteNode(N);
652   }
653 }
654
655
656 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
657 /// the main function.
658 void X86DAGToDAGISel::EmitSpecialCodeForMain() {
659   if (Subtarget->isTargetCygMing()) {
660     TargetLowering::ArgListTy Args;
661     auto &DL = CurDAG->getDataLayout();
662
663     TargetLowering::CallLoweringInfo CLI(*CurDAG);
664     CLI.setChain(CurDAG->getRoot())
665         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
666                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
667                    std::move(Args), 0);
668     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
669     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
670     CurDAG->setRoot(Result.second);
671   }
672 }
673
674 void X86DAGToDAGISel::EmitFunctionEntryCode() {
675   // If this is main, emit special code for main.
676   if (const Function *Fn = MF->getFunction())
677     if (Fn->hasExternalLinkage() && Fn->getName() == "main")
678       EmitSpecialCodeForMain();
679 }
680
681 static bool isDispSafeForFrameIndex(int64_t Val) {
682   // On 64-bit platforms, we can run into an issue where a frame index
683   // includes a displacement that, when added to the explicit displacement,
684   // will overflow the displacement field. Assuming that the frame index
685   // displacement fits into a 31-bit integer  (which is only slightly more
686   // aggressive than the current fundamental assumption that it fits into
687   // a 32-bit integer), a 31-bit disp should always be safe.
688   return isInt<31>(Val);
689 }
690
691 bool X86DAGToDAGISel::FoldOffsetIntoAddress(uint64_t Offset,
692                                             X86ISelAddressMode &AM) {
693   // Cannot combine ExternalSymbol displacements with integer offsets.
694   if (Offset != 0 && (AM.ES || AM.MCSym))
695     return true;
696   int64_t Val = AM.Disp + Offset;
697   CodeModel::Model M = TM.getCodeModel();
698   if (Subtarget->is64Bit()) {
699     if (!X86::isOffsetSuitableForCodeModel(Val, M,
700                                            AM.hasSymbolicDisplacement()))
701       return true;
702     // In addition to the checks required for a register base, check that
703     // we do not try to use an unsafe Disp with a frame index.
704     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
705         !isDispSafeForFrameIndex(Val))
706       return true;
707   }
708   AM.Disp = Val;
709   return false;
710
711 }
712
713 bool X86DAGToDAGISel::MatchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
714   SDValue Address = N->getOperand(1);
715
716   // load gs:0 -> GS segment register.
717   // load fs:0 -> FS segment register.
718   //
719   // This optimization is valid because the GNU TLS model defines that
720   // gs:0 (or fs:0 on X86-64) contains its own address.
721   // For more information see http://people.redhat.com/drepper/tls.pdf
722   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
723     if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
724         Subtarget->isTargetLinux())
725       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;
732       }
733
734   return true;
735 }
736
737 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
738 /// into an addressing mode.  These wrap things that will resolve down into a
739 /// symbol reference.  If no match is possible, this returns true, otherwise it
740 /// returns false.
741 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
742   // If the addressing mode already has a symbol as the displacement, we can
743   // never match another symbol.
744   if (AM.hasSymbolicDisplacement())
745     return true;
746
747   SDValue N0 = N.getOperand(0);
748   CodeModel::Model M = TM.getCodeModel();
749
750   // Handle X86-64 rip-relative addresses.  We check this before checking direct
751   // folding because RIP is preferable to non-RIP accesses.
752   if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
753       // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
754       // they cannot be folded into immediate fields.
755       // FIXME: This can be improved for kernel and other models?
756       (M == CodeModel::Small || M == CodeModel::Kernel)) {
757     // Base and index reg must be 0 in order to use %rip as base.
758     if (AM.hasBaseOrIndexReg())
759       return true;
760     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
761       X86ISelAddressMode Backup = AM;
762       AM.GV = G->getGlobal();
763       AM.SymbolFlags = G->getTargetFlags();
764       if (FoldOffsetIntoAddress(G->getOffset(), AM)) {
765         AM = Backup;
766         return true;
767       }
768     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
769       X86ISelAddressMode Backup = AM;
770       AM.CP = CP->getConstVal();
771       AM.Align = CP->getAlignment();
772       AM.SymbolFlags = CP->getTargetFlags();
773       if (FoldOffsetIntoAddress(CP->getOffset(), AM)) {
774         AM = Backup;
775         return true;
776       }
777     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
778       AM.ES = S->getSymbol();
779       AM.SymbolFlags = S->getTargetFlags();
780     } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
781       AM.MCSym = S->getMCSymbol();
782     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
783       AM.JT = J->getIndex();
784       AM.SymbolFlags = J->getTargetFlags();
785     } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
786       X86ISelAddressMode Backup = AM;
787       AM.BlockAddr = BA->getBlockAddress();
788       AM.SymbolFlags = BA->getTargetFlags();
789       if (FoldOffsetIntoAddress(BA->getOffset(), AM)) {
790         AM = Backup;
791         return true;
792       }
793     } else
794       llvm_unreachable("Unhandled symbol reference node.");
795
796     if (N.getOpcode() == X86ISD::WrapperRIP)
797       AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
798     return false;
799   }
800
801   // Handle the case when globals fit in our immediate field: This is true for
802   // X86-32 always and X86-64 when in -mcmodel=small mode.  In 64-bit
803   // mode, this only applies to a non-RIP-relative computation.
804   if (!Subtarget->is64Bit() ||
805       M == CodeModel::Small || M == CodeModel::Kernel) {
806     assert(N.getOpcode() != X86ISD::WrapperRIP &&
807            "RIP-relative addressing already handled");
808     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
809       AM.GV = G->getGlobal();
810       AM.Disp += G->getOffset();
811       AM.SymbolFlags = G->getTargetFlags();
812     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
813       AM.CP = CP->getConstVal();
814       AM.Align = CP->getAlignment();
815       AM.Disp += CP->getOffset();
816       AM.SymbolFlags = CP->getTargetFlags();
817     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
818       AM.ES = S->getSymbol();
819       AM.SymbolFlags = S->getTargetFlags();
820     } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
821       AM.MCSym = S->getMCSymbol();
822     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
823       AM.JT = J->getIndex();
824       AM.SymbolFlags = J->getTargetFlags();
825     } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
826       AM.BlockAddr = BA->getBlockAddress();
827       AM.Disp += BA->getOffset();
828       AM.SymbolFlags = BA->getTargetFlags();
829     } else
830       llvm_unreachable("Unhandled symbol reference node.");
831     return false;
832   }
833
834   return true;
835 }
836
837 /// MatchAddress - Add the specified node to the specified addressing mode,
838 /// returning true if it cannot be done.  This just pattern matches for the
839 /// addressing mode.
840 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
841   if (MatchAddressRecursively(N, AM, 0))
842     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 &&
848       AM.Base_Reg.getNode() == nullptr) {
849     AM.Base_Reg = AM.IndexReg;
850     AM.Scale = 1;
851   }
852
853   // 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 &&
860       AM.Base_Reg.getNode() == nullptr &&
861       AM.IndexReg.getNode() == nullptr &&
862       AM.SymbolFlags == X86II::MO_NO_FLAG &&
863       AM.hasSymbolicDisplacement())
864     AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
865
866   return false;
867 }
868
869 // Insert a node into the DAG at least before the Pos node's position. This
870 // will reposition the node as needed, and will assign it a node ID that is <=
871 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
872 // IDs! The selection DAG must no longer depend on their uniqueness when this
873 // is used.
874 static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
875   if (N.getNode()->getNodeId() == -1 ||
876       N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
877     DAG.RepositionNode(Pos.getNode(), N.getNode());
878     N.getNode()->setNodeId(Pos.getNode()->getNodeId());
879   }
880 }
881
882 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
883 // safe. This allows us to convert the shift and and into an h-register
884 // extract and a scaled index. Returns false if the simplification is
885 // performed.
886 static bool FoldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
887                                       uint64_t Mask,
888                                       SDValue Shift, SDValue X,
889                                       X86ISelAddressMode &AM) {
890   if (Shift.getOpcode() != ISD::SRL ||
891       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
892       !Shift.hasOneUse())
893     return true;
894
895   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
896   if (ScaleLog <= 0 || ScaleLog >= 4 ||
897       Mask != (0xffu << ScaleLog))
898     return true;
899
900   MVT VT = N.getSimpleValueType();
901   SDLoc DL(N);
902   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
903   SDValue NewMask = DAG.getConstant(0xff, DL, VT);
904   SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
905   SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
906   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
907   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
908
909   // Insert the new nodes into the topological ordering. We must do this in
910   // a valid topological ordering as nothing is going to go back and re-sort
911   // these nodes. We continually insert before 'N' in sequence as this is
912   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
913   // hierarchy left to express.
914   InsertDAGNode(DAG, N, Eight);
915   InsertDAGNode(DAG, N, Srl);
916   InsertDAGNode(DAG, N, NewMask);
917   InsertDAGNode(DAG, N, And);
918   InsertDAGNode(DAG, N, ShlCount);
919   InsertDAGNode(DAG, N, Shl);
920   DAG.ReplaceAllUsesWith(N, Shl);
921   AM.IndexReg = And;
922   AM.Scale = (1 << ScaleLog);
923   return false;
924 }
925
926 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
927 // allows us to fold the shift into this addressing mode. Returns false if the
928 // transform succeeded.
929 static bool FoldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
930                                         uint64_t Mask,
931                                         SDValue Shift, SDValue X,
932                                         X86ISelAddressMode &AM) {
933   if (Shift.getOpcode() != ISD::SHL ||
934       !isa<ConstantSDNode>(Shift.getOperand(1)))
935     return true;
936
937   // Not likely to be profitable if either the AND or SHIFT node has more
938   // than one use (unless all uses are for address computation). Besides,
939   // isel mechanism requires their node ids to be reused.
940   if (!N.hasOneUse() || !Shift.hasOneUse())
941     return true;
942
943   // Verify that the shift amount is something we can fold.
944   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
945   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
946     return true;
947
948   MVT VT = N.getSimpleValueType();
949   SDLoc DL(N);
950   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
951   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
952   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
953
954   // Insert the new nodes into the topological ordering. We must do this in
955   // a valid topological ordering as nothing is going to go back and re-sort
956   // these nodes. We continually insert before 'N' in sequence as this is
957   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
958   // hierarchy left to express.
959   InsertDAGNode(DAG, N, NewMask);
960   InsertDAGNode(DAG, N, NewAnd);
961   InsertDAGNode(DAG, N, NewShift);
962   DAG.ReplaceAllUsesWith(N, NewShift);
963
964   AM.Scale = 1 << ShiftAmt;
965   AM.IndexReg = NewAnd;
966   return false;
967 }
968
969 // Implement some heroics to detect shifts of masked values where the mask can
970 // be replaced by extending the shift and undoing that in the addressing mode
971 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
972 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
973 // the addressing mode. This results in code such as:
974 //
975 //   int f(short *y, int *lookup_table) {
976 //     ...
977 //     return *y + lookup_table[*y >> 11];
978 //   }
979 //
980 // Turning into:
981 //   movzwl (%rdi), %eax
982 //   movl %eax, %ecx
983 //   shrl $11, %ecx
984 //   addl (%rsi,%rcx,4), %eax
985 //
986 // Instead of:
987 //   movzwl (%rdi), %eax
988 //   movl %eax, %ecx
989 //   shrl $9, %ecx
990 //   andl $124, %rcx
991 //   addl (%rsi,%rcx), %eax
992 //
993 // Note that this function assumes the mask is provided as a mask *after* the
994 // value is shifted. The input chain may or may not match that, but computing
995 // such a mask is trivial.
996 static bool FoldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
997                                     uint64_t Mask,
998                                     SDValue Shift, SDValue X,
999                                     X86ISelAddressMode &AM) {
1000   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1001       !isa<ConstantSDNode>(Shift.getOperand(1)))
1002     return true;
1003
1004   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1005   unsigned MaskLZ = countLeadingZeros(Mask);
1006   unsigned MaskTZ = countTrailingZeros(Mask);
1007
1008   // The amount of shift we're trying to fit into the addressing mode is taken
1009   // from the trailing zeros of the mask.
1010   unsigned AMShiftAmt = MaskTZ;
1011
1012   // There is nothing we can do here unless the mask is removing some bits.
1013   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1014   if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1015
1016   // We also need to ensure that mask is a continuous run of bits.
1017   if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1018
1019   // Scale the leading zero count down based on the actual size of the value.
1020   // Also scale it down based on the size of the shift.
1021   MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1022
1023   // The final check is to ensure that any masked out high bits of X are
1024   // already known to be zero. Otherwise, the mask has a semantic impact
1025   // other than masking out a couple of low bits. Unfortunately, because of
1026   // the mask, zero extensions will be removed from operands in some cases.
1027   // This code works extra hard to look through extensions because we can
1028   // replace them with zero extensions cheaply if necessary.
1029   bool ReplacingAnyExtend = false;
1030   if (X.getOpcode() == ISD::ANY_EXTEND) {
1031     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1032                           X.getOperand(0).getSimpleValueType().getSizeInBits();
1033     // Assume that we'll replace the any-extend with a zero-extend, and
1034     // narrow the search to the extended value.
1035     X = X.getOperand(0);
1036     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1037     ReplacingAnyExtend = true;
1038   }
1039   APInt MaskedHighBits =
1040     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1041   APInt KnownZero, KnownOne;
1042   DAG.computeKnownBits(X, KnownZero, KnownOne);
1043   if (MaskedHighBits != KnownZero) return true;
1044
1045   // We've identified a pattern that can be transformed into a single shift
1046   // and an addressing mode. Make it so.
1047   MVT VT = N.getSimpleValueType();
1048   if (ReplacingAnyExtend) {
1049     assert(X.getValueType() != VT);
1050     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1051     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1052     InsertDAGNode(DAG, N, NewX);
1053     X = NewX;
1054   }
1055   SDLoc DL(N);
1056   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1057   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1058   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1059   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1060
1061   // Insert the new nodes into the topological ordering. We must do this in
1062   // a valid topological ordering as nothing is going to go back and re-sort
1063   // these nodes. We continually insert before 'N' in sequence as this is
1064   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1065   // hierarchy left to express.
1066   InsertDAGNode(DAG, N, NewSRLAmt);
1067   InsertDAGNode(DAG, N, NewSRL);
1068   InsertDAGNode(DAG, N, NewSHLAmt);
1069   InsertDAGNode(DAG, N, NewSHL);
1070   DAG.ReplaceAllUsesWith(N, NewSHL);
1071
1072   AM.Scale = 1 << AMShiftAmt;
1073   AM.IndexReg = NewSRL;
1074   return false;
1075 }
1076
1077 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1078                                               unsigned Depth) {
1079   SDLoc dl(N);
1080   DEBUG({
1081       dbgs() << "MatchAddress: ";
1082       AM.dump();
1083     });
1084   // Limit recursion.
1085   if (Depth > 5)
1086     return MatchAddressBase(N, AM);
1087
1088   // If this is already a %rip relative address, we can only merge immediates
1089   // into it.  Instead of handling this in every case, we handle it here.
1090   // RIP relative addressing: %rip + 32-bit displacement!
1091   if (AM.isRIPRelative()) {
1092     // FIXME: JumpTable and ExternalSymbol address currently don't like
1093     // displacements.  It isn't very important, but this should be fixed for
1094     // consistency.
1095     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1096       return true;
1097
1098     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1099       if (!FoldOffsetIntoAddress(Cst->getSExtValue(), AM))
1100         return false;
1101     return true;
1102   }
1103
1104   switch (N.getOpcode()) {
1105   default: break;
1106   case ISD::LOCAL_RECOVER: {
1107     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1108       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1109         // Use the symbol and don't prefix it.
1110         AM.MCSym = ESNode->getMCSymbol();
1111         return false;
1112       }
1113     break;
1114   }
1115   case ISD::Constant: {
1116     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1117     if (!FoldOffsetIntoAddress(Val, AM))
1118       return false;
1119     break;
1120   }
1121
1122   case X86ISD::Wrapper:
1123   case X86ISD::WrapperRIP:
1124     if (!MatchWrapper(N, AM))
1125       return false;
1126     break;
1127
1128   case ISD::LOAD:
1129     if (!MatchLoadInAddress(cast<LoadSDNode>(N), AM))
1130       return false;
1131     break;
1132
1133   case ISD::FrameIndex:
1134     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1135         AM.Base_Reg.getNode() == nullptr &&
1136         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1137       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1138       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1139       return false;
1140     }
1141     break;
1142
1143   case ISD::SHL:
1144     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1145       break;
1146
1147     if (ConstantSDNode
1148           *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
1149       unsigned Val = CN->getZExtValue();
1150       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1151       // that the base operand remains free for further matching. If
1152       // the base doesn't end up getting used, a post-processing step
1153       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1154       if (Val == 1 || Val == 2 || Val == 3) {
1155         AM.Scale = 1 << Val;
1156         SDValue ShVal = N.getNode()->getOperand(0);
1157
1158         // Okay, we know that we have a scale by now.  However, if the scaled
1159         // value is an add of something and a constant, we can fold the
1160         // constant into the disp field here.
1161         if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1162           AM.IndexReg = ShVal.getNode()->getOperand(0);
1163           ConstantSDNode *AddVal =
1164             cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
1165           uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1166           if (!FoldOffsetIntoAddress(Disp, AM))
1167             return false;
1168         }
1169
1170         AM.IndexReg = ShVal;
1171         return false;
1172       }
1173     }
1174     break;
1175
1176   case ISD::SRL: {
1177     // Scale must not be used already.
1178     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1179
1180     SDValue And = N.getOperand(0);
1181     if (And.getOpcode() != ISD::AND) break;
1182     SDValue X = And.getOperand(0);
1183
1184     // We only handle up to 64-bit values here as those are what matter for
1185     // addressing mode optimizations.
1186     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1187
1188     // The mask used for the transform is expected to be post-shift, but we
1189     // found the shift first so just apply the shift to the mask before passing
1190     // it down.
1191     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1192         !isa<ConstantSDNode>(And.getOperand(1)))
1193       break;
1194     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1195
1196     // Try to fold the mask and shift into the scale, and return false if we
1197     // succeed.
1198     if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1199       return false;
1200     break;
1201   }
1202
1203   case ISD::SMUL_LOHI:
1204   case ISD::UMUL_LOHI:
1205     // A mul_lohi where we need the low part can be folded as a plain multiply.
1206     if (N.getResNo() != 0) break;
1207     // FALL THROUGH
1208   case ISD::MUL:
1209   case X86ISD::MUL_IMM:
1210     // X*[3,5,9] -> X+X*[2,4,8]
1211     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1212         AM.Base_Reg.getNode() == nullptr &&
1213         AM.IndexReg.getNode() == nullptr) {
1214       if (ConstantSDNode
1215             *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
1216         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1217             CN->getZExtValue() == 9) {
1218           AM.Scale = unsigned(CN->getZExtValue())-1;
1219
1220           SDValue MulVal = N.getNode()->getOperand(0);
1221           SDValue Reg;
1222
1223           // Okay, we know that we have a scale by now.  However, if the scaled
1224           // value is an add of something and a constant, we can fold the
1225           // constant into the disp field here.
1226           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1227               isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1228             Reg = MulVal.getNode()->getOperand(0);
1229             ConstantSDNode *AddVal =
1230               cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
1231             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1232             if (FoldOffsetIntoAddress(Disp, AM))
1233               Reg = N.getNode()->getOperand(0);
1234           } else {
1235             Reg = N.getNode()->getOperand(0);
1236           }
1237
1238           AM.IndexReg = AM.Base_Reg = Reg;
1239           return false;
1240         }
1241     }
1242     break;
1243
1244   case ISD::SUB: {
1245     // Given A-B, if A can be completely folded into the address and
1246     // the index field with the index field unused, use -B as the index.
1247     // This is a win if a has multiple parts that can be folded into
1248     // the address. Also, this saves a mov if the base register has
1249     // other uses, since it avoids a two-address sub instruction, however
1250     // it costs an additional mov if the index register has other uses.
1251
1252     // Add an artificial use to this node so that we can keep track of
1253     // it if it gets CSE'd with a different node.
1254     HandleSDNode Handle(N);
1255
1256     // Test if the LHS of the sub can be folded.
1257     X86ISelAddressMode Backup = AM;
1258     if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1259       AM = Backup;
1260       break;
1261     }
1262     // Test if the index field is free for use.
1263     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1264       AM = Backup;
1265       break;
1266     }
1267
1268     int Cost = 0;
1269     SDValue RHS = Handle.getValue().getNode()->getOperand(1);
1270     // If the RHS involves a register with multiple uses, this
1271     // transformation incurs an extra mov, due to the neg instruction
1272     // clobbering its operand.
1273     if (!RHS.getNode()->hasOneUse() ||
1274         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1275         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1276         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1277         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1278          RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1279       ++Cost;
1280     // If the base is a register with multiple uses, this
1281     // transformation may save a mov.
1282     if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1283          AM.Base_Reg.getNode() &&
1284          !AM.Base_Reg.getNode()->hasOneUse()) ||
1285         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1286       --Cost;
1287     // If the folded LHS was interesting, this transformation saves
1288     // address arithmetic.
1289     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1290         ((AM.Disp != 0) && (Backup.Disp == 0)) +
1291         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1292       --Cost;
1293     // If it doesn't look like it may be an overall win, don't do it.
1294     if (Cost >= 0) {
1295       AM = Backup;
1296       break;
1297     }
1298
1299     // Ok, the transformation is legal and appears profitable. Go for it.
1300     SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1301     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1302     AM.IndexReg = Neg;
1303     AM.Scale = 1;
1304
1305     // Insert the new nodes into the topological ordering.
1306     InsertDAGNode(*CurDAG, N, Zero);
1307     InsertDAGNode(*CurDAG, N, Neg);
1308     return false;
1309   }
1310
1311   case ISD::ADD: {
1312     // Add an artificial use to this node so that we can keep track of
1313     // it if it gets CSE'd with a different node.
1314     HandleSDNode Handle(N);
1315
1316     X86ISelAddressMode Backup = AM;
1317     if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1318         !MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1319       return false;
1320     AM = Backup;
1321
1322     // Try again after commuting the operands.
1323     if (!MatchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)&&
1324         !MatchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1325       return false;
1326     AM = Backup;
1327
1328     // If we couldn't fold both operands into the address at the same time,
1329     // see if we can just put each operand into a register and fold at least
1330     // the add.
1331     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1332         !AM.Base_Reg.getNode() &&
1333         !AM.IndexReg.getNode()) {
1334       N = Handle.getValue();
1335       AM.Base_Reg = N.getOperand(0);
1336       AM.IndexReg = N.getOperand(1);
1337       AM.Scale = 1;
1338       return false;
1339     }
1340     N = Handle.getValue();
1341     break;
1342   }
1343
1344   case ISD::OR:
1345     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1346     if (CurDAG->isBaseWithConstantOffset(N)) {
1347       X86ISelAddressMode Backup = AM;
1348       ConstantSDNode *CN = cast<ConstantSDNode>(N.getOperand(1));
1349
1350       // Start with the LHS as an addr mode.
1351       if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1352           !FoldOffsetIntoAddress(CN->getSExtValue(), AM))
1353         return false;
1354       AM = Backup;
1355     }
1356     break;
1357
1358   case ISD::AND: {
1359     // Perform some heroic transforms on an and of a constant-count shift
1360     // with a constant to enable use of the scaled offset field.
1361
1362     // Scale must not be used already.
1363     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1364
1365     SDValue Shift = N.getOperand(0);
1366     if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1367     SDValue X = Shift.getOperand(0);
1368
1369     // We only handle up to 64-bit values here as those are what matter for
1370     // addressing mode optimizations.
1371     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1372
1373     if (!isa<ConstantSDNode>(N.getOperand(1)))
1374       break;
1375     uint64_t Mask = N.getConstantOperandVal(1);
1376
1377     // Try to fold the mask and shift into an extract and scale.
1378     if (!FoldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1379       return false;
1380
1381     // Try to fold the mask and shift directly into the scale.
1382     if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1383       return false;
1384
1385     // Try to swap the mask and shift to place shifts which can be done as
1386     // a scale on the outside of the mask.
1387     if (!FoldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1388       return false;
1389     break;
1390   }
1391   }
1392
1393   return MatchAddressBase(N, AM);
1394 }
1395
1396 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1397 /// specified addressing mode without any further recursion.
1398 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1399   // Is the base register already occupied?
1400   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1401     // If so, check to see if the scale index register is set.
1402     if (!AM.IndexReg.getNode()) {
1403       AM.IndexReg = N;
1404       AM.Scale = 1;
1405       return false;
1406     }
1407
1408     // Otherwise, we cannot select it.
1409     return true;
1410   }
1411
1412   // Default, generate it as a register.
1413   AM.BaseType = X86ISelAddressMode::RegBase;
1414   AM.Base_Reg = N;
1415   return false;
1416 }
1417
1418 bool X86DAGToDAGISel::SelectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1419                                       SDValue &Scale, SDValue &Index,
1420                                       SDValue &Disp, SDValue &Segment) {
1421
1422   MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1423   if (!Mgs)
1424     return false;
1425   X86ISelAddressMode AM;
1426   unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1427   // AddrSpace 256 -> GS, 257 -> FS.
1428   if (AddrSpace == 256)
1429     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1430   if (AddrSpace == 257)
1431     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1432
1433   SDLoc DL(N);
1434   Base = Mgs->getBasePtr();
1435   Index = Mgs->getIndex();
1436   unsigned ScalarSize = Mgs->getValue().getValueType().getScalarSizeInBits();
1437   Scale = getI8Imm(ScalarSize/8, DL);
1438
1439   // If Base is 0, the whole address is in index and the Scale is 1
1440   if (isa<ConstantSDNode>(Base)) {
1441     assert(dyn_cast<ConstantSDNode>(Base)->isNullValue() &&
1442            "Unexpected base in gather/scatter");
1443     Scale = getI8Imm(1, DL);
1444     Base = CurDAG->getRegister(0, MVT::i32);
1445   }
1446   if (AM.Segment.getNode())
1447     Segment = AM.Segment;
1448   else
1449     Segment = CurDAG->getRegister(0, MVT::i32);
1450   Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1451   return true;
1452 }
1453
1454 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1455 /// It returns the operands which make up the maximal addressing mode it can
1456 /// match by reference.
1457 ///
1458 /// Parent is the parent node of the addr operand that is being matched.  It
1459 /// is always a load, store, atomic node, or null.  It is only null when
1460 /// checking memory operands for inline asm nodes.
1461 bool X86DAGToDAGISel::SelectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1462                                  SDValue &Scale, SDValue &Index,
1463                                  SDValue &Disp, SDValue &Segment) {
1464   X86ISelAddressMode AM;
1465
1466   if (Parent &&
1467       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1468       // that are not a MemSDNode, and thus don't have proper addrspace info.
1469       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1470       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1471       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1472       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1473       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1474     unsigned AddrSpace =
1475       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1476     // AddrSpace 256 -> GS, 257 -> FS.
1477     if (AddrSpace == 256)
1478       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1479     if (AddrSpace == 257)
1480       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1481   }
1482
1483   if (MatchAddress(N, AM))
1484     return false;
1485
1486   MVT VT = N.getSimpleValueType();
1487   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1488     if (!AM.Base_Reg.getNode())
1489       AM.Base_Reg = CurDAG->getRegister(0, VT);
1490   }
1491
1492   if (!AM.IndexReg.getNode())
1493     AM.IndexReg = CurDAG->getRegister(0, VT);
1494
1495   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1496   return true;
1497 }
1498
1499 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
1500 /// match a load whose top elements are either undef or zeros.  The load flavor
1501 /// is derived from the type of N, which is either v4f32 or v2f64.
1502 ///
1503 /// We also return:
1504 ///   PatternChainNode: this is the matched node that has a chain input and
1505 ///   output.
1506 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1507                                           SDValue N, SDValue &Base,
1508                                           SDValue &Scale, SDValue &Index,
1509                                           SDValue &Disp, SDValue &Segment,
1510                                           SDValue &PatternNodeWithChain) {
1511   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1512     PatternNodeWithChain = N.getOperand(0);
1513     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1514         PatternNodeWithChain.hasOneUse() &&
1515         IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1516         IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1517       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1518       if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1519         return false;
1520       return true;
1521     }
1522   }
1523
1524   // Also handle the case where we explicitly require zeros in the top
1525   // elements.  This is a vector shuffle from the zero vector.
1526   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1527       // Check to see if the top elements are all zeros (or bitcast of zeros).
1528       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1529       N.getOperand(0).getNode()->hasOneUse() &&
1530       ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1531       N.getOperand(0).getOperand(0).hasOneUse() &&
1532       IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1533       IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1534     // Okay, this is a zero extending load.  Fold it.
1535     LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1536     if (!SelectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1537       return false;
1538     PatternNodeWithChain = SDValue(LD, 0);
1539     return true;
1540   }
1541   return false;
1542 }
1543
1544
1545 bool X86DAGToDAGISel::SelectMOV64Imm32(SDValue N, SDValue &Imm) {
1546   if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1547     uint64_t ImmVal = CN->getZExtValue();
1548     if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1549       return false;
1550
1551     Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1552     return true;
1553   }
1554
1555   // In static codegen with small code model, we can get the address of a label
1556   // into a register with 'movl'. TableGen has already made sure we're looking
1557   // at a label of some kind.
1558   assert(N->getOpcode() == X86ISD::Wrapper &&
1559          "Unexpected node type for MOV32ri64");
1560   N = N.getOperand(0);
1561
1562   if (N->getOpcode() != ISD::TargetConstantPool &&
1563       N->getOpcode() != ISD::TargetJumpTable &&
1564       N->getOpcode() != ISD::TargetGlobalAddress &&
1565       N->getOpcode() != ISD::TargetExternalSymbol &&
1566       N->getOpcode() != ISD::MCSymbol &&
1567       N->getOpcode() != ISD::TargetBlockAddress)
1568     return false;
1569
1570   Imm = N;
1571   return TM.getCodeModel() == CodeModel::Small;
1572 }
1573
1574 bool X86DAGToDAGISel::SelectLEA64_32Addr(SDValue N, SDValue &Base,
1575                                          SDValue &Scale, SDValue &Index,
1576                                          SDValue &Disp, SDValue &Segment) {
1577   if (!SelectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1578     return false;
1579
1580   SDLoc DL(N);
1581   RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1582   if (RN && RN->getReg() == 0)
1583     Base = CurDAG->getRegister(0, MVT::i64);
1584   else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1585     // Base could already be %rip, particularly in the x32 ABI.
1586     Base = SDValue(CurDAG->getMachineNode(
1587                        TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1588                        CurDAG->getTargetConstant(0, DL, MVT::i64),
1589                        Base,
1590                        CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1591                    0);
1592   }
1593
1594   RN = dyn_cast<RegisterSDNode>(Index);
1595   if (RN && RN->getReg() == 0)
1596     Index = CurDAG->getRegister(0, MVT::i64);
1597   else {
1598     assert(Index.getValueType() == MVT::i32 &&
1599            "Expect to be extending 32-bit registers for use in LEA");
1600     Index = SDValue(CurDAG->getMachineNode(
1601                         TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1602                         CurDAG->getTargetConstant(0, DL, MVT::i64),
1603                         Index,
1604                         CurDAG->getTargetConstant(X86::sub_32bit, DL,
1605                                                   MVT::i32)),
1606                     0);
1607   }
1608
1609   return true;
1610 }
1611
1612 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1613 /// mode it matches can be cost effectively emitted as an LEA instruction.
1614 bool X86DAGToDAGISel::SelectLEAAddr(SDValue N,
1615                                     SDValue &Base, SDValue &Scale,
1616                                     SDValue &Index, SDValue &Disp,
1617                                     SDValue &Segment) {
1618   X86ISelAddressMode AM;
1619
1620   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1621   // segments.
1622   SDValue Copy = AM.Segment;
1623   SDValue T = CurDAG->getRegister(0, MVT::i32);
1624   AM.Segment = T;
1625   if (MatchAddress(N, AM))
1626     return false;
1627   assert (T == AM.Segment);
1628   AM.Segment = Copy;
1629
1630   MVT VT = N.getSimpleValueType();
1631   unsigned Complexity = 0;
1632   if (AM.BaseType == X86ISelAddressMode::RegBase)
1633     if (AM.Base_Reg.getNode())
1634       Complexity = 1;
1635     else
1636       AM.Base_Reg = CurDAG->getRegister(0, VT);
1637   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1638     Complexity = 4;
1639
1640   if (AM.IndexReg.getNode())
1641     Complexity++;
1642   else
1643     AM.IndexReg = CurDAG->getRegister(0, VT);
1644
1645   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1646   // a simple shift.
1647   if (AM.Scale > 1)
1648     Complexity++;
1649
1650   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1651   // to a LEA. This is determined with some expermentation but is by no means
1652   // optimal (especially for code size consideration). LEA is nice because of
1653   // its three-address nature. Tweak the cost function again when we can run
1654   // convertToThreeAddress() at register allocation time.
1655   if (AM.hasSymbolicDisplacement()) {
1656     // For X86-64, we should always use lea to materialize RIP relative
1657     // addresses.
1658     if (Subtarget->is64Bit())
1659       Complexity = 4;
1660     else
1661       Complexity += 2;
1662   }
1663
1664   if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1665     Complexity++;
1666
1667   // If it isn't worth using an LEA, reject it.
1668   if (Complexity <= 2)
1669     return false;
1670
1671   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1672   return true;
1673 }
1674
1675 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1676 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue N, SDValue &Base,
1677                                         SDValue &Scale, SDValue &Index,
1678                                         SDValue &Disp, SDValue &Segment) {
1679   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1680   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1681
1682   X86ISelAddressMode AM;
1683   AM.GV = GA->getGlobal();
1684   AM.Disp += GA->getOffset();
1685   AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1686   AM.SymbolFlags = GA->getTargetFlags();
1687
1688   if (N.getValueType() == MVT::i32) {
1689     AM.Scale = 1;
1690     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1691   } else {
1692     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1693   }
1694
1695   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1696   return true;
1697 }
1698
1699
1700 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1701                                   SDValue &Base, SDValue &Scale,
1702                                   SDValue &Index, SDValue &Disp,
1703                                   SDValue &Segment) {
1704   if (!ISD::isNON_EXTLoad(N.getNode()) ||
1705       !IsProfitableToFold(N, P, P) ||
1706       !IsLegalToFold(N, P, P, OptLevel))
1707     return false;
1708
1709   return SelectAddr(N.getNode(),
1710                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
1711 }
1712
1713 /// getGlobalBaseReg - Return an SDNode that returns the value of
1714 /// the global base register. Output instructions required to
1715 /// initialize the global base register, if necessary.
1716 ///
1717 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1718   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1719   auto &DL = MF->getDataLayout();
1720   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1721 }
1722
1723 /// Atomic opcode table
1724 ///
1725 enum AtomicOpc {
1726   ADD,
1727   SUB,
1728   INC,
1729   DEC,
1730   OR,
1731   AND,
1732   XOR,
1733   AtomicOpcEnd
1734 };
1735
1736 enum AtomicSz {
1737   ConstantI8,
1738   I8,
1739   SextConstantI16,
1740   ConstantI16,
1741   I16,
1742   SextConstantI32,
1743   ConstantI32,
1744   I32,
1745   SextConstantI64,
1746   ConstantI64,
1747   I64,
1748   AtomicSzEnd
1749 };
1750
1751 static const uint16_t AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] = {
1752   {
1753     X86::LOCK_ADD8mi,
1754     X86::LOCK_ADD8mr,
1755     X86::LOCK_ADD16mi8,
1756     X86::LOCK_ADD16mi,
1757     X86::LOCK_ADD16mr,
1758     X86::LOCK_ADD32mi8,
1759     X86::LOCK_ADD32mi,
1760     X86::LOCK_ADD32mr,
1761     X86::LOCK_ADD64mi8,
1762     X86::LOCK_ADD64mi32,
1763     X86::LOCK_ADD64mr,
1764   },
1765   {
1766     X86::LOCK_SUB8mi,
1767     X86::LOCK_SUB8mr,
1768     X86::LOCK_SUB16mi8,
1769     X86::LOCK_SUB16mi,
1770     X86::LOCK_SUB16mr,
1771     X86::LOCK_SUB32mi8,
1772     X86::LOCK_SUB32mi,
1773     X86::LOCK_SUB32mr,
1774     X86::LOCK_SUB64mi8,
1775     X86::LOCK_SUB64mi32,
1776     X86::LOCK_SUB64mr,
1777   },
1778   {
1779     0,
1780     X86::LOCK_INC8m,
1781     0,
1782     0,
1783     X86::LOCK_INC16m,
1784     0,
1785     0,
1786     X86::LOCK_INC32m,
1787     0,
1788     0,
1789     X86::LOCK_INC64m,
1790   },
1791   {
1792     0,
1793     X86::LOCK_DEC8m,
1794     0,
1795     0,
1796     X86::LOCK_DEC16m,
1797     0,
1798     0,
1799     X86::LOCK_DEC32m,
1800     0,
1801     0,
1802     X86::LOCK_DEC64m,
1803   },
1804   {
1805     X86::LOCK_OR8mi,
1806     X86::LOCK_OR8mr,
1807     X86::LOCK_OR16mi8,
1808     X86::LOCK_OR16mi,
1809     X86::LOCK_OR16mr,
1810     X86::LOCK_OR32mi8,
1811     X86::LOCK_OR32mi,
1812     X86::LOCK_OR32mr,
1813     X86::LOCK_OR64mi8,
1814     X86::LOCK_OR64mi32,
1815     X86::LOCK_OR64mr,
1816   },
1817   {
1818     X86::LOCK_AND8mi,
1819     X86::LOCK_AND8mr,
1820     X86::LOCK_AND16mi8,
1821     X86::LOCK_AND16mi,
1822     X86::LOCK_AND16mr,
1823     X86::LOCK_AND32mi8,
1824     X86::LOCK_AND32mi,
1825     X86::LOCK_AND32mr,
1826     X86::LOCK_AND64mi8,
1827     X86::LOCK_AND64mi32,
1828     X86::LOCK_AND64mr,
1829   },
1830   {
1831     X86::LOCK_XOR8mi,
1832     X86::LOCK_XOR8mr,
1833     X86::LOCK_XOR16mi8,
1834     X86::LOCK_XOR16mi,
1835     X86::LOCK_XOR16mr,
1836     X86::LOCK_XOR32mi8,
1837     X86::LOCK_XOR32mi,
1838     X86::LOCK_XOR32mr,
1839     X86::LOCK_XOR64mi8,
1840     X86::LOCK_XOR64mi32,
1841     X86::LOCK_XOR64mr,
1842   }
1843 };
1844
1845 // Return the target constant operand for atomic-load-op and do simple
1846 // translations, such as from atomic-load-add to lock-sub. The return value is
1847 // one of the following 3 cases:
1848 // + target-constant, the operand could be supported as a target constant.
1849 // + empty, the operand is not needed any more with the new op selected.
1850 // + non-empty, otherwise.
1851 static SDValue getAtomicLoadArithTargetConstant(SelectionDAG *CurDAG,
1852                                                 SDLoc dl,
1853                                                 enum AtomicOpc &Op, MVT NVT,
1854                                                 SDValue Val,
1855                                                 const X86Subtarget *Subtarget) {
1856   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val)) {
1857     int64_t CNVal = CN->getSExtValue();
1858     // Quit if not 32-bit imm.
1859     if ((int32_t)CNVal != CNVal)
1860       return Val;
1861     // Quit if INT32_MIN: it would be negated as it is negative and overflow,
1862     // producing an immediate that does not fit in the 32 bits available for
1863     // an immediate operand to sub. However, it still fits in 32 bits for the
1864     // add (since it is not negated) so we can return target-constant.
1865     if (CNVal == INT32_MIN)
1866       return CurDAG->getTargetConstant(CNVal, dl, NVT);
1867     // For atomic-load-add, we could do some optimizations.
1868     if (Op == ADD) {
1869       // Translate to INC/DEC if ADD by 1 or -1.
1870       if (((CNVal == 1) || (CNVal == -1)) && !Subtarget->slowIncDec()) {
1871         Op = (CNVal == 1) ? INC : DEC;
1872         // No more constant operand after being translated into INC/DEC.
1873         return SDValue();
1874       }
1875       // Translate to SUB if ADD by negative value.
1876       if (CNVal < 0) {
1877         Op = SUB;
1878         CNVal = -CNVal;
1879       }
1880     }
1881     return CurDAG->getTargetConstant(CNVal, dl, NVT);
1882   }
1883
1884   // If the value operand is single-used, try to optimize it.
1885   if (Op == ADD && Val.hasOneUse()) {
1886     // Translate (atomic-load-add ptr (sub 0 x)) back to (lock-sub x).
1887     if (Val.getOpcode() == ISD::SUB && X86::isZeroNode(Val.getOperand(0))) {
1888       Op = SUB;
1889       return Val.getOperand(1);
1890     }
1891     // A special case for i16, which needs truncating as, in most cases, it's
1892     // promoted to i32. We will translate
1893     // (atomic-load-add (truncate (sub 0 x))) to (lock-sub (EXTRACT_SUBREG x))
1894     if (Val.getOpcode() == ISD::TRUNCATE && NVT == MVT::i16 &&
1895         Val.getOperand(0).getOpcode() == ISD::SUB &&
1896         X86::isZeroNode(Val.getOperand(0).getOperand(0))) {
1897       Op = SUB;
1898       Val = Val.getOperand(0);
1899       return CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl, NVT,
1900                                             Val.getOperand(1));
1901     }
1902   }
1903
1904   return Val;
1905 }
1906
1907 SDNode *X86DAGToDAGISel::SelectAtomicLoadArith(SDNode *Node, MVT NVT) {
1908   if (Node->hasAnyUseOfValue(0))
1909     return nullptr;
1910
1911   SDLoc dl(Node);
1912
1913   // Optimize common patterns for __sync_or_and_fetch and similar arith
1914   // operations where the result is not used. This allows us to use the "lock"
1915   // version of the arithmetic instruction.
1916   SDValue Chain = Node->getOperand(0);
1917   SDValue Ptr = Node->getOperand(1);
1918   SDValue Val = Node->getOperand(2);
1919   SDValue Base, Scale, Index, Disp, Segment;
1920   if (!SelectAddr(Node, Ptr, Base, Scale, Index, Disp, Segment))
1921     return nullptr;
1922
1923   // Which index into the table.
1924   enum AtomicOpc Op;
1925   switch (Node->getOpcode()) {
1926     default:
1927       return nullptr;
1928     case ISD::ATOMIC_LOAD_OR:
1929       Op = OR;
1930       break;
1931     case ISD::ATOMIC_LOAD_AND:
1932       Op = AND;
1933       break;
1934     case ISD::ATOMIC_LOAD_XOR:
1935       Op = XOR;
1936       break;
1937     case ISD::ATOMIC_LOAD_ADD:
1938       Op = ADD;
1939       break;
1940   }
1941
1942   Val = getAtomicLoadArithTargetConstant(CurDAG, dl, Op, NVT, Val, Subtarget);
1943   bool isUnOp = !Val.getNode();
1944   bool isCN = Val.getNode() && (Val.getOpcode() == ISD::TargetConstant);
1945
1946   unsigned Opc = 0;
1947   switch (NVT.SimpleTy) {
1948     default: return nullptr;
1949     case MVT::i8:
1950       if (isCN)
1951         Opc = AtomicOpcTbl[Op][ConstantI8];
1952       else
1953         Opc = AtomicOpcTbl[Op][I8];
1954       break;
1955     case MVT::i16:
1956       if (isCN) {
1957         if (immSext8(Val.getNode()))
1958           Opc = AtomicOpcTbl[Op][SextConstantI16];
1959         else
1960           Opc = AtomicOpcTbl[Op][ConstantI16];
1961       } else
1962         Opc = AtomicOpcTbl[Op][I16];
1963       break;
1964     case MVT::i32:
1965       if (isCN) {
1966         if (immSext8(Val.getNode()))
1967           Opc = AtomicOpcTbl[Op][SextConstantI32];
1968         else
1969           Opc = AtomicOpcTbl[Op][ConstantI32];
1970       } else
1971         Opc = AtomicOpcTbl[Op][I32];
1972       break;
1973     case MVT::i64:
1974       if (isCN) {
1975         if (immSext8(Val.getNode()))
1976           Opc = AtomicOpcTbl[Op][SextConstantI64];
1977         else if (i64immSExt32(Val.getNode()))
1978           Opc = AtomicOpcTbl[Op][ConstantI64];
1979         else
1980           llvm_unreachable("True 64 bits constant in SelectAtomicLoadArith");
1981       } else
1982         Opc = AtomicOpcTbl[Op][I64];
1983       break;
1984   }
1985
1986   assert(Opc != 0 && "Invalid arith lock transform!");
1987
1988   // Building the new node.
1989   SDValue Ret;
1990   if (isUnOp) {
1991     SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Chain };
1992     Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1993   } else {
1994     SDValue Ops[] = { Base, Scale, Index, Disp, Segment, Val, Chain };
1995     Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops), 0);
1996   }
1997
1998   // Copying the MachineMemOperand.
1999   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2000   MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
2001   cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
2002
2003   // We need to have two outputs as that is what the original instruction had.
2004   // So we add a dummy, undefined output. This is safe as we checked first
2005   // that no-one uses our output anyway.
2006   SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
2007                                                  dl, NVT), 0);
2008   SDValue RetVals[] = { Undef, Ret };
2009   return CurDAG->getMergeValues(RetVals, dl).getNode();
2010 }
2011
2012 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
2013 /// any uses which require the SF or OF bits to be accurate.
2014 static bool HasNoSignedComparisonUses(SDNode *N) {
2015   // Examine each user of the node.
2016   for (SDNode::use_iterator UI = N->use_begin(),
2017          UE = N->use_end(); UI != UE; ++UI) {
2018     // Only examine CopyToReg uses.
2019     if (UI->getOpcode() != ISD::CopyToReg)
2020       return false;
2021     // Only examine CopyToReg uses that copy to EFLAGS.
2022     if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
2023           X86::EFLAGS)
2024       return false;
2025     // Examine each user of the CopyToReg use.
2026     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2027            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2028       // Only examine the Flag result.
2029       if (FlagUI.getUse().getResNo() != 1) continue;
2030       // Anything unusual: assume conservatively.
2031       if (!FlagUI->isMachineOpcode()) return false;
2032       // Examine the opcode of the user.
2033       switch (FlagUI->getMachineOpcode()) {
2034       // These comparisons don't treat the most significant bit specially.
2035       case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
2036       case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
2037       case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
2038       case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
2039       case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
2040       case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
2041       case X86::CMOVA16rr: case X86::CMOVA16rm:
2042       case X86::CMOVA32rr: case X86::CMOVA32rm:
2043       case X86::CMOVA64rr: case X86::CMOVA64rm:
2044       case X86::CMOVAE16rr: case X86::CMOVAE16rm:
2045       case X86::CMOVAE32rr: case X86::CMOVAE32rm:
2046       case X86::CMOVAE64rr: case X86::CMOVAE64rm:
2047       case X86::CMOVB16rr: case X86::CMOVB16rm:
2048       case X86::CMOVB32rr: case X86::CMOVB32rm:
2049       case X86::CMOVB64rr: case X86::CMOVB64rm:
2050       case X86::CMOVBE16rr: case X86::CMOVBE16rm:
2051       case X86::CMOVBE32rr: case X86::CMOVBE32rm:
2052       case X86::CMOVBE64rr: case X86::CMOVBE64rm:
2053       case X86::CMOVE16rr: case X86::CMOVE16rm:
2054       case X86::CMOVE32rr: case X86::CMOVE32rm:
2055       case X86::CMOVE64rr: case X86::CMOVE64rm:
2056       case X86::CMOVNE16rr: case X86::CMOVNE16rm:
2057       case X86::CMOVNE32rr: case X86::CMOVNE32rm:
2058       case X86::CMOVNE64rr: case X86::CMOVNE64rm:
2059       case X86::CMOVNP16rr: case X86::CMOVNP16rm:
2060       case X86::CMOVNP32rr: case X86::CMOVNP32rm:
2061       case X86::CMOVNP64rr: case X86::CMOVNP64rm:
2062       case X86::CMOVP16rr: case X86::CMOVP16rm:
2063       case X86::CMOVP32rr: case X86::CMOVP32rm:
2064       case X86::CMOVP64rr: case X86::CMOVP64rm:
2065         continue;
2066       // Anything else: assume conservatively.
2067       default: return false;
2068       }
2069     }
2070   }
2071   return true;
2072 }
2073
2074 /// isLoadIncOrDecStore - Check whether or not the chain ending in StoreNode
2075 /// is suitable for doing the {load; increment or decrement; store} to modify
2076 /// transformation.
2077 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
2078                                 SDValue StoredVal, SelectionDAG *CurDAG,
2079                                 LoadSDNode* &LoadNode, SDValue &InputChain) {
2080
2081   // is the value stored the result of a DEC or INC?
2082   if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
2083
2084   // is the stored value result 0 of the load?
2085   if (StoredVal.getResNo() != 0) return false;
2086
2087   // are there other uses of the loaded value than the inc or dec?
2088   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2089
2090   // is the store non-extending and non-indexed?
2091   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2092     return false;
2093
2094   SDValue Load = StoredVal->getOperand(0);
2095   // Is the stored value a non-extending and non-indexed load?
2096   if (!ISD::isNormalLoad(Load.getNode())) return false;
2097
2098   // Return LoadNode by reference.
2099   LoadNode = cast<LoadSDNode>(Load);
2100   // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
2101   EVT LdVT = LoadNode->getMemoryVT();
2102   if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
2103       LdVT != MVT::i8)
2104     return false;
2105
2106   // Is store the only read of the loaded value?
2107   if (!Load.hasOneUse())
2108     return false;
2109
2110   // Is the address of the store the same as the load?
2111   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2112       LoadNode->getOffset() != StoreNode->getOffset())
2113     return false;
2114
2115   // Check if the chain is produced by the load or is a TokenFactor with
2116   // the load output chain as an operand. Return InputChain by reference.
2117   SDValue Chain = StoreNode->getChain();
2118
2119   bool ChainCheck = false;
2120   if (Chain == Load.getValue(1)) {
2121     ChainCheck = true;
2122     InputChain = LoadNode->getChain();
2123   } else if (Chain.getOpcode() == ISD::TokenFactor) {
2124     SmallVector<SDValue, 4> ChainOps;
2125     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2126       SDValue Op = Chain.getOperand(i);
2127       if (Op == Load.getValue(1)) {
2128         ChainCheck = true;
2129         continue;
2130       }
2131
2132       // Make sure using Op as part of the chain would not cause a cycle here.
2133       // In theory, we could check whether the chain node is a predecessor of
2134       // the load. But that can be very expensive. Instead visit the uses and
2135       // make sure they all have smaller node id than the load.
2136       int LoadId = LoadNode->getNodeId();
2137       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
2138              UE = UI->use_end(); UI != UE; ++UI) {
2139         if (UI.getUse().getResNo() != 0)
2140           continue;
2141         if (UI->getNodeId() > LoadId)
2142           return false;
2143       }
2144
2145       ChainOps.push_back(Op);
2146     }
2147
2148     if (ChainCheck)
2149       // Make a new TokenFactor with all the other input chains except
2150       // for the load.
2151       InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
2152                                    MVT::Other, ChainOps);
2153   }
2154   if (!ChainCheck)
2155     return false;
2156
2157   return true;
2158 }
2159
2160 /// getFusedLdStOpcode - Get the appropriate X86 opcode for an in memory
2161 /// increment or decrement. Opc should be X86ISD::DEC or X86ISD::INC.
2162 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
2163   if (Opc == X86ISD::DEC) {
2164     if (LdVT == MVT::i64) return X86::DEC64m;
2165     if (LdVT == MVT::i32) return X86::DEC32m;
2166     if (LdVT == MVT::i16) return X86::DEC16m;
2167     if (LdVT == MVT::i8)  return X86::DEC8m;
2168   } else {
2169     assert(Opc == X86ISD::INC && "unrecognized opcode");
2170     if (LdVT == MVT::i64) return X86::INC64m;
2171     if (LdVT == MVT::i32) return X86::INC32m;
2172     if (LdVT == MVT::i16) return X86::INC16m;
2173     if (LdVT == MVT::i8)  return X86::INC8m;
2174   }
2175   llvm_unreachable("unrecognized size for LdVT");
2176 }
2177
2178 /// SelectGather - Customized ISel for GATHER operations.
2179 ///
2180 SDNode *X86DAGToDAGISel::SelectGather(SDNode *Node, unsigned Opc) {
2181   // Operands of Gather: VSrc, Base, VIdx, VMask, Scale
2182   SDValue Chain = Node->getOperand(0);
2183   SDValue VSrc = Node->getOperand(2);
2184   SDValue Base = Node->getOperand(3);
2185   SDValue VIdx = Node->getOperand(4);
2186   SDValue VMask = Node->getOperand(5);
2187   ConstantSDNode *Scale = dyn_cast<ConstantSDNode>(Node->getOperand(6));
2188   if (!Scale)
2189     return nullptr;
2190
2191   SDVTList VTs = CurDAG->getVTList(VSrc.getValueType(), VSrc.getValueType(),
2192                                    MVT::Other);
2193
2194   SDLoc DL(Node);
2195
2196   // Memory Operands: Base, Scale, Index, Disp, Segment
2197   SDValue Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
2198   SDValue Segment = CurDAG->getRegister(0, MVT::i32);
2199   const SDValue Ops[] = { VSrc, Base, getI8Imm(Scale->getSExtValue(), DL), VIdx,
2200                           Disp, Segment, VMask, Chain};
2201   SDNode *ResNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
2202   // Node has 2 outputs: VDst and MVT::Other.
2203   // ResNode has 3 outputs: VDst, VMask_wb, and MVT::Other.
2204   // We replace VDst of Node with VDst of ResNode, and Other of Node with Other
2205   // of ResNode.
2206   ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
2207   ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 2));
2208   return ResNode;
2209 }
2210
2211 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
2212   MVT NVT = Node->getSimpleValueType(0);
2213   unsigned Opc, MOpc;
2214   unsigned Opcode = Node->getOpcode();
2215   SDLoc dl(Node);
2216
2217   DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
2218
2219   if (Node->isMachineOpcode()) {
2220     DEBUG(dbgs() << "== ";  Node->dump(CurDAG); dbgs() << '\n');
2221     Node->setNodeId(-1);
2222     return nullptr;   // Already selected.
2223   }
2224
2225   switch (Opcode) {
2226   default: break;
2227   case ISD::INTRINSIC_W_CHAIN: {
2228     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2229     switch (IntNo) {
2230     default: break;
2231     case Intrinsic::x86_avx2_gather_d_pd:
2232     case Intrinsic::x86_avx2_gather_d_pd_256:
2233     case Intrinsic::x86_avx2_gather_q_pd:
2234     case Intrinsic::x86_avx2_gather_q_pd_256:
2235     case Intrinsic::x86_avx2_gather_d_ps:
2236     case Intrinsic::x86_avx2_gather_d_ps_256:
2237     case Intrinsic::x86_avx2_gather_q_ps:
2238     case Intrinsic::x86_avx2_gather_q_ps_256:
2239     case Intrinsic::x86_avx2_gather_d_q:
2240     case Intrinsic::x86_avx2_gather_d_q_256:
2241     case Intrinsic::x86_avx2_gather_q_q:
2242     case Intrinsic::x86_avx2_gather_q_q_256:
2243     case Intrinsic::x86_avx2_gather_d_d:
2244     case Intrinsic::x86_avx2_gather_d_d_256:
2245     case Intrinsic::x86_avx2_gather_q_d:
2246     case Intrinsic::x86_avx2_gather_q_d_256: {
2247       if (!Subtarget->hasAVX2())
2248         break;
2249       unsigned Opc;
2250       switch (IntNo) {
2251       default: llvm_unreachable("Impossible intrinsic");
2252       case Intrinsic::x86_avx2_gather_d_pd:     Opc = X86::VGATHERDPDrm;  break;
2253       case Intrinsic::x86_avx2_gather_d_pd_256: Opc = X86::VGATHERDPDYrm; break;
2254       case Intrinsic::x86_avx2_gather_q_pd:     Opc = X86::VGATHERQPDrm;  break;
2255       case Intrinsic::x86_avx2_gather_q_pd_256: Opc = X86::VGATHERQPDYrm; break;
2256       case Intrinsic::x86_avx2_gather_d_ps:     Opc = X86::VGATHERDPSrm;  break;
2257       case Intrinsic::x86_avx2_gather_d_ps_256: Opc = X86::VGATHERDPSYrm; break;
2258       case Intrinsic::x86_avx2_gather_q_ps:     Opc = X86::VGATHERQPSrm;  break;
2259       case Intrinsic::x86_avx2_gather_q_ps_256: Opc = X86::VGATHERQPSYrm; break;
2260       case Intrinsic::x86_avx2_gather_d_q:      Opc = X86::VPGATHERDQrm;  break;
2261       case Intrinsic::x86_avx2_gather_d_q_256:  Opc = X86::VPGATHERDQYrm; break;
2262       case Intrinsic::x86_avx2_gather_q_q:      Opc = X86::VPGATHERQQrm;  break;
2263       case Intrinsic::x86_avx2_gather_q_q_256:  Opc = X86::VPGATHERQQYrm; break;
2264       case Intrinsic::x86_avx2_gather_d_d:      Opc = X86::VPGATHERDDrm;  break;
2265       case Intrinsic::x86_avx2_gather_d_d_256:  Opc = X86::VPGATHERDDYrm; break;
2266       case Intrinsic::x86_avx2_gather_q_d:      Opc = X86::VPGATHERQDrm;  break;
2267       case Intrinsic::x86_avx2_gather_q_d_256:  Opc = X86::VPGATHERQDYrm; break;
2268       }
2269       SDNode *RetVal = SelectGather(Node, Opc);
2270       if (RetVal)
2271         // We already called ReplaceUses inside SelectGather.
2272         return nullptr;
2273       break;
2274     }
2275     }
2276     break;
2277   }
2278   case X86ISD::GlobalBaseReg:
2279     return getGlobalBaseReg();
2280
2281   case X86ISD::SHRUNKBLEND: {
2282     // SHRUNKBLEND selects like a regular VSELECT.
2283     SDValue VSelect = CurDAG->getNode(
2284         ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2285         Node->getOperand(1), Node->getOperand(2));
2286     ReplaceUses(SDValue(Node, 0), VSelect);
2287     SelectCode(VSelect.getNode());
2288     // We already called ReplaceUses.
2289     return nullptr;
2290   }
2291
2292   case ISD::ATOMIC_LOAD_XOR:
2293   case ISD::ATOMIC_LOAD_AND:
2294   case ISD::ATOMIC_LOAD_OR:
2295   case ISD::ATOMIC_LOAD_ADD: {
2296     SDNode *RetVal = SelectAtomicLoadArith(Node, NVT);
2297     if (RetVal)
2298       return RetVal;
2299     break;
2300   }
2301   case ISD::AND:
2302   case ISD::OR:
2303   case ISD::XOR: {
2304     // For operations of the form (x << C1) op C2, check if we can use a smaller
2305     // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2306     SDValue N0 = Node->getOperand(0);
2307     SDValue N1 = Node->getOperand(1);
2308
2309     if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2310       break;
2311
2312     // i8 is unshrinkable, i16 should be promoted to i32.
2313     if (NVT != MVT::i32 && NVT != MVT::i64)
2314       break;
2315
2316     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2317     ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2318     if (!Cst || !ShlCst)
2319       break;
2320
2321     int64_t Val = Cst->getSExtValue();
2322     uint64_t ShlVal = ShlCst->getZExtValue();
2323
2324     // Make sure that we don't change the operation by removing bits.
2325     // This only matters for OR and XOR, AND is unaffected.
2326     uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2327     if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2328       break;
2329
2330     unsigned ShlOp, AddOp, Op;
2331     MVT CstVT = NVT;
2332
2333     // Check the minimum bitwidth for the new constant.
2334     // TODO: AND32ri is the same as AND64ri32 with zext imm.
2335     // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2336     // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2337     if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2338       CstVT = MVT::i8;
2339     else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2340       CstVT = MVT::i32;
2341
2342     // Bail if there is no smaller encoding.
2343     if (NVT == CstVT)
2344       break;
2345
2346     switch (NVT.SimpleTy) {
2347     default: llvm_unreachable("Unsupported VT!");
2348     case MVT::i32:
2349       assert(CstVT == MVT::i8);
2350       ShlOp = X86::SHL32ri;
2351       AddOp = X86::ADD32rr;
2352
2353       switch (Opcode) {
2354       default: llvm_unreachable("Impossible opcode");
2355       case ISD::AND: Op = X86::AND32ri8; break;
2356       case ISD::OR:  Op =  X86::OR32ri8; break;
2357       case ISD::XOR: Op = X86::XOR32ri8; break;
2358       }
2359       break;
2360     case MVT::i64:
2361       assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2362       ShlOp = X86::SHL64ri;
2363       AddOp = X86::ADD64rr;
2364
2365       switch (Opcode) {
2366       default: llvm_unreachable("Impossible opcode");
2367       case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2368       case ISD::OR:  Op = CstVT==MVT::i8?  X86::OR64ri8 :  X86::OR64ri32; break;
2369       case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2370       }
2371       break;
2372     }
2373
2374     // Emit the smaller op and the shift.
2375     SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2376     SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2377     if (ShlVal == 1)
2378       return CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2379                                   SDValue(New, 0));
2380     return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2381                                 getI8Imm(ShlVal, dl));
2382   }
2383   case X86ISD::UMUL8:
2384   case X86ISD::SMUL8: {
2385     SDValue N0 = Node->getOperand(0);
2386     SDValue N1 = Node->getOperand(1);
2387
2388     Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2389
2390     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2391                                           N0, SDValue()).getValue(1);
2392
2393     SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2394     SDValue Ops[] = {N1, InFlag};
2395     SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2396
2397     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2398     ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2399     return nullptr;
2400   }
2401
2402   case X86ISD::UMUL: {
2403     SDValue N0 = Node->getOperand(0);
2404     SDValue N1 = Node->getOperand(1);
2405
2406     unsigned LoReg;
2407     switch (NVT.SimpleTy) {
2408     default: llvm_unreachable("Unsupported VT!");
2409     case MVT::i8:  LoReg = X86::AL;  Opc = X86::MUL8r; break;
2410     case MVT::i16: LoReg = X86::AX;  Opc = X86::MUL16r; break;
2411     case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2412     case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2413     }
2414
2415     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2416                                           N0, SDValue()).getValue(1);
2417
2418     SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2419     SDValue Ops[] = {N1, InFlag};
2420     SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2421
2422     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2423     ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2424     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 2));
2425     return nullptr;
2426   }
2427
2428   case ISD::SMUL_LOHI:
2429   case ISD::UMUL_LOHI: {
2430     SDValue N0 = Node->getOperand(0);
2431     SDValue N1 = Node->getOperand(1);
2432
2433     bool isSigned = Opcode == ISD::SMUL_LOHI;
2434     bool hasBMI2 = Subtarget->hasBMI2();
2435     if (!isSigned) {
2436       switch (NVT.SimpleTy) {
2437       default: llvm_unreachable("Unsupported VT!");
2438       case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
2439       case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2440       case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2441                      MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2442       case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2443                      MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2444       }
2445     } else {
2446       switch (NVT.SimpleTy) {
2447       default: llvm_unreachable("Unsupported VT!");
2448       case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
2449       case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2450       case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2451       case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2452       }
2453     }
2454
2455     unsigned SrcReg, LoReg, HiReg;
2456     switch (Opc) {
2457     default: llvm_unreachable("Unknown MUL opcode!");
2458     case X86::IMUL8r:
2459     case X86::MUL8r:
2460       SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2461       break;
2462     case X86::IMUL16r:
2463     case X86::MUL16r:
2464       SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2465       break;
2466     case X86::IMUL32r:
2467     case X86::MUL32r:
2468       SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2469       break;
2470     case X86::IMUL64r:
2471     case X86::MUL64r:
2472       SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2473       break;
2474     case X86::MULX32rr:
2475       SrcReg = X86::EDX; LoReg = HiReg = 0;
2476       break;
2477     case X86::MULX64rr:
2478       SrcReg = X86::RDX; LoReg = HiReg = 0;
2479       break;
2480     }
2481
2482     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2483     bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2484     // Multiply is commmutative.
2485     if (!foldedLoad) {
2486       foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2487       if (foldedLoad)
2488         std::swap(N0, N1);
2489     }
2490
2491     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2492                                           N0, SDValue()).getValue(1);
2493     SDValue ResHi, ResLo;
2494
2495     if (foldedLoad) {
2496       SDValue Chain;
2497       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2498                         InFlag };
2499       if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2500         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2501         SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2502         ResHi = SDValue(CNode, 0);
2503         ResLo = SDValue(CNode, 1);
2504         Chain = SDValue(CNode, 2);
2505         InFlag = SDValue(CNode, 3);
2506       } else {
2507         SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2508         SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2509         Chain = SDValue(CNode, 0);
2510         InFlag = SDValue(CNode, 1);
2511       }
2512
2513       // Update the chain.
2514       ReplaceUses(N1.getValue(1), Chain);
2515     } else {
2516       SDValue Ops[] = { N1, InFlag };
2517       if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2518         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2519         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2520         ResHi = SDValue(CNode, 0);
2521         ResLo = SDValue(CNode, 1);
2522         InFlag = SDValue(CNode, 2);
2523       } else {
2524         SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2525         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2526         InFlag = SDValue(CNode, 0);
2527       }
2528     }
2529
2530     // Prevent use of AH in a REX instruction by referencing AX instead.
2531     if (HiReg == X86::AH && Subtarget->is64Bit() &&
2532         !SDValue(Node, 1).use_empty()) {
2533       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2534                                               X86::AX, MVT::i16, InFlag);
2535       InFlag = Result.getValue(2);
2536       // Get the low part if needed. Don't use getCopyFromReg for aliasing
2537       // registers.
2538       if (!SDValue(Node, 0).use_empty())
2539         ReplaceUses(SDValue(Node, 1),
2540           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2541
2542       // Shift AX down 8 bits.
2543       Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2544                                               Result,
2545                                      CurDAG->getTargetConstant(8, dl, MVT::i8)),
2546                        0);
2547       // Then truncate it down to i8.
2548       ReplaceUses(SDValue(Node, 1),
2549         CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2550     }
2551     // Copy the low half of the result, if it is needed.
2552     if (!SDValue(Node, 0).use_empty()) {
2553       if (!ResLo.getNode()) {
2554         assert(LoReg && "Register for low half is not defined!");
2555         ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2556                                        InFlag);
2557         InFlag = ResLo.getValue(2);
2558       }
2559       ReplaceUses(SDValue(Node, 0), ResLo);
2560       DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2561     }
2562     // Copy the high half of the result, if it is needed.
2563     if (!SDValue(Node, 1).use_empty()) {
2564       if (!ResHi.getNode()) {
2565         assert(HiReg && "Register for high half is not defined!");
2566         ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2567                                        InFlag);
2568         InFlag = ResHi.getValue(2);
2569       }
2570       ReplaceUses(SDValue(Node, 1), ResHi);
2571       DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2572     }
2573
2574     return nullptr;
2575   }
2576
2577   case ISD::SDIVREM:
2578   case ISD::UDIVREM:
2579   case X86ISD::SDIVREM8_SEXT_HREG:
2580   case X86ISD::UDIVREM8_ZEXT_HREG: {
2581     SDValue N0 = Node->getOperand(0);
2582     SDValue N1 = Node->getOperand(1);
2583
2584     bool isSigned = (Opcode == ISD::SDIVREM ||
2585                      Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2586     if (!isSigned) {
2587       switch (NVT.SimpleTy) {
2588       default: llvm_unreachable("Unsupported VT!");
2589       case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
2590       case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2591       case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2592       case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2593       }
2594     } else {
2595       switch (NVT.SimpleTy) {
2596       default: llvm_unreachable("Unsupported VT!");
2597       case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
2598       case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2599       case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2600       case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2601       }
2602     }
2603
2604     unsigned LoReg, HiReg, ClrReg;
2605     unsigned SExtOpcode;
2606     switch (NVT.SimpleTy) {
2607     default: llvm_unreachable("Unsupported VT!");
2608     case MVT::i8:
2609       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
2610       SExtOpcode = X86::CBW;
2611       break;
2612     case MVT::i16:
2613       LoReg = X86::AX;  HiReg = X86::DX;
2614       ClrReg = X86::DX;
2615       SExtOpcode = X86::CWD;
2616       break;
2617     case MVT::i32:
2618       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2619       SExtOpcode = X86::CDQ;
2620       break;
2621     case MVT::i64:
2622       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2623       SExtOpcode = X86::CQO;
2624       break;
2625     }
2626
2627     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2628     bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2629     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2630
2631     SDValue InFlag;
2632     if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2633       // Special case for div8, just use a move with zero extension to AX to
2634       // clear the upper 8 bits (AH).
2635       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2636       if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2637         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2638         Move =
2639           SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2640                                          MVT::Other, Ops), 0);
2641         Chain = Move.getValue(1);
2642         ReplaceUses(N0.getValue(1), Chain);
2643       } else {
2644         Move =
2645           SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2646         Chain = CurDAG->getEntryNode();
2647       }
2648       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2649       InFlag = Chain.getValue(1);
2650     } else {
2651       InFlag =
2652         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2653                              LoReg, N0, SDValue()).getValue(1);
2654       if (isSigned && !signBitIsZero) {
2655         // Sign extend the low part into the high part.
2656         InFlag =
2657           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2658       } else {
2659         // Zero out the high part, effectively zero extending the input.
2660         SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2661         switch (NVT.SimpleTy) {
2662         case MVT::i16:
2663           ClrNode =
2664               SDValue(CurDAG->getMachineNode(
2665                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2666                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
2667                                                     MVT::i32)),
2668                       0);
2669           break;
2670         case MVT::i32:
2671           break;
2672         case MVT::i64:
2673           ClrNode =
2674               SDValue(CurDAG->getMachineNode(
2675                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2676                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2677                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
2678                                                     MVT::i32)),
2679                       0);
2680           break;
2681         default:
2682           llvm_unreachable("Unexpected division source");
2683         }
2684
2685         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2686                                       ClrNode, InFlag).getValue(1);
2687       }
2688     }
2689
2690     if (foldedLoad) {
2691       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2692                         InFlag };
2693       SDNode *CNode =
2694         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2695       InFlag = SDValue(CNode, 1);
2696       // Update the chain.
2697       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2698     } else {
2699       InFlag =
2700         SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2701     }
2702
2703     // Prevent use of AH in a REX instruction by explicitly copying it to
2704     // an ABCD_L register.
2705     //
2706     // The current assumption of the register allocator is that isel
2707     // won't generate explicit references to the GR8_ABCD_H registers. If
2708     // the allocator and/or the backend get enhanced to be more robust in
2709     // that regard, this can be, and should be, removed.
2710     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2711       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2712       unsigned AHExtOpcode =
2713           isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2714
2715       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2716                                              MVT::Glue, AHCopy, InFlag);
2717       SDValue Result(RNode, 0);
2718       InFlag = SDValue(RNode, 1);
2719
2720       if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2721           Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2722         if (Node->getValueType(1) == MVT::i64) {
2723           // It's not possible to directly movsx AH to a 64bit register, because
2724           // the latter needs the REX prefix, but the former can't have it.
2725           assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2726                  "Unexpected i64 sext of h-register");
2727           Result =
2728               SDValue(CurDAG->getMachineNode(
2729                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2730                           CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2731                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
2732                                                     MVT::i32)),
2733                       0);
2734         }
2735       } else {
2736         Result =
2737             CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2738       }
2739       ReplaceUses(SDValue(Node, 1), Result);
2740       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2741     }
2742     // Copy the division (low) result, if it is needed.
2743     if (!SDValue(Node, 0).use_empty()) {
2744       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2745                                                 LoReg, NVT, InFlag);
2746       InFlag = Result.getValue(2);
2747       ReplaceUses(SDValue(Node, 0), Result);
2748       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2749     }
2750     // Copy the remainder (high) result, if it is needed.
2751     if (!SDValue(Node, 1).use_empty()) {
2752       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2753                                               HiReg, NVT, InFlag);
2754       InFlag = Result.getValue(2);
2755       ReplaceUses(SDValue(Node, 1), Result);
2756       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2757     }
2758     return nullptr;
2759   }
2760
2761   case X86ISD::CMP:
2762   case X86ISD::SUB: {
2763     // Sometimes a SUB is used to perform comparison.
2764     if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2765       // This node is not a CMP.
2766       break;
2767     SDValue N0 = Node->getOperand(0);
2768     SDValue N1 = Node->getOperand(1);
2769
2770     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2771         HasNoSignedComparisonUses(Node))
2772       N0 = N0.getOperand(0);
2773
2774     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2775     // use a smaller encoding.
2776     // Look past the truncate if CMP is the only use of it.
2777     if ((N0.getNode()->getOpcode() == ISD::AND ||
2778          (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2779         N0.getNode()->hasOneUse() &&
2780         N0.getValueType() != MVT::i8 &&
2781         X86::isZeroNode(N1)) {
2782       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2783       if (!C) break;
2784
2785       // For example, convert "testl %eax, $8" to "testb %al, $8"
2786       if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2787           (!(C->getZExtValue() & 0x80) ||
2788            HasNoSignedComparisonUses(Node))) {
2789         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2790         SDValue Reg = N0.getNode()->getOperand(0);
2791
2792         // On x86-32, only the ABCD registers have 8-bit subregisters.
2793         if (!Subtarget->is64Bit()) {
2794           const TargetRegisterClass *TRC;
2795           switch (N0.getSimpleValueType().SimpleTy) {
2796           case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2797           case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2798           default: llvm_unreachable("Unsupported TEST operand type!");
2799           }
2800           SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2801           Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2802                                                Reg.getValueType(), Reg, RC), 0);
2803         }
2804
2805         // Extract the l-register.
2806         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2807                                                         MVT::i8, Reg);
2808
2809         // Emit a testb.
2810         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2811                                                  Subreg, Imm);
2812         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2813         // one, do not call ReplaceAllUsesWith.
2814         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2815                     SDValue(NewNode, 0));
2816         return nullptr;
2817       }
2818
2819       // For example, "testl %eax, $2048" to "testb %ah, $8".
2820       if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2821           (!(C->getZExtValue() & 0x8000) ||
2822            HasNoSignedComparisonUses(Node))) {
2823         // Shift the immediate right by 8 bits.
2824         SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2825                                                        dl, MVT::i8);
2826         SDValue Reg = N0.getNode()->getOperand(0);
2827
2828         // Put the value in an ABCD register.
2829         const TargetRegisterClass *TRC;
2830         switch (N0.getSimpleValueType().SimpleTy) {
2831         case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2832         case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2833         case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2834         default: llvm_unreachable("Unsupported TEST operand type!");
2835         }
2836         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2837         Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2838                                              Reg.getValueType(), Reg, RC), 0);
2839
2840         // Extract the h-register.
2841         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2842                                                         MVT::i8, Reg);
2843
2844         // Emit a testb.  The EXTRACT_SUBREG becomes a COPY that can only
2845         // target GR8_NOREX registers, so make sure the register class is
2846         // forced.
2847         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2848                                                  MVT::i32, Subreg, ShiftedImm);
2849         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2850         // one, do not call ReplaceAllUsesWith.
2851         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2852                     SDValue(NewNode, 0));
2853         return nullptr;
2854       }
2855
2856       // For example, "testl %eax, $32776" to "testw %ax, $32776".
2857       if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2858           N0.getValueType() != MVT::i16 &&
2859           (!(C->getZExtValue() & 0x8000) ||
2860            HasNoSignedComparisonUses(Node))) {
2861         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2862                                                 MVT::i16);
2863         SDValue Reg = N0.getNode()->getOperand(0);
2864
2865         // Extract the 16-bit subregister.
2866         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2867                                                         MVT::i16, Reg);
2868
2869         // Emit a testw.
2870         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2871                                                  Subreg, Imm);
2872         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2873         // one, do not call ReplaceAllUsesWith.
2874         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2875                     SDValue(NewNode, 0));
2876         return nullptr;
2877       }
2878
2879       // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2880       if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2881           N0.getValueType() == MVT::i64 &&
2882           (!(C->getZExtValue() & 0x80000000) ||
2883            HasNoSignedComparisonUses(Node))) {
2884         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2885                                                 MVT::i32);
2886         SDValue Reg = N0.getNode()->getOperand(0);
2887
2888         // Extract the 32-bit subregister.
2889         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2890                                                         MVT::i32, Reg);
2891
2892         // Emit a testl.
2893         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2894                                                  Subreg, Imm);
2895         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2896         // one, do not call ReplaceAllUsesWith.
2897         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2898                     SDValue(NewNode, 0));
2899         return nullptr;
2900       }
2901     }
2902     break;
2903   }
2904   case ISD::STORE: {
2905     // Change a chain of {load; incr or dec; store} of the same value into
2906     // a simple increment or decrement through memory of that value, if the
2907     // uses of the modified value and its address are suitable.
2908     // The DEC64m tablegen pattern is currently not able to match the case where
2909     // the EFLAGS on the original DEC are used. (This also applies to
2910     // {INC,DEC}X{64,32,16,8}.)
2911     // We'll need to improve tablegen to allow flags to be transferred from a
2912     // node in the pattern to the result node.  probably with a new keyword
2913     // for example, we have this
2914     // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2915     //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2916     //   (implicit EFLAGS)]>;
2917     // but maybe need something like this
2918     // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2919     //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2920     //   (transferrable EFLAGS)]>;
2921
2922     StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2923     SDValue StoredVal = StoreNode->getOperand(1);
2924     unsigned Opc = StoredVal->getOpcode();
2925
2926     LoadSDNode *LoadNode = nullptr;
2927     SDValue InputChain;
2928     if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2929                              LoadNode, InputChain))
2930       break;
2931
2932     SDValue Base, Scale, Index, Disp, Segment;
2933     if (!SelectAddr(LoadNode, LoadNode->getBasePtr(),
2934                     Base, Scale, Index, Disp, Segment))
2935       break;
2936
2937     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2938     MemOp[0] = StoreNode->getMemOperand();
2939     MemOp[1] = LoadNode->getMemOperand();
2940     const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2941     EVT LdVT = LoadNode->getMemoryVT();
2942     unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2943     MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2944                                                    SDLoc(Node),
2945                                                    MVT::i32, MVT::Other, Ops);
2946     Result->setMemRefs(MemOp, MemOp + 2);
2947
2948     ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2949     ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2950
2951     return Result;
2952   }
2953   }
2954
2955   SDNode *ResNode = SelectCode(Node);
2956
2957   DEBUG(dbgs() << "=> ";
2958         if (ResNode == nullptr || ResNode == Node)
2959           Node->dump(CurDAG);
2960         else
2961           ResNode->dump(CurDAG);
2962         dbgs() << '\n');
2963
2964   return ResNode;
2965 }
2966
2967 bool X86DAGToDAGISel::
2968 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2969                              std::vector<SDValue> &OutOps) {
2970   SDValue Op0, Op1, Op2, Op3, Op4;
2971   switch (ConstraintID) {
2972   default:
2973     llvm_unreachable("Unexpected asm memory constraint");
2974   case InlineAsm::Constraint_i:
2975     // FIXME: It seems strange that 'i' is needed here since it's supposed to
2976     //        be an immediate and not a memory constraint.
2977     // Fallthrough.
2978   case InlineAsm::Constraint_o: // offsetable        ??
2979   case InlineAsm::Constraint_v: // not offsetable    ??
2980   case InlineAsm::Constraint_m: // memory
2981   case InlineAsm::Constraint_X:
2982     if (!SelectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2983       return true;
2984     break;
2985   }
2986
2987   OutOps.push_back(Op0);
2988   OutOps.push_back(Op1);
2989   OutOps.push_back(Op2);
2990   OutOps.push_back(Op3);
2991   OutOps.push_back(Op4);
2992   return false;
2993 }
2994
2995 /// createX86ISelDag - This pass converts a legalized DAG into a
2996 /// X86-specific DAG, ready for instruction scheduling.
2997 ///
2998 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2999                                      CodeGenOpt::Level OptLevel) {
3000   return new X86DAGToDAGISel(TM, OptLevel);
3001 }