]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
Update llvm to release_39 branch r278877.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / SelectionDAG / TargetLowering.cpp
1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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 implements the TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include <cctype>
36 using namespace llvm;
37
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40   : TargetLoweringBase(tm) {}
41
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
43   return nullptr;
44 }
45
46 bool TargetLowering::isPositionIndependent() const {
47   return getTargetMachine().isPositionIndependent();
48 }
49
50 /// Check whether a given call node is in tail position within its function. If
51 /// so, it sets Chain to the input chain of the tail call.
52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
53                                           SDValue &Chain) const {
54   const Function *F = DAG.getMachineFunction().getFunction();
55
56   // Conservatively require the attributes of the call to match those of
57   // the return. Ignore noalias because it doesn't affect the call sequence.
58   AttributeSet CallerAttrs = F->getAttributes();
59   if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
60       .removeAttribute(Attribute::NoAlias).hasAttributes())
61     return false;
62
63   // It's not safe to eliminate the sign / zero extension of the return value.
64   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
65       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
66     return false;
67
68   // Check if the only use is a function return node.
69   return isUsedByReturnOnly(Node, Chain);
70 }
71
72 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
73     const uint32_t *CallerPreservedMask,
74     const SmallVectorImpl<CCValAssign> &ArgLocs,
75     const SmallVectorImpl<SDValue> &OutVals) const {
76   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
77     const CCValAssign &ArgLoc = ArgLocs[I];
78     if (!ArgLoc.isRegLoc())
79       continue;
80     unsigned Reg = ArgLoc.getLocReg();
81     // Only look at callee saved registers.
82     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
83       continue;
84     // Check that we pass the value used for the caller.
85     // (We look for a CopyFromReg reading a virtual register that is used
86     //  for the function live-in value of register Reg)
87     SDValue Value = OutVals[I];
88     if (Value->getOpcode() != ISD::CopyFromReg)
89       return false;
90     unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
91     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
92       return false;
93   }
94   return true;
95 }
96
97 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
98 /// and called function attributes.
99 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
100                                                  unsigned AttrIdx) {
101   isSExt     = CS->paramHasAttr(AttrIdx, Attribute::SExt);
102   isZExt     = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
103   isInReg    = CS->paramHasAttr(AttrIdx, Attribute::InReg);
104   isSRet     = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
105   isNest     = CS->paramHasAttr(AttrIdx, Attribute::Nest);
106   isByVal    = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
107   isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
108   isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
109   isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
110   isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
111   Alignment  = CS->getParamAlignment(AttrIdx);
112 }
113
114 /// Generate a libcall taking the given operands as arguments and returning a
115 /// result of type RetVT.
116 std::pair<SDValue, SDValue>
117 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
118                             ArrayRef<SDValue> Ops, bool isSigned,
119                             const SDLoc &dl, bool doesNotReturn,
120                             bool isReturnValueUsed) const {
121   TargetLowering::ArgListTy Args;
122   Args.reserve(Ops.size());
123
124   TargetLowering::ArgListEntry Entry;
125   for (SDValue Op : Ops) {
126     Entry.Node = Op;
127     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
128     Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
129     Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
130     Args.push_back(Entry);
131   }
132
133   if (LC == RTLIB::UNKNOWN_LIBCALL)
134     report_fatal_error("Unsupported library call operation!");
135   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
136                                          getPointerTy(DAG.getDataLayout()));
137
138   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
139   TargetLowering::CallLoweringInfo CLI(DAG);
140   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
141   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
142     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
143     .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
144     .setSExtResult(signExtend).setZExtResult(!signExtend);
145   return LowerCallTo(CLI);
146 }
147
148 /// Soften the operands of a comparison. This code is shared among BR_CC,
149 /// SELECT_CC, and SETCC handlers.
150 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
151                                          SDValue &NewLHS, SDValue &NewRHS,
152                                          ISD::CondCode &CCCode,
153                                          const SDLoc &dl) const {
154   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
155          && "Unsupported setcc type!");
156
157   // Expand into one or more soft-fp libcall(s).
158   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
159   bool ShouldInvertCC = false;
160   switch (CCCode) {
161   case ISD::SETEQ:
162   case ISD::SETOEQ:
163     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
164           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
165           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
166     break;
167   case ISD::SETNE:
168   case ISD::SETUNE:
169     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
170           (VT == MVT::f64) ? RTLIB::UNE_F64 :
171           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
172     break;
173   case ISD::SETGE:
174   case ISD::SETOGE:
175     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
176           (VT == MVT::f64) ? RTLIB::OGE_F64 :
177           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
178     break;
179   case ISD::SETLT:
180   case ISD::SETOLT:
181     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
182           (VT == MVT::f64) ? RTLIB::OLT_F64 :
183           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
184     break;
185   case ISD::SETLE:
186   case ISD::SETOLE:
187     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
188           (VT == MVT::f64) ? RTLIB::OLE_F64 :
189           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
190     break;
191   case ISD::SETGT:
192   case ISD::SETOGT:
193     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
194           (VT == MVT::f64) ? RTLIB::OGT_F64 :
195           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
196     break;
197   case ISD::SETUO:
198     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
199           (VT == MVT::f64) ? RTLIB::UO_F64 :
200           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
201     break;
202   case ISD::SETO:
203     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
204           (VT == MVT::f64) ? RTLIB::O_F64 :
205           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
206     break;
207   case ISD::SETONE:
208     // SETONE = SETOLT | SETOGT
209     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
210           (VT == MVT::f64) ? RTLIB::OLT_F64 :
211           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
212     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
213           (VT == MVT::f64) ? RTLIB::OGT_F64 :
214           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
215     break;
216   case ISD::SETUEQ:
217     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
218           (VT == MVT::f64) ? RTLIB::UO_F64 :
219           (VT == MVT::f128) ? RTLIB::UO_F64 : RTLIB::UO_PPCF128;
220     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
221           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
222           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
223     break;
224   default:
225     // Invert CC for unordered comparisons
226     ShouldInvertCC = true;
227     switch (CCCode) {
228     case ISD::SETULT:
229       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
230             (VT == MVT::f64) ? RTLIB::OGE_F64 :
231             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
232       break;
233     case ISD::SETULE:
234       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
235             (VT == MVT::f64) ? RTLIB::OGT_F64 :
236             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
237       break;
238     case ISD::SETUGT:
239       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
240             (VT == MVT::f64) ? RTLIB::OLE_F64 :
241             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
242       break;
243     case ISD::SETUGE:
244       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
245             (VT == MVT::f64) ? RTLIB::OLT_F64 :
246             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
247       break;
248     default: llvm_unreachable("Do not know how to soften this setcc!");
249     }
250   }
251
252   // Use the target specific return value for comparions lib calls.
253   EVT RetVT = getCmpLibcallReturnType();
254   SDValue Ops[2] = {NewLHS, NewRHS};
255   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
256                        dl).first;
257   NewRHS = DAG.getConstant(0, dl, RetVT);
258
259   CCCode = getCmpLibcallCC(LC1);
260   if (ShouldInvertCC)
261     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
262
263   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
264     SDValue Tmp = DAG.getNode(
265         ISD::SETCC, dl,
266         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
267         NewLHS, NewRHS, DAG.getCondCode(CCCode));
268     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
269                          dl).first;
270     NewLHS = DAG.getNode(
271         ISD::SETCC, dl,
272         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
273         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
274     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
275     NewRHS = SDValue();
276   }
277 }
278
279 /// Return the entry encoding for a jump table in the current function. The
280 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
281 unsigned TargetLowering::getJumpTableEncoding() const {
282   // In non-pic modes, just use the address of a block.
283   if (!isPositionIndependent())
284     return MachineJumpTableInfo::EK_BlockAddress;
285
286   // In PIC mode, if the target supports a GPRel32 directive, use it.
287   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
288     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
289
290   // Otherwise, use a label difference.
291   return MachineJumpTableInfo::EK_LabelDifference32;
292 }
293
294 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
295                                                  SelectionDAG &DAG) const {
296   // If our PIC model is GP relative, use the global offset table as the base.
297   unsigned JTEncoding = getJumpTableEncoding();
298
299   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
300       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
301     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
302
303   return Table;
304 }
305
306 /// This returns the relocation base for the given PIC jumptable, the same as
307 /// getPICJumpTableRelocBase, but as an MCExpr.
308 const MCExpr *
309 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
310                                              unsigned JTI,MCContext &Ctx) const{
311   // The normal PIC reloc base is the label at the start of the jump table.
312   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
313 }
314
315 bool
316 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
317   const TargetMachine &TM = getTargetMachine();
318   const GlobalValue *GV = GA->getGlobal();
319
320   // If the address is not even local to this DSO we will have to load it from
321   // a got and then add the offset.
322   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
323     return false;
324
325   // If the code is position independent we will have to add a base register.
326   if (isPositionIndependent())
327     return false;
328
329   // Otherwise we can do it.
330   return true;
331 }
332
333 //===----------------------------------------------------------------------===//
334 //  Optimization Methods
335 //===----------------------------------------------------------------------===//
336
337 /// Check to see if the specified operand of the specified instruction is a
338 /// constant integer. If so, check to see if there are any bits set in the
339 /// constant that are not demanded. If so, shrink the constant and return true.
340 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
341                                                         const APInt &Demanded) {
342   SDLoc dl(Op);
343
344   // FIXME: ISD::SELECT, ISD::SELECT_CC
345   switch (Op.getOpcode()) {
346   default: break;
347   case ISD::XOR:
348   case ISD::AND:
349   case ISD::OR: {
350     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
351     if (!C) return false;
352
353     if (Op.getOpcode() == ISD::XOR &&
354         (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
355       return false;
356
357     // if we can expand it to have all bits set, do it
358     if (C->getAPIntValue().intersects(~Demanded)) {
359       EVT VT = Op.getValueType();
360       SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
361                                 DAG.getConstant(Demanded &
362                                                 C->getAPIntValue(),
363                                                 dl, VT));
364       return CombineTo(Op, New);
365     }
366
367     break;
368   }
369   }
370
371   return false;
372 }
373
374 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
375 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
376 /// generalized for targets with other types of implicit widening casts.
377 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
378                                                          unsigned BitWidth,
379                                                          const APInt &Demanded,
380                                                          const SDLoc &dl) {
381   assert(Op.getNumOperands() == 2 &&
382          "ShrinkDemandedOp only supports binary operators!");
383   assert(Op.getNode()->getNumValues() == 1 &&
384          "ShrinkDemandedOp only supports nodes with one result!");
385
386   // Early return, as this function cannot handle vector types.
387   if (Op.getValueType().isVector())
388     return false;
389
390   // Don't do this if the node has another user, which may require the
391   // full value.
392   if (!Op.getNode()->hasOneUse())
393     return false;
394
395   // Search for the smallest integer type with free casts to and from
396   // Op's type. For expedience, just check power-of-2 integer types.
397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
398   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
399   unsigned SmallVTBits = DemandedSize;
400   if (!isPowerOf2_32(SmallVTBits))
401     SmallVTBits = NextPowerOf2(SmallVTBits);
402   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
403     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
404     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
405         TLI.isZExtFree(SmallVT, Op.getValueType())) {
406       // We found a type with free casts.
407       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
408                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
409                                           Op.getNode()->getOperand(0)),
410                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
411                                           Op.getNode()->getOperand(1)));
412       bool NeedZext = DemandedSize > SmallVTBits;
413       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
414                               dl, Op.getValueType(), X);
415       return CombineTo(Op, Z);
416     }
417   }
418   return false;
419 }
420
421 /// Look at Op. At this point, we know that only the DemandedMask bits of the
422 /// result of Op are ever used downstream. If we can use this information to
423 /// simplify Op, create a new simplified DAG node and return true, returning the
424 /// original and new nodes in Old and New. Otherwise, analyze the expression and
425 /// return a mask of KnownOne and KnownZero bits for the expression (used to
426 /// simplify the caller).  The KnownZero/One bits may only be accurate for those
427 /// bits in the DemandedMask.
428 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
429                                           const APInt &DemandedMask,
430                                           APInt &KnownZero,
431                                           APInt &KnownOne,
432                                           TargetLoweringOpt &TLO,
433                                           unsigned Depth) const {
434   unsigned BitWidth = DemandedMask.getBitWidth();
435   assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
436          "Mask size mismatches value type size!");
437   APInt NewMask = DemandedMask;
438   SDLoc dl(Op);
439   auto &DL = TLO.DAG.getDataLayout();
440
441   // Don't know anything.
442   KnownZero = KnownOne = APInt(BitWidth, 0);
443
444   // Other users may use these bits.
445   if (!Op.getNode()->hasOneUse()) {
446     if (Depth != 0) {
447       // If not at the root, Just compute the KnownZero/KnownOne bits to
448       // simplify things downstream.
449       TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
450       return false;
451     }
452     // If this is the root being simplified, allow it to have multiple uses,
453     // just set the NewMask to all bits.
454     NewMask = APInt::getAllOnesValue(BitWidth);
455   } else if (DemandedMask == 0) {
456     // Not demanding any bits from Op.
457     if (!Op.isUndef())
458       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
459     return false;
460   } else if (Depth == 6) {        // Limit search depth.
461     return false;
462   }
463
464   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
465   switch (Op.getOpcode()) {
466   case ISD::Constant:
467     // We know all of the bits for a constant!
468     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
469     KnownZero = ~KnownOne;
470     return false;   // Don't fall through, will infinitely loop.
471   case ISD::AND:
472     // If the RHS is a constant, check to see if the LHS would be zero without
473     // using the bits from the RHS.  Below, we use knowledge about the RHS to
474     // simplify the LHS, here we're using information from the LHS to simplify
475     // the RHS.
476     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
477       APInt LHSZero, LHSOne;
478       // Do not increment Depth here; that can cause an infinite loop.
479       TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
480       // If the LHS already has zeros where RHSC does, this and is dead.
481       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
482         return TLO.CombineTo(Op, Op.getOperand(0));
483       // If any of the set bits in the RHS are known zero on the LHS, shrink
484       // the constant.
485       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
486         return true;
487     }
488
489     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
490                              KnownOne, TLO, Depth+1))
491       return true;
492     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
493     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
494                              KnownZero2, KnownOne2, TLO, Depth+1))
495       return true;
496     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
497
498     // If all of the demanded bits are known one on one side, return the other.
499     // These bits cannot contribute to the result of the 'and'.
500     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
501       return TLO.CombineTo(Op, Op.getOperand(0));
502     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
503       return TLO.CombineTo(Op, Op.getOperand(1));
504     // If all of the demanded bits in the inputs are known zeros, return zero.
505     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
506       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
507     // If the RHS is a constant, see if we can simplify it.
508     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
509       return true;
510     // If the operation can be done in a smaller type, do so.
511     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
512       return true;
513
514     // Output known-1 bits are only known if set in both the LHS & RHS.
515     KnownOne &= KnownOne2;
516     // Output known-0 are known to be clear if zero in either the LHS | RHS.
517     KnownZero |= KnownZero2;
518     break;
519   case ISD::OR:
520     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
521                              KnownOne, TLO, Depth+1))
522       return true;
523     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
524     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
525                              KnownZero2, KnownOne2, TLO, Depth+1))
526       return true;
527     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
528
529     // If all of the demanded bits are known zero on one side, return the other.
530     // These bits cannot contribute to the result of the 'or'.
531     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
532       return TLO.CombineTo(Op, Op.getOperand(0));
533     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
534       return TLO.CombineTo(Op, Op.getOperand(1));
535     // If all of the potentially set bits on one side are known to be set on
536     // the other side, just use the 'other' side.
537     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
538       return TLO.CombineTo(Op, Op.getOperand(0));
539     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
540       return TLO.CombineTo(Op, Op.getOperand(1));
541     // If the RHS is a constant, see if we can simplify it.
542     if (TLO.ShrinkDemandedConstant(Op, NewMask))
543       return true;
544     // If the operation can be done in a smaller type, do so.
545     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
546       return true;
547
548     // Output known-0 bits are only known if clear in both the LHS & RHS.
549     KnownZero &= KnownZero2;
550     // Output known-1 are known to be set if set in either the LHS | RHS.
551     KnownOne |= KnownOne2;
552     break;
553   case ISD::XOR:
554     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
555                              KnownOne, TLO, Depth+1))
556       return true;
557     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
558     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
559                              KnownOne2, TLO, Depth+1))
560       return true;
561     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
562
563     // If all of the demanded bits are known zero on one side, return the other.
564     // These bits cannot contribute to the result of the 'xor'.
565     if ((KnownZero & NewMask) == NewMask)
566       return TLO.CombineTo(Op, Op.getOperand(0));
567     if ((KnownZero2 & NewMask) == NewMask)
568       return TLO.CombineTo(Op, Op.getOperand(1));
569     // If the operation can be done in a smaller type, do so.
570     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
571       return true;
572
573     // If all of the unknown bits are known to be zero on one side or the other
574     // (but not both) turn this into an *inclusive* or.
575     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
576     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
577       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
578                                                Op.getOperand(0),
579                                                Op.getOperand(1)));
580
581     // Output known-0 bits are known if clear or set in both the LHS & RHS.
582     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
583     // Output known-1 are known to be set if set in only one of the LHS, RHS.
584     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
585
586     // If all of the demanded bits on one side are known, and all of the set
587     // bits on that side are also known to be set on the other side, turn this
588     // into an AND, as we know the bits will be cleared.
589     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
590     // NB: it is okay if more bits are known than are requested
591     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
592       if (KnownOne == KnownOne2) { // set bits are the same on both sides
593         EVT VT = Op.getValueType();
594         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
595         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
596                                                  Op.getOperand(0), ANDC));
597       }
598     }
599
600     // If the RHS is a constant, see if we can simplify it.
601     // for XOR, we prefer to force bits to 1 if they will make a -1.
602     // if we can't force bits, try to shrink constant
603     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
604       APInt Expanded = C->getAPIntValue() | (~NewMask);
605       // if we can expand it to have all bits set, do it
606       if (Expanded.isAllOnesValue()) {
607         if (Expanded != C->getAPIntValue()) {
608           EVT VT = Op.getValueType();
609           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
610                                         TLO.DAG.getConstant(Expanded, dl, VT));
611           return TLO.CombineTo(Op, New);
612         }
613         // if it already has all the bits set, nothing to change
614         // but don't shrink either!
615       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
616         return true;
617       }
618     }
619
620     KnownZero = KnownZeroOut;
621     KnownOne  = KnownOneOut;
622     break;
623   case ISD::SELECT:
624     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
625                              KnownOne, TLO, Depth+1))
626       return true;
627     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
628                              KnownOne2, TLO, Depth+1))
629       return true;
630     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
631     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
632
633     // If the operands are constants, see if we can simplify them.
634     if (TLO.ShrinkDemandedConstant(Op, NewMask))
635       return true;
636
637     // Only known if known in both the LHS and RHS.
638     KnownOne &= KnownOne2;
639     KnownZero &= KnownZero2;
640     break;
641   case ISD::SELECT_CC:
642     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
643                              KnownOne, TLO, Depth+1))
644       return true;
645     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
646                              KnownOne2, TLO, Depth+1))
647       return true;
648     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
650
651     // If the operands are constants, see if we can simplify them.
652     if (TLO.ShrinkDemandedConstant(Op, NewMask))
653       return true;
654
655     // Only known if known in both the LHS and RHS.
656     KnownOne &= KnownOne2;
657     KnownZero &= KnownZero2;
658     break;
659   case ISD::SHL:
660     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
661       unsigned ShAmt = SA->getZExtValue();
662       SDValue InOp = Op.getOperand(0);
663
664       // If the shift count is an invalid immediate, don't do anything.
665       if (ShAmt >= BitWidth)
666         break;
667
668       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
669       // single shift.  We can do this if the bottom bits (which are shifted
670       // out) are never demanded.
671       if (InOp.getOpcode() == ISD::SRL &&
672           isa<ConstantSDNode>(InOp.getOperand(1))) {
673         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
674           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
675           unsigned Opc = ISD::SHL;
676           int Diff = ShAmt-C1;
677           if (Diff < 0) {
678             Diff = -Diff;
679             Opc = ISD::SRL;
680           }
681
682           SDValue NewSA =
683             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
684           EVT VT = Op.getValueType();
685           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
686                                                    InOp.getOperand(0), NewSA));
687         }
688       }
689
690       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
691                                KnownZero, KnownOne, TLO, Depth+1))
692         return true;
693
694       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
695       // are not demanded. This will likely allow the anyext to be folded away.
696       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
697         SDValue InnerOp = InOp.getNode()->getOperand(0);
698         EVT InnerVT = InnerOp.getValueType();
699         unsigned InnerBits = InnerVT.getSizeInBits();
700         if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
701             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
702           EVT ShTy = getShiftAmountTy(InnerVT, DL);
703           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
704             ShTy = InnerVT;
705           SDValue NarrowShl =
706             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
707                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
708           return
709             TLO.CombineTo(Op,
710                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
711                                           NarrowShl));
712         }
713         // Repeat the SHL optimization above in cases where an extension
714         // intervenes: (shl (anyext (shr x, c1)), c2) to
715         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
716         // aren't demanded (as above) and that the shifted upper c1 bits of
717         // x aren't demanded.
718         if (InOp.hasOneUse() &&
719             InnerOp.getOpcode() == ISD::SRL &&
720             InnerOp.hasOneUse() &&
721             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
722           uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
723             ->getZExtValue();
724           if (InnerShAmt < ShAmt &&
725               InnerShAmt < InnerBits &&
726               NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
727               NewMask.trunc(ShAmt) == 0) {
728             SDValue NewSA =
729               TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
730                                   Op.getOperand(1).getValueType());
731             EVT VT = Op.getValueType();
732             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
733                                              InnerOp.getOperand(0));
734             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
735                                                      NewExt, NewSA));
736           }
737         }
738       }
739
740       KnownZero <<= SA->getZExtValue();
741       KnownOne  <<= SA->getZExtValue();
742       // low bits known zero.
743       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
744     }
745     break;
746   case ISD::SRL:
747     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
748       EVT VT = Op.getValueType();
749       unsigned ShAmt = SA->getZExtValue();
750       unsigned VTSize = VT.getSizeInBits();
751       SDValue InOp = Op.getOperand(0);
752
753       // If the shift count is an invalid immediate, don't do anything.
754       if (ShAmt >= BitWidth)
755         break;
756
757       APInt InDemandedMask = (NewMask << ShAmt);
758
759       // If the shift is exact, then it does demand the low bits (and knows that
760       // they are zero).
761       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
762         InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
763
764       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
765       // single shift.  We can do this if the top bits (which are shifted out)
766       // are never demanded.
767       if (InOp.getOpcode() == ISD::SHL &&
768           isa<ConstantSDNode>(InOp.getOperand(1))) {
769         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
770           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
771           unsigned Opc = ISD::SRL;
772           int Diff = ShAmt-C1;
773           if (Diff < 0) {
774             Diff = -Diff;
775             Opc = ISD::SHL;
776           }
777
778           SDValue NewSA =
779             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
780           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
781                                                    InOp.getOperand(0), NewSA));
782         }
783       }
784
785       // Compute the new bits that are at the top now.
786       if (SimplifyDemandedBits(InOp, InDemandedMask,
787                                KnownZero, KnownOne, TLO, Depth+1))
788         return true;
789       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
790       KnownZero = KnownZero.lshr(ShAmt);
791       KnownOne  = KnownOne.lshr(ShAmt);
792
793       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
794       KnownZero |= HighBits;  // High bits known zero.
795     }
796     break;
797   case ISD::SRA:
798     // If this is an arithmetic shift right and only the low-bit is set, we can
799     // always convert this into a logical shr, even if the shift amount is
800     // variable.  The low bit of the shift cannot be an input sign bit unless
801     // the shift amount is >= the size of the datatype, which is undefined.
802     if (NewMask == 1)
803       return TLO.CombineTo(Op,
804                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
805                                            Op.getOperand(0), Op.getOperand(1)));
806
807     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
808       EVT VT = Op.getValueType();
809       unsigned ShAmt = SA->getZExtValue();
810
811       // If the shift count is an invalid immediate, don't do anything.
812       if (ShAmt >= BitWidth)
813         break;
814
815       APInt InDemandedMask = (NewMask << ShAmt);
816
817       // If the shift is exact, then it does demand the low bits (and knows that
818       // they are zero).
819       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
820         InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
821
822       // If any of the demanded bits are produced by the sign extension, we also
823       // demand the input sign bit.
824       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
825       if (HighBits.intersects(NewMask))
826         InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
827
828       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
829                                KnownZero, KnownOne, TLO, Depth+1))
830         return true;
831       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
832       KnownZero = KnownZero.lshr(ShAmt);
833       KnownOne  = KnownOne.lshr(ShAmt);
834
835       // Handle the sign bit, adjusted to where it is now in the mask.
836       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
837
838       // If the input sign bit is known to be zero, or if none of the top bits
839       // are demanded, turn this into an unsigned shift right.
840       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
841         SDNodeFlags Flags;
842         Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
843         return TLO.CombineTo(Op,
844                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
845                                              Op.getOperand(1), &Flags));
846       }
847
848       int Log2 = NewMask.exactLogBase2();
849       if (Log2 >= 0) {
850         // The bit must come from the sign.
851         SDValue NewSA =
852           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
853                               Op.getOperand(1).getValueType());
854         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
855                                                  Op.getOperand(0), NewSA));
856       }
857
858       if (KnownOne.intersects(SignBit))
859         // New bits are known one.
860         KnownOne |= HighBits;
861     }
862     break;
863   case ISD::SIGN_EXTEND_INREG: {
864     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
865
866     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
867     // If we only care about the highest bit, don't bother shifting right.
868     if (MsbMask == NewMask) {
869       unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
870       SDValue InOp = Op.getOperand(0);
871       unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
872       bool AlreadySignExtended =
873         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
874       // However if the input is already sign extended we expect the sign
875       // extension to be dropped altogether later and do not simplify.
876       if (!AlreadySignExtended) {
877         // Compute the correct shift amount type, which must be getShiftAmountTy
878         // for scalar types after legalization.
879         EVT ShiftAmtTy = Op.getValueType();
880         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
881           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
882
883         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
884                                                ShiftAmtTy);
885         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
886                                                  Op.getValueType(), InOp,
887                                                  ShiftAmt));
888       }
889     }
890
891     // Sign extension.  Compute the demanded bits in the result that are not
892     // present in the input.
893     APInt NewBits =
894       APInt::getHighBitsSet(BitWidth,
895                             BitWidth - ExVT.getScalarType().getSizeInBits());
896
897     // If none of the extended bits are demanded, eliminate the sextinreg.
898     if ((NewBits & NewMask) == 0)
899       return TLO.CombineTo(Op, Op.getOperand(0));
900
901     APInt InSignBit =
902       APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
903     APInt InputDemandedBits =
904       APInt::getLowBitsSet(BitWidth,
905                            ExVT.getScalarType().getSizeInBits()) &
906       NewMask;
907
908     // Since the sign extended bits are demanded, we know that the sign
909     // bit is demanded.
910     InputDemandedBits |= InSignBit;
911
912     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
913                              KnownZero, KnownOne, TLO, Depth+1))
914       return true;
915     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
916
917     // If the sign bit of the input is known set or clear, then we know the
918     // top bits of the result.
919
920     // If the input sign bit is known zero, convert this into a zero extension.
921     if (KnownZero.intersects(InSignBit))
922       return TLO.CombineTo(Op,
923                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
924
925     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
926       KnownOne |= NewBits;
927       KnownZero &= ~NewBits;
928     } else {                       // Input sign bit unknown
929       KnownZero &= ~NewBits;
930       KnownOne &= ~NewBits;
931     }
932     break;
933   }
934   case ISD::BUILD_PAIR: {
935     EVT HalfVT = Op.getOperand(0).getValueType();
936     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
937
938     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
939     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
940
941     APInt KnownZeroLo, KnownOneLo;
942     APInt KnownZeroHi, KnownOneHi;
943
944     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
945                              KnownOneLo, TLO, Depth + 1))
946       return true;
947
948     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
949                              KnownOneHi, TLO, Depth + 1))
950       return true;
951
952     KnownZero = KnownZeroLo.zext(BitWidth) |
953                 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
954
955     KnownOne = KnownOneLo.zext(BitWidth) |
956                KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
957     break;
958   }
959   case ISD::ZERO_EXTEND: {
960     unsigned OperandBitWidth =
961       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
962     APInt InMask = NewMask.trunc(OperandBitWidth);
963
964     // If none of the top bits are demanded, convert this into an any_extend.
965     APInt NewBits =
966       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
967     if (!NewBits.intersects(NewMask))
968       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
969                                                Op.getValueType(),
970                                                Op.getOperand(0)));
971
972     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
973                              KnownZero, KnownOne, TLO, Depth+1))
974       return true;
975     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
976     KnownZero = KnownZero.zext(BitWidth);
977     KnownOne = KnownOne.zext(BitWidth);
978     KnownZero |= NewBits;
979     break;
980   }
981   case ISD::SIGN_EXTEND: {
982     EVT InVT = Op.getOperand(0).getValueType();
983     unsigned InBits = InVT.getScalarType().getSizeInBits();
984     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
985     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
986     APInt NewBits   = ~InMask & NewMask;
987
988     // If none of the top bits are demanded, convert this into an any_extend.
989     if (NewBits == 0)
990       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
991                                               Op.getValueType(),
992                                               Op.getOperand(0)));
993
994     // Since some of the sign extended bits are demanded, we know that the sign
995     // bit is demanded.
996     APInt InDemandedBits = InMask & NewMask;
997     InDemandedBits |= InSignBit;
998     InDemandedBits = InDemandedBits.trunc(InBits);
999
1000     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1001                              KnownOne, TLO, Depth+1))
1002       return true;
1003     KnownZero = KnownZero.zext(BitWidth);
1004     KnownOne = KnownOne.zext(BitWidth);
1005
1006     // If the sign bit is known zero, convert this to a zero extend.
1007     if (KnownZero.intersects(InSignBit))
1008       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1009                                                Op.getValueType(),
1010                                                Op.getOperand(0)));
1011
1012     // If the sign bit is known one, the top bits match.
1013     if (KnownOne.intersects(InSignBit)) {
1014       KnownOne |= NewBits;
1015       assert((KnownZero & NewBits) == 0);
1016     } else {   // Otherwise, top bits aren't known.
1017       assert((KnownOne & NewBits) == 0);
1018       assert((KnownZero & NewBits) == 0);
1019     }
1020     break;
1021   }
1022   case ISD::ANY_EXTEND: {
1023     unsigned OperandBitWidth =
1024       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1025     APInt InMask = NewMask.trunc(OperandBitWidth);
1026     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1027                              KnownZero, KnownOne, TLO, Depth+1))
1028       return true;
1029     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1030     KnownZero = KnownZero.zext(BitWidth);
1031     KnownOne = KnownOne.zext(BitWidth);
1032     break;
1033   }
1034   case ISD::TRUNCATE: {
1035     // Simplify the input, using demanded bit information, and compute the known
1036     // zero/one bits live out.
1037     unsigned OperandBitWidth =
1038       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1039     APInt TruncMask = NewMask.zext(OperandBitWidth);
1040     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1041                              KnownZero, KnownOne, TLO, Depth+1))
1042       return true;
1043     KnownZero = KnownZero.trunc(BitWidth);
1044     KnownOne = KnownOne.trunc(BitWidth);
1045
1046     // If the input is only used by this truncate, see if we can shrink it based
1047     // on the known demanded bits.
1048     if (Op.getOperand(0).getNode()->hasOneUse()) {
1049       SDValue In = Op.getOperand(0);
1050       switch (In.getOpcode()) {
1051       default: break;
1052       case ISD::SRL:
1053         // Shrink SRL by a constant if none of the high bits shifted in are
1054         // demanded.
1055         if (TLO.LegalTypes() &&
1056             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1057           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1058           // undesirable.
1059           break;
1060         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1061         if (!ShAmt)
1062           break;
1063         SDValue Shift = In.getOperand(1);
1064         if (TLO.LegalTypes()) {
1065           uint64_t ShVal = ShAmt->getZExtValue();
1066           Shift = TLO.DAG.getConstant(ShVal, dl,
1067                                       getShiftAmountTy(Op.getValueType(), DL));
1068         }
1069
1070         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1071                                                OperandBitWidth - BitWidth);
1072         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1073
1074         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1075           // None of the shifted in bits are needed.  Add a truncate of the
1076           // shift input, then shift it.
1077           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1078                                              Op.getValueType(),
1079                                              In.getOperand(0));
1080           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1081                                                    Op.getValueType(),
1082                                                    NewTrunc,
1083                                                    Shift));
1084         }
1085         break;
1086       }
1087     }
1088
1089     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1090     break;
1091   }
1092   case ISD::AssertZext: {
1093     // AssertZext demands all of the high bits, plus any of the low bits
1094     // demanded by its users.
1095     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1096     APInt InMask = APInt::getLowBitsSet(BitWidth,
1097                                         VT.getSizeInBits());
1098     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1099                              KnownZero, KnownOne, TLO, Depth+1))
1100       return true;
1101     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1102
1103     KnownZero |= ~InMask & NewMask;
1104     break;
1105   }
1106   case ISD::BITCAST:
1107     // If this is an FP->Int bitcast and if the sign bit is the only
1108     // thing demanded, turn this into a FGETSIGN.
1109     if (!TLO.LegalOperations() &&
1110         !Op.getValueType().isVector() &&
1111         !Op.getOperand(0).getValueType().isVector() &&
1112         NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1113         Op.getOperand(0).getValueType().isFloatingPoint()) {
1114       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1115       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1116       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1117            Op.getOperand(0).getValueType() != MVT::f128) {
1118         // Cannot eliminate/lower SHL for f128 yet.
1119         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1120         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1121         // place.  We expect the SHL to be eliminated by other optimizations.
1122         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1123         unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1124         if (!OpVTLegal && OpVTSizeInBits > 32)
1125           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1126         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1127         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1128         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1129                                                  Op.getValueType(),
1130                                                  Sign, ShAmt));
1131       }
1132     }
1133     break;
1134   case ISD::ADD:
1135   case ISD::MUL:
1136   case ISD::SUB: {
1137     // Add, Sub, and Mul don't demand any bits in positions beyond that
1138     // of the highest bit demanded of them.
1139     APInt LoMask = APInt::getLowBitsSet(BitWidth,
1140                                         BitWidth - NewMask.countLeadingZeros());
1141     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1142                              KnownOne2, TLO, Depth+1))
1143       return true;
1144     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1145                              KnownOne2, TLO, Depth+1))
1146       return true;
1147     // See if the operation should be performed at a smaller bit width.
1148     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1149       return true;
1150   }
1151   // FALL THROUGH
1152   default:
1153     // Just use computeKnownBits to compute output bits.
1154     TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1155     break;
1156   }
1157
1158   // If we know the value of all of the demanded bits, return this as a
1159   // constant.
1160   if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1161     // Avoid folding to a constant if any OpaqueConstant is involved.
1162     const SDNode *N = Op.getNode();
1163     for (SDNodeIterator I = SDNodeIterator::begin(N),
1164          E = SDNodeIterator::end(N); I != E; ++I) {
1165       SDNode *Op = *I;
1166       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1167         if (C->isOpaque())
1168           return false;
1169     }
1170     return TLO.CombineTo(Op,
1171                          TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1172   }
1173
1174   return false;
1175 }
1176
1177 /// Determine which of the bits specified in Mask are known to be either zero or
1178 /// one and return them in the KnownZero/KnownOne bitsets.
1179 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1180                                                    APInt &KnownZero,
1181                                                    APInt &KnownOne,
1182                                                    const SelectionDAG &DAG,
1183                                                    unsigned Depth) const {
1184   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1185           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1186           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1187           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1188          "Should use MaskedValueIsZero if you don't know whether Op"
1189          " is a target node!");
1190   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1191 }
1192
1193 /// This method can be implemented by targets that want to expose additional
1194 /// information about sign bits to the DAG Combiner.
1195 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1196                                                          const SelectionDAG &,
1197                                                          unsigned Depth) const {
1198   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1199           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1200           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1201           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1202          "Should use ComputeNumSignBits if you don't know whether Op"
1203          " is a target node!");
1204   return 1;
1205 }
1206
1207 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1208   if (!N)
1209     return false;
1210
1211   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1212   if (!CN) {
1213     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1214     if (!BV)
1215       return false;
1216
1217     BitVector UndefElements;
1218     CN = BV->getConstantSplatNode(&UndefElements);
1219     // Only interested in constant splats, and we don't try to handle undef
1220     // elements in identifying boolean constants.
1221     if (!CN || UndefElements.none())
1222       return false;
1223   }
1224
1225   switch (getBooleanContents(N->getValueType(0))) {
1226   case UndefinedBooleanContent:
1227     return CN->getAPIntValue()[0];
1228   case ZeroOrOneBooleanContent:
1229     return CN->isOne();
1230   case ZeroOrNegativeOneBooleanContent:
1231     return CN->isAllOnesValue();
1232   }
1233
1234   llvm_unreachable("Invalid boolean contents");
1235 }
1236
1237 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1238                                         const SDLoc &DL) const {
1239   unsigned ElementWidth = VT.getScalarSizeInBits();
1240   APInt TrueInt =
1241       getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1242           ? APInt(ElementWidth, 1)
1243           : APInt::getAllOnesValue(ElementWidth);
1244   return DAG.getConstant(TrueInt, DL, VT);
1245 }
1246
1247 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1248   if (!N)
1249     return false;
1250
1251   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1252   if (!CN) {
1253     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1254     if (!BV)
1255       return false;
1256
1257     BitVector UndefElements;
1258     CN = BV->getConstantSplatNode(&UndefElements);
1259     // Only interested in constant splats, and we don't try to handle undef
1260     // elements in identifying boolean constants.
1261     if (!CN || UndefElements.none())
1262       return false;
1263   }
1264
1265   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1266     return !CN->getAPIntValue()[0];
1267
1268   return CN->isNullValue();
1269 }
1270
1271 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1272                                        bool SExt) const {
1273   if (VT == MVT::i1)
1274     return N->isOne();
1275
1276   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1277   switch (Cnt) {
1278   case TargetLowering::ZeroOrOneBooleanContent:
1279     // An extended value of 1 is always true, unless its original type is i1,
1280     // in which case it will be sign extended to -1.
1281     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1282   case TargetLowering::UndefinedBooleanContent:
1283   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1284     return N->isAllOnesValue() && SExt;
1285   }
1286   llvm_unreachable("Unexpected enumeration.");
1287 }
1288
1289 /// This helper function of SimplifySetCC tries to optimize the comparison when
1290 /// either operand of the SetCC node is a bitwise-and instruction.
1291 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1292                                              ISD::CondCode Cond,
1293                                              DAGCombinerInfo &DCI,
1294                                              const SDLoc &DL) const {
1295   // Match these patterns in any of their permutations:
1296   // (X & Y) == Y
1297   // (X & Y) != Y
1298   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1299     std::swap(N0, N1);
1300
1301   EVT OpVT = N0.getValueType();
1302   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1303       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1304     return SDValue();
1305
1306   SDValue X, Y;
1307   if (N0.getOperand(0) == N1) {
1308     X = N0.getOperand(1);
1309     Y = N0.getOperand(0);
1310   } else if (N0.getOperand(1) == N1) {
1311     X = N0.getOperand(0);
1312     Y = N0.getOperand(1);
1313   } else {
1314     return SDValue();
1315   }
1316
1317   SelectionDAG &DAG = DCI.DAG;
1318   SDValue Zero = DAG.getConstant(0, DL, OpVT);
1319   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1320     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1321     // Note that where Y is variable and is known to have at most one bit set
1322     // (for example, if it is Z & 1) we cannot do this; the expressions are not
1323     // equivalent when Y == 0.
1324     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1325     if (DCI.isBeforeLegalizeOps() ||
1326         isCondCodeLegal(Cond, N0.getSimpleValueType()))
1327       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1328   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1329     // If the target supports an 'and-not' or 'and-complement' logic operation,
1330     // try to use that to make a comparison operation more efficient.
1331     // But don't do this transform if the mask is a single bit because there are
1332     // more efficient ways to deal with that case (for example, 'bt' on x86 or
1333     // 'rlwinm' on PPC).
1334
1335     // Bail out if the compare operand that we want to turn into a zero is
1336     // already a zero (otherwise, infinite loop).
1337     auto *YConst = dyn_cast<ConstantSDNode>(Y);
1338     if (YConst && YConst->isNullValue())
1339       return SDValue();
1340
1341     // Transform this into: ~X & Y == 0.
1342     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1343     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1344     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1345   }
1346
1347   return SDValue();
1348 }
1349
1350 /// Try to simplify a setcc built with the specified operands and cc. If it is
1351 /// unable to simplify it, return a null SDValue.
1352 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1353                                       ISD::CondCode Cond, bool foldBooleans,
1354                                       DAGCombinerInfo &DCI,
1355                                       const SDLoc &dl) const {
1356   SelectionDAG &DAG = DCI.DAG;
1357
1358   // These setcc operations always fold.
1359   switch (Cond) {
1360   default: break;
1361   case ISD::SETFALSE:
1362   case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1363   case ISD::SETTRUE:
1364   case ISD::SETTRUE2: {
1365     TargetLowering::BooleanContent Cnt =
1366         getBooleanContents(N0->getValueType(0));
1367     return DAG.getConstant(
1368         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1369         VT);
1370   }
1371   }
1372
1373   // Ensure that the constant occurs on the RHS, and fold constant
1374   // comparisons.
1375   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1376   if (isa<ConstantSDNode>(N0.getNode()) &&
1377       (DCI.isBeforeLegalizeOps() ||
1378        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1379     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1380
1381   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1382     const APInt &C1 = N1C->getAPIntValue();
1383
1384     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1385     // equality comparison, then we're just comparing whether X itself is
1386     // zero.
1387     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1388         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1389         N0.getOperand(1).getOpcode() == ISD::Constant) {
1390       const APInt &ShAmt
1391         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1392       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1393           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1394         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1395           // (srl (ctlz x), 5) == 0  -> X != 0
1396           // (srl (ctlz x), 5) != 1  -> X != 0
1397           Cond = ISD::SETNE;
1398         } else {
1399           // (srl (ctlz x), 5) != 0  -> X == 0
1400           // (srl (ctlz x), 5) == 1  -> X == 0
1401           Cond = ISD::SETEQ;
1402         }
1403         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1404         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1405                             Zero, Cond);
1406       }
1407     }
1408
1409     SDValue CTPOP = N0;
1410     // Look through truncs that don't change the value of a ctpop.
1411     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1412       CTPOP = N0.getOperand(0);
1413
1414     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1415         (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1416                         Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1417       EVT CTVT = CTPOP.getValueType();
1418       SDValue CTOp = CTPOP.getOperand(0);
1419
1420       // (ctpop x) u< 2 -> (x & x-1) == 0
1421       // (ctpop x) u> 1 -> (x & x-1) != 0
1422       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1423         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1424                                   DAG.getConstant(1, dl, CTVT));
1425         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1426         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1427         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1428       }
1429
1430       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1431     }
1432
1433     // (zext x) == C --> x == (trunc C)
1434     // (sext x) == C --> x == (trunc C)
1435     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1436         DCI.isBeforeLegalize() && N0->hasOneUse()) {
1437       unsigned MinBits = N0.getValueSizeInBits();
1438       SDValue PreExt;
1439       bool Signed = false;
1440       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1441         // ZExt
1442         MinBits = N0->getOperand(0).getValueSizeInBits();
1443         PreExt = N0->getOperand(0);
1444       } else if (N0->getOpcode() == ISD::AND) {
1445         // DAGCombine turns costly ZExts into ANDs
1446         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1447           if ((C->getAPIntValue()+1).isPowerOf2()) {
1448             MinBits = C->getAPIntValue().countTrailingOnes();
1449             PreExt = N0->getOperand(0);
1450           }
1451       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1452         // SExt
1453         MinBits = N0->getOperand(0).getValueSizeInBits();
1454         PreExt = N0->getOperand(0);
1455         Signed = true;
1456       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1457         // ZEXTLOAD / SEXTLOAD
1458         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1459           MinBits = LN0->getMemoryVT().getSizeInBits();
1460           PreExt = N0;
1461         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1462           Signed = true;
1463           MinBits = LN0->getMemoryVT().getSizeInBits();
1464           PreExt = N0;
1465         }
1466       }
1467
1468       // Figure out how many bits we need to preserve this constant.
1469       unsigned ReqdBits = Signed ?
1470         C1.getBitWidth() - C1.getNumSignBits() + 1 :
1471         C1.getActiveBits();
1472
1473       // Make sure we're not losing bits from the constant.
1474       if (MinBits > 0 &&
1475           MinBits < C1.getBitWidth() &&
1476           MinBits >= ReqdBits) {
1477         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1478         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1479           // Will get folded away.
1480           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1481           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1482           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1483         }
1484
1485         // If truncating the setcc operands is not desirable, we can still
1486         // simplify the expression in some cases:
1487         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1488         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1489         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1490         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1491         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1492         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1493         SDValue TopSetCC = N0->getOperand(0);
1494         unsigned N0Opc = N0->getOpcode();
1495         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1496         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1497             TopSetCC.getOpcode() == ISD::SETCC &&
1498             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1499             (isConstFalseVal(N1C) ||
1500              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1501
1502           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1503                          (!N1C->isNullValue() && Cond == ISD::SETNE);
1504
1505           if (!Inverse)
1506             return TopSetCC;
1507
1508           ISD::CondCode InvCond = ISD::getSetCCInverse(
1509               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1510               TopSetCC.getOperand(0).getValueType().isInteger());
1511           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1512                                       TopSetCC.getOperand(1),
1513                                       InvCond);
1514
1515         }
1516       }
1517     }
1518
1519     // If the LHS is '(and load, const)', the RHS is 0,
1520     // the test is for equality or unsigned, and all 1 bits of the const are
1521     // in the same partial word, see if we can shorten the load.
1522     if (DCI.isBeforeLegalize() &&
1523         !ISD::isSignedIntSetCC(Cond) &&
1524         N0.getOpcode() == ISD::AND && C1 == 0 &&
1525         N0.getNode()->hasOneUse() &&
1526         isa<LoadSDNode>(N0.getOperand(0)) &&
1527         N0.getOperand(0).getNode()->hasOneUse() &&
1528         isa<ConstantSDNode>(N0.getOperand(1))) {
1529       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1530       APInt bestMask;
1531       unsigned bestWidth = 0, bestOffset = 0;
1532       if (!Lod->isVolatile() && Lod->isUnindexed()) {
1533         unsigned origWidth = N0.getValueType().getSizeInBits();
1534         unsigned maskWidth = origWidth;
1535         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1536         // 8 bits, but have to be careful...
1537         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1538           origWidth = Lod->getMemoryVT().getSizeInBits();
1539         const APInt &Mask =
1540           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1541         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1542           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1543           for (unsigned offset=0; offset<origWidth/width; offset++) {
1544             if ((newMask & Mask) == Mask) {
1545               if (!DAG.getDataLayout().isLittleEndian())
1546                 bestOffset = (origWidth/width - offset - 1) * (width/8);
1547               else
1548                 bestOffset = (uint64_t)offset * (width/8);
1549               bestMask = Mask.lshr(offset * (width/8) * 8);
1550               bestWidth = width;
1551               break;
1552             }
1553             newMask = newMask << width;
1554           }
1555         }
1556       }
1557       if (bestWidth) {
1558         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1559         if (newVT.isRound()) {
1560           EVT PtrType = Lod->getOperand(1).getValueType();
1561           SDValue Ptr = Lod->getBasePtr();
1562           if (bestOffset != 0)
1563             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1564                               DAG.getConstant(bestOffset, dl, PtrType));
1565           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1566           SDValue NewLoad = DAG.getLoad(
1567               newVT, dl, Lod->getChain(), Ptr,
1568               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1569           return DAG.getSetCC(dl, VT,
1570                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1571                                       DAG.getConstant(bestMask.trunc(bestWidth),
1572                                                       dl, newVT)),
1573                               DAG.getConstant(0LL, dl, newVT), Cond);
1574         }
1575       }
1576     }
1577
1578     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1579     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1580       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1581
1582       // If the comparison constant has bits in the upper part, the
1583       // zero-extended value could never match.
1584       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1585                                               C1.getBitWidth() - InSize))) {
1586         switch (Cond) {
1587         case ISD::SETUGT:
1588         case ISD::SETUGE:
1589         case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1590         case ISD::SETULT:
1591         case ISD::SETULE:
1592         case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1593         case ISD::SETGT:
1594         case ISD::SETGE:
1595           // True if the sign bit of C1 is set.
1596           return DAG.getConstant(C1.isNegative(), dl, VT);
1597         case ISD::SETLT:
1598         case ISD::SETLE:
1599           // True if the sign bit of C1 isn't set.
1600           return DAG.getConstant(C1.isNonNegative(), dl, VT);
1601         default:
1602           break;
1603         }
1604       }
1605
1606       // Otherwise, we can perform the comparison with the low bits.
1607       switch (Cond) {
1608       case ISD::SETEQ:
1609       case ISD::SETNE:
1610       case ISD::SETUGT:
1611       case ISD::SETUGE:
1612       case ISD::SETULT:
1613       case ISD::SETULE: {
1614         EVT newVT = N0.getOperand(0).getValueType();
1615         if (DCI.isBeforeLegalizeOps() ||
1616             (isOperationLegal(ISD::SETCC, newVT) &&
1617              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1618           EVT NewSetCCVT =
1619               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1620           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1621
1622           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1623                                           NewConst, Cond);
1624           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1625         }
1626         break;
1627       }
1628       default:
1629         break;   // todo, be more careful with signed comparisons
1630       }
1631     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1632                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1633       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1634       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1635       EVT ExtDstTy = N0.getValueType();
1636       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1637
1638       // If the constant doesn't fit into the number of bits for the source of
1639       // the sign extension, it is impossible for both sides to be equal.
1640       if (C1.getMinSignedBits() > ExtSrcTyBits)
1641         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1642
1643       SDValue ZextOp;
1644       EVT Op0Ty = N0.getOperand(0).getValueType();
1645       if (Op0Ty == ExtSrcTy) {
1646         ZextOp = N0.getOperand(0);
1647       } else {
1648         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1649         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1650                               DAG.getConstant(Imm, dl, Op0Ty));
1651       }
1652       if (!DCI.isCalledByLegalizer())
1653         DCI.AddToWorklist(ZextOp.getNode());
1654       // Otherwise, make this a use of a zext.
1655       return DAG.getSetCC(dl, VT, ZextOp,
1656                           DAG.getConstant(C1 & APInt::getLowBitsSet(
1657                                                               ExtDstTyBits,
1658                                                               ExtSrcTyBits),
1659                                           dl, ExtDstTy),
1660                           Cond);
1661     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1662                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1663       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1664       if (N0.getOpcode() == ISD::SETCC &&
1665           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1666         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1667         if (TrueWhenTrue)
1668           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1669         // Invert the condition.
1670         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1671         CC = ISD::getSetCCInverse(CC,
1672                                   N0.getOperand(0).getValueType().isInteger());
1673         if (DCI.isBeforeLegalizeOps() ||
1674             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1675           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1676       }
1677
1678       if ((N0.getOpcode() == ISD::XOR ||
1679            (N0.getOpcode() == ISD::AND &&
1680             N0.getOperand(0).getOpcode() == ISD::XOR &&
1681             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1682           isa<ConstantSDNode>(N0.getOperand(1)) &&
1683           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1684         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1685         // can only do this if the top bits are known zero.
1686         unsigned BitWidth = N0.getValueSizeInBits();
1687         if (DAG.MaskedValueIsZero(N0,
1688                                   APInt::getHighBitsSet(BitWidth,
1689                                                         BitWidth-1))) {
1690           // Okay, get the un-inverted input value.
1691           SDValue Val;
1692           if (N0.getOpcode() == ISD::XOR)
1693             Val = N0.getOperand(0);
1694           else {
1695             assert(N0.getOpcode() == ISD::AND &&
1696                     N0.getOperand(0).getOpcode() == ISD::XOR);
1697             // ((X^1)&1)^1 -> X & 1
1698             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1699                               N0.getOperand(0).getOperand(0),
1700                               N0.getOperand(1));
1701           }
1702
1703           return DAG.getSetCC(dl, VT, Val, N1,
1704                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1705         }
1706       } else if (N1C->getAPIntValue() == 1 &&
1707                  (VT == MVT::i1 ||
1708                   getBooleanContents(N0->getValueType(0)) ==
1709                       ZeroOrOneBooleanContent)) {
1710         SDValue Op0 = N0;
1711         if (Op0.getOpcode() == ISD::TRUNCATE)
1712           Op0 = Op0.getOperand(0);
1713
1714         if ((Op0.getOpcode() == ISD::XOR) &&
1715             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1716             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1717           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1718           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1719           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1720                               Cond);
1721         }
1722         if (Op0.getOpcode() == ISD::AND &&
1723             isa<ConstantSDNode>(Op0.getOperand(1)) &&
1724             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1725           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1726           if (Op0.getValueType().bitsGT(VT))
1727             Op0 = DAG.getNode(ISD::AND, dl, VT,
1728                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1729                           DAG.getConstant(1, dl, VT));
1730           else if (Op0.getValueType().bitsLT(VT))
1731             Op0 = DAG.getNode(ISD::AND, dl, VT,
1732                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1733                         DAG.getConstant(1, dl, VT));
1734
1735           return DAG.getSetCC(dl, VT, Op0,
1736                               DAG.getConstant(0, dl, Op0.getValueType()),
1737                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1738         }
1739         if (Op0.getOpcode() == ISD::AssertZext &&
1740             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1741           return DAG.getSetCC(dl, VT, Op0,
1742                               DAG.getConstant(0, dl, Op0.getValueType()),
1743                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1744       }
1745     }
1746
1747     APInt MinVal, MaxVal;
1748     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1749     if (ISD::isSignedIntSetCC(Cond)) {
1750       MinVal = APInt::getSignedMinValue(OperandBitSize);
1751       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1752     } else {
1753       MinVal = APInt::getMinValue(OperandBitSize);
1754       MaxVal = APInt::getMaxValue(OperandBitSize);
1755     }
1756
1757     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1758     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1759       if (C1 == MinVal) return DAG.getConstant(1, dl, VT);  // X >= MIN --> true
1760       // X >= C0 --> X > (C0 - 1)
1761       APInt C = C1 - 1;
1762       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1763       if ((DCI.isBeforeLegalizeOps() ||
1764            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1765           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1766                                 isLegalICmpImmediate(C.getSExtValue())))) {
1767         return DAG.getSetCC(dl, VT, N0,
1768                             DAG.getConstant(C, dl, N1.getValueType()),
1769                             NewCC);
1770       }
1771     }
1772
1773     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1774       if (C1 == MaxVal) return DAG.getConstant(1, dl, VT);  // X <= MAX --> true
1775       // X <= C0 --> X < (C0 + 1)
1776       APInt C = C1 + 1;
1777       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1778       if ((DCI.isBeforeLegalizeOps() ||
1779            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1780           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1781                                 isLegalICmpImmediate(C.getSExtValue())))) {
1782         return DAG.getSetCC(dl, VT, N0,
1783                             DAG.getConstant(C, dl, N1.getValueType()),
1784                             NewCC);
1785       }
1786     }
1787
1788     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1789       return DAG.getConstant(0, dl, VT);      // X < MIN --> false
1790     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1791       return DAG.getConstant(1, dl, VT);      // X >= MIN --> true
1792     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1793       return DAG.getConstant(0, dl, VT);      // X > MAX --> false
1794     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1795       return DAG.getConstant(1, dl, VT);      // X <= MAX --> true
1796
1797     // Canonicalize setgt X, Min --> setne X, Min
1798     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1799       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1800     // Canonicalize setlt X, Max --> setne X, Max
1801     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1802       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1803
1804     // If we have setult X, 1, turn it into seteq X, 0
1805     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1806       return DAG.getSetCC(dl, VT, N0,
1807                           DAG.getConstant(MinVal, dl, N0.getValueType()),
1808                           ISD::SETEQ);
1809     // If we have setugt X, Max-1, turn it into seteq X, Max
1810     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1811       return DAG.getSetCC(dl, VT, N0,
1812                           DAG.getConstant(MaxVal, dl, N0.getValueType()),
1813                           ISD::SETEQ);
1814
1815     // If we have "setcc X, C0", check to see if we can shrink the immediate
1816     // by changing cc.
1817
1818     // SETUGT X, SINTMAX  -> SETLT X, 0
1819     if (Cond == ISD::SETUGT &&
1820         C1 == APInt::getSignedMaxValue(OperandBitSize))
1821       return DAG.getSetCC(dl, VT, N0,
1822                           DAG.getConstant(0, dl, N1.getValueType()),
1823                           ISD::SETLT);
1824
1825     // SETULT X, SINTMIN  -> SETGT X, -1
1826     if (Cond == ISD::SETULT &&
1827         C1 == APInt::getSignedMinValue(OperandBitSize)) {
1828       SDValue ConstMinusOne =
1829           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
1830                           N1.getValueType());
1831       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1832     }
1833
1834     // Fold bit comparisons when we can.
1835     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1836         (VT == N0.getValueType() ||
1837          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1838         N0.getOpcode() == ISD::AND) {
1839       auto &DL = DAG.getDataLayout();
1840       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1841         EVT ShiftTy = DCI.isBeforeLegalize()
1842                           ? getPointerTy(DL)
1843                           : getShiftAmountTy(N0.getValueType(), DL);
1844         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1845           // Perform the xform if the AND RHS is a single bit.
1846           if (AndRHS->getAPIntValue().isPowerOf2()) {
1847             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1848                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1849                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1850                                    ShiftTy)));
1851           }
1852         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1853           // (X & 8) == 8  -->  (X & 8) >> 3
1854           // Perform the xform if C1 is a single bit.
1855           if (C1.isPowerOf2()) {
1856             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1857                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1858                                       DAG.getConstant(C1.logBase2(), dl,
1859                                                       ShiftTy)));
1860           }
1861         }
1862       }
1863     }
1864
1865     if (C1.getMinSignedBits() <= 64 &&
1866         !isLegalICmpImmediate(C1.getSExtValue())) {
1867       // (X & -256) == 256 -> (X >> 8) == 1
1868       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1869           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
1870         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1871           const APInt &AndRHSC = AndRHS->getAPIntValue();
1872           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1873             unsigned ShiftBits = AndRHSC.countTrailingZeros();
1874             auto &DL = DAG.getDataLayout();
1875             EVT ShiftTy = DCI.isBeforeLegalize()
1876                               ? getPointerTy(DL)
1877                               : getShiftAmountTy(N0.getValueType(), DL);
1878             EVT CmpTy = N0.getValueType();
1879             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
1880                                         DAG.getConstant(ShiftBits, dl,
1881                                                         ShiftTy));
1882             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
1883             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1884           }
1885         }
1886       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1887                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1888         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1889         // X <  0x100000000 -> (X >> 32) <  1
1890         // X >= 0x100000000 -> (X >> 32) >= 1
1891         // X <= 0x0ffffffff -> (X >> 32) <  1
1892         // X >  0x0ffffffff -> (X >> 32) >= 1
1893         unsigned ShiftBits;
1894         APInt NewC = C1;
1895         ISD::CondCode NewCond = Cond;
1896         if (AdjOne) {
1897           ShiftBits = C1.countTrailingOnes();
1898           NewC = NewC + 1;
1899           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1900         } else {
1901           ShiftBits = C1.countTrailingZeros();
1902         }
1903         NewC = NewC.lshr(ShiftBits);
1904         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1905           isLegalICmpImmediate(NewC.getSExtValue())) {
1906           auto &DL = DAG.getDataLayout();
1907           EVT ShiftTy = DCI.isBeforeLegalize()
1908                             ? getPointerTy(DL)
1909                             : getShiftAmountTy(N0.getValueType(), DL);
1910           EVT CmpTy = N0.getValueType();
1911           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
1912                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
1913           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
1914           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1915         }
1916       }
1917     }
1918   }
1919
1920   if (isa<ConstantFPSDNode>(N0.getNode())) {
1921     // Constant fold or commute setcc.
1922     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1923     if (O.getNode()) return O;
1924   } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1925     // If the RHS of an FP comparison is a constant, simplify it away in
1926     // some cases.
1927     if (CFP->getValueAPF().isNaN()) {
1928       // If an operand is known to be a nan, we can fold it.
1929       switch (ISD::getUnorderedFlavor(Cond)) {
1930       default: llvm_unreachable("Unknown flavor!");
1931       case 0:  // Known false.
1932         return DAG.getConstant(0, dl, VT);
1933       case 1:  // Known true.
1934         return DAG.getConstant(1, dl, VT);
1935       case 2:  // Undefined.
1936         return DAG.getUNDEF(VT);
1937       }
1938     }
1939
1940     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
1941     // constant if knowing that the operand is non-nan is enough.  We prefer to
1942     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1943     // materialize 0.0.
1944     if (Cond == ISD::SETO || Cond == ISD::SETUO)
1945       return DAG.getSetCC(dl, VT, N0, N0, Cond);
1946
1947     // If the condition is not legal, see if we can find an equivalent one
1948     // which is legal.
1949     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1950       // If the comparison was an awkward floating-point == or != and one of
1951       // the comparison operands is infinity or negative infinity, convert the
1952       // condition to a less-awkward <= or >=.
1953       if (CFP->getValueAPF().isInfinity()) {
1954         if (CFP->getValueAPF().isNegative()) {
1955           if (Cond == ISD::SETOEQ &&
1956               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1957             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1958           if (Cond == ISD::SETUEQ &&
1959               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1960             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1961           if (Cond == ISD::SETUNE &&
1962               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1963             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1964           if (Cond == ISD::SETONE &&
1965               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1966             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1967         } else {
1968           if (Cond == ISD::SETOEQ &&
1969               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1970             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1971           if (Cond == ISD::SETUEQ &&
1972               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1973             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1974           if (Cond == ISD::SETUNE &&
1975               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1976             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1977           if (Cond == ISD::SETONE &&
1978               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1979             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1980         }
1981       }
1982     }
1983   }
1984
1985   if (N0 == N1) {
1986     // The sext(setcc()) => setcc() optimization relies on the appropriate
1987     // constant being emitted.
1988     uint64_t EqVal = 0;
1989     switch (getBooleanContents(N0.getValueType())) {
1990     case UndefinedBooleanContent:
1991     case ZeroOrOneBooleanContent:
1992       EqVal = ISD::isTrueWhenEqual(Cond);
1993       break;
1994     case ZeroOrNegativeOneBooleanContent:
1995       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1996       break;
1997     }
1998
1999     // We can always fold X == X for integer setcc's.
2000     if (N0.getValueType().isInteger()) {
2001       return DAG.getConstant(EqVal, dl, VT);
2002     }
2003     unsigned UOF = ISD::getUnorderedFlavor(Cond);
2004     if (UOF == 2)   // FP operators that are undefined on NaNs.
2005       return DAG.getConstant(EqVal, dl, VT);
2006     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2007       return DAG.getConstant(EqVal, dl, VT);
2008     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2009     // if it is not already.
2010     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2011     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2012           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2013       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2014   }
2015
2016   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2017       N0.getValueType().isInteger()) {
2018     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2019         N0.getOpcode() == ISD::XOR) {
2020       // Simplify (X+Y) == (X+Z) -->  Y == Z
2021       if (N0.getOpcode() == N1.getOpcode()) {
2022         if (N0.getOperand(0) == N1.getOperand(0))
2023           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2024         if (N0.getOperand(1) == N1.getOperand(1))
2025           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2026         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2027           // If X op Y == Y op X, try other combinations.
2028           if (N0.getOperand(0) == N1.getOperand(1))
2029             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2030                                 Cond);
2031           if (N0.getOperand(1) == N1.getOperand(0))
2032             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2033                                 Cond);
2034         }
2035       }
2036
2037       // If RHS is a legal immediate value for a compare instruction, we need
2038       // to be careful about increasing register pressure needlessly.
2039       bool LegalRHSImm = false;
2040
2041       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2042         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2043           // Turn (X+C1) == C2 --> X == C2-C1
2044           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2045             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2046                                 DAG.getConstant(RHSC->getAPIntValue()-
2047                                                 LHSR->getAPIntValue(),
2048                                 dl, N0.getValueType()), Cond);
2049           }
2050
2051           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2052           if (N0.getOpcode() == ISD::XOR)
2053             // If we know that all of the inverted bits are zero, don't bother
2054             // performing the inversion.
2055             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2056               return
2057                 DAG.getSetCC(dl, VT, N0.getOperand(0),
2058                              DAG.getConstant(LHSR->getAPIntValue() ^
2059                                                RHSC->getAPIntValue(),
2060                                              dl, N0.getValueType()),
2061                              Cond);
2062         }
2063
2064         // Turn (C1-X) == C2 --> X == C1-C2
2065         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2066           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2067             return
2068               DAG.getSetCC(dl, VT, N0.getOperand(1),
2069                            DAG.getConstant(SUBC->getAPIntValue() -
2070                                              RHSC->getAPIntValue(),
2071                                            dl, N0.getValueType()),
2072                            Cond);
2073           }
2074         }
2075
2076         // Could RHSC fold directly into a compare?
2077         if (RHSC->getValueType(0).getSizeInBits() <= 64)
2078           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2079       }
2080
2081       // Simplify (X+Z) == X -->  Z == 0
2082       // Don't do this if X is an immediate that can fold into a cmp
2083       // instruction and X+Z has other uses. It could be an induction variable
2084       // chain, and the transform would increase register pressure.
2085       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2086         if (N0.getOperand(0) == N1)
2087           return DAG.getSetCC(dl, VT, N0.getOperand(1),
2088                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
2089         if (N0.getOperand(1) == N1) {
2090           if (DAG.isCommutativeBinOp(N0.getOpcode()))
2091             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2092                                 DAG.getConstant(0, dl, N0.getValueType()),
2093                                 Cond);
2094           if (N0.getNode()->hasOneUse()) {
2095             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2096             auto &DL = DAG.getDataLayout();
2097             // (Z-X) == X  --> Z == X<<1
2098             SDValue SH = DAG.getNode(
2099                 ISD::SHL, dl, N1.getValueType(), N1,
2100                 DAG.getConstant(1, dl,
2101                                 getShiftAmountTy(N1.getValueType(), DL)));
2102             if (!DCI.isCalledByLegalizer())
2103               DCI.AddToWorklist(SH.getNode());
2104             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2105           }
2106         }
2107       }
2108     }
2109
2110     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2111         N1.getOpcode() == ISD::XOR) {
2112       // Simplify  X == (X+Z) -->  Z == 0
2113       if (N1.getOperand(0) == N0)
2114         return DAG.getSetCC(dl, VT, N1.getOperand(1),
2115                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
2116       if (N1.getOperand(1) == N0) {
2117         if (DAG.isCommutativeBinOp(N1.getOpcode()))
2118           return DAG.getSetCC(dl, VT, N1.getOperand(0),
2119                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
2120         if (N1.getNode()->hasOneUse()) {
2121           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2122           auto &DL = DAG.getDataLayout();
2123           // X == (Z-X)  --> X<<1 == Z
2124           SDValue SH = DAG.getNode(
2125               ISD::SHL, dl, N1.getValueType(), N0,
2126               DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
2127           if (!DCI.isCalledByLegalizer())
2128             DCI.AddToWorklist(SH.getNode());
2129           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2130         }
2131       }
2132     }
2133
2134     if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2135       return V;
2136   }
2137
2138   // Fold away ALL boolean setcc's.
2139   SDValue Temp;
2140   if (N0.getValueType() == MVT::i1 && foldBooleans) {
2141     switch (Cond) {
2142     default: llvm_unreachable("Unknown integer setcc!");
2143     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2144       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2145       N0 = DAG.getNOT(dl, Temp, MVT::i1);
2146       if (!DCI.isCalledByLegalizer())
2147         DCI.AddToWorklist(Temp.getNode());
2148       break;
2149     case ISD::SETNE:  // X != Y   -->  (X^Y)
2150       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2151       break;
2152     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2153     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2154       Temp = DAG.getNOT(dl, N0, MVT::i1);
2155       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2156       if (!DCI.isCalledByLegalizer())
2157         DCI.AddToWorklist(Temp.getNode());
2158       break;
2159     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2160     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2161       Temp = DAG.getNOT(dl, N1, MVT::i1);
2162       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2163       if (!DCI.isCalledByLegalizer())
2164         DCI.AddToWorklist(Temp.getNode());
2165       break;
2166     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2167     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2168       Temp = DAG.getNOT(dl, N0, MVT::i1);
2169       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2170       if (!DCI.isCalledByLegalizer())
2171         DCI.AddToWorklist(Temp.getNode());
2172       break;
2173     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2174     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2175       Temp = DAG.getNOT(dl, N1, MVT::i1);
2176       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2177       break;
2178     }
2179     if (VT != MVT::i1) {
2180       if (!DCI.isCalledByLegalizer())
2181         DCI.AddToWorklist(N0.getNode());
2182       // FIXME: If running after legalize, we probably can't do this.
2183       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2184     }
2185     return N0;
2186   }
2187
2188   // Could not fold it.
2189   return SDValue();
2190 }
2191
2192 /// Returns true (and the GlobalValue and the offset) if the node is a
2193 /// GlobalAddress + offset.
2194 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2195                                     int64_t &Offset) const {
2196   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2197     GA = GASD->getGlobal();
2198     Offset += GASD->getOffset();
2199     return true;
2200   }
2201
2202   if (N->getOpcode() == ISD::ADD) {
2203     SDValue N1 = N->getOperand(0);
2204     SDValue N2 = N->getOperand(1);
2205     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2206       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2207         Offset += V->getSExtValue();
2208         return true;
2209       }
2210     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2211       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2212         Offset += V->getSExtValue();
2213         return true;
2214       }
2215     }
2216   }
2217
2218   return false;
2219 }
2220
2221 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2222                                           DAGCombinerInfo &DCI) const {
2223   // Default implementation: no optimization.
2224   return SDValue();
2225 }
2226
2227 //===----------------------------------------------------------------------===//
2228 //  Inline Assembler Implementation Methods
2229 //===----------------------------------------------------------------------===//
2230
2231 TargetLowering::ConstraintType
2232 TargetLowering::getConstraintType(StringRef Constraint) const {
2233   unsigned S = Constraint.size();
2234
2235   if (S == 1) {
2236     switch (Constraint[0]) {
2237     default: break;
2238     case 'r': return C_RegisterClass;
2239     case 'm':    // memory
2240     case 'o':    // offsetable
2241     case 'V':    // not offsetable
2242       return C_Memory;
2243     case 'i':    // Simple Integer or Relocatable Constant
2244     case 'n':    // Simple Integer
2245     case 'E':    // Floating Point Constant
2246     case 'F':    // Floating Point Constant
2247     case 's':    // Relocatable Constant
2248     case 'p':    // Address.
2249     case 'X':    // Allow ANY value.
2250     case 'I':    // Target registers.
2251     case 'J':
2252     case 'K':
2253     case 'L':
2254     case 'M':
2255     case 'N':
2256     case 'O':
2257     case 'P':
2258     case '<':
2259     case '>':
2260       return C_Other;
2261     }
2262   }
2263
2264   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2265     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2266       return C_Memory;
2267     return C_Register;
2268   }
2269   return C_Unknown;
2270 }
2271
2272 /// Try to replace an X constraint, which matches anything, with another that
2273 /// has more specific requirements based on the type of the corresponding
2274 /// operand.
2275 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2276   if (ConstraintVT.isInteger())
2277     return "r";
2278   if (ConstraintVT.isFloatingPoint())
2279     return "f";      // works for many targets
2280   return nullptr;
2281 }
2282
2283 /// Lower the specified operand into the Ops vector.
2284 /// If it is invalid, don't add anything to Ops.
2285 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2286                                                   std::string &Constraint,
2287                                                   std::vector<SDValue> &Ops,
2288                                                   SelectionDAG &DAG) const {
2289
2290   if (Constraint.length() > 1) return;
2291
2292   char ConstraintLetter = Constraint[0];
2293   switch (ConstraintLetter) {
2294   default: break;
2295   case 'X':     // Allows any operand; labels (basic block) use this.
2296     if (Op.getOpcode() == ISD::BasicBlock) {
2297       Ops.push_back(Op);
2298       return;
2299     }
2300     // fall through
2301   case 'i':    // Simple Integer or Relocatable Constant
2302   case 'n':    // Simple Integer
2303   case 's': {  // Relocatable Constant
2304     // These operands are interested in values of the form (GV+C), where C may
2305     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2306     // is possible and fine if either GV or C are missing.
2307     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2308     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2309
2310     // If we have "(add GV, C)", pull out GV/C
2311     if (Op.getOpcode() == ISD::ADD) {
2312       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2313       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2314       if (!C || !GA) {
2315         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2316         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2317       }
2318       if (!C || !GA) {
2319         C = nullptr;
2320         GA = nullptr;
2321       }
2322     }
2323
2324     // If we find a valid operand, map to the TargetXXX version so that the
2325     // value itself doesn't get selected.
2326     if (GA) {   // Either &GV   or   &GV+C
2327       if (ConstraintLetter != 'n') {
2328         int64_t Offs = GA->getOffset();
2329         if (C) Offs += C->getZExtValue();
2330         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2331                                                  C ? SDLoc(C) : SDLoc(),
2332                                                  Op.getValueType(), Offs));
2333       }
2334       return;
2335     }
2336     if (C) {   // just C, no GV.
2337       // Simple constants are not allowed for 's'.
2338       if (ConstraintLetter != 's') {
2339         // gcc prints these as sign extended.  Sign extend value to 64 bits
2340         // now; without this it would get ZExt'd later in
2341         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2342         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2343                                             SDLoc(C), MVT::i64));
2344       }
2345       return;
2346     }
2347     break;
2348   }
2349   }
2350 }
2351
2352 std::pair<unsigned, const TargetRegisterClass *>
2353 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2354                                              StringRef Constraint,
2355                                              MVT VT) const {
2356   if (Constraint.empty() || Constraint[0] != '{')
2357     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2358   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2359
2360   // Remove the braces from around the name.
2361   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2362
2363   std::pair<unsigned, const TargetRegisterClass*> R =
2364     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2365
2366   // Figure out which register class contains this reg.
2367   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2368        E = RI->regclass_end(); RCI != E; ++RCI) {
2369     const TargetRegisterClass *RC = *RCI;
2370
2371     // If none of the value types for this register class are valid, we
2372     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2373     if (!isLegalRC(RC))
2374       continue;
2375
2376     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2377          I != E; ++I) {
2378       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2379         std::pair<unsigned, const TargetRegisterClass*> S =
2380           std::make_pair(*I, RC);
2381
2382         // If this register class has the requested value type, return it,
2383         // otherwise keep searching and return the first class found
2384         // if no other is found which explicitly has the requested type.
2385         if (RC->hasType(VT))
2386           return S;
2387         else if (!R.second)
2388           R = S;
2389       }
2390     }
2391   }
2392
2393   return R;
2394 }
2395
2396 //===----------------------------------------------------------------------===//
2397 // Constraint Selection.
2398
2399 /// Return true of this is an input operand that is a matching constraint like
2400 /// "4".
2401 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2402   assert(!ConstraintCode.empty() && "No known constraint!");
2403   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2404 }
2405
2406 /// If this is an input matching constraint, this method returns the output
2407 /// operand it matches.
2408 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2409   assert(!ConstraintCode.empty() && "No known constraint!");
2410   return atoi(ConstraintCode.c_str());
2411 }
2412
2413 /// Split up the constraint string from the inline assembly value into the
2414 /// specific constraints and their prefixes, and also tie in the associated
2415 /// operand values.
2416 /// If this returns an empty vector, and if the constraint string itself
2417 /// isn't empty, there was an error parsing.
2418 TargetLowering::AsmOperandInfoVector
2419 TargetLowering::ParseConstraints(const DataLayout &DL,
2420                                  const TargetRegisterInfo *TRI,
2421                                  ImmutableCallSite CS) const {
2422   /// Information about all of the constraints.
2423   AsmOperandInfoVector ConstraintOperands;
2424   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2425   unsigned maCount = 0; // Largest number of multiple alternative constraints.
2426
2427   // Do a prepass over the constraints, canonicalizing them, and building up the
2428   // ConstraintOperands list.
2429   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2430   unsigned ResNo = 0;   // ResNo - The result number of the next output.
2431
2432   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2433     ConstraintOperands.emplace_back(std::move(CI));
2434     AsmOperandInfo &OpInfo = ConstraintOperands.back();
2435
2436     // Update multiple alternative constraint count.
2437     if (OpInfo.multipleAlternatives.size() > maCount)
2438       maCount = OpInfo.multipleAlternatives.size();
2439
2440     OpInfo.ConstraintVT = MVT::Other;
2441
2442     // Compute the value type for each operand.
2443     switch (OpInfo.Type) {
2444     case InlineAsm::isOutput:
2445       // Indirect outputs just consume an argument.
2446       if (OpInfo.isIndirect) {
2447         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2448         break;
2449       }
2450
2451       // The return value of the call is this value.  As such, there is no
2452       // corresponding argument.
2453       assert(!CS.getType()->isVoidTy() &&
2454              "Bad inline asm!");
2455       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2456         OpInfo.ConstraintVT =
2457             getSimpleValueType(DL, STy->getElementType(ResNo));
2458       } else {
2459         assert(ResNo == 0 && "Asm only has one result!");
2460         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2461       }
2462       ++ResNo;
2463       break;
2464     case InlineAsm::isInput:
2465       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2466       break;
2467     case InlineAsm::isClobber:
2468       // Nothing to do.
2469       break;
2470     }
2471
2472     if (OpInfo.CallOperandVal) {
2473       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2474       if (OpInfo.isIndirect) {
2475         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2476         if (!PtrTy)
2477           report_fatal_error("Indirect operand for inline asm not a pointer!");
2478         OpTy = PtrTy->getElementType();
2479       }
2480
2481       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2482       if (StructType *STy = dyn_cast<StructType>(OpTy))
2483         if (STy->getNumElements() == 1)
2484           OpTy = STy->getElementType(0);
2485
2486       // If OpTy is not a single value, it may be a struct/union that we
2487       // can tile with integers.
2488       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2489         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2490         switch (BitSize) {
2491         default: break;
2492         case 1:
2493         case 8:
2494         case 16:
2495         case 32:
2496         case 64:
2497         case 128:
2498           OpInfo.ConstraintVT =
2499             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2500           break;
2501         }
2502       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2503         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2504         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2505       } else {
2506         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2507       }
2508     }
2509   }
2510
2511   // If we have multiple alternative constraints, select the best alternative.
2512   if (!ConstraintOperands.empty()) {
2513     if (maCount) {
2514       unsigned bestMAIndex = 0;
2515       int bestWeight = -1;
2516       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2517       int weight = -1;
2518       unsigned maIndex;
2519       // Compute the sums of the weights for each alternative, keeping track
2520       // of the best (highest weight) one so far.
2521       for (maIndex = 0; maIndex < maCount; ++maIndex) {
2522         int weightSum = 0;
2523         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2524             cIndex != eIndex; ++cIndex) {
2525           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2526           if (OpInfo.Type == InlineAsm::isClobber)
2527             continue;
2528
2529           // If this is an output operand with a matching input operand,
2530           // look up the matching input. If their types mismatch, e.g. one
2531           // is an integer, the other is floating point, or their sizes are
2532           // different, flag it as an maCantMatch.
2533           if (OpInfo.hasMatchingInput()) {
2534             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2535             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2536               if ((OpInfo.ConstraintVT.isInteger() !=
2537                    Input.ConstraintVT.isInteger()) ||
2538                   (OpInfo.ConstraintVT.getSizeInBits() !=
2539                    Input.ConstraintVT.getSizeInBits())) {
2540                 weightSum = -1;  // Can't match.
2541                 break;
2542               }
2543             }
2544           }
2545           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2546           if (weight == -1) {
2547             weightSum = -1;
2548             break;
2549           }
2550           weightSum += weight;
2551         }
2552         // Update best.
2553         if (weightSum > bestWeight) {
2554           bestWeight = weightSum;
2555           bestMAIndex = maIndex;
2556         }
2557       }
2558
2559       // Now select chosen alternative in each constraint.
2560       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2561           cIndex != eIndex; ++cIndex) {
2562         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2563         if (cInfo.Type == InlineAsm::isClobber)
2564           continue;
2565         cInfo.selectAlternative(bestMAIndex);
2566       }
2567     }
2568   }
2569
2570   // Check and hook up tied operands, choose constraint code to use.
2571   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2572       cIndex != eIndex; ++cIndex) {
2573     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2574
2575     // If this is an output operand with a matching input operand, look up the
2576     // matching input. If their types mismatch, e.g. one is an integer, the
2577     // other is floating point, or their sizes are different, flag it as an
2578     // error.
2579     if (OpInfo.hasMatchingInput()) {
2580       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2581
2582       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2583         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2584             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2585                                          OpInfo.ConstraintVT);
2586         std::pair<unsigned, const TargetRegisterClass *> InputRC =
2587             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2588                                          Input.ConstraintVT);
2589         if ((OpInfo.ConstraintVT.isInteger() !=
2590              Input.ConstraintVT.isInteger()) ||
2591             (MatchRC.second != InputRC.second)) {
2592           report_fatal_error("Unsupported asm: input constraint"
2593                              " with a matching output constraint of"
2594                              " incompatible type!");
2595         }
2596       }
2597     }
2598   }
2599
2600   return ConstraintOperands;
2601 }
2602
2603 /// Return an integer indicating how general CT is.
2604 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2605   switch (CT) {
2606   case TargetLowering::C_Other:
2607   case TargetLowering::C_Unknown:
2608     return 0;
2609   case TargetLowering::C_Register:
2610     return 1;
2611   case TargetLowering::C_RegisterClass:
2612     return 2;
2613   case TargetLowering::C_Memory:
2614     return 3;
2615   }
2616   llvm_unreachable("Invalid constraint type");
2617 }
2618
2619 /// Examine constraint type and operand type and determine a weight value.
2620 /// This object must already have been set up with the operand type
2621 /// and the current alternative constraint selected.
2622 TargetLowering::ConstraintWeight
2623   TargetLowering::getMultipleConstraintMatchWeight(
2624     AsmOperandInfo &info, int maIndex) const {
2625   InlineAsm::ConstraintCodeVector *rCodes;
2626   if (maIndex >= (int)info.multipleAlternatives.size())
2627     rCodes = &info.Codes;
2628   else
2629     rCodes = &info.multipleAlternatives[maIndex].Codes;
2630   ConstraintWeight BestWeight = CW_Invalid;
2631
2632   // Loop over the options, keeping track of the most general one.
2633   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2634     ConstraintWeight weight =
2635       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2636     if (weight > BestWeight)
2637       BestWeight = weight;
2638   }
2639
2640   return BestWeight;
2641 }
2642
2643 /// Examine constraint type and operand type and determine a weight value.
2644 /// This object must already have been set up with the operand type
2645 /// and the current alternative constraint selected.
2646 TargetLowering::ConstraintWeight
2647   TargetLowering::getSingleConstraintMatchWeight(
2648     AsmOperandInfo &info, const char *constraint) const {
2649   ConstraintWeight weight = CW_Invalid;
2650   Value *CallOperandVal = info.CallOperandVal;
2651     // If we don't have a value, we can't do a match,
2652     // but allow it at the lowest weight.
2653   if (!CallOperandVal)
2654     return CW_Default;
2655   // Look at the constraint type.
2656   switch (*constraint) {
2657     case 'i': // immediate integer.
2658     case 'n': // immediate integer with a known value.
2659       if (isa<ConstantInt>(CallOperandVal))
2660         weight = CW_Constant;
2661       break;
2662     case 's': // non-explicit intregal immediate.
2663       if (isa<GlobalValue>(CallOperandVal))
2664         weight = CW_Constant;
2665       break;
2666     case 'E': // immediate float if host format.
2667     case 'F': // immediate float.
2668       if (isa<ConstantFP>(CallOperandVal))
2669         weight = CW_Constant;
2670       break;
2671     case '<': // memory operand with autodecrement.
2672     case '>': // memory operand with autoincrement.
2673     case 'm': // memory operand.
2674     case 'o': // offsettable memory operand
2675     case 'V': // non-offsettable memory operand
2676       weight = CW_Memory;
2677       break;
2678     case 'r': // general register.
2679     case 'g': // general register, memory operand or immediate integer.
2680               // note: Clang converts "g" to "imr".
2681       if (CallOperandVal->getType()->isIntegerTy())
2682         weight = CW_Register;
2683       break;
2684     case 'X': // any operand.
2685     default:
2686       weight = CW_Default;
2687       break;
2688   }
2689   return weight;
2690 }
2691
2692 /// If there are multiple different constraints that we could pick for this
2693 /// operand (e.g. "imr") try to pick the 'best' one.
2694 /// This is somewhat tricky: constraints fall into four classes:
2695 ///    Other         -> immediates and magic values
2696 ///    Register      -> one specific register
2697 ///    RegisterClass -> a group of regs
2698 ///    Memory        -> memory
2699 /// Ideally, we would pick the most specific constraint possible: if we have
2700 /// something that fits into a register, we would pick it.  The problem here
2701 /// is that if we have something that could either be in a register or in
2702 /// memory that use of the register could cause selection of *other*
2703 /// operands to fail: they might only succeed if we pick memory.  Because of
2704 /// this the heuristic we use is:
2705 ///
2706 ///  1) If there is an 'other' constraint, and if the operand is valid for
2707 ///     that constraint, use it.  This makes us take advantage of 'i'
2708 ///     constraints when available.
2709 ///  2) Otherwise, pick the most general constraint present.  This prefers
2710 ///     'm' over 'r', for example.
2711 ///
2712 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2713                              const TargetLowering &TLI,
2714                              SDValue Op, SelectionDAG *DAG) {
2715   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2716   unsigned BestIdx = 0;
2717   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2718   int BestGenerality = -1;
2719
2720   // Loop over the options, keeping track of the most general one.
2721   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2722     TargetLowering::ConstraintType CType =
2723       TLI.getConstraintType(OpInfo.Codes[i]);
2724
2725     // If this is an 'other' constraint, see if the operand is valid for it.
2726     // For example, on X86 we might have an 'rI' constraint.  If the operand
2727     // is an integer in the range [0..31] we want to use I (saving a load
2728     // of a register), otherwise we must use 'r'.
2729     if (CType == TargetLowering::C_Other && Op.getNode()) {
2730       assert(OpInfo.Codes[i].size() == 1 &&
2731              "Unhandled multi-letter 'other' constraint");
2732       std::vector<SDValue> ResultOps;
2733       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2734                                        ResultOps, *DAG);
2735       if (!ResultOps.empty()) {
2736         BestType = CType;
2737         BestIdx = i;
2738         break;
2739       }
2740     }
2741
2742     // Things with matching constraints can only be registers, per gcc
2743     // documentation.  This mainly affects "g" constraints.
2744     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2745       continue;
2746
2747     // This constraint letter is more general than the previous one, use it.
2748     int Generality = getConstraintGenerality(CType);
2749     if (Generality > BestGenerality) {
2750       BestType = CType;
2751       BestIdx = i;
2752       BestGenerality = Generality;
2753     }
2754   }
2755
2756   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2757   OpInfo.ConstraintType = BestType;
2758 }
2759
2760 /// Determines the constraint code and constraint type to use for the specific
2761 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2762 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2763                                             SDValue Op,
2764                                             SelectionDAG *DAG) const {
2765   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2766
2767   // Single-letter constraints ('r') are very common.
2768   if (OpInfo.Codes.size() == 1) {
2769     OpInfo.ConstraintCode = OpInfo.Codes[0];
2770     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2771   } else {
2772     ChooseConstraint(OpInfo, *this, Op, DAG);
2773   }
2774
2775   // 'X' matches anything.
2776   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2777     // Labels and constants are handled elsewhere ('X' is the only thing
2778     // that matches labels).  For Functions, the type here is the type of
2779     // the result, which is not what we want to look at; leave them alone.
2780     Value *v = OpInfo.CallOperandVal;
2781     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2782       OpInfo.CallOperandVal = v;
2783       return;
2784     }
2785
2786     // Otherwise, try to resolve it to something we know about by looking at
2787     // the actual operand type.
2788     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2789       OpInfo.ConstraintCode = Repl;
2790       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2791     }
2792   }
2793 }
2794
2795 /// \brief Given an exact SDIV by a constant, create a multiplication
2796 /// with the multiplicative inverse of the constant.
2797 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2798                               const SDLoc &dl, SelectionDAG &DAG,
2799                               std::vector<SDNode *> &Created) {
2800   assert(d != 0 && "Division by zero!");
2801
2802   // Shift the value upfront if it is even, so the LSB is one.
2803   unsigned ShAmt = d.countTrailingZeros();
2804   if (ShAmt) {
2805     // TODO: For UDIV use SRL instead of SRA.
2806     SDValue Amt =
2807         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2808                                                         DAG.getDataLayout()));
2809     SDNodeFlags Flags;
2810     Flags.setExact(true);
2811     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2812     Created.push_back(Op1.getNode());
2813     d = d.ashr(ShAmt);
2814   }
2815
2816   // Calculate the multiplicative inverse, using Newton's method.
2817   APInt t, xn = d;
2818   while ((t = d*xn) != 1)
2819     xn *= APInt(d.getBitWidth(), 2) - t;
2820
2821   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2822   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2823   Created.push_back(Mul.getNode());
2824   return Mul;
2825 }
2826
2827 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2828                                       SelectionDAG &DAG,
2829                                       std::vector<SDNode *> *Created) const {
2830   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2832   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2833     return SDValue(N,0); // Lower SDIV as SDIV
2834   return SDValue();
2835 }
2836
2837 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2838 /// return a DAG expression to select that will generate the same value by
2839 /// multiplying by a magic number.
2840 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2841 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2842                                   SelectionDAG &DAG, bool IsAfterLegalization,
2843                                   std::vector<SDNode *> *Created) const {
2844   assert(Created && "No vector to hold sdiv ops.");
2845
2846   EVT VT = N->getValueType(0);
2847   SDLoc dl(N);
2848
2849   // Check to see if we can do this.
2850   // FIXME: We should be more aggressive here.
2851   if (!isTypeLegal(VT))
2852     return SDValue();
2853
2854   // If the sdiv has an 'exact' bit we can use a simpler lowering.
2855   if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2856     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2857
2858   APInt::ms magics = Divisor.magic();
2859
2860   // Multiply the numerator (operand 0) by the magic value
2861   // FIXME: We should support doing a MUL in a wider type
2862   SDValue Q;
2863   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2864                             isOperationLegalOrCustom(ISD::MULHS, VT))
2865     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2866                     DAG.getConstant(magics.m, dl, VT));
2867   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2868                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2869     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2870                               N->getOperand(0),
2871                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
2872   else
2873     return SDValue();       // No mulhs or equvialent
2874   // If d > 0 and m < 0, add the numerator
2875   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
2876     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2877     Created->push_back(Q.getNode());
2878   }
2879   // If d < 0 and m > 0, subtract the numerator.
2880   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
2881     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2882     Created->push_back(Q.getNode());
2883   }
2884   auto &DL = DAG.getDataLayout();
2885   // Shift right algebraic if shift value is nonzero
2886   if (magics.s > 0) {
2887     Q = DAG.getNode(
2888         ISD::SRA, dl, VT, Q,
2889         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
2890     Created->push_back(Q.getNode());
2891   }
2892   // Extract the sign bit and add it to the quotient
2893   SDValue T =
2894       DAG.getNode(ISD::SRL, dl, VT, Q,
2895                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2896                                   getShiftAmountTy(Q.getValueType(), DL)));
2897   Created->push_back(T.getNode());
2898   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2899 }
2900
2901 /// \brief Given an ISD::UDIV node expressing a divide by constant,
2902 /// return a DAG expression to select that will generate the same value by
2903 /// multiplying by a magic number.
2904 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2905 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2906                                   SelectionDAG &DAG, bool IsAfterLegalization,
2907                                   std::vector<SDNode *> *Created) const {
2908   assert(Created && "No vector to hold udiv ops.");
2909
2910   EVT VT = N->getValueType(0);
2911   SDLoc dl(N);
2912   auto &DL = DAG.getDataLayout();
2913
2914   // Check to see if we can do this.
2915   // FIXME: We should be more aggressive here.
2916   if (!isTypeLegal(VT))
2917     return SDValue();
2918
2919   // FIXME: We should use a narrower constant when the upper
2920   // bits are known to be zero.
2921   APInt::mu magics = Divisor.magicu();
2922
2923   SDValue Q = N->getOperand(0);
2924
2925   // If the divisor is even, we can avoid using the expensive fixup by shifting
2926   // the divided value upfront.
2927   if (magics.a != 0 && !Divisor[0]) {
2928     unsigned Shift = Divisor.countTrailingZeros();
2929     Q = DAG.getNode(
2930         ISD::SRL, dl, VT, Q,
2931         DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
2932     Created->push_back(Q.getNode());
2933
2934     // Get magic number for the shifted divisor.
2935     magics = Divisor.lshr(Shift).magicu(Shift);
2936     assert(magics.a == 0 && "Should use cheap fixup now");
2937   }
2938
2939   // Multiply the numerator (operand 0) by the magic value
2940   // FIXME: We should support doing a MUL in a wider type
2941   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2942                             isOperationLegalOrCustom(ISD::MULHU, VT))
2943     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
2944   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2945                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2946     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
2947                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
2948   else
2949     return SDValue();       // No mulhu or equvialent
2950
2951   Created->push_back(Q.getNode());
2952
2953   if (magics.a == 0) {
2954     assert(magics.s < Divisor.getBitWidth() &&
2955            "We shouldn't generate an undefined shift!");
2956     return DAG.getNode(
2957         ISD::SRL, dl, VT, Q,
2958         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
2959   } else {
2960     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2961     Created->push_back(NPQ.getNode());
2962     NPQ = DAG.getNode(
2963         ISD::SRL, dl, VT, NPQ,
2964         DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
2965     Created->push_back(NPQ.getNode());
2966     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2967     Created->push_back(NPQ.getNode());
2968     return DAG.getNode(
2969         ISD::SRL, dl, VT, NPQ,
2970         DAG.getConstant(magics.s - 1, dl,
2971                         getShiftAmountTy(NPQ.getValueType(), DL)));
2972   }
2973 }
2974
2975 bool TargetLowering::
2976 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2977   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2978     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2979                                 "be a constant integer");
2980     return true;
2981   }
2982
2983   return false;
2984 }
2985
2986 //===----------------------------------------------------------------------===//
2987 // Legalization Utilities
2988 //===----------------------------------------------------------------------===//
2989
2990 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2991                                SelectionDAG &DAG, SDValue LL, SDValue LH,
2992                                SDValue RL, SDValue RH) const {
2993   EVT VT = N->getValueType(0);
2994   SDLoc dl(N);
2995
2996   bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
2997   bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
2998   bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
2999   bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3000   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
3001     unsigned OuterBitSize = VT.getSizeInBits();
3002     unsigned InnerBitSize = HiLoVT.getSizeInBits();
3003     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
3004     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
3005
3006     // LL, LH, RL, and RH must be either all NULL or all set to a value.
3007     assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3008            (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3009
3010     if (!LL.getNode() && !RL.getNode() &&
3011         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3012       LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
3013       RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
3014     }
3015
3016     if (!LL.getNode())
3017       return false;
3018
3019     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3020     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
3021         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
3022       // The inputs are both zero-extended.
3023       if (HasUMUL_LOHI) {
3024         // We can emit a umul_lohi.
3025         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3026                          RL);
3027         Hi = SDValue(Lo.getNode(), 1);
3028         return true;
3029       }
3030       if (HasMULHU) {
3031         // We can emit a mulhu+mul.
3032         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3033         Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3034         return true;
3035       }
3036     }
3037     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
3038       // The input values are both sign-extended.
3039       if (HasSMUL_LOHI) {
3040         // We can emit a smul_lohi.
3041         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3042                          RL);
3043         Hi = SDValue(Lo.getNode(), 1);
3044         return true;
3045       }
3046       if (HasMULHS) {
3047         // We can emit a mulhs+mul.
3048         Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3049         Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
3050         return true;
3051       }
3052     }
3053
3054     if (!LH.getNode() && !RH.getNode() &&
3055         isOperationLegalOrCustom(ISD::SRL, VT) &&
3056         isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3057       auto &DL = DAG.getDataLayout();
3058       unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
3059       SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL));
3060       LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
3061       LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3062       RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
3063       RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3064     }
3065
3066     if (!LH.getNode())
3067       return false;
3068
3069     if (HasUMUL_LOHI) {
3070       // Lo,Hi = umul LHS, RHS.
3071       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
3072                                      DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
3073       Lo = UMulLOHI;
3074       Hi = UMulLOHI.getValue(1);
3075       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3076       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3077       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3078       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3079       return true;
3080     }
3081     if (HasMULHU) {
3082       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3083       Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3084       RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3085       LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3086       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3087       Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3088       return true;
3089     }
3090   }
3091   return false;
3092 }
3093
3094 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3095                                SelectionDAG &DAG) const {
3096   EVT VT = Node->getOperand(0).getValueType();
3097   EVT NVT = Node->getValueType(0);
3098   SDLoc dl(SDValue(Node, 0));
3099
3100   // FIXME: Only f32 to i64 conversions are supported.
3101   if (VT != MVT::f32 || NVT != MVT::i64)
3102     return false;
3103
3104   // Expand f32 -> i64 conversion
3105   // This algorithm comes from compiler-rt's implementation of fixsfdi:
3106   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3107   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3108                                 VT.getSizeInBits());
3109   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3110   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3111   SDValue Bias = DAG.getConstant(127, dl, IntVT);
3112   SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
3113                                      IntVT);
3114   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3115   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3116
3117   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3118
3119   auto &DL = DAG.getDataLayout();
3120   SDValue ExponentBits = DAG.getNode(
3121       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3122       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3123   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3124
3125   SDValue Sign = DAG.getNode(
3126       ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3127       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3128   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3129
3130   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3131       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3132       DAG.getConstant(0x00800000, dl, IntVT));
3133
3134   R = DAG.getZExtOrTrunc(R, dl, NVT);
3135
3136   R = DAG.getSelectCC(
3137       dl, Exponent, ExponentLoBit,
3138       DAG.getNode(ISD::SHL, dl, NVT, R,
3139                   DAG.getZExtOrTrunc(
3140                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3141                       dl, getShiftAmountTy(IntVT, DL))),
3142       DAG.getNode(ISD::SRL, dl, NVT, R,
3143                   DAG.getZExtOrTrunc(
3144                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3145                       dl, getShiftAmountTy(IntVT, DL))),
3146       ISD::SETGT);
3147
3148   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3149       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3150       Sign);
3151
3152   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3153       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3154   return true;
3155 }
3156
3157 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3158                                             SelectionDAG &DAG) const {
3159   SDLoc SL(LD);
3160   SDValue Chain = LD->getChain();
3161   SDValue BasePTR = LD->getBasePtr();
3162   EVT SrcVT = LD->getMemoryVT();
3163   ISD::LoadExtType ExtType = LD->getExtensionType();
3164
3165   unsigned NumElem = SrcVT.getVectorNumElements();
3166
3167   EVT SrcEltVT = SrcVT.getScalarType();
3168   EVT DstEltVT = LD->getValueType(0).getScalarType();
3169
3170   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3171   assert(SrcEltVT.isByteSized());
3172
3173   EVT PtrVT = BasePTR.getValueType();
3174
3175   SmallVector<SDValue, 8> Vals;
3176   SmallVector<SDValue, 8> LoadChains;
3177
3178   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3179     SDValue ScalarLoad =
3180         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3181                        LD->getPointerInfo().getWithOffset(Idx * Stride),
3182                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3183                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3184
3185     BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3186                           DAG.getConstant(Stride, SL, PtrVT));
3187
3188     Vals.push_back(ScalarLoad.getValue(0));
3189     LoadChains.push_back(ScalarLoad.getValue(1));
3190   }
3191
3192   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3193   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, SL, LD->getValueType(0), Vals);
3194
3195   return DAG.getMergeValues({ Value, NewChain }, SL);
3196 }
3197
3198 // FIXME: This relies on each element having a byte size, otherwise the stride
3199 // is 0 and just overwrites the same location. ExpandStore currently expects
3200 // this broken behavior.
3201 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3202                                              SelectionDAG &DAG) const {
3203   SDLoc SL(ST);
3204
3205   SDValue Chain = ST->getChain();
3206   SDValue BasePtr = ST->getBasePtr();
3207   SDValue Value = ST->getValue();
3208   EVT StVT = ST->getMemoryVT();
3209
3210   // The type of the data we want to save
3211   EVT RegVT = Value.getValueType();
3212   EVT RegSclVT = RegVT.getScalarType();
3213
3214   // The type of data as saved in memory.
3215   EVT MemSclVT = StVT.getScalarType();
3216
3217   EVT PtrVT = BasePtr.getValueType();
3218
3219   // Store Stride in bytes
3220   unsigned Stride = MemSclVT.getSizeInBits() / 8;
3221   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3222   unsigned NumElem = StVT.getVectorNumElements();
3223
3224   // Extract each of the elements from the original vector and save them into
3225   // memory individually.
3226   SmallVector<SDValue, 8> Stores;
3227   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3228     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3229                               DAG.getConstant(Idx, SL, IdxVT));
3230
3231     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3232                               DAG.getConstant(Idx * Stride, SL, PtrVT));
3233
3234     // This scalar TruncStore may be illegal, but we legalize it later.
3235     SDValue Store = DAG.getTruncStore(
3236         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3237         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3238         ST->getMemOperand()->getFlags(), ST->getAAInfo());
3239
3240     Stores.push_back(Store);
3241   }
3242
3243   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3244 }
3245
3246 std::pair<SDValue, SDValue>
3247 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3248   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3249          "unaligned indexed loads not implemented!");
3250   SDValue Chain = LD->getChain();
3251   SDValue Ptr = LD->getBasePtr();
3252   EVT VT = LD->getValueType(0);
3253   EVT LoadedVT = LD->getMemoryVT();
3254   SDLoc dl(LD);
3255   if (VT.isFloatingPoint() || VT.isVector()) {
3256     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3257     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3258       if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3259         // Scalarize the load and let the individual components be handled.
3260         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3261         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3262       }
3263
3264       // Expand to a (misaligned) integer load of the same size,
3265       // then bitconvert to floating point or vector.
3266       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3267                                     LD->getMemOperand());
3268       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3269       if (LoadedVT != VT)
3270         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3271                              ISD::ANY_EXTEND, dl, VT, Result);
3272
3273       return std::make_pair(Result, newLoad.getValue(1));
3274     }
3275
3276     // Copy the value to a (aligned) stack slot using (unaligned) integer
3277     // loads and stores, then do a (aligned) load from the stack slot.
3278     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3279     unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3280     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3281     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3282
3283     // Make sure the stack slot is also aligned for the register type.
3284     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3285
3286     SmallVector<SDValue, 8> Stores;
3287     SDValue StackPtr = StackBase;
3288     unsigned Offset = 0;
3289
3290     EVT PtrVT = Ptr.getValueType();
3291     EVT StackPtrVT = StackPtr.getValueType();
3292
3293     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3294     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3295
3296     // Do all but one copies using the full register width.
3297     for (unsigned i = 1; i < NumRegs; i++) {
3298       // Load one integer register's worth from the original location.
3299       SDValue Load = DAG.getLoad(
3300           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3301           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3302           LD->getAAInfo());
3303       // Follow the load with a store to the stack slot.  Remember the store.
3304       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3305                                     MachinePointerInfo()));
3306       // Increment the pointers.
3307       Offset += RegBytes;
3308       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3309       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3310                              StackPtrIncrement);
3311     }
3312
3313     // The last copy may be partial.  Do an extending load.
3314     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3315                                   8 * (LoadedBytes - Offset));
3316     SDValue Load =
3317         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3318                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
3319                        MinAlign(LD->getAlignment(), Offset),
3320                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3321     // Follow the load with a store to the stack slot.  Remember the store.
3322     // On big-endian machines this requires a truncating store to ensure
3323     // that the bits end up in the right place.
3324     Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3325                                        MachinePointerInfo(), MemVT));
3326
3327     // The order of the stores doesn't matter - say it with a TokenFactor.
3328     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3329
3330     // Finally, perform the original load only redirected to the stack slot.
3331     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3332                           MachinePointerInfo(), LoadedVT);
3333
3334     // Callers expect a MERGE_VALUES node.
3335     return std::make_pair(Load, TF);
3336   }
3337
3338   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3339          "Unaligned load of unsupported type.");
3340
3341   // Compute the new VT that is half the size of the old one.  This is an
3342   // integer MVT.
3343   unsigned NumBits = LoadedVT.getSizeInBits();
3344   EVT NewLoadedVT;
3345   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3346   NumBits >>= 1;
3347
3348   unsigned Alignment = LD->getAlignment();
3349   unsigned IncrementSize = NumBits / 8;
3350   ISD::LoadExtType HiExtType = LD->getExtensionType();
3351
3352   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3353   if (HiExtType == ISD::NON_EXTLOAD)
3354     HiExtType = ISD::ZEXTLOAD;
3355
3356   // Load the value in two parts
3357   SDValue Lo, Hi;
3358   if (DAG.getDataLayout().isLittleEndian()) {
3359     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3360                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3361                         LD->getAAInfo());
3362     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3363                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3364     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3365                         LD->getPointerInfo().getWithOffset(IncrementSize),
3366                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3367                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3368   } else {
3369     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3370                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3371                         LD->getAAInfo());
3372     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3373                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3374     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3375                         LD->getPointerInfo().getWithOffset(IncrementSize),
3376                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3377                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3378   }
3379
3380   // aggregate the two parts
3381   SDValue ShiftAmount =
3382       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3383                                                     DAG.getDataLayout()));
3384   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3385   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3386
3387   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3388                              Hi.getValue(1));
3389
3390   return std::make_pair(Result, TF);
3391 }
3392
3393 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3394                                              SelectionDAG &DAG) const {
3395   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3396          "unaligned indexed stores not implemented!");
3397   SDValue Chain = ST->getChain();
3398   SDValue Ptr = ST->getBasePtr();
3399   SDValue Val = ST->getValue();
3400   EVT VT = Val.getValueType();
3401   int Alignment = ST->getAlignment();
3402
3403   SDLoc dl(ST);
3404   if (ST->getMemoryVT().isFloatingPoint() ||
3405       ST->getMemoryVT().isVector()) {
3406     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3407     if (isTypeLegal(intVT)) {
3408       if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3409         // Scalarize the store and let the individual components be handled.
3410         SDValue Result = scalarizeVectorStore(ST, DAG);
3411
3412         return Result;
3413       }
3414       // Expand to a bitconvert of the value to the integer type of the
3415       // same size, then a (misaligned) int store.
3416       // FIXME: Does not handle truncating floating point stores!
3417       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3418       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3419                             Alignment, ST->getMemOperand()->getFlags());
3420       return Result;
3421     }
3422     // Do a (aligned) store to a stack slot, then copy from the stack slot
3423     // to the final destination using (unaligned) integer loads and stores.
3424     EVT StoredVT = ST->getMemoryVT();
3425     MVT RegVT =
3426       getRegisterType(*DAG.getContext(),
3427                       EVT::getIntegerVT(*DAG.getContext(),
3428                                         StoredVT.getSizeInBits()));
3429     EVT PtrVT = Ptr.getValueType();
3430     unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3431     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3432     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3433
3434     // Make sure the stack slot is also aligned for the register type.
3435     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3436
3437     // Perform the original store, only redirected to the stack slot.
3438     SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3439                                       MachinePointerInfo(), StoredVT);
3440
3441     EVT StackPtrVT = StackPtr.getValueType();
3442
3443     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3444     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3445     SmallVector<SDValue, 8> Stores;
3446     unsigned Offset = 0;
3447
3448     // Do all but one copies using the full register width.
3449     for (unsigned i = 1; i < NumRegs; i++) {
3450       // Load one integer register's worth from the stack slot.
3451       SDValue Load =
3452           DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
3453       // Store it to the final location.  Remember the store.
3454       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3455                                     ST->getPointerInfo().getWithOffset(Offset),
3456                                     MinAlign(ST->getAlignment(), Offset),
3457                                     ST->getMemOperand()->getFlags()));
3458       // Increment the pointers.
3459       Offset += RegBytes;
3460       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3461                              StackPtr, StackPtrIncrement);
3462       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3463     }
3464
3465     // The last store may be partial.  Do a truncating store.  On big-endian
3466     // machines this requires an extending load from the stack slot to ensure
3467     // that the bits are in the right place.
3468     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3469                                   8 * (StoredBytes - Offset));
3470
3471     // Load from the stack slot.
3472     SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3473                                   MachinePointerInfo(), MemVT);
3474
3475     Stores.push_back(
3476         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3477                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
3478                           MinAlign(ST->getAlignment(), Offset),
3479                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
3480     // The order of the stores doesn't matter - say it with a TokenFactor.
3481     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3482     return Result;
3483   }
3484
3485   assert(ST->getMemoryVT().isInteger() &&
3486          !ST->getMemoryVT().isVector() &&
3487          "Unaligned store of unknown type.");
3488   // Get the half-size VT
3489   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3490   int NumBits = NewStoredVT.getSizeInBits();
3491   int IncrementSize = NumBits / 8;
3492
3493   // Divide the stored value in two parts.
3494   SDValue ShiftAmount =
3495       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3496                                                     DAG.getDataLayout()));
3497   SDValue Lo = Val;
3498   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3499
3500   // Store the two parts
3501   SDValue Store1, Store2;
3502   Store1 = DAG.getTruncStore(Chain, dl,
3503                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3504                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3505                              ST->getMemOperand()->getFlags());
3506
3507   EVT PtrVT = Ptr.getValueType();
3508   Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3509                     DAG.getConstant(IncrementSize, dl, PtrVT));
3510   Alignment = MinAlign(Alignment, IncrementSize);
3511   Store2 = DAG.getTruncStore(
3512       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3513       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3514       ST->getMemOperand()->getFlags(), ST->getAAInfo());
3515
3516   SDValue Result =
3517     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3518   return Result;
3519 }
3520
3521 //===----------------------------------------------------------------------===//
3522 // Implementation of Emulated TLS Model
3523 //===----------------------------------------------------------------------===//
3524
3525 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3526                                                 SelectionDAG &DAG) const {
3527   // Access to address of TLS varialbe xyz is lowered to a function call:
3528   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3529   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3530   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3531   SDLoc dl(GA);
3532
3533   ArgListTy Args;
3534   ArgListEntry Entry;
3535   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3536   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3537   StringRef EmuTlsVarName(NameString);
3538   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3539   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
3540   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3541   Entry.Ty = VoidPtrType;
3542   Args.push_back(Entry);
3543
3544   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3545
3546   TargetLowering::CallLoweringInfo CLI(DAG);
3547   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3548   CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
3549   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3550
3551   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3552   // At last for X86 targets, maybe good for other targets too?
3553   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3554   MFI->setAdjustsStack(true);  // Is this only for X86 target?
3555   MFI->setHasCalls(true);
3556
3557   assert((GA->getOffset() == 0) &&
3558          "Emulated TLS must have zero offset in GlobalAddressSDNode");
3559   return CallResult.first;
3560 }