blob: d582a4b5b8a7445c41795dfa1f497d9082094105 [file] [log] [blame]
Chris Lattner3a4d1b22005-01-07 07:44:53 +00001//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Chris Lattner3a4d1b22005-01-07 07:44:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Chris Lattner3a4d1b22005-01-07 07:44:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Target/TargetLowering.h"
Jakob Stoklund Olesen75fbe902012-05-04 02:19:22 +000015#include "llvm/ADT/BitVector.h"
Owen Andersone2f23a32007-09-07 04:06:50 +000016#include "llvm/ADT/STLExtras.h"
Matthias Braun46b0f032016-04-14 01:10:42 +000017#include "llvm/CodeGen/CallingConvLower.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
Matthias Braun46b0f032016-04-14 01:10:42 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalVariable.h"
Bill Wendling908bf812014-01-06 00:43:20 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/MC/MCAsmInfo.h"
28#include "llvm/MC/MCExpr.h"
Torok Edwin56d06592009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf0b24d22006-01-30 04:09:27 +000030#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetLoweringObjectFile.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000035#include <cctype>
Chris Lattner3a4d1b22005-01-07 07:44:53 +000036using namespace llvm;
37
Aditya Nandakumar30531552014-11-13 21:29:21 +000038/// NOTE: The TargetMachine owns TLOF.
39TargetLowering::TargetLowering(const TargetMachine &tm)
40 : TargetLoweringBase(tm) {}
Chris Lattner6f809792005-01-16 07:28:11 +000041
Evan Cheng6af02632005-12-20 06:22:03 +000042const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
Craig Topperc0196b12014-04-14 00:51:57 +000043 return nullptr;
Evan Cheng6af02632005-12-20 06:22:03 +000044}
Evan Cheng9cdc16c2005-12-21 23:05:39 +000045
Rafael Espindolaae0d8662016-06-26 22:13:55 +000046bool TargetLowering::isPositionIndependent() const {
Rafael Espindolab1556c42016-06-28 20:13:36 +000047 return getTargetMachine().isPositionIndependent();
Rafael Espindolaae0d8662016-06-26 22:13:55 +000048}
49
Tim Northoverf1450d82013-01-09 13:18:15 +000050/// Check whether a given call node is in tail position within its function. If
51/// so, it sets Chain to the input chain of the tail call.
52bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
53 SDValue &Chain) const {
54 const Function *F = DAG.getMachineFunction().getFunction();
55
56 // Conservatively require the attributes of the call to match those of
57 // the return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +000058 AttributeSet CallerAttrs = F->getAttributes();
59 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
Tim Northoverf1450d82013-01-09 13:18:15 +000060 .removeAttribute(Attribute::NoAlias).hasAttributes())
61 return false;
62
63 // It's not safe to eliminate the sign / zero extension of the return value.
Bill Wendling658d24d2013-01-18 21:53:16 +000064 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
65 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Tim Northoverf1450d82013-01-09 13:18:15 +000066 return false;
67
68 // Check if the only use is a function return node.
69 return isUsedByReturnOnly(Node, Chain);
70}
71
Matthias Braun46b0f032016-04-14 01:10:42 +000072bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
73 const uint32_t *CallerPreservedMask,
74 const SmallVectorImpl<CCValAssign> &ArgLocs,
75 const SmallVectorImpl<SDValue> &OutVals) const {
76 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
77 const CCValAssign &ArgLoc = ArgLocs[I];
78 if (!ArgLoc.isRegLoc())
79 continue;
80 unsigned Reg = ArgLoc.getLocReg();
81 // Only look at callee saved registers.
82 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
83 continue;
84 // Check that we pass the value used for the caller.
85 // (We look for a CopyFromReg reading a virtual register that is used
86 // for the function live-in value of register Reg)
87 SDValue Value = OutVals[I];
88 if (Value->getOpcode() != ISD::CopyFromReg)
89 return false;
90 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
91 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
92 return false;
93 }
94 return true;
95}
96
Andrew Trick74f4c742013-10-31 17:18:24 +000097/// \brief Set CallLoweringInfo attribute flags based on a call instruction
98/// and called function attributes.
99void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
100 unsigned AttrIdx) {
101 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
102 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
103 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
104 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
105 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
106 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
Reid Klecknerf5b76512014-01-31 23:50:57 +0000107 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
Andrew Trick74f4c742013-10-31 17:18:24 +0000108 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
Manman Renf46262e2016-03-29 17:37:21 +0000109 isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
Manman Ren9bfd0d02016-04-01 21:41:15 +0000110 isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
Andrew Trick74f4c742013-10-31 17:18:24 +0000111 Alignment = CS->getParamAlignment(AttrIdx);
112}
Tim Northoverf1450d82013-01-09 13:18:15 +0000113
114/// Generate a libcall taking the given operands as arguments and returning a
115/// result of type RetVT.
Michael Gottesman7a801722013-08-13 17:54:56 +0000116std::pair<SDValue, SDValue>
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000117TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
118 ArrayRef<SDValue> Ops, bool isSigned,
119 const SDLoc &dl, bool doesNotReturn,
Michael Gottesman7a801722013-08-13 17:54:56 +0000120 bool isReturnValueUsed) const {
Tim Northoverf1450d82013-01-09 13:18:15 +0000121 TargetLowering::ArgListTy Args;
Craig Topper8fe40e02015-10-22 17:05:00 +0000122 Args.reserve(Ops.size());
Tim Northoverf1450d82013-01-09 13:18:15 +0000123
124 TargetLowering::ArgListEntry Entry;
Craig Topper8fe40e02015-10-22 17:05:00 +0000125 for (SDValue Op : Ops) {
126 Entry.Node = Op;
Tim Northoverf1450d82013-01-09 13:18:15 +0000127 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
Craig Topper8fe40e02015-10-22 17:05:00 +0000128 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
129 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
Tim Northoverf1450d82013-01-09 13:18:15 +0000130 Args.push_back(Entry);
131 }
Michael Kupersteineaa16002015-10-25 08:14:05 +0000132
Ahmed Bougachae85a2d32015-03-26 22:46:58 +0000133 if (LC == RTLIB::UNKNOWN_LIBCALL)
134 report_fatal_error("Unsupported library call operation!");
Mehdi Amini44ede332015-07-09 02:09:04 +0000135 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
136 getPointerTy(DAG.getDataLayout()));
Tim Northoverf1450d82013-01-09 13:18:15 +0000137
138 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000139 TargetLowering::CallLoweringInfo CLI(DAG);
Petar Jovanovic5b436222015-03-23 12:28:13 +0000140 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000141 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +0000142 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000143 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
Petar Jovanovic5b436222015-03-23 12:28:13 +0000144 .setSExtResult(signExtend).setZExtResult(!signExtend);
Michael Gottesman7a801722013-08-13 17:54:56 +0000145 return LowerCallTo(CLI);
Tim Northoverf1450d82013-01-09 13:18:15 +0000146}
147
Sanjay Patelac6e9102015-12-29 22:11:50 +0000148/// Soften the operands of a comparison. This code is shared among BR_CC,
149/// SELECT_CC, and SETCC handlers.
Tim Northoverf1450d82013-01-09 13:18:15 +0000150void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
151 SDValue &NewLHS, SDValue &NewRHS,
152 ISD::CondCode &CCCode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000153 const SDLoc &dl) const {
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000154 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
Tim Northoverf1450d82013-01-09 13:18:15 +0000155 && "Unsupported setcc type!");
156
157 // Expand into one or more soft-fp libcall(s).
158 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
Alexey Bataevb9288602015-07-15 08:39:35 +0000159 bool ShouldInvertCC = false;
Tim Northoverf1450d82013-01-09 13:18:15 +0000160 switch (CCCode) {
161 case ISD::SETEQ:
162 case ISD::SETOEQ:
163 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000164 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
165 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000166 break;
167 case ISD::SETNE:
168 case ISD::SETUNE:
169 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000170 (VT == MVT::f64) ? RTLIB::UNE_F64 :
171 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000172 break;
173 case ISD::SETGE:
174 case ISD::SETOGE:
175 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000176 (VT == MVT::f64) ? RTLIB::OGE_F64 :
177 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000178 break;
179 case ISD::SETLT:
180 case ISD::SETOLT:
181 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000182 (VT == MVT::f64) ? RTLIB::OLT_F64 :
183 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000184 break;
185 case ISD::SETLE:
186 case ISD::SETOLE:
187 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000188 (VT == MVT::f64) ? RTLIB::OLE_F64 :
189 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000190 break;
191 case ISD::SETGT:
192 case ISD::SETOGT:
193 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000194 (VT == MVT::f64) ? RTLIB::OGT_F64 :
195 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000196 break;
197 case ISD::SETUO:
198 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000199 (VT == MVT::f64) ? RTLIB::UO_F64 :
200 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000201 break;
202 case ISD::SETO:
203 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000204 (VT == MVT::f64) ? RTLIB::O_F64 :
205 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000206 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000207 case ISD::SETONE:
208 // SETONE = SETOLT | SETOGT
209 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000210 (VT == MVT::f64) ? RTLIB::OLT_F64 :
211 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000212 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000213 (VT == MVT::f64) ? RTLIB::OGT_F64 :
214 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000215 break;
216 case ISD::SETUEQ:
Tim Northoverf1450d82013-01-09 13:18:15 +0000217 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000218 (VT == MVT::f64) ? RTLIB::UO_F64 :
Eli Friedman98151d62016-08-15 21:46:19 +0000219 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000220 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000221 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
222 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000223 break;
224 default:
225 // Invert CC for unordered comparisons
226 ShouldInvertCC = true;
Tim Northoverf1450d82013-01-09 13:18:15 +0000227 switch (CCCode) {
Alexey Bataevb9288602015-07-15 08:39:35 +0000228 case ISD::SETULT:
229 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000230 (VT == MVT::f64) ? RTLIB::OGE_F64 :
231 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000232 break;
Tim Northoverf1450d82013-01-09 13:18:15 +0000233 case ISD::SETULE:
Alexey Bataevb9288602015-07-15 08:39:35 +0000234 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000235 (VT == MVT::f64) ? RTLIB::OGT_F64 :
236 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000237 break;
238 case ISD::SETUGT:
239 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000240 (VT == MVT::f64) ? RTLIB::OLE_F64 :
241 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000242 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000243 case ISD::SETUGE:
244 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000245 (VT == MVT::f64) ? RTLIB::OLT_F64 :
246 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000247 break;
248 default: llvm_unreachable("Do not know how to soften this setcc!");
249 }
250 }
251
252 // Use the target specific return value for comparions lib calls.
253 EVT RetVT = getCmpLibcallReturnType();
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000254 SDValue Ops[2] = {NewLHS, NewRHS};
Craig Topper8fe40e02015-10-22 17:05:00 +0000255 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
256 dl).first;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000257 NewRHS = DAG.getConstant(0, dl, RetVT);
Alexey Bataevb9288602015-07-15 08:39:35 +0000258
Tim Northoverf1450d82013-01-09 13:18:15 +0000259 CCCode = getCmpLibcallCC(LC1);
Alexey Bataevb9288602015-07-15 08:39:35 +0000260 if (ShouldInvertCC)
261 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
262
Tim Northoverf1450d82013-01-09 13:18:15 +0000263 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000264 SDValue Tmp = DAG.getNode(
265 ISD::SETCC, dl,
266 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
267 NewLHS, NewRHS, DAG.getCondCode(CCCode));
Craig Topper8fe40e02015-10-22 17:05:00 +0000268 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
269 dl).first;
Mehdi Amini44ede332015-07-09 02:09:04 +0000270 NewLHS = DAG.getNode(
271 ISD::SETCC, dl,
272 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
273 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
Tim Northoverf1450d82013-01-09 13:18:15 +0000274 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
275 NewRHS = SDValue();
276 }
277}
278
Sanjay Patelac6e9102015-12-29 22:11:50 +0000279/// Return the entry encoding for a jump table in the current function. The
280/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000281unsigned TargetLowering::getJumpTableEncoding() const {
282 // In non-pic modes, just use the address of a block.
Rafael Espindola12bb38d2016-06-26 22:30:06 +0000283 if (!isPositionIndependent())
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000284 return MachineJumpTableInfo::EK_BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000285
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000286 // In PIC mode, if the target supports a GPRel32 directive, use it.
Craig Topperc0196b12014-04-14 00:51:57 +0000287 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000288 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000289
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000290 // Otherwise, use a label difference.
291 return MachineJumpTableInfo::EK_LabelDifference32;
292}
293
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000294SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
295 SelectionDAG &DAG) const {
Chris Lattner547c7612010-01-26 06:53:37 +0000296 // If our PIC model is GP relative, use the global offset table as the base.
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000297 unsigned JTEncoding = getJumpTableEncoding();
298
299 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
300 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
Mehdi Amini44ede332015-07-09 02:09:04 +0000301 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000302
Evan Cheng797d56f2007-11-09 01:32:10 +0000303 return Table;
304}
305
Sanjay Patelac6e9102015-12-29 22:11:50 +0000306/// This returns the relocation base for the given PIC jumptable, the same as
307/// getPICJumpTableRelocBase, but as an MCExpr.
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000308const MCExpr *
Chris Lattner8a785d72010-01-26 06:28:43 +0000309TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
310 unsigned JTI,MCContext &Ctx) const{
Chris Lattner273735b2010-01-26 05:58:28 +0000311 // The normal PIC reloc base is the label at the start of the jump table.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000312 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000313}
314
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000315bool
316TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000317 const TargetMachine &TM = getTargetMachine();
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000318 const GlobalValue *GV = GA->getGlobal();
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000319
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000320 // If the address is not even local to this DSO we will have to load it from
321 // a got and then add the offset.
Rafael Espindola3beef8d2016-06-27 23:15:57 +0000322 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000323 return false;
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000324
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000325 // If the code is position independent we will have to add a base register.
Rafael Espindola0a68bf92016-06-26 22:38:44 +0000326 if (isPositionIndependent())
Rafael Espindola88ae09e2016-06-24 18:48:36 +0000327 return false;
328
329 // Otherwise we can do it.
330 return true;
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000331}
332
Chris Lattneree1dadb2006-02-04 02:13:02 +0000333//===----------------------------------------------------------------------===//
334// Optimization Methods
335//===----------------------------------------------------------------------===//
336
Sanjay Patelac6e9102015-12-29 22:11:50 +0000337/// Check to see if the specified operand of the specified instruction is a
338/// constant integer. If so, check to see if there are any bits set in the
339/// constant that are not demanded. If so, shrink the constant and return true.
Wesley Peck527da1b2010-11-23 03:31:01 +0000340bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000341 const APInt &Demanded) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000342 SDLoc dl(Op);
Bill Wendling6d271472009-03-04 00:18:06 +0000343
Chris Lattner118ddba2006-02-26 23:36:02 +0000344 // FIXME: ISD::SELECT, ISD::SELECT_CC
Dan Gohmane58ab792009-01-29 01:59:02 +0000345 switch (Op.getOpcode()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000346 default: break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000347 case ISD::XOR:
Bill Wendling6d271472009-03-04 00:18:06 +0000348 case ISD::AND:
349 case ISD::OR: {
350 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
351 if (!C) return false;
352
353 if (Op.getOpcode() == ISD::XOR &&
354 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
355 return false;
356
357 // if we can expand it to have all bits set, do it
358 if (C->getAPIntValue().intersects(~Demanded)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000359 EVT VT = Op.getValueType();
Bill Wendling6d271472009-03-04 00:18:06 +0000360 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
361 DAG.getConstant(Demanded &
Wesley Peck527da1b2010-11-23 03:31:01 +0000362 C->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000363 dl, VT));
Bill Wendling6d271472009-03-04 00:18:06 +0000364 return CombineTo(Op, New);
365 }
366
Nate Begemandc7bba92006-02-03 22:24:05 +0000367 break;
368 }
Bill Wendling6d271472009-03-04 00:18:06 +0000369 }
370
Nate Begemandc7bba92006-02-03 22:24:05 +0000371 return false;
372}
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000373
Sanjay Patelac6e9102015-12-29 22:11:50 +0000374/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
375/// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
376/// generalized for targets with other types of implicit widening casts.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000377bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
378 unsigned BitWidth,
379 const APInt &Demanded,
380 const SDLoc &dl) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000381 assert(Op.getNumOperands() == 2 &&
382 "ShrinkDemandedOp only supports binary operators!");
383 assert(Op.getNode()->getNumValues() == 1 &&
384 "ShrinkDemandedOp only supports nodes with one result!");
385
Hao Liu40914502014-05-29 09:19:07 +0000386 // Early return, as this function cannot handle vector types.
387 if (Op.getValueType().isVector())
388 return false;
389
Dan Gohmanad3e5492009-04-08 00:15:30 +0000390 // Don't do this if the node has another user, which may require the
391 // full value.
392 if (!Op.getNode()->hasOneUse())
393 return false;
394
395 // Search for the smallest integer type with free casts to and from
396 // Op's type. For expedience, just check power-of-2 integer types.
397 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Nadav Rotem33360d82012-12-19 07:39:08 +0000398 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
399 unsigned SmallVTBits = DemandedSize;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000400 if (!isPowerOf2_32(SmallVTBits))
401 SmallVTBits = NextPowerOf2(SmallVTBits);
402 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
Owen Anderson117c9e82009-08-12 00:36:31 +0000403 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000404 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
405 TLI.isZExtFree(SmallVT, Op.getValueType())) {
406 // We found a type with free casts.
407 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
408 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
409 Op.getNode()->getOperand(0)),
410 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
411 Op.getNode()->getOperand(1)));
Nadav Rotem33360d82012-12-19 07:39:08 +0000412 bool NeedZext = DemandedSize > SmallVTBits;
413 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
414 dl, Op.getValueType(), X);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000415 return CombineTo(Op, Z);
416 }
417 }
418 return false;
419}
420
Sanjay Patelac6e9102015-12-29 22:11:50 +0000421/// Look at Op. At this point, we know that only the DemandedMask bits of the
422/// result of Op are ever used downstream. If we can use this information to
423/// simplify Op, create a new simplified DAG node and return true, returning the
424/// original and new nodes in Old and New. Otherwise, analyze the expression and
425/// return a mask of KnownOne and KnownZero bits for the expression (used to
426/// simplify the caller). The KnownZero/One bits may only be accurate for those
427/// bits in the DemandedMask.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000428bool TargetLowering::SimplifyDemandedBits(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000429 const APInt &DemandedMask,
430 APInt &KnownZero,
431 APInt &KnownOne,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000432 TargetLoweringOpt &TLO,
433 unsigned Depth) const {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000434 unsigned BitWidth = DemandedMask.getBitWidth();
Dan Gohman1d459e42009-12-11 21:31:27 +0000435 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000436 "Mask size mismatches value type size!");
437 APInt NewMask = DemandedMask;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000438 SDLoc dl(Op);
Mehdi Amini9639d652015-07-09 02:09:20 +0000439 auto &DL = TLO.DAG.getDataLayout();
Chris Lattner0184f882007-05-17 18:19:23 +0000440
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000441 // Don't know anything.
442 KnownZero = KnownOne = APInt(BitWidth, 0);
443
Nate Begeman8a77efe2006-02-16 21:11:51 +0000444 // Other users may use these bits.
Wesley Peck527da1b2010-11-23 03:31:01 +0000445 if (!Op.getNode()->hasOneUse()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000446 if (Depth != 0) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000447 // If not at the root, Just compute the KnownZero/KnownOne bits to
Nate Begeman8a77efe2006-02-16 21:11:51 +0000448 // simplify things downstream.
Jay Foada0653a32014-05-14 21:14:37 +0000449 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Nate Begeman8a77efe2006-02-16 21:11:51 +0000450 return false;
451 }
452 // If this is the root being simplified, allow it to have multiple uses,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000453 // just set the NewMask to all bits.
454 NewMask = APInt::getAllOnesValue(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000455 } else if (DemandedMask == 0) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000456 // Not demanding any bits from Op.
Sanjay Patel75068522016-03-14 18:09:43 +0000457 if (!Op.isUndef())
Dale Johannesen84935752009-02-06 23:05:02 +0000458 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000459 return false;
460 } else if (Depth == 6) { // Limit search depth.
461 return false;
462 }
463
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000464 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000465 switch (Op.getOpcode()) {
466 case ISD::Constant:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000467 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000468 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
469 KnownZero = ~KnownOne;
Chris Lattner118ddba2006-02-26 23:36:02 +0000470 return false; // Don't fall through, will infinitely loop.
Simon Pilgrimcc7b4b52016-09-08 12:57:51 +0000471 case ISD::BUILD_VECTOR:
472 // Collect the known bits that are shared by every constant vector element.
473 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
474 for (SDValue SrcOp : Op->ops()) {
475 if (!isa<ConstantSDNode>(SrcOp)) {
476 // We can only handle all constant values - bail out with no known bits.
477 KnownZero = KnownOne = APInt(BitWidth, 0);
478 return false;
479 }
480 KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
481 KnownZero2 = ~KnownOne2;
482
483 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
484 if (KnownOne2.getBitWidth() != BitWidth) {
485 assert(KnownOne2.getBitWidth() > BitWidth &&
486 KnownZero2.getBitWidth() > BitWidth &&
487 "Expected BUILD_VECTOR implicit truncation");
488 KnownOne2 = KnownOne2.trunc(BitWidth);
489 KnownZero2 = KnownZero2.trunc(BitWidth);
490 }
491
492 // Known bits are the values that are shared by every element.
493 // TODO: support per-element known bits.
494 KnownOne &= KnownOne2;
495 KnownZero &= KnownZero2;
496 }
497 return false; // Don't fall through, will infinitely loop.
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000498 case ISD::AND:
Chris Lattnera60751d2006-02-27 00:36:27 +0000499 // If the RHS is a constant, check to see if the LHS would be zero without
500 // using the bits from the RHS. Below, we use knowledge about the RHS to
501 // simplify the LHS, here we're using information from the LHS to simplify
502 // the RHS.
503 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000504 APInt LHSZero, LHSOne;
Dale Johannesend2b48112011-01-10 21:53:07 +0000505 // Do not increment Depth here; that can cause an infinite loop.
Jay Foada0653a32014-05-14 21:14:37 +0000506 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
Chris Lattnera60751d2006-02-27 00:36:27 +0000507 // If the LHS already has zeros where RHSC does, this and is dead.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000508 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000509 return TLO.CombineTo(Op, Op.getOperand(0));
510 // If any of the set bits in the RHS are known zero on the LHS, shrink
511 // the constant.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000512 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000513 return true;
514 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000515
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000516 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000517 KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000518 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000519 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000520 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000521 KnownZero2, KnownOne2, TLO, Depth+1))
522 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000523 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
524
Nate Begeman8a77efe2006-02-16 21:11:51 +0000525 // If all of the demanded bits are known one on one side, return the other.
526 // These bits cannot contribute to the result of the 'and'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000527 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000528 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000529 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000530 return TLO.CombineTo(Op, Op.getOperand(1));
531 // If all of the demanded bits in the inputs are known zeros, return zero.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000532 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000533 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000534 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000535 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000536 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000537 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000538 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000539 return true;
540
Nate Begeman8a77efe2006-02-16 21:11:51 +0000541 // Output known-1 bits are only known if set in both the LHS & RHS.
542 KnownOne &= KnownOne2;
543 // Output known-0 are known to be clear if zero in either the LHS | RHS.
544 KnownZero |= KnownZero2;
545 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000546 case ISD::OR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000547 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000548 KnownOne, TLO, Depth+1))
549 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000550 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000551 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000552 KnownZero2, KnownOne2, TLO, Depth+1))
553 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000554 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
555
Nate Begeman8a77efe2006-02-16 21:11:51 +0000556 // If all of the demanded bits are known zero on one side, return the other.
557 // These bits cannot contribute to the result of the 'or'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000558 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000559 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000560 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000561 return TLO.CombineTo(Op, Op.getOperand(1));
562 // If all of the potentially set bits on one side are known to be set on
563 // the other side, just use the 'other' side.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000564 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000565 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000566 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000567 return TLO.CombineTo(Op, Op.getOperand(1));
568 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000569 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000570 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000571 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000572 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000573 return true;
574
Nate Begeman8a77efe2006-02-16 21:11:51 +0000575 // Output known-0 bits are only known if clear in both the LHS & RHS.
576 KnownZero &= KnownZero2;
577 // Output known-1 are known to be set if set in either the LHS | RHS.
578 KnownOne |= KnownOne2;
579 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000580 case ISD::XOR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000581 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000582 KnownOne, TLO, Depth+1))
583 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000584 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000585 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000586 KnownOne2, TLO, Depth+1))
587 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000588 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
589
Nate Begeman8a77efe2006-02-16 21:11:51 +0000590 // If all of the demanded bits are known zero on one side, return the other.
591 // These bits cannot contribute to the result of the 'xor'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000592 if ((KnownZero & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000593 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000594 if ((KnownZero2 & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000595 return TLO.CombineTo(Op, Op.getOperand(1));
Dan Gohmanad3e5492009-04-08 00:15:30 +0000596 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000597 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000598 return true;
599
Chris Lattner5d5916b2006-11-27 21:50:02 +0000600 // If all of the unknown bits are known to be zero on one side or the other
601 // (but not both) turn this into an *inclusive* or.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000602 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000603 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
Dale Johannesen400dc2e2009-02-06 21:50:26 +0000604 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
Chris Lattner5d5916b2006-11-27 21:50:02 +0000605 Op.getOperand(0),
606 Op.getOperand(1)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000607
Nate Begeman8a77efe2006-02-16 21:11:51 +0000608 // Output known-0 bits are known if clear or set in both the LHS & RHS.
609 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
610 // Output known-1 are known to be set if set in only one of the LHS, RHS.
611 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
Wesley Peck527da1b2010-11-23 03:31:01 +0000612
Nate Begeman8a77efe2006-02-16 21:11:51 +0000613 // If all of the demanded bits on one side are known, and all of the set
614 // bits on that side are also known to be set on the other side, turn this
615 // into an AND, as we know the bits will be cleared.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000616 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Joel Jones828531f2012-04-17 22:23:10 +0000617 // NB: it is okay if more bits are known than are requested
Stephen Lincfe7f352013-07-08 00:37:03 +0000618 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
Joel Jones828531f2012-04-17 22:23:10 +0000619 if (KnownOne == KnownOne2) { // set bits are the same on both sides
Owen Anderson53aa7a92009-08-10 22:56:29 +0000620 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000621 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000622 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
Dale Johannesenf1163e92009-02-03 00:47:48 +0000623 Op.getOperand(0), ANDC));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000624 }
625 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000626
Nate Begeman8a77efe2006-02-16 21:11:51 +0000627 // If the RHS is a constant, see if we can simplify it.
Torok Edwin613d7af2008-04-06 21:23:02 +0000628 // for XOR, we prefer to force bits to 1 if they will make a -1.
629 // if we can't force bits, try to shrink constant
630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
631 APInt Expanded = C->getAPIntValue() | (~NewMask);
632 // if we can expand it to have all bits set, do it
633 if (Expanded.isAllOnesValue()) {
634 if (Expanded != C->getAPIntValue()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000635 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000636 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000637 TLO.DAG.getConstant(Expanded, dl, VT));
Torok Edwin613d7af2008-04-06 21:23:02 +0000638 return TLO.CombineTo(Op, New);
639 }
640 // if it already has all the bits set, nothing to change
641 // but don't shrink either!
642 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
643 return true;
644 }
645 }
646
Nate Begeman8a77efe2006-02-16 21:11:51 +0000647 KnownZero = KnownZeroOut;
648 KnownOne = KnownOneOut;
649 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000650 case ISD::SELECT:
Wesley Peck527da1b2010-11-23 03:31:01 +0000651 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000652 KnownOne, TLO, Depth+1))
653 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000654 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000655 KnownOne2, TLO, Depth+1))
656 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000657 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
658 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
659
Nate Begeman8a77efe2006-02-16 21:11:51 +0000660 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000661 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000662 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000663
Nate Begeman8a77efe2006-02-16 21:11:51 +0000664 // Only known if known in both the LHS and RHS.
665 KnownOne &= KnownOne2;
666 KnownZero &= KnownZero2;
667 break;
Chris Lattner118ddba2006-02-26 23:36:02 +0000668 case ISD::SELECT_CC:
Wesley Peck527da1b2010-11-23 03:31:01 +0000669 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +0000670 KnownOne, TLO, Depth+1))
671 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000672 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
Chris Lattner118ddba2006-02-26 23:36:02 +0000673 KnownOne2, TLO, Depth+1))
674 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000675 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
676 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
677
Chris Lattner118ddba2006-02-26 23:36:02 +0000678 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000679 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Chris Lattner118ddba2006-02-26 23:36:02 +0000680 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000681
Chris Lattner118ddba2006-02-26 23:36:02 +0000682 // Only known if known in both the LHS and RHS.
683 KnownOne &= KnownOne2;
684 KnownZero &= KnownZero2;
685 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000686 case ISD::SHL:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000687 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000688 unsigned ShAmt = SA->getZExtValue();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000689 SDValue InOp = Op.getOperand(0);
Chris Lattner9a861a82007-04-17 21:14:16 +0000690
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000691 // If the shift count is an invalid immediate, don't do anything.
692 if (ShAmt >= BitWidth)
693 break;
694
Chris Lattner9a861a82007-04-17 21:14:16 +0000695 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
696 // single shift. We can do this if the bottom bits (which are shifted
697 // out) are never demanded.
698 if (InOp.getOpcode() == ISD::SRL &&
699 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000700 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000701 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000702 unsigned Opc = ISD::SHL;
703 int Diff = ShAmt-C1;
704 if (Diff < 0) {
705 Diff = -Diff;
706 Opc = ISD::SRL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000707 }
708
709 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000710 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Owen Anderson53aa7a92009-08-10 22:56:29 +0000711 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000712 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000713 InOp.getOperand(0), NewSA));
714 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000715 }
716
Dan Gohman08186842010-07-23 18:03:30 +0000717 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
Nate Begeman8a77efe2006-02-16 21:11:51 +0000718 KnownZero, KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000719 return true;
Dan Gohman08186842010-07-23 18:03:30 +0000720
721 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
722 // are not demanded. This will likely allow the anyext to be folded away.
723 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
724 SDValue InnerOp = InOp.getNode()->getOperand(0);
725 EVT InnerVT = InnerOp.getValueType();
Eli Friedman053a7242011-12-09 01:16:26 +0000726 unsigned InnerBits = InnerVT.getSizeInBits();
727 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
Dan Gohman08186842010-07-23 18:03:30 +0000728 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +0000729 EVT ShTy = getShiftAmountTy(InnerVT, DL);
Dan Gohman55e24462010-07-23 21:08:12 +0000730 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
731 ShTy = InnerVT;
Dan Gohman08186842010-07-23 18:03:30 +0000732 SDValue NarrowShl =
733 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000734 TLO.DAG.getConstant(ShAmt, dl, ShTy));
Dan Gohman08186842010-07-23 18:03:30 +0000735 return
736 TLO.CombineTo(Op,
737 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
738 NarrowShl));
739 }
Richard Sandiford374a0e52013-10-16 10:26:19 +0000740 // Repeat the SHL optimization above in cases where an extension
741 // intervenes: (shl (anyext (shr x, c1)), c2) to
742 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
743 // aren't demanded (as above) and that the shifted upper c1 bits of
744 // x aren't demanded.
745 if (InOp.hasOneUse() &&
746 InnerOp.getOpcode() == ISD::SRL &&
747 InnerOp.hasOneUse() &&
748 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
749 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
750 ->getZExtValue();
751 if (InnerShAmt < ShAmt &&
752 InnerShAmt < InnerBits &&
753 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
754 NewMask.trunc(ShAmt) == 0) {
755 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000756 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
Richard Sandiford374a0e52013-10-16 10:26:19 +0000757 Op.getOperand(1).getValueType());
758 EVT VT = Op.getValueType();
759 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
760 InnerOp.getOperand(0));
761 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
762 NewExt, NewSA));
763 }
764 }
Dan Gohman08186842010-07-23 18:03:30 +0000765 }
766
Dan Gohmaneffb8942008-09-12 16:56:44 +0000767 KnownZero <<= SA->getZExtValue();
768 KnownOne <<= SA->getZExtValue();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000769 // low bits known zero.
Dan Gohmaneffb8942008-09-12 16:56:44 +0000770 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000771 }
772 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000773 case ISD::SRL:
774 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000775 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000776 unsigned ShAmt = SA->getZExtValue();
Duncan Sands13237ac2008-06-06 12:08:01 +0000777 unsigned VTSize = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000778 SDValue InOp = Op.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +0000779
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000780 // If the shift count is an invalid immediate, don't do anything.
781 if (ShAmt >= BitWidth)
782 break;
783
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000784 APInt InDemandedMask = (NewMask << ShAmt);
785
786 // If the shift is exact, then it does demand the low bits (and knows that
787 // they are zero).
788 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
789 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
790
Chris Lattner9a861a82007-04-17 21:14:16 +0000791 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
792 // single shift. We can do this if the top bits (which are shifted out)
793 // are never demanded.
794 if (InOp.getOpcode() == ISD::SHL &&
795 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000796 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000797 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000798 unsigned Opc = ISD::SRL;
799 int Diff = ShAmt-C1;
800 if (Diff < 0) {
801 Diff = -Diff;
802 Opc = ISD::SHL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000803 }
804
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000805 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000806 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Dale Johannesenf1163e92009-02-03 00:47:48 +0000807 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000808 InOp.getOperand(0), NewSA));
809 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000810 }
811
Nate Begeman8a77efe2006-02-16 21:11:51 +0000812 // Compute the new bits that are at the top now.
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000813 if (SimplifyDemandedBits(InOp, InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000814 KnownZero, KnownOne, TLO, Depth+1))
815 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000816 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000817 KnownZero = KnownZero.lshr(ShAmt);
818 KnownOne = KnownOne.lshr(ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000819
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000820 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000821 KnownZero |= HighBits; // High bits known zero.
Nate Begeman8a77efe2006-02-16 21:11:51 +0000822 }
823 break;
824 case ISD::SRA:
Dan Gohmane58ab792009-01-29 01:59:02 +0000825 // If this is an arithmetic shift right and only the low-bit is set, we can
826 // always convert this into a logical shr, even if the shift amount is
827 // variable. The low bit of the shift cannot be an input sign bit unless
828 // the shift amount is >= the size of the datatype, which is undefined.
Eli Friedman053a7242011-12-09 01:16:26 +0000829 if (NewMask == 1)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000830 return TLO.CombineTo(Op,
831 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
832 Op.getOperand(0), Op.getOperand(1)));
Dan Gohmane58ab792009-01-29 01:59:02 +0000833
Nate Begeman8a77efe2006-02-16 21:11:51 +0000834 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000835 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000836 unsigned ShAmt = SA->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +0000837
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000838 // If the shift count is an invalid immediate, don't do anything.
839 if (ShAmt >= BitWidth)
840 break;
841
842 APInt InDemandedMask = (NewMask << ShAmt);
Chris Lattner10c65372006-05-08 17:22:53 +0000843
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000844 // If the shift is exact, then it does demand the low bits (and knows that
845 // they are zero).
846 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
847 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
848
Chris Lattner10c65372006-05-08 17:22:53 +0000849 // If any of the demanded bits are produced by the sign extension, we also
850 // demand the input sign bit.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000851 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
852 if (HighBits.intersects(NewMask))
Dan Gohman1d459e42009-12-11 21:31:27 +0000853 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000854
Chris Lattner10c65372006-05-08 17:22:53 +0000855 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000856 KnownZero, KnownOne, TLO, Depth+1))
857 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000859 KnownZero = KnownZero.lshr(ShAmt);
860 KnownOne = KnownOne.lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000861
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000862 // Handle the sign bit, adjusted to where it is now in the mask.
863 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000864
Nate Begeman8a77efe2006-02-16 21:11:51 +0000865 // If the input sign bit is known to be zero, or if none of the top bits
866 // are demanded, turn this into an unsigned shift right.
Benjamin Kramerc2ae7672015-06-26 14:51:49 +0000867 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
868 SDNodeFlags Flags;
869 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
870 return TLO.CombineTo(Op,
871 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
872 Op.getOperand(1), &Flags));
873 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000874
875 int Log2 = NewMask.exactLogBase2();
876 if (Log2 >= 0) {
877 // The bit must come from the sign.
878 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000879 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000880 Op.getOperand(1).getValueType());
881 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
882 Op.getOperand(0), NewSA));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000883 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000884
885 if (KnownOne.intersects(SignBit))
886 // New bits are known one.
887 KnownOne |= HighBits;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000888 }
889 break;
890 case ISD::SIGN_EXTEND_INREG: {
Nadav Rotem57935242012-01-15 19:27:55 +0000891 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
892
893 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
894 // If we only care about the highest bit, don't bother shifting right.
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000895 if (MsbMask == NewMask) {
Nadav Rotem57935242012-01-15 19:27:55 +0000896 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
897 SDValue InOp = Op.getOperand(0);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000898 unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
899 bool AlreadySignExtended =
900 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
901 // However if the input is already sign extended we expect the sign
902 // extension to be dropped altogether later and do not simplify.
903 if (!AlreadySignExtended) {
904 // Compute the correct shift amount type, which must be getShiftAmountTy
905 // for scalar types after legalization.
906 EVT ShiftAmtTy = Op.getValueType();
907 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
Mehdi Amini9639d652015-07-09 02:09:20 +0000908 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
Eli Friedman18a4c312012-01-31 01:08:03 +0000909
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000910 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
911 ShiftAmtTy);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000912 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
913 Op.getValueType(), InOp,
914 ShiftAmt));
915 }
Nadav Rotem57935242012-01-15 19:27:55 +0000916 }
Nate Begeman8a77efe2006-02-16 21:11:51 +0000917
Wesley Peck527da1b2010-11-23 03:31:01 +0000918 // Sign extension. Compute the demanded bits in the result that are not
Nate Begeman8a77efe2006-02-16 21:11:51 +0000919 // present in the input.
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000920 APInt NewBits =
921 APInt::getHighBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000922 BitWidth - ExVT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000923
Chris Lattner118ddba2006-02-26 23:36:02 +0000924 // If none of the extended bits are demanded, eliminate the sextinreg.
Eli Friedman460ad412010-08-02 04:42:25 +0000925 if ((NewBits & NewMask) == 0)
Chris Lattner118ddba2006-02-26 23:36:02 +0000926 return TLO.CombineTo(Op, Op.getOperand(0));
927
Jay Foad583abbc2010-12-07 08:25:19 +0000928 APInt InSignBit =
Nadav Rotem57935242012-01-15 19:27:55 +0000929 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000930 APInt InputDemandedBits =
931 APInt::getLowBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000932 ExVT.getScalarType().getSizeInBits()) &
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000933 NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000934
Chris Lattner118ddba2006-02-26 23:36:02 +0000935 // Since the sign extended bits are demanded, we know that the sign
Nate Begeman8a77efe2006-02-16 21:11:51 +0000936 // bit is demanded.
Chris Lattner118ddba2006-02-26 23:36:02 +0000937 InputDemandedBits |= InSignBit;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000938
939 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
940 KnownZero, KnownOne, TLO, Depth+1))
941 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000942 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Nate Begeman8a77efe2006-02-16 21:11:51 +0000943
944 // If the sign bit of the input is known set or clear, then we know the
945 // top bits of the result.
Wesley Peck527da1b2010-11-23 03:31:01 +0000946
Chris Lattner118ddba2006-02-26 23:36:02 +0000947 // If the input sign bit is known zero, convert this into a zero extension.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000948 if (KnownZero.intersects(InSignBit))
Wesley Peck527da1b2010-11-23 03:31:01 +0000949 return TLO.CombineTo(Op,
Nadav Rotem57935242012-01-15 19:27:55 +0000950 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
Wesley Peck527da1b2010-11-23 03:31:01 +0000951
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000952 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
Nate Begeman8a77efe2006-02-16 21:11:51 +0000953 KnownOne |= NewBits;
954 KnownZero &= ~NewBits;
Chris Lattner118ddba2006-02-26 23:36:02 +0000955 } else { // Input sign bit unknown
Nate Begeman8a77efe2006-02-16 21:11:51 +0000956 KnownZero &= ~NewBits;
957 KnownOne &= ~NewBits;
958 }
959 break;
960 }
Matt Arsenault2adca602014-05-12 17:14:48 +0000961 case ISD::BUILD_PAIR: {
962 EVT HalfVT = Op.getOperand(0).getValueType();
963 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
964
965 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
966 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
967
968 APInt KnownZeroLo, KnownOneLo;
969 APInt KnownZeroHi, KnownOneHi;
970
971 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
972 KnownOneLo, TLO, Depth + 1))
973 return true;
974
975 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
976 KnownOneHi, TLO, Depth + 1))
977 return true;
978
979 KnownZero = KnownZeroLo.zext(BitWidth) |
980 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
981
982 KnownOne = KnownOneLo.zext(BitWidth) |
983 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
984 break;
985 }
Chris Lattner118ddba2006-02-26 23:36:02 +0000986 case ISD::ZERO_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000987 unsigned OperandBitWidth =
988 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000989 APInt InMask = NewMask.trunc(OperandBitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000990
Chris Lattner118ddba2006-02-26 23:36:02 +0000991 // If none of the top bits are demanded, convert this into an any_extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000992 APInt NewBits =
993 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
994 if (!NewBits.intersects(NewMask))
Dale Johannesenf1163e92009-02-03 00:47:48 +0000995 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +0000996 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +0000997 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000998
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000999 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001000 KnownZero, KnownOne, TLO, Depth+1))
1001 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001002 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +00001003 KnownZero = KnownZero.zext(BitWidth);
1004 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +00001005 KnownZero |= NewBits;
1006 break;
1007 }
1008 case ISD::SIGN_EXTEND: {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001009 EVT InVT = Op.getOperand(0).getValueType();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00001010 unsigned InBits = InVT.getScalarType().getSizeInBits();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001011 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
Dan Gohman44b4c072008-03-11 21:29:43 +00001012 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001013 APInt NewBits = ~InMask & NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +00001014
Chris Lattner118ddba2006-02-26 23:36:02 +00001015 // If none of the top bits are demanded, convert this into an any_extend.
1016 if (NewBits == 0)
Dale Johannesenf1163e92009-02-03 00:47:48 +00001017 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1018 Op.getValueType(),
1019 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00001020
Chris Lattner118ddba2006-02-26 23:36:02 +00001021 // Since some of the sign extended bits are demanded, we know that the sign
1022 // bit is demanded.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001023 APInt InDemandedBits = InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +00001024 InDemandedBits |= InSignBit;
Jay Foad583abbc2010-12-07 08:25:19 +00001025 InDemandedBits = InDemandedBits.trunc(InBits);
Wesley Peck527da1b2010-11-23 03:31:01 +00001026
1027 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +00001028 KnownOne, TLO, Depth+1))
1029 return true;
Jay Foad583abbc2010-12-07 08:25:19 +00001030 KnownZero = KnownZero.zext(BitWidth);
1031 KnownOne = KnownOne.zext(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +00001032
Chris Lattner118ddba2006-02-26 23:36:02 +00001033 // If the sign bit is known zero, convert this to a zero extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001034 if (KnownZero.intersects(InSignBit))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001035 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001036 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +00001037 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00001038
Chris Lattner118ddba2006-02-26 23:36:02 +00001039 // If the sign bit is known one, the top bits match.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001040 if (KnownOne.intersects(InSignBit)) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001041 KnownOne |= NewBits;
1042 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +00001043 } else { // Otherwise, top bits aren't known.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001044 assert((KnownOne & NewBits) == 0);
1045 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +00001046 }
1047 break;
1048 }
1049 case ISD::ANY_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00001050 unsigned OperandBitWidth =
1051 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +00001052 APInt InMask = NewMask.trunc(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001053 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001054 KnownZero, KnownOne, TLO, Depth+1))
1055 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001056 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +00001057 KnownZero = KnownZero.zext(BitWidth);
1058 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +00001059 break;
1060 }
Chris Lattner0f649322006-05-05 22:32:12 +00001061 case ISD::TRUNCATE: {
Chris Lattner86a14672006-05-06 00:11:52 +00001062 // Simplify the input, using demanded bit information, and compute the known
1063 // zero/one bits live out.
Dan Gohmanc3c3c682010-03-01 17:59:21 +00001064 unsigned OperandBitWidth =
1065 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +00001066 APInt TruncMask = NewMask.zext(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001067 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
Chris Lattner0f649322006-05-05 22:32:12 +00001068 KnownZero, KnownOne, TLO, Depth+1))
1069 return true;
Jay Foad583abbc2010-12-07 08:25:19 +00001070 KnownZero = KnownZero.trunc(BitWidth);
1071 KnownOne = KnownOne.trunc(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +00001072
Chris Lattner86a14672006-05-06 00:11:52 +00001073 // If the input is only used by this truncate, see if we can shrink it based
1074 // on the known demanded bits.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001075 if (Op.getOperand(0).getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001076 SDValue In = Op.getOperand(0);
Chris Lattner86a14672006-05-06 00:11:52 +00001077 switch (In.getOpcode()) {
1078 default: break;
1079 case ISD::SRL:
1080 // Shrink SRL by a constant if none of the high bits shifted in are
1081 // demanded.
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001082 if (TLO.LegalTypes() &&
1083 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1084 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1085 // undesirable.
1086 break;
1087 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1088 if (!ShAmt)
1089 break;
Owen Anderson9c128342011-04-13 23:22:23 +00001090 SDValue Shift = In.getOperand(1);
1091 if (TLO.LegalTypes()) {
1092 uint64_t ShVal = ShAmt->getZExtValue();
Mehdi Amini9639d652015-07-09 02:09:20 +00001093 Shift = TLO.DAG.getConstant(ShVal, dl,
1094 getShiftAmountTy(Op.getValueType(), DL));
Owen Anderson9c128342011-04-13 23:22:23 +00001095 }
1096
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001097 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1098 OperandBitWidth - BitWidth);
Jay Foad583abbc2010-12-07 08:25:19 +00001099 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001100
1101 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1102 // None of the shifted in bits are needed. Add a truncate of the
1103 // shift input, then shift it.
1104 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001105 Op.getValueType(),
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001106 In.getOperand(0));
1107 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1108 Op.getValueType(),
Wesley Peck527da1b2010-11-23 03:31:01 +00001109 NewTrunc,
Owen Anderson9c128342011-04-13 23:22:23 +00001110 Shift));
Chris Lattner86a14672006-05-06 00:11:52 +00001111 }
1112 break;
1113 }
1114 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001115
1116 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0f649322006-05-05 22:32:12 +00001117 break;
1118 }
Chris Lattner118ddba2006-02-26 23:36:02 +00001119 case ISD::AssertZext: {
Owen Anderson40d756e2011-09-03 00:26:49 +00001120 // AssertZext demands all of the high bits, plus any of the low bits
1121 // demanded by its users.
1122 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1123 APInt InMask = APInt::getLowBitsSet(BitWidth,
1124 VT.getSizeInBits());
1125 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001126 KnownZero, KnownOne, TLO, Depth+1))
1127 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001128 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmand83e3e72010-06-03 20:21:33 +00001129
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001130 KnownZero |= ~InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +00001131 break;
1132 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001133 case ISD::BITCAST:
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001134 // If this is an FP->Int bitcast and if the sign bit is the only
1135 // thing demanded, turn this into a FGETSIGN.
Eli Friedman2ec82492011-12-15 02:07:20 +00001136 if (!TLO.LegalOperations() &&
1137 !Op.getValueType().isVector() &&
Eli Friedman53218b62011-11-09 22:25:12 +00001138 !Op.getOperand(0).getValueType().isVector() &&
Nadav Rotem504cf0c2011-06-12 14:56:55 +00001139 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1140 Op.getOperand(0).getValueType().isFloatingPoint()) {
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001141 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1142 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
Chih-Hung Hsiehed7d81e2015-12-03 22:02:40 +00001143 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1144 Op.getOperand(0).getValueType() != MVT::f128) {
1145 // Cannot eliminate/lower SHL for f128 yet.
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001146 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
Chris Lattnerde272b12007-12-22 21:35:38 +00001147 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1148 // place. We expect the SHL to be eliminated by other optimizations.
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001149 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001150 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1151 if (!OpVTLegal && OpVTSizeInBits > 32)
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001152 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
Duncan Sands13237ac2008-06-06 12:08:01 +00001153 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001154 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
Stuart Hastings4a4e5a22011-05-19 18:48:20 +00001155 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1156 Op.getValueType(),
Chris Lattnerde272b12007-12-22 21:35:38 +00001157 Sign, ShAmt));
1158 }
1159 }
Chris Lattnerde272b12007-12-22 21:35:38 +00001160 break;
Dan Gohmanad3e5492009-04-08 00:15:30 +00001161 case ISD::ADD:
1162 case ISD::MUL:
1163 case ISD::SUB: {
1164 // Add, Sub, and Mul don't demand any bits in positions beyond that
1165 // of the highest bit demanded of them.
1166 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1167 BitWidth - NewMask.countLeadingZeros());
1168 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1169 KnownOne2, TLO, Depth+1))
1170 return true;
1171 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1172 KnownOne2, TLO, Depth+1))
1173 return true;
1174 // See if the operation should be performed at a smaller bit width.
Dan Gohman600f62b2010-06-24 14:30:44 +00001175 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +00001176 return true;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001177 LLVM_FALLTHROUGH;
Dan Gohmanad3e5492009-04-08 00:15:30 +00001178 }
Dan Gohman38dc08f2008-05-06 00:53:29 +00001179 default:
Jay Foada0653a32014-05-14 21:14:37 +00001180 // Just use computeKnownBits to compute output bits.
1181 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Chris Lattnerab816402006-02-27 01:00:42 +00001182 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +00001183 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001184
Chris Lattner118ddba2006-02-26 23:36:02 +00001185 // If we know the value of all of the demanded bits, return this as a
1186 // constant.
Matthias Braun56a78142015-05-20 18:54:02 +00001187 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1188 // Avoid folding to a constant if any OpaqueConstant is involved.
1189 const SDNode *N = Op.getNode();
1190 for (SDNodeIterator I = SDNodeIterator::begin(N),
1191 E = SDNodeIterator::end(N); I != E; ++I) {
1192 SDNode *Op = *I;
1193 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1194 if (C->isOpaque())
1195 return false;
1196 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001197 return TLO.CombineTo(Op,
1198 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
Matthias Braun56a78142015-05-20 18:54:02 +00001199 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001200
Nate Begeman8a77efe2006-02-16 21:11:51 +00001201 return false;
1202}
1203
Sanjay Patelac6e9102015-12-29 22:11:50 +00001204/// Determine which of the bits specified in Mask are known to be either zero or
1205/// one and return them in the KnownZero/KnownOne bitsets.
Jay Foada0653a32014-05-14 21:14:37 +00001206void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1207 APInt &KnownZero,
1208 APInt &KnownOne,
1209 const SelectionDAG &DAG,
1210 unsigned Depth) const {
Chris Lattner6c1321c2006-04-02 06:19:46 +00001211 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1212 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1213 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1214 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
Chris Lattnerf0b24d22006-01-30 04:09:27 +00001215 "Should use MaskedValueIsZero if you don't know whether Op"
1216 " is a target node!");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001217 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
Evan Cheng9cdc16c2005-12-21 23:05:39 +00001218}
Chris Lattner32fef532006-01-26 20:37:03 +00001219
Sanjay Patelac6e9102015-12-29 22:11:50 +00001220/// This method can be implemented by targets that want to expose additional
1221/// information about sign bits to the DAG Combiner.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001222unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
Matt Arsenaultcf6f6882014-04-04 20:13:13 +00001223 const SelectionDAG &,
Chris Lattner7206d742006-05-06 09:27:13 +00001224 unsigned Depth) const {
1225 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1226 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1227 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1228 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1229 "Should use ComputeNumSignBits if you don't know whether Op"
1230 " is a target node!");
1231 return 1;
1232}
1233
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001234bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1235 if (!N)
1236 return false;
1237
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001238 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001239 if (!CN) {
1240 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1241 if (!BV)
1242 return false;
1243
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001244 BitVector UndefElements;
1245 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001246 // Only interested in constant splats, and we don't try to handle undef
1247 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001248 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001249 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001250 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001251
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001252 switch (getBooleanContents(N->getValueType(0))) {
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001253 case UndefinedBooleanContent:
1254 return CN->getAPIntValue()[0];
1255 case ZeroOrOneBooleanContent:
1256 return CN->isOne();
1257 case ZeroOrNegativeOneBooleanContent:
1258 return CN->isAllOnesValue();
1259 }
1260
1261 llvm_unreachable("Invalid boolean contents");
1262}
1263
Michael Kupersteinc97da7f2016-08-01 19:39:49 +00001264SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1265 const SDLoc &DL) const {
1266 unsigned ElementWidth = VT.getScalarSizeInBits();
1267 APInt TrueInt =
1268 getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1269 ? APInt(ElementWidth, 1)
1270 : APInt::getAllOnesValue(ElementWidth);
1271 return DAG.getConstant(TrueInt, DL, VT);
1272}
1273
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001274bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1275 if (!N)
1276 return false;
1277
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001278 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001279 if (!CN) {
1280 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1281 if (!BV)
1282 return false;
1283
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001284 BitVector UndefElements;
1285 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001286 // Only interested in constant splats, and we don't try to handle undef
1287 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001288 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001289 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001290 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001291
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001292 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001293 return !CN->getAPIntValue()[0];
1294
1295 return CN->isNullValue();
1296}
1297
Tom Stellardccdc5392016-01-18 19:55:21 +00001298bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1299 bool SExt) const {
1300 if (VT == MVT::i1)
1301 return N->isOne();
1302
1303 TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1304 switch (Cnt) {
1305 case TargetLowering::ZeroOrOneBooleanContent:
1306 // An extended value of 1 is always true, unless its original type is i1,
1307 // in which case it will be sign extended to -1.
1308 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1309 case TargetLowering::UndefinedBooleanContent:
1310 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1311 return N->isAllOnesValue() && SExt;
1312 }
Simon Pilgrimc4d519d2016-01-18 22:54:46 +00001313 llvm_unreachable("Unexpected enumeration.");
Tom Stellardccdc5392016-01-18 19:55:21 +00001314}
1315
Sanjay Patel91592562016-05-09 16:42:50 +00001316/// This helper function of SimplifySetCC tries to optimize the comparison when
1317/// either operand of the SetCC node is a bitwise-and instruction.
1318SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1319 ISD::CondCode Cond,
1320 DAGCombinerInfo &DCI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001321 const SDLoc &DL) const {
Sanjay Patelc2751e72016-05-07 15:03:40 +00001322 // Match these patterns in any of their permutations:
1323 // (X & Y) == Y
1324 // (X & Y) != Y
1325 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1326 std::swap(N0, N1);
1327
Sanjay Patel91592562016-05-09 16:42:50 +00001328 EVT OpVT = N0.getValueType();
1329 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
Sanjay Patelc2751e72016-05-07 15:03:40 +00001330 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1331 return SDValue();
1332
1333 SDValue X, Y;
1334 if (N0.getOperand(0) == N1) {
1335 X = N0.getOperand(1);
1336 Y = N0.getOperand(0);
1337 } else if (N0.getOperand(1) == N1) {
1338 X = N0.getOperand(0);
1339 Y = N0.getOperand(1);
1340 } else {
1341 return SDValue();
1342 }
1343
Sanjay Patel91592562016-05-09 16:42:50 +00001344 SelectionDAG &DAG = DCI.DAG;
1345 SDValue Zero = DAG.getConstant(0, DL, OpVT);
Sanjay Patelf39f42d2016-05-19 15:53:52 +00001346 if (DAG.isKnownToBeAPowerOfTwo(Y)) {
Sanjay Patel91592562016-05-09 16:42:50 +00001347 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1348 // Note that where Y is variable and is known to have at most one bit set
1349 // (for example, if it is Z & 1) we cannot do this; the expressions are not
1350 // equivalent when Y == 0.
1351 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1352 if (DCI.isBeforeLegalizeOps() ||
1353 isCondCodeLegal(Cond, N0.getSimpleValueType()))
1354 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1355 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1356 // If the target supports an 'and-not' or 'and-complement' logic operation,
1357 // try to use that to make a comparison operation more efficient.
1358 // But don't do this transform if the mask is a single bit because there are
1359 // more efficient ways to deal with that case (for example, 'bt' on x86 or
1360 // 'rlwinm' on PPC).
Sanjay Patelc2751e72016-05-07 15:03:40 +00001361
Sanjay Patel91592562016-05-09 16:42:50 +00001362 // Bail out if the compare operand that we want to turn into a zero is
1363 // already a zero (otherwise, infinite loop).
1364 auto *YConst = dyn_cast<ConstantSDNode>(Y);
1365 if (YConst && YConst->isNullValue())
1366 return SDValue();
Sanjay Patelc2751e72016-05-07 15:03:40 +00001367
Sanjay Patel91592562016-05-09 16:42:50 +00001368 // Transform this into: ~X & Y == 0.
1369 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1370 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1371 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1372 }
1373
1374 return SDValue();
Sanjay Patelc2751e72016-05-07 15:03:40 +00001375}
1376
Sanjay Patelac6e9102015-12-29 22:11:50 +00001377/// Try to simplify a setcc built with the specified operands and cc. If it is
1378/// unable to simplify it, return a null SDValue.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001379SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1380 ISD::CondCode Cond, bool foldBooleans,
1381 DAGCombinerInfo &DCI,
1382 const SDLoc &dl) const {
Evan Cheng92658d52007-02-08 22:13:59 +00001383 SelectionDAG &DAG = DCI.DAG;
1384
1385 // These setcc operations always fold.
1386 switch (Cond) {
1387 default: break;
1388 case ISD::SETFALSE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001389 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001390 case ISD::SETTRUE:
Tim Northover950fcc02013-09-06 12:38:12 +00001391 case ISD::SETTRUE2: {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001392 TargetLowering::BooleanContent Cnt =
1393 getBooleanContents(N0->getValueType(0));
Tim Northover950fcc02013-09-06 12:38:12 +00001394 return DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001395 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1396 VT);
Tim Northover950fcc02013-09-06 12:38:12 +00001397 }
Evan Cheng92658d52007-02-08 22:13:59 +00001398 }
1399
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001400 // Ensure that the constant occurs on the RHS, and fold constant
1401 // comparisons.
Tom Stellardcd428182013-09-28 02:50:38 +00001402 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1403 if (isa<ConstantSDNode>(N0.getNode()) &&
1404 (DCI.isBeforeLegalizeOps() ||
1405 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1406 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00001407
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001408 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
Dan Gohman2fa65b72008-03-03 22:22:56 +00001409 const APInt &C1 = N1C->getAPIntValue();
Dale Johannesen7aad5422008-11-07 01:28:02 +00001410
Eli Friedman65919b52009-07-26 23:47:17 +00001411 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1412 // equality comparison, then we're just comparing whether X itself is
1413 // zero.
1414 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1415 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1416 N0.getOperand(1).getOpcode() == ISD::Constant) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001417 const APInt &ShAmt
1418 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001419 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1420 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1421 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1422 // (srl (ctlz x), 5) == 0 -> X != 0
1423 // (srl (ctlz x), 5) != 1 -> X != 0
1424 Cond = ISD::SETNE;
1425 } else {
1426 // (srl (ctlz x), 5) != 0 -> X == 0
1427 // (srl (ctlz x), 5) == 1 -> X == 0
1428 Cond = ISD::SETEQ;
1429 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001430 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
Eli Friedman65919b52009-07-26 23:47:17 +00001431 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1432 Zero, Cond);
1433 }
1434 }
1435
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001436 SDValue CTPOP = N0;
1437 // Look through truncs that don't change the value of a ctpop.
1438 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1439 CTPOP = N0.getOperand(0);
1440
1441 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
Benjamin Kramer45d183c2011-01-17 18:00:28 +00001442 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001443 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1444 EVT CTVT = CTPOP.getValueType();
1445 SDValue CTOp = CTPOP.getOperand(0);
1446
1447 // (ctpop x) u< 2 -> (x & x-1) == 0
1448 // (ctpop x) u> 1 -> (x & x-1) != 0
1449 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1450 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001451 DAG.getConstant(1, dl, CTVT));
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001452 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1453 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001454 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001455 }
1456
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001457 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001458 }
1459
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001460 // (zext x) == C --> x == (trunc C)
Matt Arsenault22b4c252014-12-21 16:48:42 +00001461 // (sext x) == C --> x == (trunc C)
1462 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1463 DCI.isBeforeLegalize() && N0->hasOneUse()) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001464 unsigned MinBits = N0.getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001465 SDValue PreExt;
1466 bool Signed = false;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001467 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1468 // ZExt
1469 MinBits = N0->getOperand(0).getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001470 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001471 } else if (N0->getOpcode() == ISD::AND) {
1472 // DAGCombine turns costly ZExts into ANDs
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001473 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001474 if ((C->getAPIntValue()+1).isPowerOf2()) {
1475 MinBits = C->getAPIntValue().countTrailingOnes();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001476 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001477 }
Matt Arsenault22b4c252014-12-21 16:48:42 +00001478 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1479 // SExt
1480 MinBits = N0->getOperand(0).getValueSizeInBits();
1481 PreExt = N0->getOperand(0);
1482 Signed = true;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001483 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
Matt Arsenault22b4c252014-12-21 16:48:42 +00001484 // ZEXTLOAD / SEXTLOAD
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001485 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1486 MinBits = LN0->getMemoryVT().getSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001487 PreExt = N0;
1488 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1489 Signed = true;
1490 MinBits = LN0->getMemoryVT().getSizeInBits();
1491 PreExt = N0;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001492 }
1493 }
1494
Matt Arsenault22b4c252014-12-21 16:48:42 +00001495 // Figure out how many bits we need to preserve this constant.
1496 unsigned ReqdBits = Signed ?
1497 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1498 C1.getActiveBits();
1499
Benjamin Kramerbde91762012-06-02 10:20:22 +00001500 // Make sure we're not losing bits from the constant.
Benjamin Kramer8aaf1972013-05-21 08:51:09 +00001501 if (MinBits > 0 &&
Matt Arsenault22b4c252014-12-21 16:48:42 +00001502 MinBits < C1.getBitWidth() &&
1503 MinBits >= ReqdBits) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001504 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1505 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1506 // Will get folded away.
Matt Arsenault22b4c252014-12-21 16:48:42 +00001507 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
Elena Demikhovsky2c0780b2016-07-19 07:14:21 +00001508 if (MinBits == 1 && C1 == 1)
1509 // Invert the condition.
1510 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
1511 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001512 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001513 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1514 }
Tom Stellardccdc5392016-01-18 19:55:21 +00001515
1516 // If truncating the setcc operands is not desirable, we can still
1517 // simplify the expression in some cases:
1518 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1519 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1520 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1521 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1522 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1523 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1524 SDValue TopSetCC = N0->getOperand(0);
1525 unsigned N0Opc = N0->getOpcode();
1526 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1527 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1528 TopSetCC.getOpcode() == ISD::SETCC &&
1529 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1530 (isConstFalseVal(N1C) ||
1531 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1532
1533 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1534 (!N1C->isNullValue() && Cond == ISD::SETNE);
1535
1536 if (!Inverse)
1537 return TopSetCC;
1538
1539 ISD::CondCode InvCond = ISD::getSetCCInverse(
1540 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1541 TopSetCC.getOperand(0).getValueType().isInteger());
1542 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1543 TopSetCC.getOperand(1),
1544 InvCond);
1545
1546 }
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001547 }
1548 }
1549
Eli Friedman65919b52009-07-26 23:47:17 +00001550 // If the LHS is '(and load, const)', the RHS is 0,
1551 // the test is for equality or unsigned, and all 1 bits of the const are
1552 // in the same partial word, see if we can shorten the load.
1553 if (DCI.isBeforeLegalize() &&
Eli Friedmana961d692013-09-24 22:50:14 +00001554 !ISD::isSignedIntSetCC(Cond) &&
Eli Friedman65919b52009-07-26 23:47:17 +00001555 N0.getOpcode() == ISD::AND && C1 == 0 &&
1556 N0.getNode()->hasOneUse() &&
1557 isa<LoadSDNode>(N0.getOperand(0)) &&
1558 N0.getOperand(0).getNode()->hasOneUse() &&
1559 isa<ConstantSDNode>(N0.getOperand(1))) {
1560 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
Evan Cheng16b75ce2010-01-07 20:58:44 +00001561 APInt bestMask;
Eli Friedman65919b52009-07-26 23:47:17 +00001562 unsigned bestWidth = 0, bestOffset = 0;
Evan Cheng16b75ce2010-01-07 20:58:44 +00001563 if (!Lod->isVolatile() && Lod->isUnindexed()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001564 unsigned origWidth = N0.getValueType().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001565 unsigned maskWidth = origWidth;
Wesley Peck527da1b2010-11-23 03:31:01 +00001566 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
Eli Friedman65919b52009-07-26 23:47:17 +00001567 // 8 bits, but have to be careful...
1568 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1569 origWidth = Lod->getMemoryVT().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001570 const APInt &Mask =
1571 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001572 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001573 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
Eli Friedman65919b52009-07-26 23:47:17 +00001574 for (unsigned offset=0; offset<origWidth/width; offset++) {
1575 if ((newMask & Mask) == Mask) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00001576 if (!DAG.getDataLayout().isLittleEndian())
Eli Friedman65919b52009-07-26 23:47:17 +00001577 bestOffset = (origWidth/width - offset - 1) * (width/8);
1578 else
1579 bestOffset = (uint64_t)offset * (width/8);
Evan Cheng16b75ce2010-01-07 20:58:44 +00001580 bestMask = Mask.lshr(offset * (width/8) * 8);
Eli Friedman65919b52009-07-26 23:47:17 +00001581 bestWidth = width;
1582 break;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001583 }
Eli Friedman65919b52009-07-26 23:47:17 +00001584 newMask = newMask << width;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001585 }
1586 }
1587 }
Eli Friedman65919b52009-07-26 23:47:17 +00001588 if (bestWidth) {
Chris Lattner493b3e72011-04-14 04:12:47 +00001589 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
Eli Friedman65919b52009-07-26 23:47:17 +00001590 if (newVT.isRound()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001591 EVT PtrType = Lod->getOperand(1).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001592 SDValue Ptr = Lod->getBasePtr();
1593 if (bestOffset != 0)
1594 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001595 DAG.getConstant(bestOffset, dl, PtrType));
Eli Friedman65919b52009-07-26 23:47:17 +00001596 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
Justin Lebar9c375812016-07-15 18:27:10 +00001597 SDValue NewLoad = DAG.getLoad(
1598 newVT, dl, Lod->getChain(), Ptr,
1599 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
Wesley Peck527da1b2010-11-23 03:31:01 +00001600 return DAG.getSetCC(dl, VT,
Eli Friedman65919b52009-07-26 23:47:17 +00001601 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
Evan Cheng16b75ce2010-01-07 20:58:44 +00001602 DAG.getConstant(bestMask.trunc(bestWidth),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001603 dl, newVT)),
1604 DAG.getConstant(0LL, dl, newVT), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001605 }
Eli Friedman65919b52009-07-26 23:47:17 +00001606 }
1607 }
Evan Cheng92658d52007-02-08 22:13:59 +00001608
Eli Friedman65919b52009-07-26 23:47:17 +00001609 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1610 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1611 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1612
1613 // If the comparison constant has bits in the upper part, the
1614 // zero-extended value could never match.
1615 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1616 C1.getBitWidth() - InSize))) {
Evan Cheng92658d52007-02-08 22:13:59 +00001617 switch (Cond) {
Evan Cheng92658d52007-02-08 22:13:59 +00001618 case ISD::SETUGT:
1619 case ISD::SETUGE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001620 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001621 case ISD::SETULT:
Eli Friedman65919b52009-07-26 23:47:17 +00001622 case ISD::SETULE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001623 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001624 case ISD::SETGT:
1625 case ISD::SETGE:
1626 // True if the sign bit of C1 is set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001627 return DAG.getConstant(C1.isNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001628 case ISD::SETLT:
1629 case ISD::SETLE:
1630 // True if the sign bit of C1 isn't set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001631 return DAG.getConstant(C1.isNonNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001632 default:
Jakob Stoklund Olesen1ae07362009-07-24 18:22:59 +00001633 break;
1634 }
Eli Friedman65919b52009-07-26 23:47:17 +00001635 }
Evan Cheng92658d52007-02-08 22:13:59 +00001636
Eli Friedman65919b52009-07-26 23:47:17 +00001637 // Otherwise, we can perform the comparison with the low bits.
1638 switch (Cond) {
1639 case ISD::SETEQ:
1640 case ISD::SETNE:
1641 case ISD::SETUGT:
1642 case ISD::SETUGE:
1643 case ISD::SETULT:
1644 case ISD::SETULE: {
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001645 EVT newVT = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001646 if (DCI.isBeforeLegalizeOps() ||
1647 (isOperationLegal(ISD::SETCC, newVT) &&
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001648 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001649 EVT NewSetCCVT =
1650 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001651 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001652
1653 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1654 NewConst, Cond);
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001655 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001656 }
Eli Friedman65919b52009-07-26 23:47:17 +00001657 break;
1658 }
1659 default:
1660 break; // todo, be more careful with signed comparisons
1661 }
1662 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Evan Cheng228c31f2010-02-27 07:36:59 +00001663 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001664 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
Eli Friedman65919b52009-07-26 23:47:17 +00001665 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
Owen Anderson53aa7a92009-08-10 22:56:29 +00001666 EVT ExtDstTy = N0.getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001667 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1668
Eli Friedmanffe64c02010-07-30 06:44:31 +00001669 // If the constant doesn't fit into the number of bits for the source of
1670 // the sign extension, it is impossible for both sides to be equal.
1671 if (C1.getMinSignedBits() > ExtSrcTyBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001672 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +00001673
Eli Friedman65919b52009-07-26 23:47:17 +00001674 SDValue ZextOp;
Owen Anderson53aa7a92009-08-10 22:56:29 +00001675 EVT Op0Ty = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001676 if (Op0Ty == ExtSrcTy) {
1677 ZextOp = N0.getOperand(0);
1678 } else {
1679 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1680 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001681 DAG.getConstant(Imm, dl, Op0Ty));
Eli Friedman65919b52009-07-26 23:47:17 +00001682 }
1683 if (!DCI.isCalledByLegalizer())
1684 DCI.AddToWorklist(ZextOp.getNode());
1685 // Otherwise, make this a use of a zext.
Wesley Peck527da1b2010-11-23 03:31:01 +00001686 return DAG.getSetCC(dl, VT, ZextOp,
Eli Friedman65919b52009-07-26 23:47:17 +00001687 DAG.getConstant(C1 & APInt::getLowBitsSet(
1688 ExtDstTyBits,
Wesley Peck527da1b2010-11-23 03:31:01 +00001689 ExtSrcTyBits),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001690 dl, ExtDstTy),
Eli Friedman65919b52009-07-26 23:47:17 +00001691 Cond);
1692 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1693 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Eli Friedman65919b52009-07-26 23:47:17 +00001694 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00001695 if (N0.getOpcode() == ISD::SETCC &&
1696 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001697 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
Eli Friedman65919b52009-07-26 23:47:17 +00001698 if (TrueWhenTrue)
Wesley Peck527da1b2010-11-23 03:31:01 +00001699 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
Eli Friedman65919b52009-07-26 23:47:17 +00001700 // Invert the condition.
1701 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Wesley Peck527da1b2010-11-23 03:31:01 +00001702 CC = ISD::getSetCCInverse(CC,
Eli Friedman65919b52009-07-26 23:47:17 +00001703 N0.getOperand(0).getValueType().isInteger());
Tom Stellardcd428182013-09-28 02:50:38 +00001704 if (DCI.isBeforeLegalizeOps() ||
1705 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1706 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
Evan Cheng92658d52007-02-08 22:13:59 +00001707 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001708
Eli Friedman65919b52009-07-26 23:47:17 +00001709 if ((N0.getOpcode() == ISD::XOR ||
Wesley Peck527da1b2010-11-23 03:31:01 +00001710 (N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001711 N0.getOperand(0).getOpcode() == ISD::XOR &&
1712 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1713 isa<ConstantSDNode>(N0.getOperand(1)) &&
1714 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1715 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1716 // can only do this if the top bits are known zero.
1717 unsigned BitWidth = N0.getValueSizeInBits();
1718 if (DAG.MaskedValueIsZero(N0,
1719 APInt::getHighBitsSet(BitWidth,
1720 BitWidth-1))) {
1721 // Okay, get the un-inverted input value.
1722 SDValue Val;
1723 if (N0.getOpcode() == ISD::XOR)
1724 Val = N0.getOperand(0);
1725 else {
Wesley Peck527da1b2010-11-23 03:31:01 +00001726 assert(N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001727 N0.getOperand(0).getOpcode() == ISD::XOR);
1728 // ((X^1)&1)^1 -> X & 1
1729 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1730 N0.getOperand(0).getOperand(0),
1731 N0.getOperand(1));
1732 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001733
Eli Friedman65919b52009-07-26 23:47:17 +00001734 return DAG.getSetCC(dl, VT, Val, N1,
1735 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1736 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001737 } else if (N1C->getAPIntValue() == 1 &&
1738 (VT == MVT::i1 ||
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001739 getBooleanContents(N0->getValueType(0)) ==
1740 ZeroOrOneBooleanContent)) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001741 SDValue Op0 = N0;
1742 if (Op0.getOpcode() == ISD::TRUNCATE)
1743 Op0 = Op0.getOperand(0);
1744
1745 if ((Op0.getOpcode() == ISD::XOR) &&
1746 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1747 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1748 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1749 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1750 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1751 Cond);
Craig Topper63f59212012-12-19 06:12:28 +00001752 }
1753 if (Op0.getOpcode() == ISD::AND &&
1754 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1755 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001756 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001757 if (Op0.getValueType().bitsGT(VT))
Evan Cheng228c31f2010-02-27 07:36:59 +00001758 Op0 = DAG.getNode(ISD::AND, dl, VT,
1759 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001760 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001761 else if (Op0.getValueType().bitsLT(VT))
1762 Op0 = DAG.getNode(ISD::AND, dl, VT,
1763 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001764 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001765
Evan Cheng228c31f2010-02-27 07:36:59 +00001766 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001767 DAG.getConstant(0, dl, Op0.getValueType()),
Evan Cheng228c31f2010-02-27 07:36:59 +00001768 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1769 }
Craig Topper63f59212012-12-19 06:12:28 +00001770 if (Op0.getOpcode() == ISD::AssertZext &&
1771 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1772 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001773 DAG.getConstant(0, dl, Op0.getValueType()),
Craig Topper63f59212012-12-19 06:12:28 +00001774 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001775 }
Eli Friedman65919b52009-07-26 23:47:17 +00001776 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001777
Eli Friedman65919b52009-07-26 23:47:17 +00001778 APInt MinVal, MaxVal;
1779 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1780 if (ISD::isSignedIntSetCC(Cond)) {
1781 MinVal = APInt::getSignedMinValue(OperandBitSize);
1782 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1783 } else {
1784 MinVal = APInt::getMinValue(OperandBitSize);
1785 MaxVal = APInt::getMaxValue(OperandBitSize);
1786 }
Evan Cheng92658d52007-02-08 22:13:59 +00001787
Eli Friedman65919b52009-07-26 23:47:17 +00001788 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1789 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001790 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001791 // X >= C0 --> X > (C0 - 1)
1792 APInt C = C1 - 1;
1793 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1794 if ((DCI.isBeforeLegalizeOps() ||
1795 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1796 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1797 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001798 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001799 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001800 NewCC);
1801 }
Eli Friedman65919b52009-07-26 23:47:17 +00001802 }
Evan Cheng92658d52007-02-08 22:13:59 +00001803
Eli Friedman65919b52009-07-26 23:47:17 +00001804 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001805 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001806 // X <= C0 --> X < (C0 + 1)
1807 APInt C = C1 + 1;
1808 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1809 if ((DCI.isBeforeLegalizeOps() ||
1810 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1811 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1812 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001813 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001814 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001815 NewCC);
1816 }
Eli Friedman65919b52009-07-26 23:47:17 +00001817 }
Evan Cheng92658d52007-02-08 22:13:59 +00001818
Eli Friedman65919b52009-07-26 23:47:17 +00001819 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001820 return DAG.getConstant(0, dl, VT); // X < MIN --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001821 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001822 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Eli Friedman65919b52009-07-26 23:47:17 +00001823 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001824 return DAG.getConstant(0, dl, VT); // X > MAX --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001825 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001826 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Evan Cheng92658d52007-02-08 22:13:59 +00001827
Eli Friedman65919b52009-07-26 23:47:17 +00001828 // Canonicalize setgt X, Min --> setne X, Min
1829 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1830 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1831 // Canonicalize setlt X, Max --> setne X, Max
1832 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1833 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
Evan Cheng92658d52007-02-08 22:13:59 +00001834
Eli Friedman65919b52009-07-26 23:47:17 +00001835 // If we have setult X, 1, turn it into seteq X, 0
1836 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001837 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001838 DAG.getConstant(MinVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001839 ISD::SETEQ);
1840 // If we have setugt X, Max-1, turn it into seteq X, Max
Craig Topper3f194c82012-12-19 06:43:58 +00001841 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001842 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001843 DAG.getConstant(MaxVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001844 ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001845
Eli Friedman65919b52009-07-26 23:47:17 +00001846 // If we have "setcc X, C0", check to see if we can shrink the immediate
1847 // by changing cc.
Evan Cheng92658d52007-02-08 22:13:59 +00001848
Eli Friedman65919b52009-07-26 23:47:17 +00001849 // SETUGT X, SINTMAX -> SETLT X, 0
Wesley Peck527da1b2010-11-23 03:31:01 +00001850 if (Cond == ISD::SETUGT &&
Eli Friedman65919b52009-07-26 23:47:17 +00001851 C1 == APInt::getSignedMaxValue(OperandBitSize))
Wesley Peck527da1b2010-11-23 03:31:01 +00001852 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001853 DAG.getConstant(0, dl, N1.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001854 ISD::SETLT);
Evan Cheng92658d52007-02-08 22:13:59 +00001855
Eli Friedman65919b52009-07-26 23:47:17 +00001856 // SETULT X, SINTMIN -> SETGT X, -1
1857 if (Cond == ISD::SETULT &&
1858 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1859 SDValue ConstMinusOne =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001860 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
Eli Friedman65919b52009-07-26 23:47:17 +00001861 N1.getValueType());
1862 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1863 }
Evan Cheng92658d52007-02-08 22:13:59 +00001864
Eli Friedman65919b52009-07-26 23:47:17 +00001865 // Fold bit comparisons when we can.
1866 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Evan Cheng166a4e62010-01-06 19:38:29 +00001867 (VT == N0.getValueType() ||
1868 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001869 N0.getOpcode() == ISD::AND) {
1870 auto &DL = DAG.getDataLayout();
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001871 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001872 EVT ShiftTy = DCI.isBeforeLegalize()
1873 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001874 : getShiftAmountTy(N0.getValueType(), DL);
Eli Friedman65919b52009-07-26 23:47:17 +00001875 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1876 // Perform the xform if the AND RHS is a single bit.
Evan Cheng16b75ce2010-01-07 20:58:44 +00001877 if (AndRHS->getAPIntValue().isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001878 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1879 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001880 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1881 ShiftTy)));
Eli Friedman65919b52009-07-26 23:47:17 +00001882 }
Evan Cheng16b75ce2010-01-07 20:58:44 +00001883 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001884 // (X & 8) == 8 --> (X & 8) >> 3
1885 // Perform the xform if C1 is a single bit.
1886 if (C1.isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001887 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1888 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001889 DAG.getConstant(C1.logBase2(), dl,
1890 ShiftTy)));
Evan Cheng92658d52007-02-08 22:13:59 +00001891 }
1892 }
Eli Friedman65919b52009-07-26 23:47:17 +00001893 }
Mehdi Amini44ede332015-07-09 02:09:04 +00001894 }
Evan Chengf579bec2012-07-17 06:53:39 +00001895
Evan Cheng47d7be92012-07-17 07:47:50 +00001896 if (C1.getMinSignedBits() <= 64 &&
1897 !isLegalICmpImmediate(C1.getSExtValue())) {
Evan Chengf579bec2012-07-17 06:53:39 +00001898 // (X & -256) == 256 -> (X >> 8) == 1
1899 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1900 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001901 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Chengf579bec2012-07-17 06:53:39 +00001902 const APInt &AndRHSC = AndRHS->getAPIntValue();
1903 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1904 unsigned ShiftBits = AndRHSC.countTrailingZeros();
Mehdi Amini44ede332015-07-09 02:09:04 +00001905 auto &DL = DAG.getDataLayout();
1906 EVT ShiftTy = DCI.isBeforeLegalize()
1907 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001908 : getShiftAmountTy(N0.getValueType(), DL);
Evan Chengf579bec2012-07-17 06:53:39 +00001909 EVT CmpTy = N0.getValueType();
1910 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001911 DAG.getConstant(ShiftBits, dl,
1912 ShiftTy));
1913 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
Evan Chengf579bec2012-07-17 06:53:39 +00001914 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1915 }
1916 }
Evan Cheng780f9b52012-07-17 08:31:11 +00001917 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1918 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1919 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1920 // X < 0x100000000 -> (X >> 32) < 1
1921 // X >= 0x100000000 -> (X >> 32) >= 1
1922 // X <= 0x0ffffffff -> (X >> 32) < 1
1923 // X > 0x0ffffffff -> (X >> 32) >= 1
1924 unsigned ShiftBits;
1925 APInt NewC = C1;
1926 ISD::CondCode NewCond = Cond;
1927 if (AdjOne) {
1928 ShiftBits = C1.countTrailingOnes();
1929 NewC = NewC + 1;
1930 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1931 } else {
1932 ShiftBits = C1.countTrailingZeros();
1933 }
1934 NewC = NewC.lshr(ShiftBits);
Pawel Bylica8011da92015-05-20 17:21:09 +00001935 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1936 isLegalICmpImmediate(NewC.getSExtValue())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001937 auto &DL = DAG.getDataLayout();
1938 EVT ShiftTy = DCI.isBeforeLegalize()
1939 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001940 : getShiftAmountTy(N0.getValueType(), DL);
Evan Cheng780f9b52012-07-17 08:31:11 +00001941 EVT CmpTy = N0.getValueType();
1942 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001943 DAG.getConstant(ShiftBits, dl, ShiftTy));
1944 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
Evan Cheng780f9b52012-07-17 08:31:11 +00001945 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1946 }
Evan Chengf579bec2012-07-17 06:53:39 +00001947 }
1948 }
Evan Cheng92658d52007-02-08 22:13:59 +00001949 }
1950
Gabor Greiff304a7a2008-08-28 21:40:38 +00001951 if (isa<ConstantFPSDNode>(N0.getNode())) {
Evan Cheng92658d52007-02-08 22:13:59 +00001952 // Constant fold or commute setcc.
Dale Johannesenf1163e92009-02-03 00:47:48 +00001953 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001954 if (O.getNode()) return O;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001955 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
Chris Lattner3b6a8212007-12-29 08:37:08 +00001956 // If the RHS of an FP comparison is a constant, simplify it away in
1957 // some cases.
1958 if (CFP->getValueAPF().isNaN()) {
1959 // If an operand is known to be a nan, we can fold it.
1960 switch (ISD::getUnorderedFlavor(Cond)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001961 default: llvm_unreachable("Unknown flavor!");
Chris Lattner3b6a8212007-12-29 08:37:08 +00001962 case 0: // Known false.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001963 return DAG.getConstant(0, dl, VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001964 case 1: // Known true.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001965 return DAG.getConstant(1, dl, VT);
Chris Lattner96317d22007-12-30 21:21:10 +00001966 case 2: // Undefined.
Dale Johannesen84935752009-02-06 23:05:02 +00001967 return DAG.getUNDEF(VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001968 }
1969 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001970
Chris Lattner3b6a8212007-12-29 08:37:08 +00001971 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1972 // constant if knowing that the operand is non-nan is enough. We prefer to
1973 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1974 // materialize 0.0.
1975 if (Cond == ISD::SETO || Cond == ISD::SETUO)
Dale Johannesenf1163e92009-02-03 00:47:48 +00001976 return DAG.getSetCC(dl, VT, N0, N0, Cond);
Dan Gohman832800a2009-09-26 15:24:17 +00001977
1978 // If the condition is not legal, see if we can find an equivalent one
1979 // which is legal.
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001980 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
Dan Gohman832800a2009-09-26 15:24:17 +00001981 // If the comparison was an awkward floating-point == or != and one of
1982 // the comparison operands is infinity or negative infinity, convert the
1983 // condition to a less-awkward <= or >=.
1984 if (CFP->getValueAPF().isInfinity()) {
1985 if (CFP->getValueAPF().isNegative()) {
1986 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001987 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001988 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1989 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001990 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001991 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1992 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001993 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001994 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1995 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001996 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001997 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1998 } else {
1999 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002000 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00002001 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2002 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002003 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00002004 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2005 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002006 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00002007 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2008 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002009 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00002010 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2011 }
2012 }
2013 }
Evan Cheng92658d52007-02-08 22:13:59 +00002014 }
2015
2016 if (N0 == N1) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00002017 // The sext(setcc()) => setcc() optimization relies on the appropriate
2018 // constant being emitted.
Nadav Rotema8e15b02012-09-06 11:13:55 +00002019 uint64_t EqVal = 0;
Daniel Sanderscbd44c52014-07-10 10:18:12 +00002020 switch (getBooleanContents(N0.getValueType())) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00002021 case UndefinedBooleanContent:
2022 case ZeroOrOneBooleanContent:
2023 EqVal = ISD::isTrueWhenEqual(Cond);
2024 break;
2025 case ZeroOrNegativeOneBooleanContent:
2026 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2027 break;
2028 }
2029
Evan Cheng92658d52007-02-08 22:13:59 +00002030 // We can always fold X == X for integer setcc's.
Chad Rosier2a02fe12012-04-03 20:11:24 +00002031 if (N0.getValueType().isInteger()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002032 return DAG.getConstant(EqVal, dl, VT);
Chad Rosier2a02fe12012-04-03 20:11:24 +00002033 }
Evan Cheng92658d52007-02-08 22:13:59 +00002034 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2035 if (UOF == 2) // FP operators that are undefined on NaNs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002036 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00002037 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002038 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00002039 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2040 // if it is not already.
2041 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
Micah Villmowb67d7a32012-07-31 18:07:43 +00002042 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
Patrik Hagglunddeee9002012-12-19 10:09:26 +00002043 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002044 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
Evan Cheng92658d52007-02-08 22:13:59 +00002045 }
2046
2047 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002048 N0.getValueType().isInteger()) {
Evan Cheng92658d52007-02-08 22:13:59 +00002049 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2050 N0.getOpcode() == ISD::XOR) {
2051 // Simplify (X+Y) == (X+Z) --> Y == Z
2052 if (N0.getOpcode() == N1.getOpcode()) {
2053 if (N0.getOperand(0) == N1.getOperand(0))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002054 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002055 if (N0.getOperand(1) == N1.getOperand(1))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002056 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002057 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2058 // If X op Y == Y op X, try other combinations.
2059 if (N0.getOperand(0) == N1.getOperand(1))
Wesley Peck527da1b2010-11-23 03:31:01 +00002060 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
Dale Johannesenf1163e92009-02-03 00:47:48 +00002061 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002062 if (N0.getOperand(1) == N1.getOperand(0))
Wesley Peck527da1b2010-11-23 03:31:01 +00002063 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00002064 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002065 }
2066 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002067
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002068 // If RHS is a legal immediate value for a compare instruction, we need
2069 // to be careful about increasing register pressure needlessly.
2070 bool LegalRHSImm = false;
2071
Sanjay Patel7a7abc92015-12-29 21:49:08 +00002072 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2073 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Cheng92658d52007-02-08 22:13:59 +00002074 // Turn (X+C1) == C2 --> X == C2-C1
Gabor Greiff304a7a2008-08-28 21:40:38 +00002075 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002076 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohmaneffb8942008-09-12 16:56:44 +00002077 DAG.getConstant(RHSC->getAPIntValue()-
2078 LHSR->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002079 dl, N0.getValueType()), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002080 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002081
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002082 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
Evan Cheng92658d52007-02-08 22:13:59 +00002083 if (N0.getOpcode() == ISD::XOR)
2084 // If we know that all of the inverted bits are zero, don't bother
2085 // performing the inversion.
Dan Gohman1f372ed2008-02-25 21:11:39 +00002086 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2087 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00002088 DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002089 DAG.getConstant(LHSR->getAPIntValue() ^
2090 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002091 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002092 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002093 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002094
Evan Cheng92658d52007-02-08 22:13:59 +00002095 // Turn (C1-X) == C2 --> X == C1-C2
Sanjay Patel7a7abc92015-12-29 21:49:08 +00002096 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00002097 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002098 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00002099 DAG.getSetCC(dl, VT, N0.getOperand(1),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002100 DAG.getConstant(SUBC->getAPIntValue() -
2101 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002102 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002103 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002104 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002105 }
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002106
2107 // Could RHSC fold directly into a compare?
2108 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2109 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
Evan Cheng92658d52007-02-08 22:13:59 +00002110 }
2111
2112 // Simplify (X+Z) == X --> Z == 0
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002113 // Don't do this if X is an immediate that can fold into a cmp
2114 // instruction and X+Z has other uses. It could be an induction variable
2115 // chain, and the transform would increase register pressure.
2116 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2117 if (N0.getOperand(0) == N1)
2118 return DAG.getSetCC(dl, VT, N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002119 DAG.getConstant(0, dl, N0.getValueType()), Cond);
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002120 if (N0.getOperand(1) == N1) {
2121 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2122 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002123 DAG.getConstant(0, dl, N0.getValueType()),
2124 Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002125 if (N0.getNode()->hasOneUse()) {
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002126 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002127 auto &DL = DAG.getDataLayout();
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002128 // (Z-X) == X --> Z == X<<1
Mehdi Amini9639d652015-07-09 02:09:20 +00002129 SDValue SH = DAG.getNode(
2130 ISD::SHL, dl, N1.getValueType(), N1,
2131 DAG.getConstant(1, dl,
2132 getShiftAmountTy(N1.getValueType(), DL)));
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002133 if (!DCI.isCalledByLegalizer())
2134 DCI.AddToWorklist(SH.getNode());
2135 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2136 }
Evan Cheng92658d52007-02-08 22:13:59 +00002137 }
2138 }
2139 }
2140
2141 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2142 N1.getOpcode() == ISD::XOR) {
2143 // Simplify X == (X+Z) --> Z == 0
Craig Topper3f194c82012-12-19 06:43:58 +00002144 if (N1.getOperand(0) == N0)
Dale Johannesenf1163e92009-02-03 00:47:48 +00002145 return DAG.getSetCC(dl, VT, N1.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002146 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002147 if (N1.getOperand(1) == N0) {
2148 if (DAG.isCommutativeBinOp(N1.getOpcode()))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002149 return DAG.getSetCC(dl, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002150 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002151 if (N1.getNode()->hasOneUse()) {
Evan Cheng92658d52007-02-08 22:13:59 +00002152 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002153 auto &DL = DAG.getDataLayout();
Evan Cheng92658d52007-02-08 22:13:59 +00002154 // X == (Z-X) --> X<<1 == Z
Mehdi Amini9639d652015-07-09 02:09:20 +00002155 SDValue SH = DAG.getNode(
2156 ISD::SHL, dl, N1.getValueType(), N0,
2157 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
Evan Cheng92658d52007-02-08 22:13:59 +00002158 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002159 DCI.AddToWorklist(SH.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002160 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002161 }
2162 }
2163 }
Dan Gohmane58ab792009-01-29 01:59:02 +00002164
Sanjay Patel91592562016-05-09 16:42:50 +00002165 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2166 return V;
Evan Cheng92658d52007-02-08 22:13:59 +00002167 }
2168
2169 // Fold away ALL boolean setcc's.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002170 SDValue Temp;
Owen Anderson9f944592009-08-11 20:47:22 +00002171 if (N0.getValueType() == MVT::i1 && foldBooleans) {
Evan Cheng92658d52007-02-08 22:13:59 +00002172 switch (Cond) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00002173 default: llvm_unreachable("Unknown integer setcc!");
Bob Wilsonc5890052009-01-22 17:39:32 +00002174 case ISD::SETEQ: // X == Y -> ~(X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002175 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2176 N0 = DAG.getNOT(dl, Temp, MVT::i1);
Evan Cheng92658d52007-02-08 22:13:59 +00002177 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002178 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002179 break;
2180 case ISD::SETNE: // X != Y --> (X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002181 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
Evan Cheng92658d52007-02-08 22:13:59 +00002182 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002183 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2184 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
Owen Anderson9f944592009-08-11 20:47:22 +00002185 Temp = DAG.getNOT(dl, N0, MVT::i1);
2186 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002187 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002188 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002189 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002190 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2191 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
Owen Anderson9f944592009-08-11 20:47:22 +00002192 Temp = DAG.getNOT(dl, N1, MVT::i1);
2193 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002194 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002195 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002196 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002197 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2198 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
Owen Anderson9f944592009-08-11 20:47:22 +00002199 Temp = DAG.getNOT(dl, N0, MVT::i1);
2200 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002201 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002202 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002203 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002204 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2205 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
Owen Anderson9f944592009-08-11 20:47:22 +00002206 Temp = DAG.getNOT(dl, N1, MVT::i1);
2207 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002208 break;
2209 }
Owen Anderson9f944592009-08-11 20:47:22 +00002210 if (VT != MVT::i1) {
Evan Cheng92658d52007-02-08 22:13:59 +00002211 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002212 DCI.AddToWorklist(N0.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002213 // FIXME: If running after legalize, we probably can't do this.
Dale Johannesenf1163e92009-02-03 00:47:48 +00002214 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
Evan Cheng92658d52007-02-08 22:13:59 +00002215 }
2216 return N0;
2217 }
2218
2219 // Could not fold it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002220 return SDValue();
Evan Cheng92658d52007-02-08 22:13:59 +00002221}
2222
Sanjay Patelac6e9102015-12-29 22:11:50 +00002223/// Returns true (and the GlobalValue and the offset) if the node is a
2224/// GlobalAddress + offset.
Chris Lattner46c01a32011-02-13 22:25:43 +00002225bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
Evan Cheng2609d5e2008-05-12 19:56:52 +00002226 int64_t &Offset) const {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002227 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
Dan Gohmane38cc012008-06-09 22:05:52 +00002228 GA = GASD->getGlobal();
2229 Offset += GASD->getOffset();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002230 return true;
2231 }
2232
2233 if (N->getOpcode() == ISD::ADD) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002234 SDValue N1 = N->getOperand(0);
2235 SDValue N2 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002236 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002237 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002238 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002239 return true;
2240 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00002241 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002242 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002243 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002244 return true;
2245 }
2246 }
2247 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002248
Evan Cheng2609d5e2008-05-12 19:56:52 +00002249 return false;
2250}
2251
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002252SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2253 DAGCombinerInfo &DCI) const {
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002254 // Default implementation: no optimization.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002255 return SDValue();
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002256}
2257
Chris Lattneree1dadb2006-02-04 02:13:02 +00002258//===----------------------------------------------------------------------===//
2259// Inline Assembler Implementation Methods
2260//===----------------------------------------------------------------------===//
2261
2262TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002263TargetLowering::getConstraintType(StringRef Constraint) const {
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002264 unsigned S = Constraint.size();
2265
2266 if (S == 1) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002267 switch (Constraint[0]) {
2268 default: break;
2269 case 'r': return C_RegisterClass;
2270 case 'm': // memory
2271 case 'o': // offsetable
2272 case 'V': // not offsetable
2273 return C_Memory;
2274 case 'i': // Simple Integer or Relocatable Constant
2275 case 'n': // Simple Integer
John Thompsonc467aa22010-09-21 22:04:54 +00002276 case 'E': // Floating Point Constant
2277 case 'F': // Floating Point Constant
Chris Lattnerd6855142007-03-25 02:14:49 +00002278 case 's': // Relocatable Constant
John Thompsonc467aa22010-09-21 22:04:54 +00002279 case 'p': // Address.
Chris Lattner3d7efa22007-03-25 04:35:41 +00002280 case 'X': // Allow ANY value.
Chris Lattnerd6855142007-03-25 02:14:49 +00002281 case 'I': // Target registers.
2282 case 'J':
2283 case 'K':
2284 case 'L':
2285 case 'M':
2286 case 'N':
2287 case 'O':
2288 case 'P':
John Thompsonc467aa22010-09-21 22:04:54 +00002289 case '<':
2290 case '>':
Chris Lattnerd6855142007-03-25 02:14:49 +00002291 return C_Other;
2292 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002293 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002294
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002295 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002296 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002297 return C_Memory;
Chris Lattner843e4452007-03-25 02:18:14 +00002298 return C_Register;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002299 }
Chris Lattnerd6855142007-03-25 02:14:49 +00002300 return C_Unknown;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002301}
2302
Sanjay Patelac6e9102015-12-29 22:11:50 +00002303/// Try to replace an X constraint, which matches anything, with another that
2304/// has more specific requirements based on the type of the corresponding
2305/// operand.
Owen Anderson53aa7a92009-08-10 22:56:29 +00002306const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
Duncan Sands13237ac2008-06-06 12:08:01 +00002307 if (ConstraintVT.isInteger())
Chris Lattner724539c2008-04-26 23:02:14 +00002308 return "r";
Duncan Sands13237ac2008-06-06 12:08:01 +00002309 if (ConstraintVT.isFloatingPoint())
Chris Lattner724539c2008-04-26 23:02:14 +00002310 return "f"; // works for many targets
Craig Topperc0196b12014-04-14 00:51:57 +00002311 return nullptr;
Dale Johannesen2b3bc302008-01-29 02:21:21 +00002312}
2313
Sanjay Patelac6e9102015-12-29 22:11:50 +00002314/// Lower the specified operand into the Ops vector.
2315/// If it is invalid, don't add anything to Ops.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002316void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
Eric Christopherde9399b2011-06-02 23:16:42 +00002317 std::string &Constraint,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002318 std::vector<SDValue> &Ops,
Chris Lattner724539c2008-04-26 23:02:14 +00002319 SelectionDAG &DAG) const {
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002320
Eric Christopherde9399b2011-06-02 23:16:42 +00002321 if (Constraint.length() > 1) return;
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002322
Eric Christopherde9399b2011-06-02 23:16:42 +00002323 char ConstraintLetter = Constraint[0];
Chris Lattneree1dadb2006-02-04 02:13:02 +00002324 switch (ConstraintLetter) {
Chris Lattnera9f917a2007-02-17 06:00:35 +00002325 default: break;
Dale Johannesen4646aa32007-11-05 21:20:28 +00002326 case 'X': // Allows any operand; labels (basic block) use this.
2327 if (Op.getOpcode() == ISD::BasicBlock) {
2328 Ops.push_back(Op);
2329 return;
2330 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002331 LLVM_FALLTHROUGH;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002332 case 'i': // Simple Integer or Relocatable Constant
2333 case 'n': // Simple Integer
Dale Johannesen4646aa32007-11-05 21:20:28 +00002334 case 's': { // Relocatable Constant
Chris Lattner44a2ed62007-05-03 16:54:34 +00002335 // These operands are interested in values of the form (GV+C), where C may
2336 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2337 // is possible and fine if either GV or C are missing.
2338 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2339 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
Wesley Peck527da1b2010-11-23 03:31:01 +00002340
Chris Lattner44a2ed62007-05-03 16:54:34 +00002341 // If we have "(add GV, C)", pull out GV/C
2342 if (Op.getOpcode() == ISD::ADD) {
2343 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2344 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
Craig Topperc0196b12014-04-14 00:51:57 +00002345 if (!C || !GA) {
Chris Lattner44a2ed62007-05-03 16:54:34 +00002346 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2347 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2348 }
Richard Trieu7a083812016-02-18 22:09:30 +00002349 if (!C || !GA) {
2350 C = nullptr;
2351 GA = nullptr;
2352 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002353 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002354
Chris Lattner44a2ed62007-05-03 16:54:34 +00002355 // If we find a valid operand, map to the TargetXXX version so that the
2356 // value itself doesn't get selected.
2357 if (GA) { // Either &GV or &GV+C
2358 if (ConstraintLetter != 'n') {
2359 int64_t Offs = GA->getOffset();
Dan Gohmaneffb8942008-09-12 16:56:44 +00002360 if (C) Offs += C->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002361 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002362 C ? SDLoc(C) : SDLoc(),
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002363 Op.getValueType(), Offs));
Chris Lattner44a2ed62007-05-03 16:54:34 +00002364 }
James Y Knight46f91c82015-07-13 16:36:22 +00002365 return;
Chris Lattner44a2ed62007-05-03 16:54:34 +00002366 }
2367 if (C) { // just C, no GV.
Chris Lattnera9f917a2007-02-17 06:00:35 +00002368 // Simple constants are not allowed for 's'.
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002369 if (ConstraintLetter != 's') {
Dale Johannesen65577522009-02-12 20:58:09 +00002370 // gcc prints these as sign extended. Sign extend value to 64 bits
2371 // now; without this it would get ZExt'd later in
2372 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2373 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002374 SDLoc(C), MVT::i64));
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002375 }
James Y Knight46f91c82015-07-13 16:36:22 +00002376 return;
Chris Lattnera9f917a2007-02-17 06:00:35 +00002377 }
Chris Lattnera9f917a2007-02-17 06:00:35 +00002378 break;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002379 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002380 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002381}
2382
Eric Christopher11e4df72015-02-26 22:38:43 +00002383std::pair<unsigned, const TargetRegisterClass *>
2384TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002385 StringRef Constraint,
Eric Christopher11e4df72015-02-26 22:38:43 +00002386 MVT VT) const {
Will Dietzae726a92013-10-13 03:08:49 +00002387 if (Constraint.empty() || Constraint[0] != '{')
Craig Topperc0196b12014-04-14 00:51:57 +00002388 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
Chris Lattner7ed31012006-02-01 01:29:47 +00002389 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2390
2391 // Remove the braces from around the name.
Benjamin Kramer68e49452009-11-12 20:36:59 +00002392 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002393
Hal Finkel943f76d2012-12-18 17:50:58 +00002394 std::pair<unsigned, const TargetRegisterClass*> R =
Craig Topperc0196b12014-04-14 00:51:57 +00002395 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
Hal Finkel943f76d2012-12-18 17:50:58 +00002396
Chris Lattner7ad77df2006-02-22 00:56:39 +00002397 // Figure out which register class contains this reg.
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002398 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
Chris Lattner7ad77df2006-02-22 00:56:39 +00002399 E = RI->regclass_end(); RCI != E; ++RCI) {
2400 const TargetRegisterClass *RC = *RCI;
Wesley Peck527da1b2010-11-23 03:31:01 +00002401
2402 // If none of the value types for this register class are valid, we
Chris Lattner2e124af2006-02-22 23:00:51 +00002403 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Jakob Stoklund Olesen35163e22011-10-12 01:24:51 +00002404 if (!isLegalRC(RC))
2405 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002406
2407 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002408 I != E; ++I) {
Tom Stellard52686e42016-04-11 16:21:12 +00002409 if (RegName.equals_lower(RI->getRegAsmName(*I))) {
Hal Finkel943f76d2012-12-18 17:50:58 +00002410 std::pair<unsigned, const TargetRegisterClass*> S =
2411 std::make_pair(*I, RC);
2412
2413 // If this register class has the requested value type, return it,
2414 // otherwise keep searching and return the first class found
2415 // if no other is found which explicitly has the requested type.
2416 if (RC->hasType(VT))
2417 return S;
2418 else if (!R.second)
2419 R = S;
2420 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002421 }
Chris Lattner32fef532006-01-26 20:37:03 +00002422 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002423
Hal Finkel943f76d2012-12-18 17:50:58 +00002424 return R;
Chris Lattner32fef532006-01-26 20:37:03 +00002425}
Evan Chengaf598d22006-03-13 23:18:16 +00002426
2427//===----------------------------------------------------------------------===//
Chris Lattner47935152008-04-27 00:09:47 +00002428// Constraint Selection.
2429
Sanjay Patelac6e9102015-12-29 22:11:50 +00002430/// Return true of this is an input operand that is a matching constraint like
2431/// "4".
Chris Lattner860df6e2008-10-17 16:47:46 +00002432bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
Chris Lattneref890172008-10-17 16:21:11 +00002433 assert(!ConstraintCode.empty() && "No known constraint!");
Guy Benyei83c74e92013-02-12 21:21:59 +00002434 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
Chris Lattneref890172008-10-17 16:21:11 +00002435}
2436
Sanjay Patelac6e9102015-12-29 22:11:50 +00002437/// If this is an input matching constraint, this method returns the output
2438/// operand it matches.
Chris Lattneref890172008-10-17 16:21:11 +00002439unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2440 assert(!ConstraintCode.empty() && "No known constraint!");
2441 return atoi(ConstraintCode.c_str());
2442}
2443
Sanjay Patelac6e9102015-12-29 22:11:50 +00002444/// Split up the constraint string from the inline assembly value into the
2445/// specific constraints and their prefixes, and also tie in the associated
2446/// operand values.
John Thompson1094c802010-09-13 18:15:37 +00002447/// If this returns an empty vector, and if the constraint string itself
2448/// isn't empty, there was an error parsing.
Eric Christopher11e4df72015-02-26 22:38:43 +00002449TargetLowering::AsmOperandInfoVector
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002450TargetLowering::ParseConstraints(const DataLayout &DL,
2451 const TargetRegisterInfo *TRI,
Eric Christopher11e4df72015-02-26 22:38:43 +00002452 ImmutableCallSite CS) const {
Sanjay Patelac6e9102015-12-29 22:11:50 +00002453 /// Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00002454 AsmOperandInfoVector ConstraintOperands;
John Thompson1094c802010-09-13 18:15:37 +00002455 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
John Thompsonc467aa22010-09-21 22:04:54 +00002456 unsigned maCount = 0; // Largest number of multiple alternative constraints.
John Thompson1094c802010-09-13 18:15:37 +00002457
2458 // Do a prepass over the constraints, canonicalizing them, and building up the
2459 // ConstraintOperands list.
John Thompson1094c802010-09-13 18:15:37 +00002460 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2461 unsigned ResNo = 0; // ResNo - The result number of the next output.
2462
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00002463 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2464 ConstraintOperands.emplace_back(std::move(CI));
John Thompson1094c802010-09-13 18:15:37 +00002465 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2466
John Thompsonc467aa22010-09-21 22:04:54 +00002467 // Update multiple alternative constraint count.
2468 if (OpInfo.multipleAlternatives.size() > maCount)
2469 maCount = OpInfo.multipleAlternatives.size();
2470
John Thompsone8360b72010-10-29 17:29:13 +00002471 OpInfo.ConstraintVT = MVT::Other;
John Thompson1094c802010-09-13 18:15:37 +00002472
2473 // Compute the value type for each operand.
2474 switch (OpInfo.Type) {
2475 case InlineAsm::isOutput:
2476 // Indirect outputs just consume an argument.
2477 if (OpInfo.isIndirect) {
2478 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2479 break;
2480 }
2481
2482 // The return value of the call is this value. As such, there is no
2483 // corresponding argument.
2484 assert(!CS.getType()->isVoidTy() &&
2485 "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00002486 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002487 OpInfo.ConstraintVT =
2488 getSimpleValueType(DL, STy->getElementType(ResNo));
John Thompson1094c802010-09-13 18:15:37 +00002489 } else {
2490 assert(ResNo == 0 && "Asm only has one result!");
Mehdi Amini44ede332015-07-09 02:09:04 +00002491 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
John Thompson1094c802010-09-13 18:15:37 +00002492 }
2493 ++ResNo;
2494 break;
2495 case InlineAsm::isInput:
2496 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2497 break;
2498 case InlineAsm::isClobber:
2499 // Nothing to do.
2500 break;
2501 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002502
John Thompsone8360b72010-10-29 17:29:13 +00002503 if (OpInfo.CallOperandVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00002504 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
John Thompsone8360b72010-10-29 17:29:13 +00002505 if (OpInfo.isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00002506 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002507 if (!PtrTy)
2508 report_fatal_error("Indirect operand for inline asm not a pointer!");
2509 OpTy = PtrTy->getElementType();
2510 }
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002511
Eric Christopher44804282011-05-09 20:04:43 +00002512 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00002513 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00002514 if (STy->getNumElements() == 1)
2515 OpTy = STy->getElementType(0);
2516
John Thompsone8360b72010-10-29 17:29:13 +00002517 // If OpTy is not a single value, it may be a struct/union that we
2518 // can tile with integers.
2519 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002520 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002521 switch (BitSize) {
2522 default: break;
2523 case 1:
2524 case 8:
2525 case 16:
2526 case 32:
2527 case 64:
2528 case 128:
Dale Johannesenf11ea9c2010-11-09 01:15:07 +00002529 OpInfo.ConstraintVT =
Patrik Hagglundf9934612012-12-19 15:19:11 +00002530 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
John Thompsone8360b72010-10-29 17:29:13 +00002531 break;
2532 }
Micah Villmow89021e42012-10-09 16:06:12 +00002533 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002534 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
Matt Arsenaulta98c3b12013-10-10 19:09:05 +00002535 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
John Thompsone8360b72010-10-29 17:29:13 +00002536 } else {
Patrik Hagglundf9934612012-12-19 15:19:11 +00002537 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
John Thompsone8360b72010-10-29 17:29:13 +00002538 }
2539 }
John Thompson1094c802010-09-13 18:15:37 +00002540 }
2541
2542 // If we have multiple alternative constraints, select the best alternative.
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002543 if (!ConstraintOperands.empty()) {
John Thompson1094c802010-09-13 18:15:37 +00002544 if (maCount) {
2545 unsigned bestMAIndex = 0;
2546 int bestWeight = -1;
2547 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2548 int weight = -1;
2549 unsigned maIndex;
2550 // Compute the sums of the weights for each alternative, keeping track
2551 // of the best (highest weight) one so far.
2552 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2553 int weightSum = 0;
2554 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2555 cIndex != eIndex; ++cIndex) {
2556 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2557 if (OpInfo.Type == InlineAsm::isClobber)
2558 continue;
John Thompson1094c802010-09-13 18:15:37 +00002559
John Thompsone8360b72010-10-29 17:29:13 +00002560 // If this is an output operand with a matching input operand,
2561 // look up the matching input. If their types mismatch, e.g. one
2562 // is an integer, the other is floating point, or their sizes are
2563 // different, flag it as an maCantMatch.
John Thompson1094c802010-09-13 18:15:37 +00002564 if (OpInfo.hasMatchingInput()) {
2565 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompson1094c802010-09-13 18:15:37 +00002566 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2567 if ((OpInfo.ConstraintVT.isInteger() !=
2568 Input.ConstraintVT.isInteger()) ||
2569 (OpInfo.ConstraintVT.getSizeInBits() !=
2570 Input.ConstraintVT.getSizeInBits())) {
2571 weightSum = -1; // Can't match.
2572 break;
2573 }
John Thompson1094c802010-09-13 18:15:37 +00002574 }
2575 }
John Thompson1094c802010-09-13 18:15:37 +00002576 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2577 if (weight == -1) {
2578 weightSum = -1;
2579 break;
2580 }
2581 weightSum += weight;
2582 }
2583 // Update best.
2584 if (weightSum > bestWeight) {
2585 bestWeight = weightSum;
2586 bestMAIndex = maIndex;
2587 }
2588 }
2589
2590 // Now select chosen alternative in each constraint.
2591 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2592 cIndex != eIndex; ++cIndex) {
2593 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2594 if (cInfo.Type == InlineAsm::isClobber)
2595 continue;
2596 cInfo.selectAlternative(bestMAIndex);
2597 }
2598 }
2599 }
2600
2601 // Check and hook up tied operands, choose constraint code to use.
2602 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2603 cIndex != eIndex; ++cIndex) {
2604 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
Wesley Peck527da1b2010-11-23 03:31:01 +00002605
John Thompson1094c802010-09-13 18:15:37 +00002606 // If this is an output operand with a matching input operand, look up the
2607 // matching input. If their types mismatch, e.g. one is an integer, the
2608 // other is floating point, or their sizes are different, flag it as an
2609 // error.
2610 if (OpInfo.hasMatchingInput()) {
2611 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompsone8360b72010-10-29 17:29:13 +00002612
John Thompson1094c802010-09-13 18:15:37 +00002613 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Eric Christopher11e4df72015-02-26 22:38:43 +00002614 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2615 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2616 OpInfo.ConstraintVT);
2617 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2618 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2619 Input.ConstraintVT);
John Thompson1094c802010-09-13 18:15:37 +00002620 if ((OpInfo.ConstraintVT.isInteger() !=
2621 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00002622 (MatchRC.second != InputRC.second)) {
John Thompson1094c802010-09-13 18:15:37 +00002623 report_fatal_error("Unsupported asm: input constraint"
2624 " with a matching output constraint of"
2625 " incompatible type!");
2626 }
John Thompson1094c802010-09-13 18:15:37 +00002627 }
2628 }
2629 }
2630
2631 return ConstraintOperands;
2632}
2633
Sanjay Patelac6e9102015-12-29 22:11:50 +00002634/// Return an integer indicating how general CT is.
Chris Lattner47935152008-04-27 00:09:47 +00002635static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2636 switch (CT) {
Chris Lattner47935152008-04-27 00:09:47 +00002637 case TargetLowering::C_Other:
2638 case TargetLowering::C_Unknown:
2639 return 0;
2640 case TargetLowering::C_Register:
2641 return 1;
2642 case TargetLowering::C_RegisterClass:
2643 return 2;
2644 case TargetLowering::C_Memory:
2645 return 3;
2646 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002647 llvm_unreachable("Invalid constraint type");
Chris Lattner47935152008-04-27 00:09:47 +00002648}
2649
John Thompsone8360b72010-10-29 17:29:13 +00002650/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002651/// This object must already have been set up with the operand type
2652/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002653TargetLowering::ConstraintWeight
2654 TargetLowering::getMultipleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002655 AsmOperandInfo &info, int maIndex) const {
John Thompsone8360b72010-10-29 17:29:13 +00002656 InlineAsm::ConstraintCodeVector *rCodes;
John Thompsonc467aa22010-09-21 22:04:54 +00002657 if (maIndex >= (int)info.multipleAlternatives.size())
2658 rCodes = &info.Codes;
2659 else
2660 rCodes = &info.multipleAlternatives[maIndex].Codes;
John Thompsone8360b72010-10-29 17:29:13 +00002661 ConstraintWeight BestWeight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002662
2663 // Loop over the options, keeping track of the most general one.
John Thompsonc467aa22010-09-21 22:04:54 +00002664 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
John Thompsone8360b72010-10-29 17:29:13 +00002665 ConstraintWeight weight =
2666 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
John Thompson1094c802010-09-13 18:15:37 +00002667 if (weight > BestWeight)
2668 BestWeight = weight;
2669 }
2670
2671 return BestWeight;
2672}
2673
John Thompsone8360b72010-10-29 17:29:13 +00002674/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002675/// This object must already have been set up with the operand type
2676/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002677TargetLowering::ConstraintWeight
2678 TargetLowering::getSingleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002679 AsmOperandInfo &info, const char *constraint) const {
John Thompsone8360b72010-10-29 17:29:13 +00002680 ConstraintWeight weight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002681 Value *CallOperandVal = info.CallOperandVal;
2682 // If we don't have a value, we can't do a match,
2683 // but allow it at the lowest weight.
Craig Topperc0196b12014-04-14 00:51:57 +00002684 if (!CallOperandVal)
John Thompsone8360b72010-10-29 17:29:13 +00002685 return CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002686 // Look at the constraint type.
2687 switch (*constraint) {
2688 case 'i': // immediate integer.
2689 case 'n': // immediate integer with a known value.
John Thompsone8360b72010-10-29 17:29:13 +00002690 if (isa<ConstantInt>(CallOperandVal))
2691 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002692 break;
2693 case 's': // non-explicit intregal immediate.
John Thompsone8360b72010-10-29 17:29:13 +00002694 if (isa<GlobalValue>(CallOperandVal))
2695 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002696 break;
John Thompsone8360b72010-10-29 17:29:13 +00002697 case 'E': // immediate float if host format.
2698 case 'F': // immediate float.
2699 if (isa<ConstantFP>(CallOperandVal))
2700 weight = CW_Constant;
2701 break;
2702 case '<': // memory operand with autodecrement.
2703 case '>': // memory operand with autoincrement.
John Thompson1094c802010-09-13 18:15:37 +00002704 case 'm': // memory operand.
2705 case 'o': // offsettable memory operand
2706 case 'V': // non-offsettable memory operand
John Thompsone8360b72010-10-29 17:29:13 +00002707 weight = CW_Memory;
John Thompson1094c802010-09-13 18:15:37 +00002708 break;
John Thompsone8360b72010-10-29 17:29:13 +00002709 case 'r': // general register.
John Thompson1094c802010-09-13 18:15:37 +00002710 case 'g': // general register, memory operand or immediate integer.
John Thompsone8360b72010-10-29 17:29:13 +00002711 // note: Clang converts "g" to "imr".
2712 if (CallOperandVal->getType()->isIntegerTy())
2713 weight = CW_Register;
John Thompson1094c802010-09-13 18:15:37 +00002714 break;
John Thompsone8360b72010-10-29 17:29:13 +00002715 case 'X': // any operand.
John Thompson1094c802010-09-13 18:15:37 +00002716 default:
John Thompsone8360b72010-10-29 17:29:13 +00002717 weight = CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002718 break;
2719 }
2720 return weight;
2721}
2722
Sanjay Patelac6e9102015-12-29 22:11:50 +00002723/// If there are multiple different constraints that we could pick for this
2724/// operand (e.g. "imr") try to pick the 'best' one.
Chris Lattner58b9ece2008-04-27 01:49:46 +00002725/// This is somewhat tricky: constraints fall into four classes:
Chris Lattner47935152008-04-27 00:09:47 +00002726/// Other -> immediates and magic values
2727/// Register -> one specific register
2728/// RegisterClass -> a group of regs
2729/// Memory -> memory
2730/// Ideally, we would pick the most specific constraint possible: if we have
2731/// something that fits into a register, we would pick it. The problem here
2732/// is that if we have something that could either be in a register or in
2733/// memory that use of the register could cause selection of *other*
2734/// operands to fail: they might only succeed if we pick memory. Because of
2735/// this the heuristic we use is:
2736///
2737/// 1) If there is an 'other' constraint, and if the operand is valid for
2738/// that constraint, use it. This makes us take advantage of 'i'
2739/// constraints when available.
2740/// 2) Otherwise, pick the most general constraint present. This prefers
2741/// 'm' over 'r', for example.
2742///
2743static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
Dale Johannesence97d552010-06-25 21:55:36 +00002744 const TargetLowering &TLI,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002745 SDValue Op, SelectionDAG *DAG) {
Chris Lattner47935152008-04-27 00:09:47 +00002746 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2747 unsigned BestIdx = 0;
2748 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2749 int BestGenerality = -1;
Dale Johannesen17feb072010-06-28 22:09:45 +00002750
Chris Lattner47935152008-04-27 00:09:47 +00002751 // Loop over the options, keeping track of the most general one.
2752 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2753 TargetLowering::ConstraintType CType =
2754 TLI.getConstraintType(OpInfo.Codes[i]);
Dale Johannesen17feb072010-06-28 22:09:45 +00002755
Chris Lattner22379732008-04-27 00:37:18 +00002756 // If this is an 'other' constraint, see if the operand is valid for it.
2757 // For example, on X86 we might have an 'rI' constraint. If the operand
2758 // is an integer in the range [0..31] we want to use I (saving a load
2759 // of a register), otherwise we must use 'r'.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002760 if (CType == TargetLowering::C_Other && Op.getNode()) {
Chris Lattner22379732008-04-27 00:37:18 +00002761 assert(OpInfo.Codes[i].size() == 1 &&
2762 "Unhandled multi-letter 'other' constraint");
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002763 std::vector<SDValue> ResultOps;
Eric Christopherde9399b2011-06-02 23:16:42 +00002764 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
Chris Lattner22379732008-04-27 00:37:18 +00002765 ResultOps, *DAG);
2766 if (!ResultOps.empty()) {
2767 BestType = CType;
2768 BestIdx = i;
2769 break;
2770 }
2771 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002772
Dale Johannesen17feb072010-06-28 22:09:45 +00002773 // Things with matching constraints can only be registers, per gcc
2774 // documentation. This mainly affects "g" constraints.
2775 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2776 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002777
Chris Lattner47935152008-04-27 00:09:47 +00002778 // This constraint letter is more general than the previous one, use it.
2779 int Generality = getConstraintGenerality(CType);
2780 if (Generality > BestGenerality) {
2781 BestType = CType;
2782 BestIdx = i;
2783 BestGenerality = Generality;
2784 }
2785 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002786
Chris Lattner47935152008-04-27 00:09:47 +00002787 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2788 OpInfo.ConstraintType = BestType;
2789}
2790
Sanjay Patelac6e9102015-12-29 22:11:50 +00002791/// Determines the constraint code and constraint type to use for the specific
2792/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
Chris Lattner22379732008-04-27 00:37:18 +00002793void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
Wesley Peck527da1b2010-11-23 03:31:01 +00002794 SDValue Op,
Chris Lattner22379732008-04-27 00:37:18 +00002795 SelectionDAG *DAG) const {
Chris Lattner47935152008-04-27 00:09:47 +00002796 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
Wesley Peck527da1b2010-11-23 03:31:01 +00002797
Chris Lattner47935152008-04-27 00:09:47 +00002798 // Single-letter constraints ('r') are very common.
2799 if (OpInfo.Codes.size() == 1) {
2800 OpInfo.ConstraintCode = OpInfo.Codes[0];
2801 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2802 } else {
Dale Johannesence97d552010-06-25 21:55:36 +00002803 ChooseConstraint(OpInfo, *this, Op, DAG);
Chris Lattner47935152008-04-27 00:09:47 +00002804 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002805
Chris Lattner47935152008-04-27 00:09:47 +00002806 // 'X' matches anything.
2807 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2808 // Labels and constants are handled elsewhere ('X' is the only thing
Dale Johannesen4e331152009-07-07 23:26:33 +00002809 // that matches labels). For Functions, the type here is the type of
Dale Johannesenade297d2009-07-20 23:27:39 +00002810 // the result, which is not what we want to look at; leave them alone.
2811 Value *v = OpInfo.CallOperandVal;
Dale Johannesen4e331152009-07-07 23:26:33 +00002812 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2813 OpInfo.CallOperandVal = v;
Chris Lattner47935152008-04-27 00:09:47 +00002814 return;
Dale Johannesen4e331152009-07-07 23:26:33 +00002815 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002816
Chris Lattner47935152008-04-27 00:09:47 +00002817 // Otherwise, try to resolve it to something we know about by looking at
2818 // the actual operand type.
2819 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2820 OpInfo.ConstraintCode = Repl;
2821 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2822 }
2823 }
2824}
2825
David Majnemer0fc86702013-06-08 23:51:45 +00002826/// \brief Given an exact SDIV by a constant, create a multiplication
Benjamin Kramer9960a252011-07-08 10:31:30 +00002827/// with the multiplicative inverse of the constant.
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002828static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002829 const SDLoc &dl, SelectionDAG &DAG,
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002830 std::vector<SDNode *> &Created) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002831 assert(d != 0 && "Division by zero!");
2832
2833 // Shift the value upfront if it is even, so the LSB is one.
2834 unsigned ShAmt = d.countTrailingZeros();
2835 if (ShAmt) {
2836 // TODO: For UDIV use SRL instead of SRA.
NAKAMURA Takumie4529982015-05-06 14:03:22 +00002837 SDValue Amt =
Mehdi Amini9639d652015-07-09 02:09:20 +00002838 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2839 DAG.getDataLayout()));
Sanjay Patelf1340482015-06-16 16:25:43 +00002840 SDNodeFlags Flags;
2841 Flags.setExact(true);
2842 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002843 Created.push_back(Op1.getNode());
Benjamin Kramer9960a252011-07-08 10:31:30 +00002844 d = d.ashr(ShAmt);
2845 }
2846
2847 // Calculate the multiplicative inverse, using Newton's method.
2848 APInt t, xn = d;
2849 while ((t = d*xn) != 1)
2850 xn *= APInt(d.getBitWidth(), 2) - t;
2851
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002852 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2853 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2854 Created.push_back(Mul.getNode());
2855 return Mul;
Benjamin Kramer9960a252011-07-08 10:31:30 +00002856}
2857
Steve King5cdbd202015-08-25 02:31:21 +00002858SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2859 SelectionDAG &DAG,
2860 std::vector<SDNode *> *Created) const {
2861 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2863 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2864 return SDValue(N,0); // Lower SDIV as SDIV
2865 return SDValue();
2866}
2867
David Majnemer0fc86702013-06-08 23:51:45 +00002868/// \brief Given an ISD::SDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002869/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002870/// multiplying by a magic number.
2871/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002872SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2873 SelectionDAG &DAG, bool IsAfterLegalization,
2874 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002875 assert(Created && "No vector to hold sdiv ops.");
2876
Owen Anderson53aa7a92009-08-10 22:56:29 +00002877 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002878 SDLoc dl(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00002879
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002880 // Check to see if we can do this.
Eli Friedmanc8228d22008-11-30 06:35:39 +00002881 // FIXME: We should be more aggressive here.
2882 if (!isTypeLegal(VT))
2883 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002884
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002885 // If the sdiv has an 'exact' bit we can use a simpler lowering.
2886 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2887 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2888
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002889 APInt::ms magics = Divisor.magic();
Wesley Peck527da1b2010-11-23 03:31:01 +00002890
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002891 // Multiply the numerator (operand 0) by the magic value
Eli Friedmanc8228d22008-11-30 06:35:39 +00002892 // FIXME: We should support doing a MUL in a wider type
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002893 SDValue Q;
Richard Osborne561fac42011-11-07 17:09:05 +00002894 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2895 isOperationLegalOrCustom(ISD::MULHS, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002896 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002897 DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002898 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2899 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002900 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
Dan Gohmana1603612007-10-08 18:33:35 +00002901 N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002902 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002903 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002904 return SDValue(); // No mulhs or equvialent
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002905 // If d > 0 and m < 0, add the numerator
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002906 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002907 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002908 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002909 }
2910 // If d < 0 and m > 0, subtract the numerator.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002911 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002912 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002913 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002914 }
Mehdi Amini9639d652015-07-09 02:09:20 +00002915 auto &DL = DAG.getDataLayout();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002916 // Shift right algebraic if shift value is nonzero
2917 if (magics.s > 0) {
Mehdi Amini9639d652015-07-09 02:09:20 +00002918 Q = DAG.getNode(
2919 ISD::SRA, dl, VT, Q,
2920 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002921 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002922 }
2923 // Extract the sign bit and add it to the quotient
Mehdi Amini9639d652015-07-09 02:09:20 +00002924 SDValue T =
2925 DAG.getNode(ISD::SRL, dl, VT, Q,
2926 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2927 getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002928 Created->push_back(T.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002929 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002930}
2931
David Majnemer0fc86702013-06-08 23:51:45 +00002932/// \brief Given an ISD::UDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002933/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002934/// multiplying by a magic number.
2935/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002936SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2937 SelectionDAG &DAG, bool IsAfterLegalization,
2938 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002939 assert(Created && "No vector to hold udiv ops.");
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002940
Owen Anderson53aa7a92009-08-10 22:56:29 +00002941 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002942 SDLoc dl(N);
Mehdi Amini9639d652015-07-09 02:09:20 +00002943 auto &DL = DAG.getDataLayout();
Eli Friedman1b7fc152008-11-30 06:02:26 +00002944
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002945 // Check to see if we can do this.
Eli Friedman1b7fc152008-11-30 06:02:26 +00002946 // FIXME: We should be more aggressive here.
2947 if (!isTypeLegal(VT))
2948 return SDValue();
2949
2950 // FIXME: We should use a narrower constant when the upper
2951 // bits are known to be zero.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002952 APInt::mu magics = Divisor.magicu();
Benjamin Kramercfcea122011-03-17 20:39:14 +00002953
2954 SDValue Q = N->getOperand(0);
2955
2956 // If the divisor is even, we can avoid using the expensive fixup by shifting
2957 // the divided value upfront.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002958 if (magics.a != 0 && !Divisor[0]) {
2959 unsigned Shift = Divisor.countTrailingZeros();
Mehdi Amini9639d652015-07-09 02:09:20 +00002960 Q = DAG.getNode(
2961 ISD::SRL, dl, VT, Q,
2962 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002963 Created->push_back(Q.getNode());
Benjamin Kramercfcea122011-03-17 20:39:14 +00002964
2965 // Get magic number for the shifted divisor.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002966 magics = Divisor.lshr(Shift).magicu(Shift);
Benjamin Kramercfcea122011-03-17 20:39:14 +00002967 assert(magics.a == 0 && "Should use cheap fixup now");
2968 }
Eli Friedman1b7fc152008-11-30 06:02:26 +00002969
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002970 // Multiply the numerator (operand 0) by the magic value
Eli Friedman1b7fc152008-11-30 06:02:26 +00002971 // FIXME: We should support doing a MUL in a wider type
Richard Osborne561fac42011-11-07 17:09:05 +00002972 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2973 isOperationLegalOrCustom(ISD::MULHU, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002974 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002975 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2976 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
Benjamin Kramercfcea122011-03-17 20:39:14 +00002977 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002978 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002979 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002980 return SDValue(); // No mulhu or equvialent
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002981
2982 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002983
2984 if (magics.a == 0) {
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002985 assert(magics.s < Divisor.getBitWidth() &&
Eli Friedman1b7fc152008-11-30 06:02:26 +00002986 "We shouldn't generate an undefined shift!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002987 return DAG.getNode(
2988 ISD::SRL, dl, VT, Q,
2989 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002990 } else {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002991 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002992 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002993 NPQ = DAG.getNode(
2994 ISD::SRL, dl, VT, NPQ,
2995 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002996 Created->push_back(NPQ.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002997 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002998 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002999 return DAG.getNode(
3000 ISD::SRL, dl, VT, NPQ,
3001 DAG.getConstant(magics.s - 1, dl,
3002 getShiftAmountTy(NPQ.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00003003 }
3004}
Bill Wendling908bf812014-01-06 00:43:20 +00003005
3006bool TargetLowering::
3007verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
3008 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3009 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3010 "be a constant integer");
3011 return true;
3012 }
3013
3014 return false;
3015}
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003016
3017//===----------------------------------------------------------------------===//
3018// Legalization Utilities
3019//===----------------------------------------------------------------------===//
3020
3021bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3022 SelectionDAG &DAG, SDValue LL, SDValue LH,
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003023 SDValue RL, SDValue RH) const {
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003024 EVT VT = N->getValueType(0);
3025 SDLoc dl(N);
3026
3027 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3028 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3029 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3030 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3031 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
3032 unsigned OuterBitSize = VT.getSizeInBits();
3033 unsigned InnerBitSize = HiLoVT.getSizeInBits();
3034 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
3035 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
3036
3037 // LL, LH, RL, and RH must be either all NULL or all set to a value.
3038 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3039 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3040
3041 if (!LL.getNode() && !RL.getNode() &&
3042 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3043 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
3044 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
3045 }
3046
3047 if (!LL.getNode())
3048 return false;
3049
3050 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3051 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
3052 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
3053 // The inputs are both zero-extended.
3054 if (HasUMUL_LOHI) {
3055 // We can emit a umul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003056 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3057 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003058 Hi = SDValue(Lo.getNode(), 1);
3059 return true;
3060 }
3061 if (HasMULHU) {
3062 // We can emit a mulhu+mul.
3063 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3064 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3065 return true;
3066 }
3067 }
3068 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
3069 // The input values are both sign-extended.
3070 if (HasSMUL_LOHI) {
3071 // We can emit a smul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003072 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3073 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003074 Hi = SDValue(Lo.getNode(), 1);
3075 return true;
3076 }
3077 if (HasMULHS) {
3078 // We can emit a mulhs+mul.
3079 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3080 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
3081 return true;
3082 }
3083 }
3084
3085 if (!LH.getNode() && !RH.getNode() &&
3086 isOperationLegalOrCustom(ISD::SRL, VT) &&
3087 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +00003088 auto &DL = DAG.getDataLayout();
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003089 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
Mehdi Amini9639d652015-07-09 02:09:20 +00003090 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL));
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003091 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
3092 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3093 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
3094 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3095 }
3096
3097 if (!LH.getNode())
3098 return false;
3099
3100 if (HasUMUL_LOHI) {
3101 // Lo,Hi = umul LHS, RHS.
3102 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
3103 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
3104 Lo = UMulLOHI;
3105 Hi = UMulLOHI.getValue(1);
3106 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3107 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3108 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3109 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3110 return true;
3111 }
3112 if (HasMULHU) {
3113 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3114 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3115 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3116 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3117 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3118 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3119 return true;
3120 }
3121 }
3122 return false;
3123}
Jan Veselyeca89d22014-07-10 22:40:18 +00003124
3125bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3126 SelectionDAG &DAG) const {
3127 EVT VT = Node->getOperand(0).getValueType();
3128 EVT NVT = Node->getValueType(0);
3129 SDLoc dl(SDValue(Node, 0));
3130
3131 // FIXME: Only f32 to i64 conversions are supported.
3132 if (VT != MVT::f32 || NVT != MVT::i64)
3133 return false;
3134
3135 // Expand f32 -> i64 conversion
3136 // This algorithm comes from compiler-rt's implementation of fixsfdi:
3137 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3138 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3139 VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003140 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3141 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3142 SDValue Bias = DAG.getConstant(127, dl, IntVT);
3143 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
Jan Veselyeca89d22014-07-10 22:40:18 +00003144 IntVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003145 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3146 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003147
3148 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3149
Mehdi Amini9639d652015-07-09 02:09:20 +00003150 auto &DL = DAG.getDataLayout();
3151 SDValue ExponentBits = DAG.getNode(
3152 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3153 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003154 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3155
Mehdi Amini9639d652015-07-09 02:09:20 +00003156 SDValue Sign = DAG.getNode(
3157 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3158 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003159 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3160
3161 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3162 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003163 DAG.getConstant(0x00800000, dl, IntVT));
Jan Veselyeca89d22014-07-10 22:40:18 +00003164
3165 R = DAG.getZExtOrTrunc(R, dl, NVT);
3166
Mehdi Amini9639d652015-07-09 02:09:20 +00003167 R = DAG.getSelectCC(
3168 dl, Exponent, ExponentLoBit,
3169 DAG.getNode(ISD::SHL, dl, NVT, R,
3170 DAG.getZExtOrTrunc(
3171 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3172 dl, getShiftAmountTy(IntVT, DL))),
3173 DAG.getNode(ISD::SRL, dl, NVT, R,
3174 DAG.getZExtOrTrunc(
3175 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3176 dl, getShiftAmountTy(IntVT, DL))),
3177 ISD::SETGT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003178
3179 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3180 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3181 Sign);
3182
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003183 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3184 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003185 return true;
3186}
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003187
Matt Arsenaulta4b1b6e2016-03-30 21:15:10 +00003188SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3189 SelectionDAG &DAG) const {
3190 SDLoc SL(LD);
3191 SDValue Chain = LD->getChain();
3192 SDValue BasePTR = LD->getBasePtr();
3193 EVT SrcVT = LD->getMemoryVT();
3194 ISD::LoadExtType ExtType = LD->getExtensionType();
3195
3196 unsigned NumElem = SrcVT.getVectorNumElements();
3197
3198 EVT SrcEltVT = SrcVT.getScalarType();
3199 EVT DstEltVT = LD->getValueType(0).getScalarType();
3200
3201 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3202 assert(SrcEltVT.isByteSized());
3203
3204 EVT PtrVT = BasePTR.getValueType();
3205
3206 SmallVector<SDValue, 8> Vals;
3207 SmallVector<SDValue, 8> LoadChains;
3208
3209 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
Justin Lebar9c375812016-07-15 18:27:10 +00003210 SDValue ScalarLoad =
3211 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3212 LD->getPointerInfo().getWithOffset(Idx * Stride),
3213 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3214 LD->getMemOperand()->getFlags(), LD->getAAInfo());
Matt Arsenaulta4b1b6e2016-03-30 21:15:10 +00003215
3216 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3217 DAG.getConstant(Stride, SL, PtrVT));
3218
3219 Vals.push_back(ScalarLoad.getValue(0));
3220 LoadChains.push_back(ScalarLoad.getValue(1));
3221 }
3222
3223 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3224 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, SL, LD->getValueType(0), Vals);
3225
3226 return DAG.getMergeValues({ Value, NewChain }, SL);
3227}
3228
Matt Arsenault46ba3162016-03-30 21:15:18 +00003229// FIXME: This relies on each element having a byte size, otherwise the stride
3230// is 0 and just overwrites the same location. ExpandStore currently expects
3231// this broken behavior.
3232SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3233 SelectionDAG &DAG) const {
3234 SDLoc SL(ST);
3235
3236 SDValue Chain = ST->getChain();
3237 SDValue BasePtr = ST->getBasePtr();
3238 SDValue Value = ST->getValue();
3239 EVT StVT = ST->getMemoryVT();
3240
Matt Arsenault46ba3162016-03-30 21:15:18 +00003241 // The type of the data we want to save
3242 EVT RegVT = Value.getValueType();
3243 EVT RegSclVT = RegVT.getScalarType();
3244
3245 // The type of data as saved in memory.
3246 EVT MemSclVT = StVT.getScalarType();
3247
3248 EVT PtrVT = BasePtr.getValueType();
3249
3250 // Store Stride in bytes
3251 unsigned Stride = MemSclVT.getSizeInBits() / 8;
3252 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3253 unsigned NumElem = StVT.getVectorNumElements();
3254
3255 // Extract each of the elements from the original vector and save them into
3256 // memory individually.
3257 SmallVector<SDValue, 8> Stores;
3258 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3259 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3260 DAG.getConstant(Idx, SL, IdxVT));
3261
3262 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3263 DAG.getConstant(Idx * Stride, SL, PtrVT));
3264
3265 // This scalar TruncStore may be illegal, but we legalize it later.
3266 SDValue Store = DAG.getTruncStore(
Justin Lebar9c375812016-07-15 18:27:10 +00003267 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3268 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3269 ST->getMemOperand()->getFlags(), ST->getAAInfo());
Matt Arsenault46ba3162016-03-30 21:15:18 +00003270
3271 Stores.push_back(Store);
3272 }
3273
3274 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3275}
3276
Matt Arsenault7846d882016-04-21 18:19:11 +00003277std::pair<SDValue, SDValue>
3278TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3279 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3280 "unaligned indexed loads not implemented!");
3281 SDValue Chain = LD->getChain();
3282 SDValue Ptr = LD->getBasePtr();
3283 EVT VT = LD->getValueType(0);
3284 EVT LoadedVT = LD->getMemoryVT();
3285 SDLoc dl(LD);
3286 if (VT.isFloatingPoint() || VT.isVector()) {
3287 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3288 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3289 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3290 // Scalarize the load and let the individual components be handled.
3291 SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3292 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3293 }
3294
3295 // Expand to a (misaligned) integer load of the same size,
3296 // then bitconvert to floating point or vector.
3297 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3298 LD->getMemOperand());
3299 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3300 if (LoadedVT != VT)
3301 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3302 ISD::ANY_EXTEND, dl, VT, Result);
3303
3304 return std::make_pair(Result, newLoad.getValue(1));
3305 }
3306
3307 // Copy the value to a (aligned) stack slot using (unaligned) integer
3308 // loads and stores, then do a (aligned) load from the stack slot.
3309 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3310 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3311 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3312 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3313
3314 // Make sure the stack slot is also aligned for the register type.
3315 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3316
3317 SmallVector<SDValue, 8> Stores;
3318 SDValue StackPtr = StackBase;
3319 unsigned Offset = 0;
3320
3321 EVT PtrVT = Ptr.getValueType();
3322 EVT StackPtrVT = StackPtr.getValueType();
3323
3324 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3325 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3326
3327 // Do all but one copies using the full register width.
3328 for (unsigned i = 1; i < NumRegs; i++) {
3329 // Load one integer register's worth from the original location.
Justin Lebar9c375812016-07-15 18:27:10 +00003330 SDValue Load = DAG.getLoad(
3331 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3332 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3333 LD->getAAInfo());
Matt Arsenault7846d882016-04-21 18:19:11 +00003334 // Follow the load with a store to the stack slot. Remember the store.
3335 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00003336 MachinePointerInfo()));
Matt Arsenault7846d882016-04-21 18:19:11 +00003337 // Increment the pointers.
3338 Offset += RegBytes;
3339 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3340 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3341 StackPtrIncrement);
3342 }
3343
3344 // The last copy may be partial. Do an extending load.
3345 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3346 8 * (LoadedBytes - Offset));
Justin Lebar9c375812016-07-15 18:27:10 +00003347 SDValue Load =
3348 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3349 LD->getPointerInfo().getWithOffset(Offset), MemVT,
3350 MinAlign(LD->getAlignment(), Offset),
3351 LD->getMemOperand()->getFlags(), LD->getAAInfo());
Matt Arsenault7846d882016-04-21 18:19:11 +00003352 // Follow the load with a store to the stack slot. Remember the store.
3353 // On big-endian machines this requires a truncating store to ensure
3354 // that the bits end up in the right place.
3355 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00003356 MachinePointerInfo(), MemVT));
Matt Arsenault7846d882016-04-21 18:19:11 +00003357
3358 // The order of the stores doesn't matter - say it with a TokenFactor.
3359 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3360
3361 // Finally, perform the original load only redirected to the stack slot.
3362 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
Justin Lebar9c375812016-07-15 18:27:10 +00003363 MachinePointerInfo(), LoadedVT);
Matt Arsenault7846d882016-04-21 18:19:11 +00003364
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(),
Justin Lebar9c375812016-07-15 18:27:10 +00003391 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
Matt Arsenault7846d882016-04-21 18:19:11 +00003392 LD->getAAInfo());
3393 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3394 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3395 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3396 LD->getPointerInfo().getWithOffset(IncrementSize),
Justin Lebar9c375812016-07-15 18:27:10 +00003397 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3398 LD->getMemOperand()->getFlags(), LD->getAAInfo());
Matt Arsenault7846d882016-04-21 18:19:11 +00003399 } else {
3400 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00003401 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
Matt Arsenault7846d882016-04-21 18:19:11 +00003402 LD->getAAInfo());
3403 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3404 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3405 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3406 LD->getPointerInfo().getWithOffset(IncrementSize),
Justin Lebar9c375812016-07-15 18:27:10 +00003407 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3408 LD->getMemOperand()->getFlags(), LD->getAAInfo());
Matt Arsenault7846d882016-04-21 18:19:11 +00003409 }
3410
3411 // aggregate the two parts
3412 SDValue ShiftAmount =
3413 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3414 DAG.getDataLayout()));
3415 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3416 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3417
3418 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3419 Hi.getValue(1));
3420
3421 return std::make_pair(Result, TF);
3422}
3423
3424SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3425 SelectionDAG &DAG) const {
3426 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3427 "unaligned indexed stores not implemented!");
3428 SDValue Chain = ST->getChain();
3429 SDValue Ptr = ST->getBasePtr();
3430 SDValue Val = ST->getValue();
3431 EVT VT = Val.getValueType();
3432 int Alignment = ST->getAlignment();
3433
3434 SDLoc dl(ST);
3435 if (ST->getMemoryVT().isFloatingPoint() ||
3436 ST->getMemoryVT().isVector()) {
3437 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3438 if (isTypeLegal(intVT)) {
3439 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3440 // Scalarize the store and let the individual components be handled.
3441 SDValue Result = scalarizeVectorStore(ST, DAG);
3442
3443 return Result;
3444 }
3445 // Expand to a bitconvert of the value to the integer type of the
3446 // same size, then a (misaligned) int store.
3447 // FIXME: Does not handle truncating floating point stores!
3448 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3449 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00003450 Alignment, ST->getMemOperand()->getFlags());
Matt Arsenault7846d882016-04-21 18:19:11 +00003451 return Result;
3452 }
3453 // Do a (aligned) store to a stack slot, then copy from the stack slot
3454 // to the final destination using (unaligned) integer loads and stores.
3455 EVT StoredVT = ST->getMemoryVT();
3456 MVT RegVT =
3457 getRegisterType(*DAG.getContext(),
3458 EVT::getIntegerVT(*DAG.getContext(),
3459 StoredVT.getSizeInBits()));
3460 EVT PtrVT = Ptr.getValueType();
3461 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3462 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3463 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3464
3465 // Make sure the stack slot is also aligned for the register type.
3466 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3467
3468 // Perform the original store, only redirected to the stack slot.
Justin Lebar9c375812016-07-15 18:27:10 +00003469 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3470 MachinePointerInfo(), StoredVT);
Matt Arsenault7846d882016-04-21 18:19:11 +00003471
3472 EVT StackPtrVT = StackPtr.getValueType();
3473
3474 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3475 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3476 SmallVector<SDValue, 8> Stores;
3477 unsigned Offset = 0;
3478
3479 // Do all but one copies using the full register width.
3480 for (unsigned i = 1; i < NumRegs; i++) {
3481 // Load one integer register's worth from the stack slot.
Justin Lebar9c375812016-07-15 18:27:10 +00003482 SDValue Load =
3483 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
Matt Arsenault7846d882016-04-21 18:19:11 +00003484 // Store it to the final location. Remember the store.
3485 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
Justin Lebar9c375812016-07-15 18:27:10 +00003486 ST->getPointerInfo().getWithOffset(Offset),
3487 MinAlign(ST->getAlignment(), Offset),
3488 ST->getMemOperand()->getFlags()));
Matt Arsenault7846d882016-04-21 18:19:11 +00003489 // Increment the pointers.
3490 Offset += RegBytes;
3491 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3492 StackPtr, StackPtrIncrement);
3493 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3494 }
3495
3496 // The last store may be partial. Do a truncating store. On big-endian
3497 // machines this requires an extending load from the stack slot to ensure
3498 // that the bits are in the right place.
3499 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3500 8 * (StoredBytes - Offset));
3501
3502 // Load from the stack slot.
3503 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00003504 MachinePointerInfo(), MemVT);
Matt Arsenault7846d882016-04-21 18:19:11 +00003505
Justin Lebar9c375812016-07-15 18:27:10 +00003506 Stores.push_back(
3507 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3508 ST->getPointerInfo().getWithOffset(Offset), MemVT,
3509 MinAlign(ST->getAlignment(), Offset),
3510 ST->getMemOperand()->getFlags(), ST->getAAInfo()));
Matt Arsenault7846d882016-04-21 18:19:11 +00003511 // The order of the stores doesn't matter - say it with a TokenFactor.
3512 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3513 return Result;
3514 }
3515
3516 assert(ST->getMemoryVT().isInteger() &&
3517 !ST->getMemoryVT().isVector() &&
3518 "Unaligned store of unknown type.");
3519 // Get the half-size VT
3520 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3521 int NumBits = NewStoredVT.getSizeInBits();
3522 int IncrementSize = NumBits / 8;
3523
3524 // Divide the stored value in two parts.
3525 SDValue ShiftAmount =
3526 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3527 DAG.getDataLayout()));
3528 SDValue Lo = Val;
3529 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3530
3531 // Store the two parts
3532 SDValue Store1, Store2;
3533 Store1 = DAG.getTruncStore(Chain, dl,
3534 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
Justin Lebar9c375812016-07-15 18:27:10 +00003535 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3536 ST->getMemOperand()->getFlags());
Matt Arsenault7846d882016-04-21 18:19:11 +00003537
3538 EVT PtrVT = Ptr.getValueType();
3539 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3540 DAG.getConstant(IncrementSize, dl, PtrVT));
3541 Alignment = MinAlign(Alignment, IncrementSize);
3542 Store2 = DAG.getTruncStore(
3543 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
Justin Lebar9c375812016-07-15 18:27:10 +00003544 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3545 ST->getMemOperand()->getFlags(), ST->getAAInfo());
Matt Arsenault7846d882016-04-21 18:19:11 +00003546
3547 SDValue Result =
3548 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3549 return Result;
3550}
3551
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003552//===----------------------------------------------------------------------===//
3553// Implementation of Emulated TLS Model
3554//===----------------------------------------------------------------------===//
3555
3556SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3557 SelectionDAG &DAG) const {
3558 // Access to address of TLS varialbe xyz is lowered to a function call:
3559 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3560 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3561 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3562 SDLoc dl(GA);
3563
3564 ArgListTy Args;
3565 ArgListEntry Entry;
3566 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3567 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3568 StringRef EmuTlsVarName(NameString);
3569 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
Chih-Hung Hsieh57886402016-01-13 23:56:37 +00003570 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003571 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3572 Entry.Ty = VoidPtrType;
3573 Args.push_back(Entry);
3574
3575 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3576
3577 TargetLowering::CallLoweringInfo CLI(DAG);
3578 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00003579 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003580 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3581
3582 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3583 // At last for X86 targets, maybe good for other targets too?
Matthias Braun941a7052016-07-28 18:40:00 +00003584 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3585 MFI.setAdjustsStack(true); // Is this only for X86 target?
3586 MFI.setHasCalls(true);
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003587
3588 assert((GA->getOffset() == 0) &&
3589 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3590 return CallResult.first;
3591}
Pierre Gousseau051db7d2016-08-16 13:53:53 +00003592
3593SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
3594 SelectionDAG &DAG) const {
3595 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
3596 if (!isCtlzFast())
3597 return SDValue();
3598 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3599 SDLoc dl(Op);
3600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3601 if (C->isNullValue() && CC == ISD::SETEQ) {
3602 EVT VT = Op.getOperand(0).getValueType();
3603 SDValue Zext = Op.getOperand(0);
3604 if (VT.bitsLT(MVT::i32)) {
3605 VT = MVT::i32;
3606 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
3607 }
3608 unsigned Log2b = Log2_32(VT.getSizeInBits());
3609 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
3610 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
3611 DAG.getConstant(Log2b, dl, MVT::i32));
3612 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
3613 }
3614 }
3615 return SDValue();
3616}