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