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