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