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